diff -Nur rt2500-1.1.0-b4/CHANGELOG rt2500-cvs-2007061011/CHANGELOG
--- rt2500-1.1.0-b4/CHANGELOG	2006-06-17 22:12:57.000000000 +0200
+++ rt2500-cvs-2007061011/CHANGELOG	2007-06-08 20:09:53.000000000 +0200
@@ -1,28 +1,40 @@
-/*************************************************************************** 
- * RT2x00 SourceForge Project - http://rt2x00.sourceforge.net              * 
- *                                                                         * 
- *   This program is free software; you can redistribute it and/or modify  * 
- *   it under the terms of the 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.             * 
- *                                                                         * 
- *   Licensed under the GNU GPL                                            * 
- *   Original code supplied under license from RaLink Inc, 2003.           * 
+/***************************************************************************
+ * RT2x00 SourceForge Project - http://rt2x00.sourceforge.net              *
+ *                                                                         *
+ *   This program is free software; you can redistribute it and/or modify  *
+ *   it under the terms of the 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.             *
+ *                                                                         *
+ *   Licensed under the GNU GPL                                            *
+ *   Original code supplied under license from RaLink Inc, 2003.           *
  ***************************************************************************/
- 
+
  Changelog for 802.11g rt2500 driver and RAConfig2500 Utility
 
- Version: 1.1.0-beta4 
+ Version: CVS
+	* Forward compatibility with kernel 2.6.22 pci bus driver i/f changes
+	  and skbuff changes.
+ 	* SIOCGIWSCAN returns EAGAIN until all channels scanned.
+ 	* More cruft removal.
+	* Updated base code to Ralink 1.4.6.6 driver version.
+	* In-kernel compile support (Bug #1642144): Declare debug var
+	  as static. Implement as bit mask.
+	* Fix to WPA RSN IE mismatched bug
+	* Compatibility fixes for kernels >= 2.6.19
+	* Fix essid truncation on kernels >= 2.6.19
+
+ Version: 1.1.0-beta4
 	* Fix pre-up config panic (1307957)
 	* Fix noise levels in scan results (1246025)
 	* RFMON TX Support for aircrack
@@ -31,9 +43,9 @@
 	* Promisc/Monitor code missing node->AP packets (1009565)
 	* Channel set in RFMON before ifup now works (1254806)
 	* Fixes for suspend/resume
-	* Enhancement for RaConfig to support non-ra? interfaces 
+	* Enhancement for RaConfig to support non-ra? interfaces
 	* Channel list updates after region change
-	* TxPower changes to support dBm values 
+	* TxPower changes to support dBm values
 	* Pre-up panic for setting WirelessMode
 	* Cleanup of iwpriv syntax
 	* Fixes for SMP support (1099089)
@@ -47,7 +59,7 @@
         * Power Saving Modes (1159331)
         * Bridging with other interfaces
 
- Version: 1.1.0-beta3 
+ Version: 1.1.0-beta3
         * PCI Management Cleanup
         * Fix for RaConfig crashing on statistics (ChrisH)
         * Big-Endian fix for RaConfig
@@ -63,15 +75,15 @@
 		* Fix iwconfig - Link Quality(means Channel Quality), Signal level and Noise level.
 		* Fix iwlist ra0 channel - print out
 
- Version: 1.1.0-beta2 
+ Version: 1.1.0-beta2
 	* Removed Kernel tainting
 	* Updated all file headers for this project
 	* kmalloc stability fixes to the MLME
         * Cleanup on memory management functions (NDisFill/Move/Zero)
         * Rollin of Robin Cornelius RFMon Patch
         * RFMon support through iwconfig mode
-        * Debugging and general logging cleanups 
-        * Rolling of changes in Ralink 1.4.5.0 release  
+        * Debugging and general logging cleanups
+        * Rolling of changes in Ralink 1.4.5.0 release
         * Debug switching
         * Spinlock changes for stability
         * GCC 3.4 compilation
@@ -86,5 +98,5 @@
 
  Version: 1.0.0
  	* Initial baseline code from Ralink (1.4.4.0)
- 
- 
+
+
diff -Nur rt2500-1.1.0-b4/LICENSE rt2500-cvs-2007061011/LICENSE
--- rt2500-1.1.0-b4/LICENSE	2006-06-17 22:12:58.000000000 +0200
+++ rt2500-cvs-2007061011/LICENSE	2007-05-29 05:57:52.000000000 +0200
@@ -1,340 +1,340 @@
-		    GNU GENERAL PUBLIC LICENSE
-		       Version 2, June 1991
-
- Copyright (C) 1989, 1991 Free Software Foundation, Inc.
-                       59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
- Everyone is permitted to copy and distribute verbatim copies
- of this license document, but changing it is not allowed.
-
-			    Preamble
-
-  The licenses for most software are designed to take away your
-freedom to share and change it.  By contrast, the GNU General Public
-License is intended to guarantee your freedom to share and change free
-software--to make sure the software is free for all its users.  This
-General Public License applies to most of the Free Software
-Foundation's software and to any other program whose authors commit to
-using it.  (Some other Free Software Foundation software is covered by
-the GNU Library General Public License instead.)  You can apply it to
-your programs, too.
-
-  When we speak of free software, we are referring to freedom, not
-price.  Our General Public Licenses are designed to make sure that you
-have the freedom to distribute copies of free software (and charge for
-this service if you wish), that you receive source code or can get it
-if you want it, that you can change the software or use pieces of it
-in new free programs; and that you know you can do these things.
-
-  To protect your rights, we need to make restrictions that forbid
-anyone to deny you these rights or to ask you to surrender the rights.
-These restrictions translate to certain responsibilities for you if you
-distribute copies of the software, or if you modify it.
-
-  For example, if you distribute copies of such a program, whether
-gratis or for a fee, you must give the recipients all the rights that
-you have.  You must make sure that they, too, receive or can get the
-source code.  And you must show them these terms so they know their
-rights.
-
-  We protect your rights with two steps: (1) copyright the software, and
-(2) offer you this license which gives you legal permission to copy,
-distribute and/or modify the software.
-
-  Also, for each author's protection and ours, we want to make certain
-that everyone understands that there is no warranty for this free
-software.  If the software is modified by someone else and passed on, we
-want its recipients to know that what they have is not the original, so
-that any problems introduced by others will not reflect on the original
-authors' reputations.
-
-  Finally, any free program is threatened constantly by software
-patents.  We wish to avoid the danger that redistributors of a free
-program will individually obtain patent licenses, in effect making the
-program proprietary.  To prevent this, we have made it clear that any
-patent must be licensed for everyone's free use or not licensed at all.
-
-  The precise terms and conditions for copying, distribution and
-modification follow.
-
-		    GNU GENERAL PUBLIC LICENSE
-   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
-
-  0. This License applies to any program or other work which contains
-a notice placed by the copyright holder saying it may be distributed
-under the terms of this General Public License.  The "Program", below,
-refers to any such program or work, and a "work based on the Program"
-means either the Program or any derivative work under copyright law:
-that is to say, a work containing the Program or a portion of it,
-either verbatim or with modifications and/or translated into another
-language.  (Hereinafter, translation is included without limitation in
-the term "modification".)  Each licensee is addressed as "you".
-
-Activities other than copying, distribution and modification are not
-covered by this License; they are outside its scope.  The act of
-running the Program is not restricted, and the output from the Program
-is covered only if its contents constitute a work based on the
-Program (independent of having been made by running the Program).
-Whether that is true depends on what the Program does.
-
-  1. You may copy and distribute verbatim copies of the Program's
-source code as you receive it, in any medium, provided that you
-conspicuously and appropriately publish on each copy an appropriate
-copyright notice and disclaimer of warranty; keep intact all the
-notices that refer to this License and to the absence of any warranty;
-and give any other recipients of the Program a copy of this License
-along with the Program.
-
-You may charge a fee for the physical act of transferring a copy, and
-you may at your option offer warranty protection in exchange for a fee.
-
-  2. You may modify your copy or copies of the Program or any portion
-of it, thus forming a work based on the Program, and copy and
-distribute such modifications or work under the terms of Section 1
-above, provided that you also meet all of these conditions:
-
-    a) You must cause the modified files to carry prominent notices
-    stating that you changed the files and the date of any change.
-
-    b) You must cause any work that you distribute or publish, that in
-    whole or in part contains or is derived from the Program or any
-    part thereof, to be licensed as a whole at no charge to all third
-    parties under the terms of this License.
-
-    c) If the modified program normally reads commands interactively
-    when run, you must cause it, when started running for such
-    interactive use in the most ordinary way, to print or display an
-    announcement including an appropriate copyright notice and a
-    notice that there is no warranty (or else, saying that you provide
-    a warranty) and that users may redistribute the program under
-    these conditions, and telling the user how to view a copy of this
-    License.  (Exception: if the Program itself is interactive but
-    does not normally print such an announcement, your work based on
-    the Program is not required to print an announcement.)
-
-These requirements apply to the modified work as a whole.  If
-identifiable sections of that work are not derived from the Program,
-and can be reasonably considered independent and separate works in
-themselves, then this License, and its terms, do not apply to those
-sections when you distribute them as separate works.  But when you
-distribute the same sections as part of a whole which is a work based
-on the Program, the distribution of the whole must be on the terms of
-this License, whose permissions for other licensees extend to the
-entire whole, and thus to each and every part regardless of who wrote it.
-
-Thus, it is not the intent of this section to claim rights or contest
-your rights to work written entirely by you; rather, the intent is to
-exercise the right to control the distribution of derivative or
-collective works based on the Program.
-
-In addition, mere aggregation of another work not based on the Program
-with the Program (or with a work based on the Program) on a volume of
-a storage or distribution medium does not bring the other work under
-the scope of this License.
-
-  3. You may copy and distribute the Program (or a work based on it,
-under Section 2) in object code or executable form under the terms of
-Sections 1 and 2 above provided that you also do one of the following:
-
-    a) Accompany it with the complete corresponding machine-readable
-    source code, which must be distributed under the terms of Sections
-    1 and 2 above on a medium customarily used for software interchange; or,
-
-    b) Accompany it with a written offer, valid for at least three
-    years, to give any third party, for a charge no more than your
-    cost of physically performing source distribution, a complete
-    machine-readable copy of the corresponding source code, to be
-    distributed under the terms of Sections 1 and 2 above on a medium
-    customarily used for software interchange; or,
-
-    c) Accompany it with the information you received as to the offer
-    to distribute corresponding source code.  (This alternative is
-    allowed only for noncommercial distribution and only if you
-    received the program in object code or executable form with such
-    an offer, in accord with Subsection b above.)
-
-The source code for a work means the preferred form of the work for
-making modifications to it.  For an executable work, complete source
-code means all the source code for all modules it contains, plus any
-associated interface definition files, plus the scripts used to
-control compilation and installation of the executable.  However, as a
-special exception, the source code distributed need not include
-anything that is normally distributed (in either source or binary
-form) with the major components (compiler, kernel, and so on) of the
-operating system on which the executable runs, unless that component
-itself accompanies the executable.
-
-If distribution of executable or object code is made by offering
-access to copy from a designated place, then offering equivalent
-access to copy the source code from the same place counts as
-distribution of the source code, even though third parties are not
-compelled to copy the source along with the object code.
-
-  4. You may not copy, modify, sublicense, or distribute the Program
-except as expressly provided under this License.  Any attempt
-otherwise to copy, modify, sublicense or distribute the Program is
-void, and will automatically terminate your rights under this License.
-However, parties who have received copies, or rights, from you under
-this License will not have their licenses terminated so long as such
-parties remain in full compliance.
-
-  5. You are not required to accept this License, since you have not
-signed it.  However, nothing else grants you permission to modify or
-distribute the Program or its derivative works.  These actions are
-prohibited by law if you do not accept this License.  Therefore, by
-modifying or distributing the Program (or any work based on the
-Program), you indicate your acceptance of this License to do so, and
-all its terms and conditions for copying, distributing or modifying
-the Program or works based on it.
-
-  6. Each time you redistribute the Program (or any work based on the
-Program), the recipient automatically receives a license from the
-original licensor to copy, distribute or modify the Program subject to
-these terms and conditions.  You may not impose any further
-restrictions on the recipients' exercise of the rights granted herein.
-You are not responsible for enforcing compliance by third parties to
-this License.
-
-  7. If, as a consequence of a court judgment or allegation of patent
-infringement or for any other reason (not limited to patent issues),
-conditions are imposed on you (whether by court order, agreement or
-otherwise) that contradict the conditions of this License, they do not
-excuse you from the conditions of this License.  If you cannot
-distribute so as to satisfy simultaneously your obligations under this
-License and any other pertinent obligations, then as a consequence you
-may not distribute the Program at all.  For example, if a patent
-license would not permit royalty-free redistribution of the Program by
-all those who receive copies directly or indirectly through you, then
-the only way you could satisfy both it and this License would be to
-refrain entirely from distribution of the Program.
-
-If any portion of this section is held invalid or unenforceable under
-any particular circumstance, the balance of the section is intended to
-apply and the section as a whole is intended to apply in other
-circumstances.
-
-It is not the purpose of this section to induce you to infringe any
-patents or other property right claims or to contest validity of any
-such claims; this section has the sole purpose of protecting the
-integrity of the free software distribution system, which is
-implemented by public license practices.  Many people have made
-generous contributions to the wide range of software distributed
-through that system in reliance on consistent application of that
-system; it is up to the author/donor to decide if he or she is willing
-to distribute software through any other system and a licensee cannot
-impose that choice.
-
-This section is intended to make thoroughly clear what is believed to
-be a consequence of the rest of this License.
-
-  8. If the distribution and/or use of the Program is restricted in
-certain countries either by patents or by copyrighted interfaces, the
-original copyright holder who places the Program under this License
-may add an explicit geographical distribution limitation excluding
-those countries, so that distribution is permitted only in or among
-countries not thus excluded.  In such case, this License incorporates
-the limitation as if written in the body of this License.
-
-  9. The Free Software Foundation may publish revised and/or new versions
-of the General Public License from time to time.  Such new versions will
-be similar in spirit to the present version, but may differ in detail to
-address new problems or concerns.
-
-Each version is given a distinguishing version number.  If the Program
-specifies a version number of this License which applies to it and "any
-later version", you have the option of following the terms and conditions
-either of that version or of any later version published by the Free
-Software Foundation.  If the Program does not specify a version number of
-this License, you may choose any version ever published by the Free Software
-Foundation.
-
-  10. If you wish to incorporate parts of the Program into other free
-programs whose distribution conditions are different, write to the author
-to ask for permission.  For software which is copyrighted by the Free
-Software Foundation, write to the Free Software Foundation; we sometimes
-make exceptions for this.  Our decision will be guided by the two goals
-of preserving the free status of all derivatives of our free software and
-of promoting the sharing and reuse of software generally.
-
-			    NO WARRANTY
-
-  11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
-FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN
-OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
-PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
-OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
-MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS
-TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE
-PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
-REPAIR OR CORRECTION.
-
-  12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
-WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
-REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
-INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
-OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
-TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
-YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
-PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
-POSSIBILITY OF SUCH DAMAGES.
-
-		     END OF TERMS AND CONDITIONS
-
-	    How to Apply These Terms to Your New Programs
-
-  If you develop a new program, and you want it to be of the greatest
-possible use to the public, the best way to achieve this is to make it
-free software which everyone can redistribute and change under these terms.
-
-  To do so, attach the following notices to the program.  It is safest
-to attach them to the start of each source file to most effectively
-convey the exclusion of warranty; and each file should have at least
-the "copyright" line and a pointer to where the full notice is found.
-
-    <one line to give the program's name and a brief idea of what it does.>
-    Copyright (C) <year>  <name of author>
-
-    This program is free software; you can redistribute it and/or modify
-    it under the terms of the 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
-
-
-Also add information on how to contact you by electronic and paper mail.
-
-If the program is interactive, make it output a short notice like this
-when it starts in an interactive mode:
-
-    Gnomovision version 69, Copyright (C) year name of author
-    Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
-    This is free software, and you are welcome to redistribute it
-    under certain conditions; type `show c' for details.
-
-The hypothetical commands `show w' and `show c' should show the appropriate
-parts of the General Public License.  Of course, the commands you use may
-be called something other than `show w' and `show c'; they could even be
-mouse-clicks or menu items--whatever suits your program.
-
-You should also get your employer (if you work as a programmer) or your
-school, if any, to sign a "copyright disclaimer" for the program, if
-necessary.  Here is a sample; alter the names:
-
-  Yoyodyne, Inc., hereby disclaims all copyright interest in the program
-  `Gnomovision' (which makes passes at compilers) written by James Hacker.
-
-  <signature of Ty Coon>, 1 April 1989
-  Ty Coon, President of Vice
-
-This General Public License does not permit incorporating your program into
-proprietary programs.  If your program is a subroutine library, you may
-consider it more useful to permit linking proprietary applications with the
-library.  If this is what you want to do, use the GNU Library General
+		    GNU GENERAL PUBLIC LICENSE
+		       Version 2, June 1991
+
+ Copyright (C) 1989, 1991 Free Software Foundation, Inc.
+                       59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+			    Preamble
+
+  The licenses for most software are designed to take away your
+freedom to share and change it.  By contrast, the GNU General Public
+License is intended to guarantee your freedom to share and change free
+software--to make sure the software is free for all its users.  This
+General Public License applies to most of the Free Software
+Foundation's software and to any other program whose authors commit to
+using it.  (Some other Free Software Foundation software is covered by
+the GNU Library General Public License instead.)  You can apply it to
+your programs, too.
+
+  When we speak of free software, we are referring to freedom, not
+price.  Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+this service if you wish), that you receive source code or can get it
+if you want it, that you can change the software or use pieces of it
+in new free programs; and that you know you can do these things.
+
+  To protect your rights, we need to make restrictions that forbid
+anyone to deny you these rights or to ask you to surrender the rights.
+These restrictions translate to certain responsibilities for you if you
+distribute copies of the software, or if you modify it.
+
+  For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must give the recipients all the rights that
+you have.  You must make sure that they, too, receive or can get the
+source code.  And you must show them these terms so they know their
+rights.
+
+  We protect your rights with two steps: (1) copyright the software, and
+(2) offer you this license which gives you legal permission to copy,
+distribute and/or modify the software.
+
+  Also, for each author's protection and ours, we want to make certain
+that everyone understands that there is no warranty for this free
+software.  If the software is modified by someone else and passed on, we
+want its recipients to know that what they have is not the original, so
+that any problems introduced by others will not reflect on the original
+authors' reputations.
+
+  Finally, any free program is threatened constantly by software
+patents.  We wish to avoid the danger that redistributors of a free
+program will individually obtain patent licenses, in effect making the
+program proprietary.  To prevent this, we have made it clear that any
+patent must be licensed for everyone's free use or not licensed at all.
+
+  The precise terms and conditions for copying, distribution and
+modification follow.
+
+		    GNU GENERAL PUBLIC LICENSE
+   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+  0. This License applies to any program or other work which contains
+a notice placed by the copyright holder saying it may be distributed
+under the terms of this General Public License.  The "Program", below,
+refers to any such program or work, and a "work based on the Program"
+means either the Program or any derivative work under copyright law:
+that is to say, a work containing the Program or a portion of it,
+either verbatim or with modifications and/or translated into another
+language.  (Hereinafter, translation is included without limitation in
+the term "modification".)  Each licensee is addressed as "you".
+
+Activities other than copying, distribution and modification are not
+covered by this License; they are outside its scope.  The act of
+running the Program is not restricted, and the output from the Program
+is covered only if its contents constitute a work based on the
+Program (independent of having been made by running the Program).
+Whether that is true depends on what the Program does.
+
+  1. You may copy and distribute verbatim copies of the Program's
+source code as you receive it, in any medium, provided that you
+conspicuously and appropriately publish on each copy an appropriate
+copyright notice and disclaimer of warranty; keep intact all the
+notices that refer to this License and to the absence of any warranty;
+and give any other recipients of the Program a copy of this License
+along with the Program.
+
+You may charge a fee for the physical act of transferring a copy, and
+you may at your option offer warranty protection in exchange for a fee.
+
+  2. You may modify your copy or copies of the Program or any portion
+of it, thus forming a work based on the Program, and copy and
+distribute such modifications or work under the terms of Section 1
+above, provided that you also meet all of these conditions:
+
+    a) You must cause the modified files to carry prominent notices
+    stating that you changed the files and the date of any change.
+
+    b) You must cause any work that you distribute or publish, that in
+    whole or in part contains or is derived from the Program or any
+    part thereof, to be licensed as a whole at no charge to all third
+    parties under the terms of this License.
+
+    c) If the modified program normally reads commands interactively
+    when run, you must cause it, when started running for such
+    interactive use in the most ordinary way, to print or display an
+    announcement including an appropriate copyright notice and a
+    notice that there is no warranty (or else, saying that you provide
+    a warranty) and that users may redistribute the program under
+    these conditions, and telling the user how to view a copy of this
+    License.  (Exception: if the Program itself is interactive but
+    does not normally print such an announcement, your work based on
+    the Program is not required to print an announcement.)
+
+These requirements apply to the modified work as a whole.  If
+identifiable sections of that work are not derived from the Program,
+and can be reasonably considered independent and separate works in
+themselves, then this License, and its terms, do not apply to those
+sections when you distribute them as separate works.  But when you
+distribute the same sections as part of a whole which is a work based
+on the Program, the distribution of the whole must be on the terms of
+this License, whose permissions for other licensees extend to the
+entire whole, and thus to each and every part regardless of who wrote it.
+
+Thus, it is not the intent of this section to claim rights or contest
+your rights to work written entirely by you; rather, the intent is to
+exercise the right to control the distribution of derivative or
+collective works based on the Program.
+
+In addition, mere aggregation of another work not based on the Program
+with the Program (or with a work based on the Program) on a volume of
+a storage or distribution medium does not bring the other work under
+the scope of this License.
+
+  3. You may copy and distribute the Program (or a work based on it,
+under Section 2) in object code or executable form under the terms of
+Sections 1 and 2 above provided that you also do one of the following:
+
+    a) Accompany it with the complete corresponding machine-readable
+    source code, which must be distributed under the terms of Sections
+    1 and 2 above on a medium customarily used for software interchange; or,
+
+    b) Accompany it with a written offer, valid for at least three
+    years, to give any third party, for a charge no more than your
+    cost of physically performing source distribution, a complete
+    machine-readable copy of the corresponding source code, to be
+    distributed under the terms of Sections 1 and 2 above on a medium
+    customarily used for software interchange; or,
+
+    c) Accompany it with the information you received as to the offer
+    to distribute corresponding source code.  (This alternative is
+    allowed only for noncommercial distribution and only if you
+    received the program in object code or executable form with such
+    an offer, in accord with Subsection b above.)
+
+The source code for a work means the preferred form of the work for
+making modifications to it.  For an executable work, complete source
+code means all the source code for all modules it contains, plus any
+associated interface definition files, plus the scripts used to
+control compilation and installation of the executable.  However, as a
+special exception, the source code distributed need not include
+anything that is normally distributed (in either source or binary
+form) with the major components (compiler, kernel, and so on) of the
+operating system on which the executable runs, unless that component
+itself accompanies the executable.
+
+If distribution of executable or object code is made by offering
+access to copy from a designated place, then offering equivalent
+access to copy the source code from the same place counts as
+distribution of the source code, even though third parties are not
+compelled to copy the source along with the object code.
+
+  4. You may not copy, modify, sublicense, or distribute the Program
+except as expressly provided under this License.  Any attempt
+otherwise to copy, modify, sublicense or distribute the Program is
+void, and will automatically terminate your rights under this License.
+However, parties who have received copies, or rights, from you under
+this License will not have their licenses terminated so long as such
+parties remain in full compliance.
+
+  5. You are not required to accept this License, since you have not
+signed it.  However, nothing else grants you permission to modify or
+distribute the Program or its derivative works.  These actions are
+prohibited by law if you do not accept this License.  Therefore, by
+modifying or distributing the Program (or any work based on the
+Program), you indicate your acceptance of this License to do so, and
+all its terms and conditions for copying, distributing or modifying
+the Program or works based on it.
+
+  6. Each time you redistribute the Program (or any work based on the
+Program), the recipient automatically receives a license from the
+original licensor to copy, distribute or modify the Program subject to
+these terms and conditions.  You may not impose any further
+restrictions on the recipients' exercise of the rights granted herein.
+You are not responsible for enforcing compliance by third parties to
+this License.
+
+  7. If, as a consequence of a court judgment or allegation of patent
+infringement or for any other reason (not limited to patent issues),
+conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License.  If you cannot
+distribute so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you
+may not distribute the Program at all.  For example, if a patent
+license would not permit royalty-free redistribution of the Program by
+all those who receive copies directly or indirectly through you, then
+the only way you could satisfy both it and this License would be to
+refrain entirely from distribution of the Program.
+
+If any portion of this section is held invalid or unenforceable under
+any particular circumstance, the balance of the section is intended to
+apply and the section as a whole is intended to apply in other
+circumstances.
+
+It is not the purpose of this section to induce you to infringe any
+patents or other property right claims or to contest validity of any
+such claims; this section has the sole purpose of protecting the
+integrity of the free software distribution system, which is
+implemented by public license practices.  Many people have made
+generous contributions to the wide range of software distributed
+through that system in reliance on consistent application of that
+system; it is up to the author/donor to decide if he or she is willing
+to distribute software through any other system and a licensee cannot
+impose that choice.
+
+This section is intended to make thoroughly clear what is believed to
+be a consequence of the rest of this License.
+
+  8. If the distribution and/or use of the Program is restricted in
+certain countries either by patents or by copyrighted interfaces, the
+original copyright holder who places the Program under this License
+may add an explicit geographical distribution limitation excluding
+those countries, so that distribution is permitted only in or among
+countries not thus excluded.  In such case, this License incorporates
+the limitation as if written in the body of this License.
+
+  9. The Free Software Foundation may publish revised and/or new versions
+of the General Public License from time to time.  Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+Each version is given a distinguishing version number.  If the Program
+specifies a version number of this License which applies to it and "any
+later version", you have the option of following the terms and conditions
+either of that version or of any later version published by the Free
+Software Foundation.  If the Program does not specify a version number of
+this License, you may choose any version ever published by the Free Software
+Foundation.
+
+  10. If you wish to incorporate parts of the Program into other free
+programs whose distribution conditions are different, write to the author
+to ask for permission.  For software which is copyrighted by the Free
+Software Foundation, write to the Free Software Foundation; we sometimes
+make exceptions for this.  Our decision will be guided by the two goals
+of preserving the free status of all derivatives of our free software and
+of promoting the sharing and reuse of software generally.
+
+			    NO WARRANTY
+
+  11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
+FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN
+OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
+PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
+OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS
+TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE
+PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
+REPAIR OR CORRECTION.
+
+  12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
+REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
+INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
+OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
+TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
+YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
+PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
+POSSIBILITY OF SUCH DAMAGES.
+
+		     END OF TERMS AND CONDITIONS
+
+	    How to Apply These Terms to Your New Programs
+
+  If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+  To do so, attach the following notices to the program.  It is safest
+to attach them to the start of each source file to most effectively
+convey the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+    <one line to give the program's name and a brief idea of what it does.>
+    Copyright (C) <year>  <name of author>
+
+    This program is free software; you can redistribute it and/or modify
+    it under the terms of the 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
+
+
+Also add information on how to contact you by electronic and paper mail.
+
+If the program is interactive, make it output a short notice like this
+when it starts in an interactive mode:
+
+    Gnomovision version 69, Copyright (C) year name of author
+    Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+    This is free software, and you are welcome to redistribute it
+    under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License.  Of course, the commands you use may
+be called something other than `show w' and `show c'; they could even be
+mouse-clicks or menu items--whatever suits your program.
+
+You should also get your employer (if you work as a programmer) or your
+school, if any, to sign a "copyright disclaimer" for the program, if
+necessary.  Here is a sample; alter the names:
+
+  Yoyodyne, Inc., hereby disclaims all copyright interest in the program
+  `Gnomovision' (which makes passes at compilers) written by James Hacker.
+
+  <signature of Ty Coon>, 1 April 1989
+  Ty Coon, President of Vice
+
+This General Public License does not permit incorporating your program into
+proprietary programs.  If your program is a subroutine library, you may
+consider it more useful to permit linking proprietary applications with the
+library.  If this is what you want to do, use the GNU Library General
 Public License instead of this License.
\ Kein Zeilenumbruch am Dateiende.
diff -Nur rt2500-1.1.0-b4/Module/Makefile rt2500-cvs-2007061011/Module/Makefile
--- rt2500-1.1.0-b4/Module/Makefile	2006-06-17 22:12:58.000000000 +0200
+++ rt2500-cvs-2007061011/Module/Makefile	2007-05-29 05:54:38.000000000 +0200
@@ -1,39 +1,39 @@
-########################################################################### 
-# RT2400/RT2500 SourceForge Project - http://rt2x00.serialmonkey.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.                          # 
-#                                                                         # 
-#   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.             # 
-#                                                                         # 
-#   Licensed under the GNU GPL                                            # 
-#   Original code supplied under license from RaLink Inc, 2004.           # 
-########################################################################### 
-
-########################################################################### 
-#      Module Name: Makefile 
-#              
-#      Abstract: Makefile for rt2500 kernel module 
-#              
-#      Revision History: 
-#      Who             When            What 
-#      --------        -----------     ----------------------------- 
-#      MarkW           8th  Dec 04     Rewrite of Makefile 
+###########################################################################
+# RT2400/RT2500 SourceForge Project - http://rt2x00.serialmonkey.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.                          #
+#                                                                         #
+#   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.             #
+#                                                                         #
+#   Licensed under the GNU GPL                                            #
+#   Original code supplied under license from RaLink Inc, 2004.           #
+###########################################################################
+
+###########################################################################
+#      Module Name: Makefile
+#
+#      Abstract: Makefile for rt2500 kernel module
+#
+#      Revision History:
+#      Who             When            What
+#      --------        -----------     -----------------------------
+#      MarkW           8th  Dec 04     Rewrite of Makefile
 #      AmirS           1st  Jan 05     Update for gmake compat
 #      MarkW           20th Jan 05     Fixed permissions on directory
 #      MichalL         5th  Mar 05     Module installation fixes
 #      MarkW           29th Jul 05     Allow install dir override
-########################################################################### 
+###########################################################################
 
 
 
@@ -41,7 +41,7 @@
 
 MODULE_NAME := rt2500
 
-#PATCHLEVEL := 6 
+#PATCHLEVEL := 6
 #KERNDIR=/usr/src/linux-2.6
 #MODDIR=/lib/modules/2.6.12/extra
 
@@ -94,7 +94,7 @@
 	$(LD) $(EXTRA_LDFLAGS) -r -o $@ $($(MODULE_NAME)-objs)
 endif
 
-KBUILD_PARAMS := -C $(KERNEL_SOURCES) SUBDIRS=$(PWD) $(KERNEL_OUTPUT)
+KBUILD_PARAMS := -C $(KERNEL_SOURCES) SUBDIRS=$(CURDIR) $(KERNEL_OUTPUT)
 
 module:
 	@$(MAKE) $(KBUILD_PARAMS) modules; \
@@ -110,22 +110,29 @@
 	exit 1; \
 	fi
 
+debugfs:
+	@$(MAKE) $(KBUILD_PARAMS) 'EXTRA_CFLAGS=-I$(src) -DRT2500_DBG -DRT2X00DEBUGFS' modules; \
+	if ! [ -f $(MODULE_OBJECT) ]; then \
+	echo "$(MODULE_OBJECT) failed to build!"; \
+	exit 1; \
+	fi
+
 clean:
 	@rm -f $(RESMAN_GLUE_OBJS) $(RESMAN_CORE_OBJS) .*.{cmd,flags}
 	@rm -f $(MODULE_NAME).{o,ko,mod.{o,c}} built-in.o $(VERSION_HEADER) *~
-	@rm -fr .tmp_versions
+	@rm -fr .tmp_versions Module.symvers
 
 modules_install:
-ifeq ($(PATCHLEVEL),4)
-	if ! [ -f $(MODULE_OBJECT) ]; then \
-	module; \
+	@if ! [ -f $(MODULE_OBJECT) ]; then \
+	$(MAKE) module; \
 	fi
+ifeq ($(PATCHLEVEL),4)
 	@echo "install '$(MODULE_OBJECT)' to $(MODULE_ROOT)"
 	install -m 755 -o 0 -g 0 -d $(MODULE_ROOT)
 	install -m 644 -o 0 -g 0 $(MODULE_OBJECT) $(MODULE_ROOT)
-	/sbin/depmod -a
+	/sbin/depmod -ae
 else
-	echo "2.6 module install"
+	@echo "2.6 module install"
 	make $(KBUILD_PARAMS) modules_install
 	/sbin/depmod -a
 endif
@@ -144,7 +151,7 @@
 	install -m 755 -o 0 -g 0 -d $(MODULE_ROOT)
 	install -m 644 -o 0 -g 0 $(MODULE_OBJECT) $(MODULE_ROOT)
 	/sbin/depmod -a
-	
+
 	@if ! grep -q 'wlan0' /etc/modprobe.conf ; then \
 		echo "append 'alias wlan0 rt2500' to /etc/modprobe.conf"; \
 		echo "alias wlan0 rt2500" >> /etc/modprobe.conf ; \
diff -Nur rt2500-1.1.0-b4/Module/README rt2500-cvs-2007061011/Module/README
--- rt2500-1.1.0-b4/Module/README	2006-06-17 22:12:58.000000000 +0200
+++ rt2500-cvs-2007061011/Module/README	2007-05-29 05:54:39.000000000 +0200
@@ -1,7 +1,7 @@
 Installation instructions for the rt2500 Module
 
 ======================================================================
-Build Instructions:  
+Build Instructions:
 ====================
 For 2.4 or 2.6 series kernel:
 a. $tar -xvzf rt2500-x.x.x.tar.gz
@@ -9,10 +9,10 @@
 
 b. $make                # compile driver source code
 
-c. $make install	# installs kernel module driver 
+c. $make install        # installs kernel module driver
+
+(read end of file for FedoraCore3 specific information)
 
-(read end of file for FedoraCore3 specific information) 
- 
 ======================================================================
 To BUILD UTILITY
 ====================
@@ -21,26 +21,26 @@
 
 b.  run 'qmake -o Makefile raconfig2500.pro'
     If qmake command is not found in your system, you can download
-    the QT tool 'qt-x11-free-3.2.1' or later at 
+    the QT tool 'qt-x11-free-3.2.1' or later at
     http://www.trolltech.com/
-    
-    (qmake comes with RedHat 7.3 or later QT Package)    
+
+    (qmake comes with RedHat 7.3 or later QT Package)
 
 c.  run 'make" to compile the utility source code.
-   
+
 d.  After all, an execution file would be generated "RaConfig2500"
     run "RaConfig2500" to config the driver as you want
 
 
 
 ======================================================================
-CONFIGURATION:  
+CONFIGURATION:
 ====================
-RT2500 driver can be configured via following interfaces, 
+RT2500 driver can be configured via following interfaces,
 i.e. (i)"iwconfig" command, (ii)"iwpriv" command, (iii) configuration
      file, (iv) RaConfig2500
 
-i)  iwconfig comes with kernel.  
+i)  iwconfig comes with kernel.
 ii) iwpriv usage, please refer to file "iwpriv_usage.txt" for details.
 iii)copy configuration file "RT2500STA.dat" to
     /etc/Wireless/RT2500STA/RT2500STA.dat.
@@ -48,7 +48,7 @@
 iv) RT2500 provides API : RaConfig2500, please go to directory
     ./Utility and refer to how-to-compile.txt
 
-           
+
 Configuration File : RT2500STA.dat
 
 # Copy this file to /etc/Wireless/RT2500STA/RT2500STA.dat
@@ -56,7 +56,7 @@
 # module.
 #
 # Use "vi -b RT2500STA.dat" to modify settings according to your need.
-# 
+#
 # 1.) set NetworkType to "Adhoc" for using Adhoc-mode, otherwise
 #     using as Infrastructure-mode.
 # 2.) set Channel to "0" for auto-select on Infrastructure mode.
@@ -94,7 +94,7 @@
 FragThreshold=2312
 PSMode=CAM
 -----------------------------------------------
-syntax is 'Param'='Value' and described below. 
+syntax is 'Param'='Value' and described below.
 
 1.  CountryRegion=value
     value
@@ -125,13 +125,14 @@
         OPEN      For Open System
         SHARED    For Shared key system
         AUTO
-        WPAPSK    
+        WPANONE   For pre-shared key in adhoc mode
+        WPAPSK    For pre-shared key in infrastructure mode
 7.  EncrypType=value
     value
         NONE      :For AuthMode=OPEN
         WEP       :For AuthMode=OPEN or AuthMode=SHARED
-        TKIP      :For AuthMode=WPAPSK
-        AES       :For AuthMode=WPAPSK
+        TKIP      :For AuthMode=WPAPSK or AuthMode=WPANONE
+        AES       :For AuthMode=WPAPSK or AuthMode=WPANONE
 8.  DefaultKeyID=value
     value
         1 ~ 4
@@ -189,7 +190,7 @@
          1:     1 Mbps
          2:     2 Mbps
          3:     5.5 Mbps
-         4:     11 Mbps 
+         4:     11 Mbps
          5:     6  Mbps  //WirelessMode must be 0
          6:     9  Mbps  //WirelessMode must be 0
          7:     12 Mbps  //WirelessMode must be 0
@@ -210,13 +211,13 @@
 
 23. AdhocOfdm=value
     value
-    0:		Tx MAX rate will be 11Mbps in Adhoc mode.
-    1:		Tx MAX rate will be 54Mbps in Adhoc mode.
+         0:     Tx MAX rate will be 11Mbps in Adhoc mode.
+         1:     Tx MAX rate will be 54Mbps in Adhoc mode.
 
 24. StaWithEtherBridge=value
     value
-    0:		Disable sta with ethernet to wireless bridge.
-    1:		Enable sta with ethernet to wireless bridge.
+         0:     Disable sta with ethernet to wireless bridge.
+         1:     Enable sta with ethernet to wireless bridge.
 
 
 MORE INFORMATION
@@ -224,25 +225,25 @@
 If you want for rt2500 driver to auto-load at boot time:
 A) choose ra0 for first RT2500 WLAN card, ra1 for second RT2500 WLAN
    card, etc.
-   
-B) create(edit) 'ifcfg-ra0' file in /etc/sysconfig/network-scripts/,      
+
+B) create(edit) 'ifcfg-ra0' file in /etc/sysconfig/network-scripts/,
    edit( or add the line) in /etc/modules.conf:
-       alias ra0 rt2500        
-   
-C) edit(create) the file /etc/sysconfig/network-scripts/ifcfg-ra0  
+       alias ra0 rt2500
+
+C) edit(create) the file /etc/sysconfig/network-scripts/ifcfg-ra0
    DEVICE='ra0'
-   ONBOOT='yes'     
+   ONBOOT='yes'
 
 
 NOTE:
    if you use dhcp, add this line too .
     BOOTPROTO='dhcp'
 
-*D) To ease the Default Gateway setting, 
+*D) To ease the Default Gateway setting,
     add the line
-    GATEWAY=x.x.x.x   
+    GATEWAY=x.x.x.x
     in /etc/sysconfig/network
-   
+
 INFORMATION FOR FEDORA CORE 3 USERS (USE AT YOUR OWN RISK !!!)
 ======================================================================
 While this information is directed to Fedora Core 3 users, there is no
@@ -267,8 +268,8 @@
 alias added to modprobe.conf (2.6 kernels) or modules.conf
 (2.4 kernels).
 
-Start 'system-config-network', 
-New->Wireless connection, 
+Start 'system-config-network',
+New->Wireless connection,
 Select 'RaLink Ralink RT2500 802.11 Cardbus Reference Card (wlan0)'
 If it does not appear, well then it didn't work for you :)
 
diff -Nur rt2500-1.1.0-b4/Module/TESTING rt2500-cvs-2007061011/Module/TESTING
--- rt2500-1.1.0-b4/Module/TESTING	2006-06-17 22:12:58.000000000 +0200
+++ rt2500-cvs-2007061011/Module/TESTING	2007-05-29 05:54:39.000000000 +0200
@@ -1,51 +1,63 @@
-Below is information on how you can help out the team with testing
-of the rt2500 kernel module.
+Below are the steps you need to follow to help out the team with
+testing/debugging of the rt2500 kernel module:
 
-1. Get the latest source from the CVS tree. Easiest way todo this is to
-get the nightly tarball from our website at
-        http://rt2x00.serialmonkey.com/rt2500-cvs-daily.tar.gz
-
-2. Enable module debugging. Todo this run 'make clean' to remove any
-compiled objects you have and then run 'make debug'.
-This will recompile the Module with debugging turned on and reinstall
-it over your existing module. 
-
-3. Install the module as per the INSTALL instructions.
-        e.g. make install
-
-4. Ensure there are no compies of the module in memory.
-	ifconfig ra0 down
-	rmmod rt2500
-
-5. Load the module with full debug enabled using the commands
-	modprobe rt2500 debug=1
-
-6. Check the output of your syslog (most likely /var/log/messages).
-If you don't see any debug you need to add the following line to
-your /etc/syslog.conf and reboot.
-        kern.*            /var/log/debug
-
-7. Any bugs/issues you find please report the following information
-to the rt2400-devel mailing list
-	* Steps to reproduce
-	* The whole contents of your debugging output 
-	* Your hardware architecture (i.e. x86, AMD64, Sparc)
-	* Your kernel version (i.e. 2.4.25 or 2.6.4)
-	* Your rt2400 hardware manufacturer and model
-	* Anything else you may think will help us resolve the issue
-	  (even a patch if you are so inclined)
-
-8. Sign up to the rt2400-devel mailing list and watch out for requests
-for testing. Whenever we do major changes to the source and always
-just before a release we will call for testing to be done before we
-make the general release.
+
+1. Get the latest source from the CVS tree.
+     Easiest way to do this is to download the hourly tarball from our website:
+     http://rt2x00.serialmonkey.com/rt2500-cvs-daily.tar.gz
+     Alternatively, you can anonymously check out the current CVS code:
+     $ cvs -d:pserver:anonymous@rt2400.cvs.sourceforge.net:/cvsroot/rt2400 login
+     $ cvs -z3 -d:pserver:anonymous@rt2400.cvs.sourceforge.net:/cvsroot/rt2400 \
+           co -P source/rt2500
+
+2. Compile the module with debug logging:
+     $ make clean
+     $ make debug
+
+3. Ensure there are no copies of the module left in memory:
+     # ifconfig ra0 down
+     # rmmod rt2500
+
+4. Load the module with full debug enabled:
+     # insmod rt2500.ko debug=31
+     Then proceed as usual (config, ifup, etc)...
+
+5. Check the debug output.
+     It is located in your system log file (most likely /var/log/debug or
+     /var/log/syslog). If you don't see any debug you probably need to add the
+     following line to your /etc/syslog.conf and reboot:
+          kern.=debug       /var/log/debug
+     If you system hard-locks before it's able to log anything interesting
+     in these files, you'll have to rely on the netconsole module to remotely
+     log your kernel messages to another box (see netconsole.txt in your
+     kernel sources Documentation folder).
+
+6. Report the following to the rt2400-devel mailing list (or rt2500 forum):
+     * Steps to reproduce the bug
+     * The _whole_content_ of your debugging output
+     * Your module details, i.e. the output of:
+         # modinfo rt2500.ko
+     * Your kernel details, i.e. the output of:
+         $ uname -a
+     * Your rt2500 hardware manufacturer, model and revision
+     * Anything else you think may help us resolve the issue (even a patch if
+       you are so inclined)
+
+7. Monitor the mailing list (or forum thread) for replies/further queries.  :-)
+
+
+Whenever we do major changes to the source - and always just before a release -
+we will call for testing to be done before we make the general release. You're
+very much welcome to help us with this testing and report any success/issue you
+experience with this code.
 
 
 !!!! NOTE !!!!
 
-AS PER STEP 7 ABOVE. Please provide the whole debug output. The last
-few lines are hardly any good. If it's large (which it will be) then
-GZip it and either upload it somewhere and give it a link or email
-it directly to the developer you are working with.
+AS PER STEP 6 ABOVE: Please provide the *whole* debug output! The last few lines
+are hardly any good.
+If it's large (which it will be) then GZip it. Either attach it to your forum
+post or, if you're going to report via the mailing list, upload it somewhere and
+give a link to it (or email it directly to the developer you are working with).
 
-!!!! END NOTE !!!! 
+!!!! END NOTE !!!!
diff -Nur rt2500-1.1.0-b4/Module/assoc.c rt2500-cvs-2007061011/Module/assoc.c
--- rt2500-1.1.0-b4/Module/assoc.c	2006-06-17 22:12:58.000000000 +0200
+++ rt2500-cvs-2007061011/Module/assoc.c	2007-03-21 05:25:34.000000000 +0100
@@ -1,36 +1,36 @@
-/*************************************************************************** 
- * RT2400/RT2500 SourceForge Project - http://rt2x00.serialmonkey.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.                          * 
- *                                                                         * 
- *   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.             * 
- *                                                                         * 
- *   Licensed under the GNU GPL                                            * 
- *   Original code supplied under license from RaLink Inc, 2004.           * 
- ***************************************************************************/ 
-
- /*************************************************************************** 
- *      Module Name: assoc.c 
- *              
- *      Abstract: 
- *              
- *      Revision History: 
- *      Who             When            What 
- *      --------        -----------     ----------------------------- 
- *      MarkW           8th  Dec 04     Baseline code  
+/***************************************************************************
+ * RT2400/RT2500 SourceForge Project - http://rt2x00.serialmonkey.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.                          *
+ *                                                                         *
+ *   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.             *
+ *                                                                         *
+ *   Licensed under the GNU GPL                                            *
+ *   Original code supplied under license from RaLink Inc, 2004.           *
+ ***************************************************************************/
+
+ /***************************************************************************
+ *      Module Name: assoc.c
+ *
+ *      Abstract:
+ *
+ *      Revision History:
+ *      Who             When            What
+ *      --------        -----------     -----------------------------
+ *      MarkW           8th  Dec 04     Baseline code
  * 		MarkW			5th  Jun 05		Fix no-SSID broadcasting assoc.
- ***************************************************************************/ 
+ ***************************************************************************/
 
 #include "rt_config.h"
 
@@ -78,15 +78,15 @@
 		};
 UCHAR	CipherSuiteWpaPskAesLen = (sizeof(CipherSuiteWpaPskAes) / sizeof(UCHAR));
 
-/*  
+/*
     ==========================================================================
-    Description: 
+    Description:
         association state machine init, including state transition and timer init
-    Parameters: 
+    Parameters:
         S - pointer to the association state machine
     Note:
-        The state machine looks like the following 
-        
+        The state machine looks like the following
+
                                ASSOC_IDLE               ASSOC_WAIT_RSP             REASSOC_WAIT_RSP             DISASSOC_WAIT_RSP
     MT2_MLME_ASSOC_REQ       mlme_assoc_req_action    invalid_state_when_assoc   invalid_state_when_assoc       invalid_state_when_assoc
     MT2_MLME_REASSOC_REQ     mlme_reassoc_req_action  invalid_state_when_reassoc invalid_state_when_reassoc     invalid_state_when_reassoc
@@ -103,9 +103,9 @@
     ==========================================================================
  */
 VOID AssocStateMachineInit(
-    IN	PRTMP_ADAPTER	pAd, 
-    IN  STATE_MACHINE *S, 
-    OUT STATE_MACHINE_FUNC Trans[]) 
+    IN	PRTMP_ADAPTER	pAd,
+    IN  STATE_MACHINE *S,
+    OUT STATE_MACHINE_FUNC Trans[])
 {
     StateMachineInit(S, (STATE_MACHINE_FUNC*)Trans, MAX_ASSOC_STATE, MAX_ASSOC_MSG, (STATE_MACHINE_FUNC)Drop, ASSOC_IDLE, ASSOC_MACHINE_BASE);
 
@@ -115,7 +115,7 @@
     StateMachineSetAction(S, ASSOC_IDLE, MT2_MLME_DISASSOC_REQ, (STATE_MACHINE_FUNC)MlmeDisassocReqAction);
     StateMachineSetAction(S, ASSOC_IDLE, MT2_PEER_DISASSOC_REQ, (STATE_MACHINE_FUNC)PeerDisassocAction);
 //  StateMachineSetAction(S, ASSOC_IDLE, MT2_CLS3ERR, (STATE_MACHINE_FUNC)Cls3errAction);
-    
+
     // 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);
@@ -151,14 +151,14 @@
 /*
     ==========================================================================
     Description:
-        Association timeout procedure. After association timeout, this function 
+        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
     ==========================================================================
  */
 VOID AssocTimeout(
-    IN	unsigned long data) 
+    IN	unsigned long data)
 {
     RTMP_ADAPTER *pAd = (RTMP_ADAPTER *)data;
     DBGPRINT(RT_DEBUG_TRACE,"ASSOC - enqueue MT2_ASSOC_TIMEOUT \n");
@@ -169,14 +169,14 @@
 /*
     ==========================================================================
     Description:
-        Reassociation timeout procedure. After reassociation timeout, this 
+        Reassociation timeout procedure. After reassociation timeout, this
         function will be called and put a message into the MLME queue
     Parameters:
         Standard timer parameters
     ==========================================================================
  */
 VOID ReassocTimeout(
-    IN	unsigned long data) 
+    IN	unsigned long data)
 {
     RTMP_ADAPTER *pAd = (RTMP_ADAPTER *)data;
     DBGPRINT(RT_DEBUG_TRACE,"ASSOC - enqueue MT2_REASSOC_TIMEOUT \n");
@@ -187,14 +187,14 @@
 /*
     ==========================================================================
     Description:
-        Disassociation timeout procedure. After disassociation timeout, this 
+        Disassociation timeout procedure. After disassociation timeout, this
         function will be called and put a message into the MLME queue
     Parameters:
         Standard timer parameters
     ==========================================================================
  */
 VOID DisassocTimeout(
-    IN	unsigned long data) 
+    IN	unsigned long data)
 {
     RTMP_ADAPTER *pAd = (RTMP_ADAPTER *)data;
     DBGPRINT(RT_DEBUG_TRACE,"ASSOC - enqueue MT2_DISASSOC_TIMEOUT \n");
@@ -222,8 +222,8 @@
     ==========================================================================
  */
 VOID MlmeAssocReqAction(
-    IN PRTMP_ADAPTER pAd, 
-    IN MLME_QUEUE_ELEM *Elem) 
+    IN PRTMP_ADAPTER pAd,
+    IN MLME_QUEUE_ELEM *Elem)
 {
     MACADDR          ApAddr;
     MACHDR           AssocHdr;
@@ -243,9 +243,9 @@
         DBGPRINT(RT_DEBUG_TRACE, "ASSOC - Block Assoc request durning WPA block period!\n");
         pAd->Mlme.AssocMachine.CurrState = ASSOC_IDLE;
         MlmeCntlConfirm(pAd, MT2_ASSOC_CONF, MLME_STATE_MACHINE_REJECT);
-	}	
+	}
     // check sanity first
-    else if (MlmeAssocReqSanity(pAd, Elem->Msg, Elem->MsgLen, &ApAddr, &CapabilityInfo, &Timeout, &ListenIntv)) 
+    else if (MlmeAssocReqSanity(pAd, Elem->Msg, Elem->MsgLen, &ApAddr, &CapabilityInfo, &Timeout, &ListenIntv))
     {
         RTMPCancelTimer(&pAd->Mlme.AssocAux.AssocTimer);
         COPY_MAC_ADDR(&pAd->Mlme.AssocAux.Addr, &ApAddr);
@@ -255,23 +255,23 @@
         pAd->Mlme.AssocAux.ListenIntv = ListenIntv;
 
         NStatus = MlmeAllocateMemory(pAd, (PVOID)&OutBuffer);  //Get an unused nonpaged memory
-        if (NStatus != NDIS_STATUS_SUCCESS) 
+        if (NStatus != NDIS_STATUS_SUCCESS)
         {
             DBGPRINT(RT_DEBUG_TRACE,"ASSOC - MlmeAssocReqAction() allocate memory failed \n");
             pAd->Mlme.AssocMachine.CurrState = ASSOC_IDLE;
             MlmeCntlConfirm(pAd, MT2_ASSOC_CONF, MLME_FAIL_NO_RESOURCE);
             return;
         }
-        
+
 		// Add by James 03/06/27
 		pAd->PortCfg.AssocInfo.Length = sizeof(NDIS_802_11_ASSOCIATION_INFORMATION); //+ sizeof(NDIS_802_11_FIXED_IEs); 	// Filled in assoc request
 		pAd->PortCfg.AssocInfo.AvailableRequestFixedIEs =
 			NDIS_802_11_AI_REQFI_CAPABILITIES | NDIS_802_11_AI_REQFI_LISTENINTERVAL | NDIS_802_11_AI_REQFI_CURRENTAPADDRESS;
 		pAd->PortCfg.AssocInfo.RequestFixedIEs.Capabilities = CapabilityInfo;
-		pAd->PortCfg.AssocInfo.RequestFixedIEs.ListenInterval = ListenIntv;		
+		pAd->PortCfg.AssocInfo.RequestFixedIEs.ListenInterval = ListenIntv;
 		memcpy(pAd->PortCfg.AssocInfo.RequestFixedIEs.CurrentAPAddress, &AssocHdr, sizeof(NDIS_802_11_MAC_ADDRESS));
 		pAd->PortCfg.AssocInfo.OffsetRequestIEs = sizeof(NDIS_802_11_ASSOCIATION_INFORMATION);		// No request Variables IEs
-		
+
 		// First add SSID
 		VarIesOffset = 0;
 		memcpy(pAd->PortCfg.ReqVarIEs + VarIesOffset, &SsidIe, 1);
@@ -299,7 +299,7 @@
 						  2,						&CapabilityInfo,
 						  2,						&ListenIntv,
 						  1,						&SsidIe,
-						  1,						&pAd->Mlme.SyncAux.SsidLen, 
+						  1,						&pAd->Mlme.SyncAux.SsidLen,
 						  pAd->Mlme.SyncAux.SsidLen, 	pAd->Mlme.SyncAux.Ssid,
 						  1,						&RateIe,
 						  1,						&pAd->PortCfg.SupRateLen,
@@ -310,11 +310,11 @@
 			MakeOutgoingFrame(OutBuffer + FrameLen, &tmp,
 						1,							&ExtRateIe,
 						1,							&pAd->PortCfg.ExtRateLen,
-						pAd->PortCfg.ExtRateLen,	pAd->PortCfg.ExtRate,							
+						pAd->PortCfg.ExtRateLen,	pAd->PortCfg.ExtRate,
 						END_OF_ARGS);
 			FrameLen += tmp;
 		}
-		
+
 		if ((pAd->PortCfg.AuthMode == Ndis802_11AuthModeWPA) && (pAd->PortCfg.WepStatus == Ndis802_11Encryption2Enabled))
 		{
 			MakeOutgoingFrame(OutBuffer + FrameLen, &tmp,
@@ -323,7 +323,7 @@
 						CipherSuiteWpaTkipLen,	  	&CipherSuiteWpaTkip[0],
 						END_OF_ARGS);
 			FrameLen += tmp;
-			
+
 			// Add by James 03/06/27
 			// Third add RSN
 			memcpy(pAd->PortCfg.ReqVarIEs + VarIesOffset, &WpaIe, 1);
@@ -339,9 +339,9 @@
 
 			// OffsetResponseIEs follow ReqVarIE
 			pAd->PortCfg.AssocInfo.OffsetResponseIEs = sizeof(NDIS_802_11_ASSOCIATION_INFORMATION) + pAd->PortCfg.ReqVarIELen;
-			// End Add by James 
+			// End Add by James
 		}
-		
+
 		else if ((pAd->PortCfg.AuthMode == Ndis802_11AuthModeWPA) && (pAd->PortCfg.WepStatus == Ndis802_11Encryption3Enabled))
 		{
 			MakeOutgoingFrame(OutBuffer + FrameLen, &tmp,
@@ -350,7 +350,7 @@
 						CipherSuiteWpaAesLen,	  	&CipherSuiteWpaAes[0],
 						END_OF_ARGS);
 			FrameLen += tmp;
-			
+
 			// Add by James 03/06/27
 			// Third add RSN
 			memcpy(pAd->PortCfg.ReqVarIEs + VarIesOffset, &WpaIe, 1);
@@ -366,7 +366,7 @@
 
 			// OffsetResponseIEs follow ReqVarIE
 			pAd->PortCfg.AssocInfo.OffsetResponseIEs = sizeof(NDIS_802_11_ASSOCIATION_INFORMATION) + pAd->PortCfg.ReqVarIELen;
-			// End Add by James 
+			// End Add by James
 		}
 		else if ((pAd->PortCfg.AuthMode == Ndis802_11AuthModeWPAPSK) && (pAd->PortCfg.WepStatus == Ndis802_11Encryption2Enabled))
 		{
@@ -392,7 +392,7 @@
 
 			// OffsetResponseIEs follow ReqVarIE
 			pAd->PortCfg.AssocInfo.OffsetResponseIEs = sizeof(NDIS_802_11_ASSOCIATION_INFORMATION) + pAd->PortCfg.ReqVarIELen;
-			// End Add by James 
+			// End Add by James
 		}
 		else if ((pAd->PortCfg.AuthMode == Ndis802_11AuthModeWPAPSK) && (pAd->PortCfg.WepStatus == Ndis802_11Encryption3Enabled))
 		{
@@ -418,7 +418,7 @@
 
 			// OffsetResponseIEs follow ReqVarIE
 			pAd->PortCfg.AssocInfo.OffsetResponseIEs = sizeof(NDIS_802_11_ASSOCIATION_INFORMATION) + pAd->PortCfg.ReqVarIELen;
-			// End Add by James 
+			// End Add by James
 		}
 		else
 		{
@@ -429,14 +429,14 @@
 
 			// OffsetResponseIEs follow ReqVarIE
 			pAd->PortCfg.AssocInfo.OffsetResponseIEs = sizeof(NDIS_802_11_ASSOCIATION_INFORMATION) + pAd->PortCfg.ReqVarIELen;
-			// End Add by James 
+			// End Add by James
 		}
         MiniportMMRequest(pAd, OutBuffer, FrameLen);
-            
+
 		RTMPSetTimer(pAd, &pAd->Mlme.AssocAux.AssocTimer, Timeout);
         pAd->Mlme.AssocMachine.CurrState = ASSOC_WAIT_RSP;
-    } 
-    else 
+    }
+    else
     {
         DBGPRINT(RT_DEBUG_TRACE,"ASSOC - MlmeAssocReqAction() sanity check failed. BUG!!!!!! \n");
         pAd->Mlme.AssocMachine.CurrState = ASSOC_IDLE;
@@ -450,7 +450,7 @@
     Description:
         mlme reassoc req handling procedure
     Parameters:
-        Elem - 
+        Elem -
     Pre:
         -# SSID  (Adapter->PortCfg.ssid[])
         -# BSSID (AP address, Adapter->PortCfg.bssid)
@@ -460,8 +460,8 @@
     ==========================================================================
  */
 VOID MlmeReassocReqAction(
-    IN PRTMP_ADAPTER pAd, 
-    IN MLME_QUEUE_ELEM *Elem) 
+    IN PRTMP_ADAPTER pAd,
+    IN MLME_QUEUE_ELEM *Elem)
 {
     MACADDR              ApAddr;
     MACHDR               ReassocHdr;
@@ -479,14 +479,14 @@
         DBGPRINT(RT_DEBUG_TRACE, "ASSOC - Block ReAssoc request durning WPA block period!\n");
         pAd->Mlme.AssocMachine.CurrState = ASSOC_IDLE;
         MlmeCntlConfirm(pAd, MT2_ASSOC_CONF, MLME_STATE_MACHINE_REJECT);
-	}	
+	}
     // the parameters are the same as the association
-    else if(MlmeAssocReqSanity(pAd, Elem->Msg, Elem->MsgLen, &ApAddr, &CapabilityInfo, &Timeout, &ListenIntv)) 
+    else if(MlmeAssocReqSanity(pAd, Elem->Msg, Elem->MsgLen, &ApAddr, &CapabilityInfo, &Timeout, &ListenIntv))
     {
         RTMPCancelTimer(&pAd->Mlme.AssocAux.ReassocTimer);
 
         NStatus = MlmeAllocateMemory(pAd, (PVOID)&OutBuffer);  //Get an unused nonpaged memory
-        if(NStatus != NDIS_STATUS_SUCCESS) 
+        if(NStatus != NDIS_STATUS_SUCCESS)
         {
             DBGPRINT(RT_DEBUG_TRACE,"ASSOC - MlmeReassocReqAction() allocate memory failed \n");
             pAd->Mlme.AssocMachine.CurrState = ASSOC_IDLE;
@@ -509,8 +509,8 @@
                           2,                    &ListenIntv,
                           ETH_ALEN,         &pAd->PortCfg.Bssid,
                           1,                    &SsidIe,
-                          1,                    &pAd->PortCfg.SsidLen, 
-                          pAd->PortCfg.SsidLen, pAd->PortCfg.Ssid, 
+                          1,                    &pAd->PortCfg.SsidLen,
+                          pAd->PortCfg.SsidLen, pAd->PortCfg.Ssid,
                           1,                    &RateIe,
 						  1,						&pAd->PortCfg.SupRateLen,
 						  pAd->PortCfg.SupRateLen,  pAd->PortCfg.SupRate,
@@ -520,16 +520,16 @@
 			MakeOutgoingFrame(OutBuffer + FrameLen, &tmp,
 						1,							&ExtRateIe,
 						1,							&pAd->PortCfg.ExtRateLen,
-						pAd->PortCfg.ExtRateLen,	pAd->PortCfg.ExtRate,							
+						pAd->PortCfg.ExtRateLen,	pAd->PortCfg.ExtRate,
 						END_OF_ARGS);
 			FrameLen += tmp;
 		}
         MiniportMMRequest(pAd, OutBuffer, FrameLen);
-            
+
         RTMPSetTimer(pAd, &pAd->Mlme.AssocAux.ReassocTimer, Timeout); /* in mSec */
         pAd->Mlme.AssocMachine.CurrState = REASSOC_WAIT_RSP;
-    } 
-    else 
+    }
+    else
     {
         DBGPRINT(RT_DEBUG_TRACE,"ASSOC - MlmeReassocReqAction() sanity check failed. BUG!!!! \n");
         pAd->Mlme.AssocMachine.CurrState = ASSOC_IDLE;
@@ -546,8 +546,8 @@
     ==========================================================================
  */
 VOID MlmeDisassocReqAction(
-    IN PRTMP_ADAPTER pAd, 
-    IN MLME_QUEUE_ELEM *Elem) 
+    IN PRTMP_ADAPTER pAd,
+    IN MLME_QUEUE_ELEM *Elem)
 {
     MLME_DISASSOC_REQ_STRUCT *DisassocReq;
     MACHDR                DisassocHdr;
@@ -560,25 +560,25 @@
     DisassocReq = (MLME_DISASSOC_REQ_STRUCT *)(Elem->Msg);
 
     NStatus = MlmeAllocateMemory(pAd, (PVOID)&OutBuffer);  //Get an unused nonpaged memory
-    if (NStatus != NDIS_STATUS_SUCCESS) 
+    if (NStatus != NDIS_STATUS_SUCCESS)
     {
         DBGPRINT(RT_DEBUG_TRACE, "ASSOC - MlmeDisassocReqAction() allocate memory failed\n");
         pAd->Mlme.AssocMachine.CurrState = ASSOC_IDLE;
         MlmeCntlConfirm(pAd, MT2_DISASSOC_CONF, MLME_FAIL_NO_RESOURCE);
         return;
     }
-    
+
     RTMPCancelTimer(&pAd->Mlme.AssocAux.DisassocTimer);
-    
+
     DBGPRINT(RT_DEBUG_TRACE, "ASSOC - Send DISASSOC request\n");
     MgtMacHeaderInit(pAd, &DisassocHdr, SUBTYPE_DISASSOC, 0, &pAd->PortCfg.Bssid, &pAd->PortCfg.Bssid);
-    MakeOutgoingFrame(OutBuffer,            &FrameLen, 
-                      sizeof(MACHDR),       &DisassocHdr, 
-                      2,                    &DisassocReq->Reason, 
+    MakeOutgoingFrame(OutBuffer,            &FrameLen,
+                      sizeof(MACHDR),       &DisassocHdr,
+                      2,                    &DisassocReq->Reason,
                       END_OF_ARGS);
     MiniportMMRequest(pAd, OutBuffer, FrameLen);
     memset(&(pAd->PortCfg.Bssid), 0, ETH_ALEN);
-    
+
     pAd->PortCfg.DisassocReason = REASON_DISASSOC_STA_LEAVING;
     COPY_MAC_ADDR(&pAd->PortCfg.DisassocSta, &DisassocReq->Addr);
 
@@ -595,31 +595,31 @@
     ==========================================================================
  */
 VOID PeerAssocRspAction(
-    IN PRTMP_ADAPTER pAd, 
-    IN MLME_QUEUE_ELEM *Elem) 
+    IN PRTMP_ADAPTER pAd,
+    IN MLME_QUEUE_ELEM *Elem)
 {
     USHORT        CapabilityInfo, Status, Aid;
     UCHAR         Rates[MAX_LEN_OF_SUPPORTED_RATES], RatesLen;
     MACADDR       Addr2;
     BOOLEAN       ExtendedRateIeExist;
 
-    if (PeerAssocRspSanity(pAd, Elem->Msg, Elem->MsgLen, &Addr2, &CapabilityInfo, &Status, &Aid, Rates, &RatesLen, &ExtendedRateIeExist)) 
+    if (PeerAssocRspSanity(pAd, Elem->Msg, Elem->MsgLen, &Addr2, &CapabilityInfo, &Status, &Aid, Rates, &RatesLen, &ExtendedRateIeExist))
     {
         // The frame is for me ?
-        if(MAC_ADDR_EQUAL(&Addr2, &pAd->Mlme.AssocAux.Addr)) 
+        if(MAC_ADDR_EQUAL(&Addr2, &pAd->Mlme.AssocAux.Addr))
         {
             DBGPRINT(RT_DEBUG_TRACE, "ASSOC - receive ASSOC_RSP to me (status=%d)\n", Status);
             RTMPCancelTimer(&pAd->Mlme.AssocAux.AssocTimer);
-            if(Status == MLME_SUCCESS) 
+            if(Status == MLME_SUCCESS)
             {
                 // go to procedure listed on page 376
 				// Mask out unnecessary capability information
 				CapabilityInfo &= SUPPORTED_CAPABILITY_INFO;  // pAd->PortCfg.SupportedCapabilityInfo;
                 AssocPostProc(pAd, &Addr2, CapabilityInfo, Aid, Rates, RatesLen, ExtendedRateIeExist);
-            } 
+            }
             pAd->Mlme.AssocMachine.CurrState = ASSOC_IDLE;
             MlmeCntlConfirm(pAd, MT2_ASSOC_CONF, Status);
-        } 
+        }
     }
     else
     {
@@ -636,8 +636,8 @@
     ==========================================================================
  */
 VOID PeerReassocRspAction(
-    IN PRTMP_ADAPTER pAd, 
-    IN MLME_QUEUE_ELEM *Elem) 
+    IN PRTMP_ADAPTER pAd,
+    IN MLME_QUEUE_ELEM *Elem)
 {
     USHORT      CapabilityInfo;
     USHORT      Status;
@@ -647,24 +647,24 @@
     MACADDR     Addr2;
     BOOLEAN     ExtendedRateIeExist;
 
-    if(PeerAssocRspSanity(pAd, Elem->Msg, Elem->MsgLen, &Addr2, &CapabilityInfo, &Status, &Aid, Rates, &RatesLen, &ExtendedRateIeExist)) 
+    if(PeerAssocRspSanity(pAd, Elem->Msg, Elem->MsgLen, &Addr2, &CapabilityInfo, &Status, &Aid, Rates, &RatesLen, &ExtendedRateIeExist))
     {
         if(MAC_ADDR_EQUAL(&Addr2, &pAd->Mlme.AssocAux.Addr)) // The frame is for me ?
         {
             DBGPRINT(RT_DEBUG_TRACE, "ASSOC - receive REASSOC_RSP to me (status=%d)\n", Status);
             RTMPCancelTimer(&pAd->Mlme.AssocAux.ReassocTimer);
-            
-            if(Status == MLME_SUCCESS) 
+
+            if(Status == MLME_SUCCESS)
             {
 				// Mask out unnecessary capability information
 				CapabilityInfo &= SUPPORTED_CAPABILITY_INFO;  // pAd->PortCfg.SupportedCapabilityInfo;
                 // go to procedure listed on page 376
                 AssocPostProc(pAd, &Addr2, CapabilityInfo, Aid, Rates, RatesLen, ExtendedRateIeExist);
-            } 
+            }
 
             pAd->Mlme.AssocMachine.CurrState = ASSOC_IDLE;
             MlmeCntlConfirm(pAd, MT2_REASSOC_CONF, Status);
-        } 
+        }
     }
     else
     {
@@ -675,28 +675,28 @@
 /*
     ==========================================================================
     Description:
-        procedures on IEEE 802.11/1999 p.376 
+        procedures on IEEE 802.11/1999 p.376
     Parametrs:
     ==========================================================================
  */
 VOID AssocPostProc(
-    IN PRTMP_ADAPTER pAd, 
-    IN PMACADDR Addr2, 
-    IN USHORT CapabilityInfo, 
-    IN USHORT Aid, 
-    IN UCHAR Rates[], 
+    IN PRTMP_ADAPTER pAd,
+    IN PMACADDR Addr2,
+    IN USHORT CapabilityInfo,
+    IN USHORT Aid,
+    IN UCHAR Rates[],
     IN UCHAR RatesLen,
-    IN BOOLEAN ExtendedRateIeExist) 
+    IN BOOLEAN ExtendedRateIeExist)
 {
 	ULONG Idx;
     UCHAR RateIe = IE_SUPP_RATES;
 	UCHAR VarIesOffset;
 
-    // 2003/12/11 -  skip the following because experiment show that we can not 
+    // 2003/12/11 -  skip the following because experiment show that we can not
     // trust the "privacy" bit in AssocRsp. We can only trust "Privacy" bit specified in
     // BEACON and ProbeRsp.
     // pAd->PortCfg.PrivacyInvoked = CAP_IS_PRIVACY_ON(CapabilityInfo);
-    
+
     pAd->PortCfg.Aid = Aid;
     memcpy(pAd->PortCfg.SupportedRates, Rates, RatesLen);
     pAd->PortCfg.SupportedRatesLen = RatesLen;
@@ -709,7 +709,7 @@
 
 	// Set New WPA information
 	Idx = BssTableSearch(&pAd->PortCfg.BssTab, Addr2);
-	if (Idx == BSS_NOT_FOUND) 
+	if (Idx == BSS_NOT_FOUND)
 	{
 		DBGPRINT(RT_DEBUG_ERROR, "ASSOC - Can't find BSS after receiving Assoc response\n");
 	}
@@ -736,7 +736,7 @@
 		// Second add RSN
 		memcpy(pAd->PortCfg.ResVarIEs + VarIesOffset, pAd->PortCfg.BssTab.BssEntry[Idx].VarIEs, pAd->PortCfg.BssTab.BssEntry[Idx].VarIELen);
 		VarIesOffset += pAd->PortCfg.BssTab.BssEntry[Idx].VarIELen;
-		
+
 		// Set Variable IEs Length
 		pAd->PortCfg.ResVarIELen = VarIesOffset;
 		pAd->PortCfg.AssocInfo.ResponseIELength = VarIesOffset;
@@ -747,22 +747,22 @@
 /*
     ==========================================================================
     Description:
-        left part of IEEE 802.11/1999 p.374 
+        left part of IEEE 802.11/1999 p.374
     Parameters:
         Elem - MLME message containing the received frame
     ==========================================================================
  */
 VOID PeerDisassocAction(
-    IN PRTMP_ADAPTER pAd, 
-    IN MLME_QUEUE_ELEM *Elem) 
+    IN PRTMP_ADAPTER pAd,
+    IN MLME_QUEUE_ELEM *Elem)
 {
     MACADDR       Addr2;
     USHORT        Reason;
 
-    if(PeerDisassocSanity(pAd, Elem->Msg, Elem->MsgLen, &Addr2, &Reason)) 
+    if(PeerDisassocSanity(pAd, Elem->Msg, Elem->MsgLen, &Addr2, &Reason))
     {
-        if (INFRA_ON(pAd) && MAC_ADDR_EQUAL(&pAd->PortCfg.Bssid, &Addr2)) 
-        {	
+        if (INFRA_ON(pAd) && MAC_ADDR_EQUAL(&pAd->PortCfg.Bssid, &Addr2))
+        {
             LinkDown(pAd);
             pAd->Mlme.AssocMachine.CurrState = ASSOC_IDLE;
 
@@ -786,8 +786,8 @@
     ==========================================================================
  */
 VOID AssocTimeoutAction(
-    IN PRTMP_ADAPTER pAd, 
-    IN MLME_QUEUE_ELEM *Elem) 
+    IN PRTMP_ADAPTER pAd,
+    IN MLME_QUEUE_ELEM *Elem)
 {
     DBGPRINT(RT_DEBUG_TRACE, "ASSOC - AssocTimeoutAction\n");
     pAd->Mlme.AssocMachine.CurrState = ASSOC_IDLE;
@@ -801,8 +801,8 @@
     ==========================================================================
  */
 VOID ReassocTimeoutAction(
-    IN PRTMP_ADAPTER pAd, 
-    IN MLME_QUEUE_ELEM *Elem) 
+    IN PRTMP_ADAPTER pAd,
+    IN MLME_QUEUE_ELEM *Elem)
 {
     DBGPRINT(RT_DEBUG_TRACE, "ASSOC - ReassocTimeoutAction\n");
     pAd->Mlme.AssocMachine.CurrState = ASSOC_IDLE;
@@ -816,8 +816,8 @@
     ==========================================================================
  */
 VOID DisassocTimeoutAction(
-    IN PRTMP_ADAPTER pAd, 
-    IN MLME_QUEUE_ELEM *Elem) 
+    IN PRTMP_ADAPTER pAd,
+    IN MLME_QUEUE_ELEM *Elem)
 {
     DBGPRINT(RT_DEBUG_TRACE, "ASSOC - DisassocTimeoutAction\n");
     pAd->Mlme.AssocMachine.CurrState = ASSOC_IDLE;
@@ -825,30 +825,30 @@
 }
 
 VOID InvalidStateWhenAssoc(
-    IN PRTMP_ADAPTER pAd, 
-    IN MLME_QUEUE_ELEM *Elem) 
+    IN PRTMP_ADAPTER pAd,
+    IN MLME_QUEUE_ELEM *Elem)
 {
-    DBGPRINT(RT_DEBUG_TRACE, "ASSOC - InvalidStateWhenAssoc(state=%d), reset ASSOC state machine\n", 
+    DBGPRINT(RT_DEBUG_TRACE, "ASSOC - InvalidStateWhenAssoc(state=%d), reset ASSOC state machine\n",
         pAd->Mlme.AssocMachine.CurrState);
     pAd->Mlme.AssocMachine.CurrState = ASSOC_IDLE;
     MlmeCntlConfirm(pAd, MT2_ASSOC_CONF, MLME_STATE_MACHINE_REJECT);
 }
 
 VOID InvalidStateWhenReassoc(
-    IN PRTMP_ADAPTER pAd, 
-    IN MLME_QUEUE_ELEM *Elem) 
+    IN PRTMP_ADAPTER pAd,
+    IN MLME_QUEUE_ELEM *Elem)
 {
-    DBGPRINT(RT_DEBUG_TRACE, "ASSOC - InvalidStateWhenReassoc(state=%d), reset ASSOC state machine\n", 
+    DBGPRINT(RT_DEBUG_TRACE, "ASSOC - InvalidStateWhenReassoc(state=%d), reset ASSOC state machine\n",
         pAd->Mlme.AssocMachine.CurrState);
     pAd->Mlme.AssocMachine.CurrState = ASSOC_IDLE;
     MlmeCntlConfirm(pAd, MT2_REASSOC_CONF, MLME_STATE_MACHINE_REJECT);
 }
 
 VOID InvalidStateWhenDisassociate(
-    IN PRTMP_ADAPTER pAd, 
-    IN MLME_QUEUE_ELEM *Elem) 
+    IN PRTMP_ADAPTER pAd,
+    IN MLME_QUEUE_ELEM *Elem)
 {
-    DBGPRINT(RT_DEBUG_TRACE, "ASSOC - InvalidStateWhenDisassoc(state=%d), reset ASSOC state machine\n", 
+    DBGPRINT(RT_DEBUG_TRACE, "ASSOC - InvalidStateWhenDisassoc(state=%d), reset ASSOC state machine\n",
         pAd->Mlme.AssocMachine.CurrState);
     pAd->Mlme.AssocMachine.CurrState = ASSOC_IDLE;
     MlmeCntlConfirm(pAd, MT2_DISASSOC_CONF, MLME_STATE_MACHINE_REJECT);
@@ -858,15 +858,15 @@
     ==========================================================================
     Description:
         right part of IEEE 802.11/1999 page 374
-    Note: 
+    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.
     ==========================================================================
  */
 VOID Cls3errAction(
-    IN PRTMP_ADAPTER pAd, 
-    IN PMACADDR      pAddr) 
+    IN PRTMP_ADAPTER pAd,
+    IN PMACADDR      pAddr)
 {
     MACHDR                DisassocHdr;
     CHAR                 *OutBuffer = NULL;
@@ -875,19 +875,19 @@
     USHORT                Reason = REASON_CLS3ERR;
 
     NStatus = MlmeAllocateMemory(pAd, (PVOID)&OutBuffer);  //Get an unused nonpaged memory
-    if (NStatus != NDIS_STATUS_SUCCESS) 
+    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->PortCfg.Bssid);
-    MakeOutgoingFrame(OutBuffer,            &FrameLen, 
-                      sizeof(MACHDR),       &DisassocHdr, 
-                      2,                    &Reason, 
+    MakeOutgoingFrame(OutBuffer,            &FrameLen,
+                      sizeof(MACHDR),       &DisassocHdr,
+                      2,                    &Reason,
                       END_OF_ARGS);
     MiniportMMRequest(pAd, OutBuffer, FrameLen);
 
     pAd->PortCfg.DisassocReason = REASON_CLS3ERR;
     COPY_MAC_ADDR(&pAd->PortCfg.DisassocSta, pAddr);
 }
- 
+
 
diff -Nur rt2500-1.1.0-b4/Module/auth.c rt2500-cvs-2007061011/Module/auth.c
--- rt2500-1.1.0-b4/Module/auth.c	2006-06-17 22:12:58.000000000 +0200
+++ rt2500-cvs-2007061011/Module/auth.c	2007-05-06 11:13:44.000000000 +0200
@@ -1,35 +1,35 @@
-/*************************************************************************** 
- * RT2400/RT2500 SourceForge Project - http://rt2x00.serialmonkey.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.                          * 
- *                                                                         * 
- *   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.             * 
- *                                                                         * 
- *   Licensed under the GNU GPL                                            * 
- *   Original code supplied under license from RaLink Inc, 2004.           * 
- ***************************************************************************/ 
-
- /*************************************************************************** 
- *      Module Name: auth.c 
- *              
- *      Abstract: 
- *              
- *      Revision History: 
- *      Who             When            What 
- *      --------        -----------     ----------------------------- 
- *      MarkW           8th  Dec 04     Baseline code  
- ***************************************************************************/ 
+/***************************************************************************
+ * RT2400/RT2500 SourceForge Project - http://rt2x00.serialmonkey.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.                          *
+ *                                                                         *
+ *   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.             *
+ *                                                                         *
+ *   Licensed under the GNU GPL                                            *
+ *   Original code supplied under license from RaLink Inc, 2004.           *
+ ***************************************************************************/
+
+ /***************************************************************************
+ *      Module Name: auth.c
+ *
+ *      Abstract:
+ *
+ *      Revision History:
+ *      Who             When            What
+ *      --------        -----------     -----------------------------
+ *      MarkW           8th  Dec 04     Baseline code
+ ***************************************************************************/
 
 #include "rt_config.h"
 
@@ -41,7 +41,7 @@
         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_MLME_DEAUTH_REQ mlme_deauth_req_action  mlme_deauth_req_action           mlme_deauth_req_action
@@ -52,12 +52,12 @@
  */
 
 void AuthStateMachineInit(
-    IN PRTMP_ADAPTER pAd, 
-    IN STATE_MACHINE *Sm, 
-    OUT STATE_MACHINE_FUNC Trans[]) 
+    IN PRTMP_ADAPTER pAd,
+    IN STATE_MACHINE *Sm,
+    OUT STATE_MACHINE_FUNC Trans[])
 {
     StateMachineInit(Sm, (STATE_MACHINE_FUNC*)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);
 //  StateMachineSetAction(Sm, AUTH_REQ_IDLE, MT2_MLME_DEAUTH_REQ, (STATE_MACHINE_FUNC)MlmeDeauthReqAction);
@@ -69,14 +69,14 @@
 //  StateMachineSetAction(Sm, AUTH_WAIT_SEQ2, MT2_CLS2ERR, (STATE_MACHINE_FUNC)Cls2errAction);
     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_MLME_DEAUTH_REQ, (STATE_MACHINE_FUNC)MlmeDeauthReqAction);
 //  StateMachineSetAction(Sm, AUTH_WAIT_SEQ4, MT2_CLS2ERR, (STATE_MACHINE_FUNC)Cls2errAction);
     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->Mlme.AuthAux.AuthTimer, AuthTimeout);
 }
 
@@ -90,7 +90,7 @@
     IN	unsigned long data)
 {
     RTMP_ADAPTER *pAd = (RTMP_ADAPTER *)data;
-    
+
     DBGPRINT(RT_DEBUG_TRACE,"AUTH - AuthTimeout\n");
     MlmeEnqueue(&pAd->Mlme.Queue, AUTH_STATE_MACHINE, MT2_AUTH_TIMEOUT, 0, NULL);
     MlmeHandler(pAd);
@@ -103,8 +103,8 @@
     ==========================================================================
  */
 VOID MlmeAuthReqAction(
-    IN PRTMP_ADAPTER pAd, 
-    IN MLME_QUEUE_ELEM *Elem) 
+    IN PRTMP_ADAPTER pAd,
+    IN MLME_QUEUE_ELEM *Elem)
 {
     MACADDR            Addr;
     USHORT             Alg, Seq, Status;
@@ -121,16 +121,15 @@
         pAd->Mlme.AuthMachine.CurrState = AUTH_REQ_IDLE;
         MlmeCntlConfirm(pAd, MT2_AUTH_CONF, MLME_STATE_MACHINE_REJECT);
     }
-    else if(MlmeAuthReqSanity(pAd, Elem->Msg, Elem->MsgLen, &Addr, &Timeout, &Alg)) 
+    else if(MlmeAuthReqSanity(pAd, Elem->Msg, Elem->MsgLen, &Addr, &Timeout, &Alg))
     {
-        // reset timer
-        RTMPCancelTimer(&pAd->Mlme.AuthAux.AuthTimer);
+	RTMPCancelTimer(&pAd->Mlme.AuthAux.AuthTimer);
         pAd->Mlme.AuthAux.Addr = Addr;
         pAd->Mlme.AuthAux.Alg  = Alg;
         pAd->PortCfg.Mauth = FALSE;
         Seq = 1;
         Status = MLME_SUCCESS;
-        
+
         NStatus = MlmeAllocateMemory(pAd, (PVOID)&OutBuffer);  //Get an unused nonpaged memory
         if(NStatus != NDIS_STATUS_SUCCESS)
         {
@@ -142,18 +141,18 @@
 
         DBGPRINT(RT_DEBUG_TRACE, "AUTH - Send AUTH request seq#1 (Alg=%d)...\n", Alg);
         MgtMacHeaderInit(pAd, &AuthHdr, SUBTYPE_AUTH, 0, &Addr, &pAd->PortCfg.Bssid);
-        MakeOutgoingFrame(OutBuffer,            &FrameLen, 
-                          MAC_HDR_LEN,          &AuthHdr, 
-                          2,                    &Alg, 
-                          2,                    &Seq, 
-                          2,                    &Status, 
+        MakeOutgoingFrame(OutBuffer,            &FrameLen,
+                          MAC_HDR_LEN,          &AuthHdr,
+                          2,                    &Alg,
+                          2,                    &Seq,
+                          2,                    &Status,
                           END_OF_ARGS);
         MiniportMMRequest(pAd, OutBuffer, FrameLen);
 
         RTMPSetTimer(pAd, &pAd->Mlme.AuthAux.AuthTimer, Timeout);
         pAd->Mlme.AuthMachine.CurrState = AUTH_WAIT_SEQ2;
-    } 
-    else 
+    }
+    else
     {
         printk(KERN_ERR DRV_NAME "AUTH - MlmeAuthReqAction() sanity check failed. BUG!!!!!\n");
         pAd->Mlme.AuthMachine.CurrState = AUTH_REQ_IDLE;
@@ -167,8 +166,8 @@
     ==========================================================================
  */
 VOID PeerAuthRspAtSeq2Action(
-    IN PRTMP_ADAPTER pAd, 
-    IN MLME_QUEUE_ELEM *Elem) 
+    IN PRTMP_ADAPTER pAd,
+    IN MLME_QUEUE_ELEM *Elem)
 {
     MACADDR       Addr2;
     USHORT        Seq, Status, RemoteStatus, Alg;
@@ -180,21 +179,21 @@
     NDIS_STATUS   NStatus;
     ULONG         FrameLen = 0;
 
-    if (PeerAuthSanity(pAd, Elem->Msg, Elem->MsgLen, &Addr2, &Alg, &Seq, &Status, ChlgText)) 
+    if (PeerAuthSanity(pAd, Elem->Msg, Elem->MsgLen, &Addr2, &Alg, &Seq, &Status, ChlgText))
     {
-        if (MAC_ADDR_EQUAL(&pAd->Mlme.AuthAux.Addr, &Addr2) && Seq == 2) 
+        if (MAC_ADDR_EQUAL(&pAd->Mlme.AuthAux.Addr, &Addr2) && Seq == 2)
         {
             DBGPRINT(RT_DEBUG_TRACE, "AUTH - Receive AUTH_RSP seq#2 to me (Alg=%d, Status=%d)\n", Alg, Status);
             RTMPCancelTimer(&pAd->Mlme.AuthAux.AuthTimer);
-            
-            if (Status == MLME_SUCCESS) 
+
+            if (Status == MLME_SUCCESS)
             {
-                if (pAd->Mlme.AuthAux.Alg == Ndis802_11AuthModeOpen) 
+                if (pAd->Mlme.AuthAux.Alg == Ndis802_11AuthModeOpen)
                 {
                     pAd->PortCfg.Mauth = TRUE;
                     pAd->Mlme.AuthMachine.CurrState = AUTH_REQ_IDLE;
                     MlmeCntlConfirm(pAd, MT2_AUTH_CONF, MLME_SUCCESS);
-                } 
+                }
                 else
                 {
                     // 2. shared key, need to be challenged
@@ -208,7 +207,7 @@
                         MlmeCntlConfirm(pAd, MT2_AUTH_CONF, MLME_FAIL_NO_RESOURCE);
                         return;
                     }
-                    
+
                     DBGPRINT(RT_DEBUG_TRACE, "AUTH - Send AUTH request seq#3...\n");
                     MgtMacHeaderInit(pAd, &AuthHdr, SUBTYPE_AUTH, 0, &Addr2, &pAd->PortCfg.Bssid);
                     AuthHdr.Wep = 1;
@@ -234,9 +233,9 @@
                     RTMPEncryptData(pAd, Element, CyperChlgText + 10, 2);
                     RTMPEncryptData(pAd, ChlgText, CyperChlgText + 12, 128);
                     RTMPSetICV(pAd, CyperChlgText + 140);
-                    MakeOutgoingFrame(OutBuffer,            &FrameLen, 
-                                      MAC_HDR_LEN,          &AuthHdr,  
-                                      CIPHER_TEXT_LEN + 16, CyperChlgText, 
+                    MakeOutgoingFrame(OutBuffer,            &FrameLen,
+                                      MAC_HDR_LEN,          &AuthHdr,
+                                      CIPHER_TEXT_LEN + 16, CyperChlgText,
                                       END_OF_ARGS);
                     MiniportMMRequest(pAd, OutBuffer, FrameLen);
 #ifdef BIG_ENDIAN
@@ -245,8 +244,8 @@
                     RTMPSetTimer(pAd, &pAd->Mlme.AuthAux.AuthTimer, AUTH_TIMEOUT);
                     pAd->Mlme.AuthMachine.CurrState = AUTH_WAIT_SEQ4;
                 }
-            } 
-            else 
+            }
+            else
             {
                 pAd->PortCfg.AuthFailReason = Status;
                 COPY_MAC_ADDR(&pAd->PortCfg.AuthFailSta, &Addr2);
@@ -267,29 +266,29 @@
     ==========================================================================
  */
 VOID PeerAuthRspAtSeq4Action(
-    IN PRTMP_ADAPTER pAd, 
-    IN MLME_QUEUE_ELEM *Elem) 
+    IN PRTMP_ADAPTER pAd,
+    IN MLME_QUEUE_ELEM *Elem)
 {
     MACADDR       Addr2;
     USHORT        Alg, Seq, Status;
     CHAR          ChlgText[CIPHER_TEXT_LEN];
 
-    if(PeerAuthSanity(pAd, Elem->Msg, Elem->MsgLen, &Addr2, &Alg, &Seq, &Status, ChlgText)) 
+    if(PeerAuthSanity(pAd, Elem->Msg, Elem->MsgLen, &Addr2, &Alg, &Seq, &Status, ChlgText))
     {
-        if(MAC_ADDR_EQUAL(&(pAd->Mlme.AuthAux.Addr), &Addr2) && Seq == 4) 
+        if(MAC_ADDR_EQUAL(&(pAd->Mlme.AuthAux.Addr), &Addr2) && Seq == 4)
         {
             DBGPRINT(RT_DEBUG_TRACE, "AUTH - Receive AUTH_RSP seq#4 to me\n");
             RTMPCancelTimer(&pAd->Mlme.AuthAux.AuthTimer);
-            
-            if(Status == MLME_SUCCESS) 
+
+            if(Status == MLME_SUCCESS)
             {
                 pAd->PortCfg.Mauth = TRUE;
-            } 
-            else 
+            }
+            else
             {
                 pAd->PortCfg.AuthFailReason = Status;
                 pAd->PortCfg.AuthFailSta = Addr2;
-            }                
+            }
 
             pAd->Mlme.AuthMachine.CurrState = AUTH_REQ_IDLE;
             MlmeCntlConfirm(pAd, MT2_AUTH_CONF, Status);
@@ -307,8 +306,8 @@
     ==========================================================================
  */
 VOID MlmeDeauthReqAction(
-    IN PRTMP_ADAPTER pAd, 
-    IN MLME_QUEUE_ELEM *Elem) 
+    IN PRTMP_ADAPTER pAd,
+    IN MLME_QUEUE_ELEM *Elem)
 {
     MLME_DEAUTH_REQ_STRUCT *Info;
     MACHDR        Hdr;
@@ -329,12 +328,12 @@
 
     DBGPRINT(RT_DEBUG_TRACE, "AUTH - Send DE-AUTH request...\n");
     MgtMacHeaderInit(pAd, &Hdr, SUBTYPE_DEAUTH, 0, &Info->Addr, &pAd->PortCfg.Bssid);
-    MakeOutgoingFrame(OutBuffer,            &FrameLen, 
-                      sizeof(MACHDR),       &Hdr, 
-                      2,                    &Info->Reason, 
+    MakeOutgoingFrame(OutBuffer,            &FrameLen,
+                      sizeof(MACHDR),       &Hdr,
+                      2,                    &Info->Reason,
                       END_OF_ARGS);
     MiniportMMRequest(pAd, OutBuffer, FrameLen);
-    
+
     pAd->PortCfg.DeauthReason = Info->Reason;
     COPY_MAC_ADDR(&pAd->PortCfg.DeauthSta, &Info->Addr);
     pAd->Mlme.AuthMachine.CurrState = AUTH_REQ_IDLE;
@@ -347,8 +346,8 @@
     ==========================================================================
  */
 VOID AuthTimeoutAction(
-    IN PRTMP_ADAPTER pAd, 
-    IN MLME_QUEUE_ELEM *Elem) 
+    IN PRTMP_ADAPTER pAd,
+    IN MLME_QUEUE_ELEM *Elem)
 {
     DBGPRINT(RT_DEBUG_TRACE, "AUTH - AuthTimeoutAction\n");
     pAd->Mlme.AuthMachine.CurrState = AUTH_REQ_IDLE;
@@ -361,8 +360,8 @@
     ==========================================================================
  */
 VOID InvalidStateWhenAuth(
-    IN PRTMP_ADAPTER pAd, 
-    IN MLME_QUEUE_ELEM *Elem) 
+    IN PRTMP_ADAPTER pAd,
+    IN MLME_QUEUE_ELEM *Elem)
 {
     DBGPRINT(RT_DEBUG_TRACE, "AUTH - InvalidStateWhenAuth (state=%d), reset AUTH state machine\n", pAd->Mlme.AuthMachine.CurrState);
     pAd->Mlme.AuthMachine.CurrState = AUTH_REQ_IDLE;
@@ -379,24 +378,24 @@
     ==========================================================================
  */
 VOID Cls2errAction(
-    IN PRTMP_ADAPTER pAd, 
-    IN PMACADDR pAddr) 
+    IN PRTMP_ADAPTER pAd,
+    IN PMACADDR pAddr)
 {
     MACHDR        Hdr;
     UCHAR        *OutBuffer = NULL;
     NDIS_STATUS   NStatus;
     ULONG         FrameLen = 0;
     USHORT        Reason = REASON_CLS2ERR;
-    
+
     NStatus = MlmeAllocateMemory(pAd, (PVOID)&OutBuffer);  //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, &Hdr, SUBTYPE_DEAUTH, 0, pAddr, &pAd->PortCfg.Bssid);
-    MakeOutgoingFrame(OutBuffer,            &FrameLen, 
-                      sizeof(MACHDR),       &Hdr, 
-                      2,                    &Reason, 
+    MakeOutgoingFrame(OutBuffer,            &FrameLen,
+                      sizeof(MACHDR),       &Hdr,
+                      2,                    &Reason,
                       END_OF_ARGS);
     MiniportMMRequest(pAd, OutBuffer, FrameLen);
 
diff -Nur rt2500-1.1.0-b4/Module/auth_rsp.c rt2500-cvs-2007061011/Module/auth_rsp.c
--- rt2500-1.1.0-b4/Module/auth_rsp.c	2006-06-17 22:12:58.000000000 +0200
+++ rt2500-cvs-2007061011/Module/auth_rsp.c	2007-03-21 05:25:34.000000000 +0100
@@ -1,35 +1,35 @@
-/*************************************************************************** 
- * RT2400/RT2500 SourceForge Project - http://rt2x00.serialmonkey.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.                          * 
- *                                                                         * 
- *   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.             * 
- *                                                                         * 
- *   Licensed under the GNU GPL                                            * 
- *   Original code supplied under license from RaLink Inc, 2004.           * 
- ***************************************************************************/ 
-
- /*************************************************************************** 
- *      Module Name: auth_rsp.c 
- *              
- *      Abstract: 
- *              
- *      Revision History: 
- *      Who             When            What 
- *      --------        -----------     ----------------------------- 
- *      MarkW           8th  Dec 04     Baseline code  
- ***************************************************************************/ 
+/***************************************************************************
+ * RT2400/RT2500 SourceForge Project - http://rt2x00.serialmonkey.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.                          *
+ *                                                                         *
+ *   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.             *
+ *                                                                         *
+ *   Licensed under the GNU GPL                                            *
+ *   Original code supplied under license from RaLink Inc, 2004.           *
+ ***************************************************************************/
+
+ /***************************************************************************
+ *      Module Name: auth_rsp.c
+ *
+ *      Abstract:
+ *
+ *      Revision History:
+ *      Who             When            What
+ *      --------        -----------     -----------------------------
+ *      MarkW           8th  Dec 04     Baseline code
+ ***************************************************************************/
 
 #include "rt_config.h"
 
@@ -40,8 +40,8 @@
     Parameters:
         Sm - the state machine
     Note:
-        the state machine looks like the following 
-        
+        the state machine looks like the following
+
                                         AUTH_RSP_IDLE                   AUTH_RSP_WAIT_CHAL
     MT2_AUTH_CHALLENGE_TIMEOUT    auth_rsp_challenge_timeout_action    auth_rsp_challenge_timeout_action
     MT2_PEER_AUTH_ODD        peer_auth_at_auth_rsp_idle_action peer_auth_at_auth_rsp_wait_action
@@ -49,9 +49,9 @@
     ==========================================================================
  */
 VOID AuthRspStateMachineInit(
-    IN PRTMP_ADAPTER pAd, 
-    IN PSTATE_MACHINE Sm, 
-    IN STATE_MACHINE_FUNC Trans[]) 
+    IN PRTMP_ADAPTER pAd,
+    IN PSTATE_MACHINE Sm,
+    IN STATE_MACHINE_FUNC Trans[])
 {
     ULONG        NOW;
 
@@ -83,10 +83,10 @@
     ==========================================================================
  */
 VOID AuthRspChallengeTimeout(
-    IN  unsigned long data) 
+    IN  unsigned long data)
 {
     RTMP_ADAPTER *pAd = (RTMP_ADAPTER *)data;
-    
+
     DBGPRINT(RT_DEBUG_TRACE,"AUTH_RSP - AuthRspChallengeTimeout \n");
     MlmeEnqueue(&pAd->Mlme.Queue, AUTH_RSP_STATE_MACHINE, MT2_AUTH_CHALLENGE_TIMEOUT, 0, NULL);
     MlmeHandler(pAd);
@@ -98,12 +98,12 @@
     ==========================================================================
 */
 VOID PeerAuthSimpleRspGenAndSend(
-    IN PRTMP_ADAPTER pAd, 
-    IN PMACHDR Hdr, 
-    IN USHORT Alg, 
-    IN USHORT Seq, 
-    IN USHORT Reason, 
-    IN USHORT Status) 
+    IN PRTMP_ADAPTER pAd,
+    IN PMACHDR Hdr,
+    IN USHORT Alg,
+    IN USHORT Seq,
+    IN USHORT Reason,
+    IN USHORT Status)
 {
     MACHDR            AuthHdr;
     UINT              FrameLen = 0;
@@ -118,11 +118,11 @@
     {
         DBGPRINT(RT_DEBUG_TRACE, "Send AUTH response (seq#2)...\n");
         MgtMacHeaderInit(pAd, &AuthHdr, SUBTYPE_AUTH, 0, &Hdr->Addr2, &pAd->PortCfg.Bssid);
-        MakeOutgoingFrame(OutBuffer,            &FrameLen, 
-                          sizeof(MACHDR),       &AuthHdr, 
-                          2,                    &Alg, 
-                          2,                    &Seq, 
-                          2,                    &Reason, 
+        MakeOutgoingFrame(OutBuffer,            &FrameLen,
+                          sizeof(MACHDR),       &AuthHdr,
+                          2,                    &Alg,
+                          2,                    &Seq,
+                          2,                    &Reason,
                           END_OF_ARGS);
         MiniportMMRequest(pAd, OutBuffer, FrameLen);
     }
@@ -139,8 +139,8 @@
     ==========================================================================
 */
 VOID PeerDeauthAction(
-    IN PRTMP_ADAPTER pAd, 
-    IN PMLME_QUEUE_ELEM Elem) 
+    IN PRTMP_ADAPTER pAd,
+    IN PMLME_QUEUE_ELEM Elem)
 {
     MACADDR     Addr2;
     USHORT      Reason;
diff -Nur rt2500-1.1.0-b4/Module/connect.c rt2500-cvs-2007061011/Module/connect.c
--- rt2500-1.1.0-b4/Module/connect.c	2006-06-17 22:12:58.000000000 +0200
+++ rt2500-cvs-2007061011/Module/connect.c	2007-03-21 05:25:34.000000000 +0100
@@ -1,36 +1,36 @@
-/*************************************************************************** 
- * RT2400/RT2500 SourceForge Project - http://rt2x00.serialmonkey.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.                          * 
- *                                                                         * 
- *   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.             * 
- *                                                                         * 
- *   Licensed under the GNU GPL                                            * 
- *   Original code supplied under license from RaLink Inc, 2004.           * 
- ***************************************************************************/ 
-
- /*************************************************************************** 
- *      Module Name: connect.c 
- *              
- *      Abstract: 
- *              
- *      Revision History: 
- *      Who             When            What 
- *      --------        -----------     ----------------------------- 
- *      MarkW           8th  Dec 04     Baseline code  
- *      Ivo (rt2400)    15th Dec 04     Timing ESSID set 
- ***************************************************************************/ 
+/***************************************************************************
+ * RT2400/RT2500 SourceForge Project - http://rt2x00.serialmonkey.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.                          *
+ *                                                                         *
+ *   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.             *
+ *                                                                         *
+ *   Licensed under the GNU GPL                                            *
+ *   Original code supplied under license from RaLink Inc, 2004.           *
+ ***************************************************************************/
+
+ /***************************************************************************
+ *      Module Name: connect.c
+ *
+ *      Abstract:
+ *
+ *      Revision History:
+ *      Who             When            What
+ *      --------        -----------     -----------------------------
+ *      MarkW           8th  Dec 04     Baseline code
+ *      Ivo (rt2400)    15th Dec 04     Timing ESSID set
+ ***************************************************************************/
 
 #include "rt_config.h"
 
@@ -62,11 +62,11 @@
     ==========================================================================
 */
 VOID MlmeCntlInit(
-    IN PRTMP_ADAPTER pAd, 
-    IN STATE_MACHINE *S, 
-    OUT STATE_MACHINE_FUNC Trans[]) 
+    IN PRTMP_ADAPTER pAd,
+    IN STATE_MACHINE *S,
+    OUT STATE_MACHINE_FUNC Trans[])
 {
-    // Control state machine differs from other state machines, the interface 
+    // Control state machine differs from other state machines, the interface
     // follows the standard interface
     pAd->Mlme.CntlMachine.CurrState = CNTL_IDLE;
 }
@@ -77,9 +77,9 @@
     ==========================================================================
 */
 VOID MlmeCntlMachinePerformAction(
-    IN PRTMP_ADAPTER pAd, 
-    IN STATE_MACHINE *S, 
-    IN MLME_QUEUE_ELEM *Elem) 
+    IN PRTMP_ADAPTER pAd,
+    IN STATE_MACHINE *S,
+    IN MLME_QUEUE_ELEM *Elem)
 {
     switch (Elem->MsgType)
     {
@@ -94,7 +94,7 @@
             return;
     }
 
-    switch(pAd->Mlme.CntlMachine.CurrState) 
+    switch(pAd->Mlme.CntlMachine.CurrState)
     {
         case CNTL_IDLE:
             CntlIdleProc(pAd, Elem);
@@ -105,17 +105,17 @@
         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" 
+        // 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;
@@ -130,7 +130,7 @@
             break;
 
         case CNTL_WAIT_OID_LIST_SCAN:
-            if(Elem->MsgType == MT2_SCAN_CONF) 
+            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
@@ -143,9 +143,9 @@
             if (pAd->MediaState == NdisMediaStateDisconnected)
                 MlmeAutoReconnectLastSSID(pAd);
             break;
-            
+
         case CNTL_WAIT_OID_DISASSOC:
-            if (Elem->MsgType == MT2_DISASSOC_CONF) 
+            if (Elem->MsgType == MT2_DISASSOC_CONF)
             {
                 LinkDown(pAd);
 
@@ -169,11 +169,11 @@
     ==========================================================================
 */
 VOID CntlIdleProc(
-    IN PRTMP_ADAPTER pAd, 
-    IN MLME_QUEUE_ELEM *Elem) 
+    IN PRTMP_ADAPTER pAd,
+    IN MLME_QUEUE_ELEM *Elem)
 {
     MLME_DISASSOC_REQ_STRUCT   DisassocReq;
-        
+
     if (RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_RADIO_OFF))
     {
         if (pAd->Mlme.CntlAux.CurrReqIsFromNdis)
@@ -183,7 +183,7 @@
         return;
     }
 
-    switch(Elem->MsgType) 
+    switch(Elem->MsgType)
     {
         case OID_802_11_DISASSOCIATE:
             DisassocParmFill(pAd, &DisassocReq, &pAd->PortCfg.Bssid, REASON_DISASSOC_STA_LEAVING);
@@ -198,7 +198,7 @@
         case MT2_MLME_ROAMING_REQ:
             CntlMlmeRoamingProc(pAd, Elem);
             break;
-            
+
         default:
             DBGPRINT(RT_DEBUG_TRACE, "CNTL - Illegal message in CntlIdleProc(MsgType=%d)\n",Elem->MsgType);
             break;
@@ -220,7 +220,7 @@
     // for best SCANNING reult;
     AsicRestoreBbpSensibility(pAd);
 
-    // record current BSS if network is connected. 
+    // 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 (pAd->MediaState == NdisMediaStateConnected) //  if (INFRA_ON(pAd) || ADHOC_ON(pAd))
     {
@@ -230,19 +230,19 @@
             memcpy(&CurrBss, &pAd->PortCfg.BssTab.BssEntry[BssIdx], sizeof(BSS_ENTRY));
 
             // 2003-2-20 reset this RSSI to a low value but not zero. In normal case, the coming SCAN
-            //     should return a correct RSSI to overwrite this. If no BEEACON received after SCAN, 
+            //     should return a correct RSSI to overwrite this. If no BEEACON received after SCAN,
             //     at least we still report a "greater than 0" RSSI since we claim it's CONNECTED.
             CurrBss.Rssi = 18; // about -82 dB
         }
     }
-            
+
     // clean up previous SCAN result, add current BSS back to table if any
-    BssTableInit(&pAd->PortCfg.BssTab); 
+    BssTableInit(&pAd->PortCfg.BssTab);
     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 
+        // 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
         memcpy(&pAd->PortCfg.BssTab.BssEntry[0], &CurrBss, sizeof(BSS_ENTRY));
@@ -251,7 +251,7 @@
 
     BroadSsid[0] = '\0';
     ScanParmFill(pAd, &ScanReq, BroadSsid, 0, BSS_ANY, SCAN_PASSIVE);
-    MlmeEnqueue(&pAd->Mlme.Queue, SYNC_STATE_MACHINE, MT2_MLME_SCAN_REQ, 
+    MlmeEnqueue(&pAd->Mlme.Queue, SYNC_STATE_MACHINE, MT2_MLME_SCAN_REQ,
         sizeof(MLME_SCAN_REQ_STRUCT), &ScanReq);
     pAd->Mlme.CntlMachine.CurrState = CNTL_WAIT_OID_LIST_SCAN;
 }
@@ -262,15 +262,15 @@
     ==========================================================================
 */
 VOID CntlOidSsidProc(
-    IN PRTMP_ADAPTER pAd, 
-    IN MLME_QUEUE_ELEM * Elem) 
+    IN PRTMP_ADAPTER pAd,
+    IN MLME_QUEUE_ELEM * Elem)
 {
     NDIS_802_11_SSID            *OidSsid = (NDIS_802_11_SSID *)Elem->Msg;
     MLME_DISASSOC_REQ_STRUCT    DisassocReq;
     ULONG                       Now;
 
-    // Step 0. 
-    //    record the desired SSID and all matching BSSes into CntlAux.SsidBssTab for 
+    // Step 0.
+    //    record the desired SSID and all matching BSSes into CntlAux.SsidBssTab for
     //    later-on iteration. Sort by RSSI order
     memcpy(pAd->Mlme.CntlAux.Ssid, OidSsid->Ssid, OidSsid->SsidLength);
     pAd->Mlme.CntlAux.SsidLen = (UCHAR)OidSsid->SsidLength;
@@ -286,11 +286,11 @@
         if (((pAd->PortCfg.AuthMode == Ndis802_11AuthModeWPA) || (pAd->PortCfg.AuthMode == Ndis802_11AuthModeWPAPSK)) &&
             (pAd->PortCfg.PortSecured == WPA_802_1X_PORT_NOT_SECURED))
         {
-            // For WPA, WPA-PSK, if the 1x port is not secured, we have to redo 
+            // For WPA, WPA-PSK, if the 1x port is not secured, we have to redo
             // connection process
             DBGPRINT(RT_DEBUG_TRACE, "CNTL - disassociate with current AP...\n");
             DisassocParmFill(pAd, &DisassocReq, &pAd->PortCfg.Bssid, REASON_DISASSOC_STA_LEAVING);
-            MlmeEnqueue(&pAd->Mlme.Queue, ASSOC_STATE_MACHINE, MT2_MLME_DISASSOC_REQ, 
+            MlmeEnqueue(&pAd->Mlme.Queue, ASSOC_STATE_MACHINE, MT2_MLME_DISASSOC_REQ,
                         sizeof(MLME_DISASSOC_REQ_STRUCT), &DisassocReq);
             pAd->Mlme.CntlMachine.CurrState = CNTL_WAIT_DISASSOC;
         }
@@ -299,7 +299,7 @@
             // Config has changed, we have to reconnect the same AP
             DBGPRINT(RT_DEBUG_TRACE, "CNTL - disassociate with current AP Because config changed...\n");
             DisassocParmFill(pAd, &DisassocReq, &pAd->PortCfg.Bssid, REASON_DISASSOC_STA_LEAVING);
-            MlmeEnqueue(&pAd->Mlme.Queue, ASSOC_STATE_MACHINE, MT2_MLME_DISASSOC_REQ, 
+            MlmeEnqueue(&pAd->Mlme.Queue, ASSOC_STATE_MACHINE, MT2_MLME_DISASSOC_REQ,
                         sizeof(MLME_DISASSOC_REQ_STRUCT), &DisassocReq);
             pAd->Mlme.CntlMachine.CurrState = CNTL_WAIT_DISASSOC;
         }
@@ -313,24 +313,24 @@
             {
             }
             pAd->Mlme.CntlMachine.CurrState = CNTL_IDLE;
-        } 
-    } 
-    else if (INFRA_ON(pAd)) 
+        }
+    }
+    else if (INFRA_ON(pAd))
     {
         // case 1. active 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 (or previous) associated AP, if any, 
-        //    then perform a new association with this new SSID, no matter the 
+        //    utility. so upon a new SET(OID_802_11_SSID) is received, we just
+        //    disassociate with the current (or previous) associated AP, if any,
+        //    then perform a new association with this new SSID, no matter the
         //    new/old SSID are the same or npt.
         DBGPRINT(RT_DEBUG_TRACE, "CNTL - disassociate with current AP...\n");
         DisassocParmFill(pAd, &DisassocReq, &pAd->PortCfg.Bssid, REASON_DISASSOC_STA_LEAVING);
-        MlmeEnqueue(&pAd->Mlme.Queue, ASSOC_STATE_MACHINE, MT2_MLME_DISASSOC_REQ, 
+        MlmeEnqueue(&pAd->Mlme.Queue, 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");
@@ -356,7 +356,7 @@
         {
             IterateOnBssTab(pAd);
         }
-    } 
+    }
 }
 
 /*
@@ -365,18 +365,18 @@
     ==========================================================================
 */
 VOID CntlOidRTBssidProc(
-    IN PRTMP_ADAPTER pAd, 
-    IN MLME_QUEUE_ELEM * Elem) 
+    IN PRTMP_ADAPTER pAd,
+    IN MLME_QUEUE_ELEM * Elem)
 {
     ULONG       BssIdx;
     MACADDR     *pOidBssid = (MACADDR *)Elem->Msg;
     MLME_DISASSOC_REQ_STRUCT    DisassocReq;
     MLME_JOIN_REQ_STRUCT        JoinReq;
- 
+
     COPY_MAC_ADDR(&pAd->Mlme.CntlAux.Bssid, pOidBssid);
     BssIdx = BssTableSearch(&pAd->PortCfg.BssTab, pOidBssid);
-       
-    if (BssIdx == BSS_NOT_FOUND) 
+
+    if (BssIdx == BSS_NOT_FOUND)
     {
     	DBGPRINT(RT_DEBUG_TRACE, "CNTL - BSSID not found. reply NDIS_STATUS_NOT_ACCEPTED\n");
         if (pAd->Mlme.CntlAux.CurrReqIsFromNdis)
@@ -394,7 +394,7 @@
 
     // Add SSID into Mlme.CntlAux for site surey joining hidden SSID
     pAd->Mlme.CntlAux.SsidLen = pAd->Mlme.CntlAux.SsidBssTab.BssEntry[0].SsidLen;
-    memcpy(pAd->Mlme.CntlAux.Ssid, pAd->Mlme.CntlAux.SsidBssTab.BssEntry[0].Ssid, pAd->Mlme.CntlAux.SsidLen);	
+    memcpy(pAd->Mlme.CntlAux.Ssid, pAd->Mlme.CntlAux.SsidBssTab.BssEntry[0].Ssid, pAd->Mlme.CntlAux.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
@@ -412,15 +412,15 @@
         {
         }
         pAd->Mlme.CntlMachine.CurrState = CNTL_IDLE;
-    } 
-    else 
+    }
+    else
     {
         if (INFRA_ON(pAd))
         {
             // disassoc from current AP first
             DBGPRINT(RT_DEBUG_TRACE, "CNTL - disassociate with current AP ...\n");
             DisassocParmFill(pAd, &DisassocReq, &pAd->PortCfg.Bssid, REASON_DISASSOC_STA_LEAVING);
-            MlmeEnqueue(&pAd->Mlme.Queue, ASSOC_STATE_MACHINE, MT2_MLME_DISASSOC_REQ, 
+            MlmeEnqueue(&pAd->Mlme.Queue, ASSOC_STATE_MACHINE, MT2_MLME_DISASSOC_REQ,
                         sizeof(MLME_DISASSOC_REQ_STRUCT), &DisassocReq);
 
             pAd->Mlme.CntlMachine.CurrState = CNTL_WAIT_DISASSOC;
@@ -434,7 +434,7 @@
                 pAd->MediaState = NdisMediaStateDisconnected;
                 DBGPRINT(RT_DEBUG_TRACE, "NDIS_STATUS_MEDIA_DISCONNECT Event C!\n");
             }
-            
+
             // No active association, join the BSS immediately
             DBGPRINT(RT_DEBUG_TRACE, "CNTL - joining %02x:%02x:%02x:%02x:%02x:%02x ...\n",
                 pOidBssid->Octet[0],pOidBssid->Octet[1],pOidBssid->Octet[2],
@@ -444,27 +444,27 @@
 
             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 
+// 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"?
 VOID CntlMlmeRoamingProc(
-    IN PRTMP_ADAPTER pAd, 
-    IN MLME_QUEUE_ELEM *Elem) 
+    IN PRTMP_ADAPTER pAd,
+    IN MLME_QUEUE_ELEM *Elem)
 {
-    // TODO: 
+    // 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 CntlAux.RoamTab...\n");
     BssTableSortByRssi(&pAd->Mlme.CntlAux.RoamTab);
     pAd->Mlme.CntlAux.RoamIdx=0;
     IterateOnBssTab2(pAd);
-    
+
 }
 
 /*
@@ -473,17 +473,17 @@
     ==========================================================================
 */
 VOID CntlWaitDisassocProc(
-    IN PRTMP_ADAPTER pAd, 
-    IN MLME_QUEUE_ELEM *Elem) 
+    IN PRTMP_ADAPTER pAd,
+    IN MLME_QUEUE_ELEM *Elem)
 {
     MLME_START_REQ_STRUCT     StartReq;
-    
-    if (Elem->MsgType == MT2_DISASSOC_CONF) 
+
+    if (Elem->MsgType == MT2_DISASSOC_CONF)
     {
         DBGPRINT(RT_DEBUG_TRACE, "CNTL - Dis-associate successful\n");
         LinkDown(pAd);
 
-        // case 1. no matching BSS, and user wants ADHOC, so we just start a new one        
+        // case 1. no matching BSS, and user wants ADHOC, so we just start a new one
         if ((pAd->Mlme.CntlAux.SsidBssTab.BssNr==0) && (pAd->PortCfg.BssType == BSS_INDEP))
         {
             DBGPRINT(RT_DEBUG_TRACE, "CNTL - No matching BSS, start a new ADHOC (Ssid=%s)...\n",pAd->Mlme.CntlAux.Ssid);
@@ -505,16 +505,16 @@
     ==========================================================================
 */
 VOID CntlWaitJoinProc(
-    IN PRTMP_ADAPTER pAd, 
-    IN MLME_QUEUE_ELEM *Elem) 
+    IN PRTMP_ADAPTER pAd,
+    IN MLME_QUEUE_ELEM *Elem)
 {
     USHORT                      Reason;
     MLME_AUTH_REQ_STRUCT        AuthReq;
 
-    if (Elem->MsgType == MT2_JOIN_CONF) 
+    if (Elem->MsgType == MT2_JOIN_CONF)
     {
         memcpy(&Reason, Elem->Msg, sizeof(USHORT));
-        if (Reason == MLME_SUCCESS) 
+        if (Reason == MLME_SUCCESS)
         {
             // 1. joined an IBSS, we are pretty much done here
             if (pAd->PortCfg.BssType == BSS_INDEP)
@@ -524,9 +524,9 @@
                 {
                 }
                 pAd->Mlme.CntlMachine.CurrState = CNTL_IDLE;
-            } 
+            }
             // 2. joined a new INFRA network, start from authentication
-            else 
+            else
             {
                 // either Ndis802_11AuthModeShared or Ndis802_11AuthModeAutoSwitch, try shared key first
                 if ((pAd->PortCfg.AuthMode == Ndis802_11AuthModeShared) ||
@@ -538,7 +538,7 @@
                 {
                     AuthParmFill(pAd, &AuthReq, &pAd->PortCfg.Bssid, Ndis802_11AuthModeOpen);
                 }
-                MlmeEnqueue(&pAd->Mlme.Queue, AUTH_STATE_MACHINE, MT2_MLME_AUTH_REQ, 
+                MlmeEnqueue(&pAd->Mlme.Queue, AUTH_STATE_MACHINE, MT2_MLME_AUTH_REQ,
                             sizeof(MLME_AUTH_REQ_STRUCT), &AuthReq);
 
                 pAd->Mlme.CntlMachine.CurrState = CNTL_WAIT_AUTH;
@@ -549,7 +549,7 @@
             // 3. failed, try next BSS
             pAd->Mlme.CntlAux.BssIdx++;
             IterateOnBssTab(pAd);
-        } 
+        }
     }
 }
 
@@ -560,18 +560,18 @@
     ==========================================================================
 */
 VOID CntlWaitStartProc(
-    IN PRTMP_ADAPTER pAd, 
-    IN MLME_QUEUE_ELEM *Elem) 
+    IN PRTMP_ADAPTER pAd,
+    IN MLME_QUEUE_ELEM *Elem)
 {
     USHORT      Result;
 
-    if (Elem->MsgType == MT2_START_CONF) 
+    if (Elem->MsgType == MT2_START_CONF)
     {
         memcpy(&Result, Elem->Msg, sizeof(USHORT));
-        if (Result == MLME_SUCCESS) 
+        if (Result == MLME_SUCCESS)
         {
             DBGPRINT(RT_DEBUG_TRACE, "CNTL - We have started a new ADHOC network\n");
-            DBGPRINT(RT_DEBUG_TRACE, "CNTL - BSSID %02x:%02x:%02x:%02x:%02x:%02x ...\n", 
+            DBGPRINT(RT_DEBUG_TRACE, "CNTL - BSSID %02x:%02x:%02x:%02x:%02x:%02x ...\n",
                 pAd->PortCfg.Bssid.Octet[0],
                 pAd->PortCfg.Bssid.Octet[1],
                 pAd->PortCfg.Bssid.Octet[2],
@@ -601,29 +601,29 @@
     ==========================================================================
 */
 VOID CntlWaitAuthProc(
-    IN PRTMP_ADAPTER pAd, 
-    IN MLME_QUEUE_ELEM *Elem) 
+    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) 
+    if (Elem->MsgType == MT2_AUTH_CONF)
     {
         memcpy(&Reason, Elem->Msg, sizeof(USHORT));
-        if (Reason == MLME_SUCCESS) 
+        if (Reason == MLME_SUCCESS)
         {
             DBGPRINT(RT_DEBUG_TRACE, "CNTL - AUTH OK\n");
-            AssocParmFill(pAd, &AssocReq, &pAd->PortCfg.Bssid, pAd->PortCfg.CapabilityInfo, 
+            AssocParmFill(pAd, &AssocReq, &pAd->PortCfg.Bssid, pAd->PortCfg.CapabilityInfo,
                           ASSOC_TIMEOUT, pAd->PortCfg.DefaultListenCount);
-            MlmeEnqueue(&pAd->Mlme.Queue, ASSOC_STATE_MACHINE, MT2_MLME_ASSOC_REQ, 
+            MlmeEnqueue(&pAd->Mlme.Queue, 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 
+            // 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");
@@ -638,7 +638,7 @@
                 AuthParmFill(pAd, &AuthReq, &pAd->PortCfg.Bssid, Ndis802_11AuthModeOpen);
             }
 
-            MlmeEnqueue(&pAd->Mlme.Queue, AUTH_STATE_MACHINE, MT2_MLME_AUTH_REQ, 
+            MlmeEnqueue(&pAd->Mlme.Queue, AUTH_STATE_MACHINE, MT2_MLME_AUTH_REQ,
                         sizeof(MLME_AUTH_REQ_STRUCT), &AuthReq);
 
             pAd->Mlme.CntlMachine.CurrState = CNTL_WAIT_AUTH2;
@@ -652,26 +652,26 @@
     ==========================================================================
 */
 VOID CntlWaitAuthProc2(
-    IN PRTMP_ADAPTER pAd, 
-    IN MLME_QUEUE_ELEM *Elem) 
+    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) 
+    if (Elem->MsgType == MT2_AUTH_CONF)
     {
         memcpy(&Reason, Elem->Msg, sizeof(USHORT));
-        if (Reason == MLME_SUCCESS) 
+        if (Reason == MLME_SUCCESS)
         {
             DBGPRINT(RT_DEBUG_TRACE, "CNTL - AUTH OK\n");
-            AssocParmFill(pAd, &AssocReq, &pAd->PortCfg.Bssid, pAd->PortCfg.CapabilityInfo, 
+            AssocParmFill(pAd, &AssocReq, &pAd->PortCfg.Bssid, pAd->PortCfg.CapabilityInfo,
                           ASSOC_TIMEOUT, pAd->PortCfg.DefaultListenCount);
-            MlmeEnqueue(&pAd->Mlme.Queue, ASSOC_STATE_MACHINE, MT2_MLME_ASSOC_REQ, 
+            MlmeEnqueue(&pAd->Mlme.Queue, ASSOC_STATE_MACHINE, MT2_MLME_ASSOC_REQ,
                         sizeof(MLME_ASSOC_REQ_STRUCT), &AssocReq);
 
             pAd->Mlme.CntlMachine.CurrState = CNTL_WAIT_ASSOC;
-        } 
+        }
         else
         {
             if ((pAd->PortCfg.AuthMode == Ndis802_11AuthModeAutoSwitch) &&
@@ -679,12 +679,12 @@
             {
                 DBGPRINT(RT_DEBUG_TRACE, "CNTL - AUTH FAIL, try OPEN system...\n");
                 AuthParmFill(pAd, &AuthReq, &pAd->PortCfg.Bssid, Ndis802_11AuthModeOpen);
-                MlmeEnqueue(&pAd->Mlme.Queue, AUTH_STATE_MACHINE, MT2_MLME_AUTH_REQ, 
+                MlmeEnqueue(&pAd->Mlme.Queue, AUTH_STATE_MACHINE, MT2_MLME_AUTH_REQ,
                             sizeof(MLME_AUTH_REQ_STRUCT), &AuthReq);
 
                 pAd->Mlme.CntlMachine.CurrState = CNTL_WAIT_AUTH2;
             }
-            else 
+            else
             {
                 // not success, try next BSS
                 DBGPRINT(RT_DEBUG_TRACE, "CNTL - AUTH FAIL, give up; try next BSS\n");
@@ -693,7 +693,7 @@
                 IterateOnBssTab(pAd);
             }
         }
-    }    
+    }
 }
 
 /*
@@ -702,15 +702,15 @@
     ==========================================================================
 */
 VOID CntlWaitAssocProc(
-    IN PRTMP_ADAPTER pAd, 
-    IN MLME_QUEUE_ELEM *Elem) 
+    IN PRTMP_ADAPTER pAd,
+    IN MLME_QUEUE_ELEM *Elem)
 {
     USHORT      Reason;
 
-    if (Elem->MsgType == MT2_ASSOC_CONF) 
+    if (Elem->MsgType == MT2_ASSOC_CONF)
     {
         memcpy(&Reason, Elem->Msg, sizeof(USHORT));
-        if (Reason == MLME_SUCCESS) 
+        if (Reason == MLME_SUCCESS)
         {
             DBGPRINT(RT_DEBUG_TRACE, "CNTL - Association successful on BSS #%d\n",pAd->Mlme.CntlAux.BssIdx);
             LinkUp(pAd, BSS_INFRA);
@@ -718,8 +718,8 @@
             {
             }
             pAd->Mlme.CntlMachine.CurrState = CNTL_IDLE;
-        } 
-        else 
+        }
+        else
         {
             // not success, try next BSS
             DBGPRINT(RT_DEBUG_TRACE, "CNTL - Association fails on BSS #%d\n",pAd->Mlme.CntlAux.BssIdx);
@@ -735,21 +735,21 @@
     ==========================================================================
 */
 VOID CntlWaitReassocProc(
-    IN PRTMP_ADAPTER pAd, 
-    IN MLME_QUEUE_ELEM *Elem) 
+    IN PRTMP_ADAPTER pAd,
+    IN MLME_QUEUE_ELEM *Elem)
 {
     USHORT      Result;
 
-    if (Elem->MsgType == MT2_REASSOC_CONF) 
+    if (Elem->MsgType == MT2_REASSOC_CONF)
     {
         memcpy(&Result, Elem->Msg, sizeof(USHORT));
-        if (Result == MLME_SUCCESS) 
+        if (Result == MLME_SUCCESS)
         {
             BSS_ENTRY *pBss = &pAd->Mlme.CntlAux.RoamTab.BssEntry[pAd->Mlme.CntlAux.RoamIdx];
 
             // COPY_MAC_ADDR(&pAd->PortCfg.Bssid, &pBss->Bssid);
             // AsicSetBssid(pAd, &pAd->PortCfg.Bssid);
-            
+
             // The following steps are supposed to be done after JOIN in normal procedure
             // But since this RE-ASSOC skips the JOIN procedure, we have to do it after
             // RE-ASSOC succeeds. If RE-ASSOC fails, then stay at original AP without any change
@@ -768,14 +768,14 @@
             pAd->PortCfg.CfpDurRemain = pBss->CfpDurRemaining;
             pAd->PortCfg.CfpCount = pBss->CfpCount;
 
-            // 
+            //
             // NDIS requires a new Link UP indication but no Link Down for RE-ASSOC
             //
             DBGPRINT(RT_DEBUG_TRACE, "CNTL - Re-assocition successful on BSS #%d\n", pAd->Mlme.CntlAux.RoamIdx);
             LinkUp(pAd, BSS_INFRA);
-            pAd->Mlme.CntlMachine.CurrState = CNTL_IDLE;            
-        } 
-        else 
+            pAd->Mlme.CntlMachine.CurrState = CNTL_IDLE;
+        }
+        else
         {
             // reassoc failed, try to pick next BSS in the BSS Table
             DBGPRINT(RT_DEBUG_TRACE, "CNTL - Re-assocition fails on BSS #%d\n", pAd->Mlme.CntlAux.RoamIdx);
@@ -792,7 +792,7 @@
 */
 VOID LinkUp(
     IN PRTMP_ADAPTER pAd,
-    IN UCHAR BssType) 
+    IN UCHAR BssType)
 {
     ULONG       Now;
 
@@ -810,7 +810,7 @@
         DBGPRINT(RT_DEBUG_TRACE, "CNTL - !!! Set to short preamble!!!\n");
         MlmeSetTxPreamble(pAd, Rt802_11PreambleShort);
     }
-    
+
     pAd->PortCfg.BssType = BssType;
     if (BssType == BSS_INDEP)
     {
@@ -856,11 +856,11 @@
         // 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);
-    
+
         // only INFRASTRUCTURE mode need to indicate connectivity immediately; ADHOC mode
         // should wait until at least 2 active nodes in this BSSID.
         pAd->MediaState = NdisMediaStateConnected;
@@ -885,7 +885,7 @@
     ==========================================================================
 */
 VOID LinkDown(
-    IN PRTMP_ADAPTER pAd) 
+    IN PRTMP_ADAPTER pAd)
 {
     DBGPRINT(RT_DEBUG_TRACE, "CNTL - !!! LINK DOWN !!!\n");
 
@@ -913,7 +913,7 @@
         DBGPRINT(RT_DEBUG_TRACE, "NDIS_STATUS_MEDIA_DISCONNECT Event A!\n");
         BssTableDeleteEntry(&pAd->PortCfg.BssTab, &(pAd->PortCfg.Bssid));
 
-        // restore back to - 
+        // 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
@@ -970,9 +970,9 @@
     ==========================================================================
 */
 VOID MlmeCntlConfirm(
-    IN PRTMP_ADAPTER pAd, 
-    IN ULONG MsgType, 
-    IN USHORT Msg) 
+    IN PRTMP_ADAPTER pAd,
+    IN ULONG MsgType,
+    IN USHORT Msg)
 {
     MlmeEnqueue(&pAd->Mlme.Queue, MLME_CNTL_STATE_MACHINE, MsgType, sizeof(USHORT), &Msg);
 }
@@ -983,16 +983,16 @@
     ==========================================================================
 */
 VOID IterateOnBssTab(
-    IN PRTMP_ADAPTER pAd) 
+    IN PRTMP_ADAPTER pAd)
 {
     MLME_START_REQ_STRUCT   StartReq;
     MLME_JOIN_REQ_STRUCT    JoinReq;
     ULONG                   BssIdx;
 
     BssIdx = pAd->Mlme.CntlAux.BssIdx;
-    if (BssIdx < pAd->Mlme.CntlAux.SsidBssTab.BssNr) 
+    if (BssIdx < pAd->Mlme.CntlAux.SsidBssTab.BssNr)
     {
-        DBGPRINT(RT_DEBUG_TRACE, "CNTL - Trying BSSID %02x:%02x:%02x:%02x:%02x:%02x ...\n", 
+        DBGPRINT(RT_DEBUG_TRACE, "CNTL - Trying BSSID %02x:%02x:%02x:%02x:%02x:%02x ...\n",
             pAd->Mlme.CntlAux.SsidBssTab.BssEntry[BssIdx].Bssid.Octet[0],
             pAd->Mlme.CntlAux.SsidBssTab.BssEntry[BssIdx].Bssid.Octet[1],
             pAd->Mlme.CntlAux.SsidBssTab.BssEntry[BssIdx].Bssid.Octet[2],
@@ -1018,12 +1018,12 @@
             DBGPRINT(RT_DEBUG_TRACE, "CNTL - All BSS fail; reply NDIS_STATUS_NOT_ACCEPTED\n");
         }
         pAd->Mlme.CntlMachine.CurrState = CNTL_IDLE;
-    } 
+    }
 }
 
 // for re-association only
 VOID IterateOnBssTab2(
-    IN PRTMP_ADAPTER pAd) 
+    IN PRTMP_ADAPTER pAd)
 {
     MLME_REASSOC_REQ_STRUCT ReassocReq;
     ULONG                   BssIdx;
@@ -1034,19 +1034,19 @@
 
     if (BssIdx < pAd->Mlme.CntlAux.RoamTab.BssNr)
     {
-        DBGPRINT(RT_DEBUG_TRACE, "CNTL - try BSS #%d %02x:%02x:%02x:%02x:%02x:%02x ...\n", 
+        DBGPRINT(RT_DEBUG_TRACE, "CNTL - try BSS #%d %02x:%02x:%02x:%02x:%02x:%02x ...\n",
             BssIdx, pBss->Bssid.Octet[0],pBss->Bssid.Octet[1],pBss->Bssid.Octet[2],
             pBss->Bssid.Octet[3],pBss->Bssid.Octet[4],pBss->Bssid.Octet[5]);
 
         AsicSwitchChannel(pAd, pBss->Channel);
 		AsicLockChannel(pAd, pBss->Channel);
-        
+
         // reassociate message has the same structure as associate message
-        AssocParmFill(pAd, &ReassocReq, &pBss->Bssid, pBss->CapabilityInfo, 
+        AssocParmFill(pAd, &ReassocReq, &pBss->Bssid, pBss->CapabilityInfo,
                       ASSOC_TIMEOUT, pAd->PortCfg.DefaultListenCount);
-        MlmeEnqueue(&pAd->Mlme.Queue, ASSOC_STATE_MACHINE, MT2_MLME_REASSOC_REQ, 
+        MlmeEnqueue(&pAd->Mlme.Queue, ASSOC_STATE_MACHINE, MT2_MLME_REASSOC_REQ,
                     sizeof(MLME_REASSOC_REQ_STRUCT), &ReassocReq);
-        
+
         pAd->Mlme.CntlMachine.CurrState = CNTL_WAIT_REASSOC;
     }
     else // no more BSS
@@ -1055,7 +1055,7 @@
         AsicSwitchChannel(pAd, pAd->PortCfg.Channel);
         AsicLockChannel(pAd, pAd->PortCfg.Channel);
         pAd->Mlme.CntlMachine.CurrState = CNTL_IDLE;
-    } 
+    }
 }
 
 /*
@@ -1064,9 +1064,9 @@
     ==========================================================================
 */
 VOID JoinParmFill(
-    IN PRTMP_ADAPTER pAd, 
-    IN OUT MLME_JOIN_REQ_STRUCT *JoinReq, 
-    IN ULONG BssIdx) 
+    IN PRTMP_ADAPTER pAd,
+    IN OUT MLME_JOIN_REQ_STRUCT *JoinReq,
+    IN ULONG BssIdx)
 {
     JoinReq->BssIdx = BssIdx;
 }
@@ -1077,12 +1077,12 @@
     ==========================================================================
 */
 VOID AssocParmFill(
-    IN PRTMP_ADAPTER pAd, 
-    IN OUT MLME_ASSOC_REQ_STRUCT *AssocReq, 
-    IN MACADDR                   *Addr, 
-    IN USHORT                     CapabilityInfo, 
-    IN ULONG                      Timeout, 
-    IN USHORT                     ListenIntv) 
+    IN PRTMP_ADAPTER pAd,
+    IN OUT MLME_ASSOC_REQ_STRUCT *AssocReq,
+    IN MACADDR                   *Addr,
+    IN USHORT                     CapabilityInfo,
+    IN ULONG                      Timeout,
+    IN USHORT                     ListenIntv)
 {
     COPY_MAC_ADDR(&AssocReq->Addr, Addr);
     // Add mask to support 802.11b mode only
@@ -1097,12 +1097,12 @@
     ==========================================================================
 */
 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) 
+    IN PRTMP_ADAPTER pAd,
+    IN OUT MLME_SCAN_REQ_STRUCT *ScanReq,
+    IN CHAR Ssid[],
+    IN UCHAR SsidLen,
+    IN UCHAR BssType,
+    IN UCHAR ScanType)
 {
     ScanReq->SsidLen = SsidLen;
     memcpy(ScanReq->Ssid, Ssid, SsidLen);
@@ -1116,10 +1116,10 @@
     ==========================================================================
 */
 VOID DisassocParmFill(
-    IN PRTMP_ADAPTER pAd, 
-    IN OUT MLME_DISASSOC_REQ_STRUCT *DisassocReq, 
-    IN MACADDR *Addr, 
-    IN USHORT Reason) 
+    IN PRTMP_ADAPTER pAd,
+    IN OUT MLME_DISASSOC_REQ_STRUCT *DisassocReq,
+    IN MACADDR *Addr,
+    IN USHORT Reason)
 {
     COPY_MAC_ADDR(&DisassocReq->Addr, Addr);
     DisassocReq->Reason = Reason;
@@ -1131,12 +1131,12 @@
     ==========================================================================
 */
 VOID StartParmFill(
-    IN PRTMP_ADAPTER pAd, 
-    IN OUT MLME_START_REQ_STRUCT *StartReq, 
-    IN CHAR Ssid[], 
-    IN UCHAR SsidLen) 
+    IN PRTMP_ADAPTER pAd,
+    IN OUT MLME_START_REQ_STRUCT *StartReq,
+    IN CHAR Ssid[],
+    IN UCHAR SsidLen)
 {
-    memcpy(StartReq->Ssid, Ssid, SsidLen); 
+    memcpy(StartReq->Ssid, Ssid, SsidLen);
     StartReq->SsidLen = SsidLen;
 }
 
@@ -1146,10 +1146,10 @@
     ==========================================================================
 */
 VOID AuthParmFill(
-    IN PRTMP_ADAPTER pAd, 
-    IN OUT MLME_AUTH_REQ_STRUCT *AuthReq, 
-    IN MACADDR *Addr, 
-    IN USHORT Alg) 
+    IN PRTMP_ADAPTER pAd,
+    IN OUT MLME_AUTH_REQ_STRUCT *AuthReq,
+    IN MACADDR *Addr,
+    IN USHORT Alg)
 {
     COPY_MAC_ADDR(&AuthReq->Addr, Addr);
     AuthReq->Alg = Alg;
@@ -1187,9 +1187,9 @@
     ==========================================================================
 */
 ULONG MakeIbssBeacon(
-    IN PRTMP_ADAPTER pAd) 
+    IN PRTMP_ADAPTER pAd)
 {
-    UCHAR           SsidIe = IE_SSID, DsIe = IE_DS_PARM, IbssIe = IE_IBSS_PARM, SuppIe = IE_SUPP_RATES, 
+    UCHAR           SsidIe = IE_SSID, DsIe = IE_DS_PARM, IbssIe = IE_IBSS_PARM, SuppIe = IE_SUPP_RATES,
                     DsLen = 1, IbssLen = 2;
     UCHAR           ExtRateIe = IE_EXT_SUPP_RATES, ExtRatesLen;
     UCHAR         ErpIe[3] = {IE_ERP, 1, 0x04};
@@ -1244,28 +1244,28 @@
 
     // compose IBSS beacon frame
     MgtMacHeaderInit(pAd, &BcnHdr, SUBTYPE_BEACON, 0, &pAd->PortCfg.Broadcast, &pAd->PortCfg.Bssid);
-    Privacy = (pAd->PortCfg.WepStatus == Ndis802_11Encryption1Enabled) || 
-              (pAd->PortCfg.WepStatus == Ndis802_11Encryption2Enabled) || 
+    Privacy = (pAd->PortCfg.WepStatus == Ndis802_11Encryption1Enabled) ||
+              (pAd->PortCfg.WepStatus == Ndis802_11Encryption2Enabled) ||
               (pAd->PortCfg.WepStatus == Ndis802_11Encryption3Enabled);
     CapabilityInfo = CAP_GENERATE(0, 1, 0, 0, Privacy, (pAd->PortCfg.WindowsTxPreamble == Rt802_11PreambleShort));
     if (SupportedRatesLen <= 8)
     {
         MakeOutgoingFrame(pBeaconFrame,                    &FrameLen,
-                          MAC_HDR_LEN,                     &BcnHdr, 
+                          MAC_HDR_LEN,                     &BcnHdr,
                           TIMESTAMP_LEN,                   &FakeTimestamp,
                           2,                               &pAd->PortCfg.BeaconPeriod,
                           2,                               &CapabilityInfo,
-                          1,                               &SsidIe, 
-                          1,                               &pAd->PortCfg.SsidLen, 
+                          1,                               &SsidIe,
+                          1,                               &pAd->PortCfg.SsidLen,
                           pAd->PortCfg.SsidLen,            pAd->PortCfg.Ssid,
-                          1,                               &SuppIe, 
+                          1,                               &SuppIe,
                           1,                               &SupportedRatesLen,
-                          SupportedRatesLen,               SupportedRates, 
-                          1,                               &DsIe, 
-                          1,                               &DsLen, 
+                          SupportedRatesLen,               SupportedRates,
+                          1,                               &DsIe,
+                          1,                               &DsLen,
                           1,                               &pAd->PortCfg.Channel,
-                          1,                               &IbssIe, 
-                          1,                               &IbssLen, 
+                          1,                               &IbssIe,
+                          1,                               &IbssLen,
                           2,                               &pAd->PortCfg.AtimWin,
                           END_OF_ARGS);
     }
@@ -1274,21 +1274,21 @@
         ExtRatesLen = SupportedRatesLen - 8;
         SupportedRatesLen = 8;
         MakeOutgoingFrame(pBeaconFrame,                    &FrameLen,
-                      MAC_HDR_LEN,                     &BcnHdr, 
+                      MAC_HDR_LEN,                     &BcnHdr,
                       TIMESTAMP_LEN,                   &FakeTimestamp,
                       2,                               &pAd->PortCfg.BeaconPeriod,
                       2,                               &CapabilityInfo,
-                      1,                               &SsidIe, 
-                      1,                               &pAd->PortCfg.SsidLen, 
+                      1,                               &SsidIe,
+                      1,                               &pAd->PortCfg.SsidLen,
                       pAd->PortCfg.SsidLen,             pAd->PortCfg.Ssid,
-                      1,                               &SuppIe, 
+                      1,                               &SuppIe,
                       1,                               &SupportedRatesLen,
-                      SupportedRatesLen,                SupportedRates, 
-                      1,                               &DsIe, 
-                      1,                               &DsLen, 
+                      SupportedRatesLen,                SupportedRates,
+                      1,                               &DsIe,
+                      1,                               &DsLen,
                       1,                               &pAd->PortCfg.Channel,
-                      1,                               &IbssIe, 
-                      1,                               &IbssLen, 
+                      1,                               &IbssIe,
+                      1,                               &IbssLen,
                       2,                               &pAd->PortCfg.AtimWin,
                       3,                               ErpIe,
                       1,                               &ExtRateIe,
@@ -1301,7 +1301,7 @@
 	{
 		ULONG	tmp;
 		UCHAR	WpaIe = IE_WPA;
-		
+
 		if (pAd->PortCfg.WepStatus == Ndis802_11Encryption2Enabled)		// Tkip
 		{
         MakeOutgoingFrame(pBeaconFrame + FrameLen,                    &tmp,
@@ -1325,7 +1325,7 @@
     RTMPFrameEndianChange(pAd, pBeaconFrame, DIR_WRITE, FALSE);
 #endif
 
-    RTMPWriteTxDescriptor(pTxD, FALSE, CIPHER_NONE, FALSE, FALSE, TRUE, SHORT_RETRY, IFS_NEW_BACKOFF, 
+    RTMPWriteTxDescriptor(pTxD, FALSE, CIPHER_NONE, FALSE, FALSE, TRUE, SHORT_RETRY, IFS_NEW_BACKOFF,
                           pAd->PortCfg.MlmeRate, 4, FrameLen, pAd->PortCfg.TxPreambleInUsed, 0);
 
     DBGPRINT(RT_DEBUG_TRACE, "MakeIbssBeacon (len=%d)\n", FrameLen);
diff -Nur rt2500-1.1.0-b4/Module/eeprom.c rt2500-cvs-2007061011/Module/eeprom.c
--- rt2500-1.1.0-b4/Module/eeprom.c	2006-06-17 22:12:58.000000000 +0200
+++ rt2500-cvs-2007061011/Module/eeprom.c	2007-03-21 05:25:34.000000000 +0100
@@ -1,35 +1,35 @@
-/*************************************************************************** 
- * RT2400/RT2500 SourceForge Project - http://rt2x00.serialmonkey.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.                          * 
- *                                                                         * 
- *   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.             * 
- *                                                                         * 
- *   Licensed under the GNU GPL                                            * 
- *   Original code supplied under license from RaLink Inc, 2004.           * 
- ***************************************************************************/ 
-
- /*************************************************************************** 
- *      Module Name: eeprom.c 
- *              
- *      Abstract: 
- *              
- *      Revision History: 
- *      Who             When            What 
- *      --------        -----------     ----------------------------- 
- *      MarkW           8th  Dec 04     Baseline code  
- ***************************************************************************/ 
+/***************************************************************************
+ * RT2400/RT2500 SourceForge Project - http://rt2x00.serialmonkey.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.                          *
+ *                                                                         *
+ *   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.             *
+ *                                                                         *
+ *   Licensed under the GNU GPL                                            *
+ *   Original code supplied under license from RaLink Inc, 2004.           *
+ ***************************************************************************/
+
+ /***************************************************************************
+ *      Module Name: eeprom.c
+ *
+ *      Abstract:
+ *
+ *      Revision History:
+ *      Who             When            What
+ *      --------        -----------     -----------------------------
+ *      MarkW           8th  Dec 04     Baseline code
+ ***************************************************************************/
 
 #include    "rt_config.h"
 
@@ -183,7 +183,7 @@
     RaiseClock(pAd, &x);
     LowerClock(pAd, &x);
 
-    // output the read_opcode and register number in that order    
+    // output the read_opcode and register number in that order
     ShiftOutBits(pAd, EEPROM_READ_OPCODE, 3);
     ShiftOutBits(pAd, Offset, pAd->EEPROMAddressNum);
 
diff -Nur rt2500-1.1.0-b4/Module/iwpriv_usage.txt rt2500-cvs-2007061011/Module/iwpriv_usage.txt
--- rt2500-1.1.0-b4/Module/iwpriv_usage.txt	2006-06-17 22:12:58.000000000 +0200
+++ rt2500-cvs-2007061011/Module/iwpriv_usage.txt	2007-01-09 12:47:14.000000000 +0100
@@ -1,151 +1,161 @@
-
-This file provides some basic examples on the configuration of the driver using standard linux wireless tools. Where possible iwconfig should be used to adjust settings. Some settings are currently not avaiable via iwconfig and these include WPA, for these functions it is currently necessary to use iwpriv. 
-
-
-Configuration Examples
-===================================================================
--------------------------------------------------------------------------------------------------------
-Example I: Config STA to link with AP which is OPEN/NONE(Authentication/Encryption)
-	1. iwconfig ra0 mode managed
-	2. iwconfig ra0 key open
-	3. iwconfig ra0 key off
-	4. iwconfig ra0 essid "AP's SSID"
-	
-Example II: Config STA to link with AP which is SHARED/WEP(Authentication/Encryption)
-	1. iwconfig ra0 mode managed
-	2. iwconfig ra0 key restricted
-	3. iwconfig ra0 Key [1] "s:AP's wep key"
-	4. iwconfig ra0 key [1]
-	5. iwconfig ra0 essid "AP's SSID"
-	
-Example III: Config STA to create/link as adhoc mode
-	1. iwconfig ra0 mode ad-hoc
-	2. iwconfig ra0 key off
-	4. iwconfig ra0 essid "AP's SSID"
-	
-Example IV: Config STA to link with AP which is WPAPSK/TKIP(Authentication/Encryption)
-	1. iwconfig ra0 mode managed
-	2. iwpriv ra0 set AuthMode=WPAPSK
-	3. iwpriv ra0 set EncrypType=TKIP
-	4. iwpriv ra0 set WPAPSK="AP's wpa-preshared key"
-	5. iwconfig ra0 essid "AP's SSID"
-	
-Example V: Config STA to link with AP which is WPAPSK/AES(Authentication/Encryption)
-	1. iwconfig ra0 mode managed
-	2. iwpriv ra0 set AuthMode=WPAPSK
-	3. iwpriv ra0 set EncrypType=AES
-	5. iwpriv ra0 set WPAPSK="AP's wpa-preshared key"
-	6. iwconfig ra0 essid "AP's SSID"
-	
-
-
-iwpriv
-=================
-This is detailed explanation of each parameters for iwpriv.
-Before reading this document, make sure you already read README.
-
--------------------------------------------------------------------------------------------------------
-USAGE:
-	iwpriv ra0 set [parameters]=[val]
-
-where
-
-[parameters]          [val] range                          explaination
------------------   -----------------------              ---------------------------------------------
-CountryRegion       {0~7}                                  Set country region 
-                                                           0: use 1 ~ 11 Channel
-                                                           1: use 1 ~ 11 Channel
-                                                           2: use 1 ~ 13 Channel
-                                                           3: use 10, 11 Channel
-                                                           4: use 10 ~ 13 Channel
-                                                           5: use 14 Channel
-                                                           6: use 1 ~ 14 Channel
-                                                           7: use 3 ~ 9 Channel
-                                                           
-WirelessMode        {0~2}				   Set Wireless Mode 
-                                                           0:11b/g mixed, 1:11B only
-
-TxRate              {0~12}				   Set TxRate 
-                                                           0:Auto, 1:1Mbps, 2:2Mbps, 3:5.5Mbps, 4:11Mbps, 
-                                                          5:6Mbps, 6:9Mbps, 7:12Mbps, 8:18Mbps, 9:24Mbps, 
-                                                           10:36Mbps, 11:48Mbps, 12:54Mbps
-                                                           
-BGProtection        {0~2}                                  Set 11B/11G Protection
-                                                           0:Auto, 1:Always on, 2:Always off
-
-TxPreamble          {0~2}                                  Set TxPreamble
-                                                           0:Preamble Long, 1:Preamble Short, 2:Auto
-
-TxBurst             {0,1}                                  Set TxBurst Enable or Disable
-                                                           0:Disable, 1:Enable
-
-TurboRate           {0,1}                                  Set TurboRate Enable or Disable
-                                                           0:Disable, 1:Enable
-
-AdhocOfdm           {0, 1}                                 Set Adhoc mode tx rate
-							   0: adhere WIFI spec., 1: violate WIFI spec.
-							   (802.11g WIFI spec disallow OFDM rates in 802.11g ADHOC mode)
-                                                                                                                                                        AuthMode            {OPEN,SHARED,WPAPSK}                   Set Authentication mode
-
-EncrypType          {NONE,WEP,TKIP,AES}                    Set Encryption Type
-
-WPAPSK              {8~63 ASCII or 64 HEX characters}       WPA Pre-Shared Key 
-
-ApClient	    {0,1}				    Set ApClient mode
-							    0:Disable, 1:Enable
-							    
-iwlist
-=================
-This is detailed explanation of each parameters for iwlist.
-
--------------------------------------------------------------------------------------------------------
-
-iwlist ra0 scanning		; list the result after scanning(site survey) 
-							    
-
-
-
-----------------------------------------------------------------------------------------------------------------------------------
-
-							    
-Deprecated iwpriv
-=================
-
-*** PLEASE DO NOT USE THESE FUNCTIONS, THIS IS FOR HISTORICAL REFERENCE ONLY ***
-As the configuration utility still uses some iwpriv commands they have not been
-removed from the driver yet. These commands are likely to dissapear if the utility is
-updated.
-	
-** ALL THESE COMMANDS HAVE A IWCONFIG REPLACEMENT, USE IT ****
-
-SSID                {0~z, less than 32 characters}         Set SoftAP SSID
-
-Channel             {1~14} depends on country region       Set Channel
-
-RTSThreshold        {1~2347}                               Set RTS Threshold                                                           
-                                                           
-FragThreshold       {256~2346}                             Set Fragment Threshold
-
-NetworkType	    {Infra,Adhoc}			   Set Network type
-
-DefaultKeyID        {1~4}                                  Set Default Key ID
-
-Key1                 {5 ascii characters or                 Set Key1 String
-                     10 hex number or 
-                     13 ascii characters or 
-                     26 hex numbers}                                                                                                                        
-
-Key2                 {5 ascii characters or                 Set Key2 String
-                     10 hex number or 
-                     13 ascii characters or 
-                     26 hex numbers}                                                                                                                        
-
-Key3                 {5 ascii characters or                 Set Key3 String
-                     10 hex number or 
-                     13 ascii characters or 
-                     26 hex numbers}                                                                                                                        
-
-Key4                 {5 ascii characters or                 Set Key4 String
-                     10 hex number or 
-                     13 ascii characters or 
-                     26 hex numbers}                                                                                                                        
+This file provides some basic examples on the configuration of the
+driver using standard linux wireless tools. Where possible iwconfig
+should be used to adjust settings. Some settings are currently not
+avaiable via iwconfig and these include WPA, for these functions it is
+currently necessary to use iwpriv.
+
+
+Configuration Examples
+======================================================================
+----------------------------------------------------------------------
+Example I: STA with AP using OPEN/NONE(Authentication/Encryption)
+    1. iwconfig ra0 mode managed
+    2. iwconfig ra0 key open
+    3. iwconfig ra0 key off
+    4. iwconfig ra0 essid "AP's SSID"
+
+Example II: STA with AP using SHARED/WEP(Authentication/Encryption)
+    1. iwconfig ra0 mode managed
+    2. iwconfig ra0 key restricted
+    3. iwconfig ra0 Key [1] "s:AP's wep key"
+    4. iwconfig ra0 key [1]
+    5. iwconfig ra0 essid "AP's SSID"
+
+Example III: STA using adhoc mode
+    1. iwconfig ra0 mode ad-hoc
+    2. iwconfig ra0 key off
+    4. iwconfig ra0 essid "STA's SSID"
+
+Example IV: STA with AP using WPAPSK/TKIP(Authentication/Encryption)
+    1. iwconfig ra0 mode managed
+    2. iwpriv ra0 set AuthMode=WPAPSK
+    3. iwpriv ra0 set EncrypType=TKIP
+    4. iwpriv ra0 set WPAPSK="AP's wpa-preshared key"
+    5. iwconfig ra0 essid "AP's SSID"
+
+Example V: STA with AP using WPAPSK/AES(Authentication/Encryption)
+    1. iwconfig ra0 mode managed
+    2. iwpriv ra0 set AuthMode=WPAPSK
+    3. iwpriv ra0 set EncrypType=AES
+    5. iwpriv ra0 set WPAPSK="AP's wpa-preshared key"
+    6. iwconfig ra0 essid "AP's SSID"
+
+
+
+iwpriv
+=================
+This is detailed explanation of each parameters for iwpriv.
+Before reading this document, make sure you already read README.
+
+----------------------------------------------------------------------
+USAGE:
+    iwpriv ra0 set [parameters]=[val]
+
+where
+
+[parameters]    [val] range             explanation
+------------    --------------------    ---------------------
+CountryRegion   {0~7}                   Set country region
+                                        0: use 1 ~ 11 Channel
+                                        1: use 1 ~ 11 Channel
+                                        2: use 1 ~ 13 Channel
+                                        3: use 10, 11 Channel
+                                        4: use 10 ~ 13 Channel
+                                        5: use 14 Channel
+                                        6: use 1 ~ 14 Channel
+                                        7: use 3 ~ 9 Channel
+
+WirelessMode    {0~2}                   Set Wireless Mode
+                                        0:11b/g mixed, 1:11B only
+
+TxRate          {0~12}                  Set TxRate
+                                        0:Auto, 1:1Mbps, 2:2Mbps,
+                                        3:5.5Mbps, 4:11Mbps, 5:6Mbps,
+                                        6:9Mbps, 7:12Mbps, 8:18Mbps,
+                                        9:24Mbps, 10:36Mbps,
+                                        11:48Mbps, 12:54Mbps
+
+BGProtection    {0~2}                   Set 11B/11G Protection
+                                        0:Auto, 1:Always on,
+                                        2:Always off
+
+TxPreamble      {0~2}                   Set TxPreamble
+                                        0:Preamble Long,
+                                        1:Preamble Short,
+                                        2:Auto
+
+TxBurst         {0,1}                   Enable/Disable
+                                        0:Disable, 1:Enable
+
+TurboRate       {0,1}                   Enable/Disable
+                                        0:Disable, 1:Enable
+
+AdhocOfdm       {0, 1}                  Adhoc mode OFDM
+                                        0: Disallow 1: Allow
+
+AuthMode        {OPEN,SHARED,WPAPSK}    Authentication mode
+
+EncrypType      {NONE,WEP,TKIP,AES}     Encryption Type
+
+WPAPSK          {8~63 ASCII or 64 HEX characters}
+                                        WPA Pre-Shared Key
+
+ApClient        {0,1}                   Set ApClient mode
+                                        0:Disable, 1:Enable
+
+iwlist
+=================
+This is detailed explanation of each parameters for iwlist.
+
+----------------------------------------------------------------------
+
+iwlist ra0 scanning; list the result after scanning(site survey)
+
+
+
+
+----------------------------------------------------------------------
+
+
+Deprecated iwpriv
+=================
+
+*** PLEASE DO NOT USE THESE FUNCTIONS, THIS IS FOR HISTORICAL
+    REFERENCE ONLY ***
+As the configuration utility still uses some iwpriv commands they have
+not been removed from the driver yet. These commands are likely to
+dissapear if the utility is updated.
+
+** ALL THESE COMMANDS HAVE A IWCONFIG REPLACEMENT, USE IT ****
+
+SSID           {0~z, less than 32 characters}       Set SoftAP SSID
+
+Channel         {1~14} depends on country region    Set Channel
+
+RTSThreshold    {1~2347}                            Set RTS Threshold
+
+FragThreshold   {256~2346}                          Set Fragment Threshold
+
+NetworkType     {Infra,Adhoc}                       Set Network type
+
+DefaultKeyID    {1~4}                               Set Default Key ID
+
+Key1            {5 ascii characters or              Set Key1 String
+                10 hex number or
+                13 ascii characters or
+                26 hex numbers}
+
+Key2            {5 ascii characters or              Set Key2 String
+                10 hex number or
+                13 ascii characters or
+                26 hex numbers}
+
+Key3            {5 ascii characters or              Set Key3 String
+                10 hex number or
+                13 ascii characters or
+                26 hex numbers}
+
+Key4            {5 ascii characters or              Set Key4 String
+                10 hex number or
+                13 ascii characters or
+                26 hex numbers}
diff -Nur rt2500-1.1.0-b4/Module/load rt2500-cvs-2007061011/Module/load
--- rt2500-1.1.0-b4/Module/load	2006-06-17 22:12:58.000000000 +0200
+++ rt2500-cvs-2007061011/Module/load	1970-01-01 01:00:00.000000000 +0100
@@ -1,3 +0,0 @@
-/sbin/insmod rt2500.o
-/sbin/ifconfig ra0 inet 192.168.1.234 up
-/sbin/route add default gw 192.168.1.1
\ Kein Zeilenumbruch am Dateiende.
diff -Nur rt2500-1.1.0-b4/Module/md5.c rt2500-cvs-2007061011/Module/md5.c
--- rt2500-1.1.0-b4/Module/md5.c	2006-06-17 22:12:58.000000000 +0200
+++ rt2500-cvs-2007061011/Module/md5.c	2007-05-29 05:49:17.000000000 +0200
@@ -1,38 +1,38 @@
-/*************************************************************************** 
- * RT2400/RT2500 SourceForge Project - http://rt2x00.serialmonkey.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.                          * 
- *                                                                         * 
- *   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.             * 
- *                                                                         * 
- *   Licensed under the GNU GPL                                            * 
- *   Original code supplied under license from RaLink Inc, 2004.           * 
+/***************************************************************************
+ * RT2400/RT2500 SourceForge Project - http://rt2x00.serialmonkey.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.                          *
+ *                                                                         *
+ *   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.             *
+ *                                                                         *
+ *   Licensed under the GNU GPL                                            *
+ *   Original code supplied under license from RaLink Inc, 2004.           *
  *   This MD5 code is based on code from Dynamics -- HUT Mobile IP         *
  *   Copyright (C) 1998-2001, Dynamics group                               *
- ***************************************************************************/ 
+ ***************************************************************************/
 
- /*************************************************************************** 
+ /***************************************************************************
  *      Module Name: md5.c
- *              
+ *
  *      Abstract: contain MD5 and AES cipher algorithm
- *              
- *      Revision History: 
- *      Who             When            What 
- *      --------        -----------     ----------------------------- 
- *      JanL            28th Oct 03     Initial code     
- *      MarkW           8th  Dec 04     Baseline code  
- ***************************************************************************/ 
+ *
+ *      Revision History:
+ *      Who             When            What
+ *      --------        -----------     -----------------------------
+ *      JanL            28th Oct 03     Initial code
+ *      MarkW           8th  Dec 04     Baseline code
+ ***************************************************************************/
 
 #include "rt_config.h"
 
@@ -48,7 +48,8 @@
  * 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)
+void md5_mac(UCHAR *key, ULONG key_len, UCHAR *data, ULONG data_len,
+	     UCHAR *mac)
 {
     MD5_CTX context;
 
@@ -71,12 +72,13 @@
  * 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)
+void hmac_md5(UCHAR *key, ULONG key_len, UCHAR *data, ULONG data_len,
+	      UCHAR *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];
+    UCHAR k_ipad[65]; /* inner padding - key XORd with ipad */
+    UCHAR k_opad[65]; /* outer padding - key XORd with opad */
+    UCHAR tk[16];
     int i;
 
     //assert(key != NULL && data != NULL && mac != NULL);
@@ -128,25 +130,6 @@
     MD5Final(mac, &context);             /* finish up 2nd pass */
 }
 
-
-/* ===== start - public domain MD5 implementation ===== */
-/*
- * This code implements the MD5 message-digest algorithm.
- * The algorithm is due to Ron Rivest.  This code was
- * written by Colin Plumb in 1993, no copyright is claimed.
- * This code is in the public domain; do with it what you wish.
- *
- * Equivalent code is available from RSA Data Security, Inc.
- * This code has been tested against that, and is equivalent,
- * except that you don't need to include two pages of legalese
- * with every copy.
- *
- * To compute the message digest of a chunk of bytes, declare an
- * MD5Context structure, pass it to MD5Init, call MD5Update as
- * needed on buffers full of bytes, and then call MD5Final, which
- * will fill a supplied 16-byte array with the digest.
- */
-
 #ifndef BIG_ENDIAN
 #define byteReverse(buf, len)   /* Nothing */
 #else
@@ -160,588 +143,808 @@
 }
 #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 )
+
 /*
- * Start MD5 accumulation.  Set bit count to 0 and buffer to mysterious
- * initialization constants.
+ *  Function Description:
+ *      Initiate MD5 Context satisfied in RFC 1321
+ *
+ *  Arguments:
+ *      pCtx        Pointer	to MD5 context
+ *
+ *  Return Value:
+ *      None
  */
-void MD5Init(struct MD5Context *ctx)
+VOID MD5Init(MD5_CTX *pCtx)
 {
-    ctx->buf[0] = 0x67452301;
-    ctx->buf[1] = 0xefcdab89;
-    ctx->buf[2] = 0x98badcfe;
-    ctx->buf[3] = 0x10325476;
+    pCtx->Buf[0] = 0x67452301;
+    pCtx->Buf[1] = 0xefcdab89;
+    pCtx->Buf[2] = 0x98badcfe;
+    pCtx->Buf[3] = 0x10325476;
 
-    ctx->bits[0] = 0;
-    ctx->bits[1] = 0;
+    pCtx->LenInBitCount[0] = 0;
+    pCtx->LenInBitCount[1] = 0;
 }
 
 /*
- * Update context to reflect the concatenation of another buffer full
- * of bytes.
+ *  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(struct MD5Context *ctx, unsigned char *buf, unsigned len)
+VOID MD5Update(MD5_CTX *pCtx, UCHAR *pData, ULONG LenInBytes)
 {
-    u32 t;
+	ULONG TfTimes;
+	ULONG temp;
+	unsigned int i;
 
-    /* Update bitcount */
+	temp = pCtx->LenInBitCount[0];
 
-    t = ctx->bits[0];
-    if ((ctx->bits[0] = t + ((u32) len << 3)) < t)
-        ctx->bits[1]++;     /* Carry from low to high */
-    ctx->bits[1] += len >> 29;
-
-    t = (t >> 3) & 0x3f;    /* Bytes already in shsInfo->data */
-
-    /* Handle any leading odd-sized chunks */
-
-    if (t) {
-        unsigned char *p = (unsigned char *) ctx->in + t;
-
-        t = 64 - t;
-        if (len < t) {
-            memcpy(p, buf, len);
-            return;
-        }
-        memcpy(p, buf, t);
-        byteReverse(ctx->in, 16);
-        MD5Transform(ctx->buf, (u32 *) ctx->in);
-        buf += t;
-        len -= t;
-    }
-    /* Process data in 64-byte chunks */
+	pCtx->LenInBitCount[0] =
+		(ULONG) (pCtx->LenInBitCount[0] + (LenInBytes << 3));
 
-    while (len >= 64) {
-        memcpy(ctx->in, buf, 64);
-        byteReverse(ctx->in, 16);
-        MD5Transform(ctx->buf, (u32 *) ctx->in);
-        buf += 64;
-        len -= 64;
-    }
+	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) {
+			memcpy(pAds, (UCHAR *) pData, LenInBytes);
+			return;
+		}
 
-    /* Handle any remaining bytes of data. */
+		memcpy(pAds, (UCHAR *) pData, 64 - temp);
+		byteReverse(pCtx->Input, 16);
+		MD5Transform(pCtx->Buf, (ULONG *) pCtx->Input);
 
-    memcpy(ctx->in, buf, len);
+		pData += 64 - temp;
+		LenInBytes -= 64 - temp;
+	}			// end of if (temp)
+
+	TfTimes = (LenInBytes >> 6);
+
+	for (i = TfTimes; i > 0; i--) {
+		memcpy(pCtx->Input, (UCHAR *) pData, 64);
+		byteReverse(pCtx->Input, 16);
+		MD5Transform(pCtx->Buf, (ULONG *) pCtx->Input);
+		pData += 64;
+		LenInBytes -= 64;
+	}			// end of for
+
+	// buffering lacks of 64-byte data
+	if (LenInBytes)
+		memcpy(pCtx->Input, (UCHAR *) pData, LenInBytes);
 }
 
 /*
- * Final wrapup - pad to 64-byte boundary with the bit pattern
- * 1 0* (64-bit count of bits processed, MSB-first)
+ *  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(unsigned char digest[16], struct MD5Context *ctx)
+VOID MD5Final(UCHAR Digest[16], MD5_CTX *pCtx)
 {
-    unsigned count;
-    unsigned char *p;
-
-    /* Compute number of bytes mod 64 */
-    count = (ctx->bits[0] >> 3) & 0x3F;
-
-    /* Set the first char of padding to 0x80.  This is safe since there is
-       always at least one byte free */
-    p = ctx->in + count;
-    *p++ = 0x80;
-
-    /* Bytes of padding needed to make 64 bytes */
-    count = 64 - 1 - count;
-
-    /* Pad out to 56 mod 64 */
-    if (count < 8) {
-        /* Two lots of padding:  Pad the first block to 64 bytes */
-        memset(p, 0, count);
-        byteReverse(ctx->in, 16);
-        MD5Transform(ctx->buf, (u32 *) ctx->in);
-
-        /* Now fill the next block with 56 bytes */
-        memset(ctx->in, 0, 56);
-    } else {
-        /* Pad block to 56 bytes */
-        memset(p, 0, count - 8);
-    }
-    byteReverse(ctx->in, 14);
+	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--;
+
+		memset((UCHAR *) pCtx->Input + Remainder + 1, 0,
+			       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, (ULONG *) pCtx->Input);
+	}			// end of if
+
+	// padding bits with crossing block(64-byte based) boundary
+	else {
+		// the first block ===
+		*pAppend = 0x80;
+		PadLenInBytes--;
+
+		memset((UCHAR *) pCtx->Input + Remainder + 1, 0,
+			       (64 - Remainder - 1));
+		PadLenInBytes -= (64 - Remainder - 1);
+
+		byteReverse(pCtx->Input, 16);
+		MD5Transform(pCtx->Buf, (ULONG *) pCtx->Input);
+
+		// the second block ===
+		memset((UCHAR *) pCtx->Input, 0, 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, (ULONG *) pCtx->Input);
+	}			// end of else
+
+	memcpy((UCHAR *) Digest, (ULONG *) pCtx->Buf, 16);	// output
+	byteReverse((UCHAR *) Digest, 4);
+	memset(pCtx, 0, sizeof(pCtx));	// memory free
+}
 
-    /* Append length in bits and transform */
-    ((u32 *) ctx->in)[14] = ctx->bits[0];
-    ((u32 *) ctx->in)[15] = ctx->bits[1];
+/*
+ *  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(ULONG Buf[4], ULONG Mes[16])
+{
+	ULONG Reg[4], Temp;
+	unsigned int i;
 
-    MD5Transform(ctx->buf, (u32 *) ctx->in);
-    byteReverse((unsigned char *) ctx->buf, 4);
-    memcpy(digest, ctx->buf, 16);
-    memset(ctx, 0, sizeof(ctx));  /* In case it's sensitive */
+	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 ULONG 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];
 }
 
-//#ifndef ASM_MD5
-#if 1
+/* =========================  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) )
 
-/* The four core functions - F1 is optimized somewhat */
-
-/* #define F1(x, y, z) (x & y | ~x & z) */
-#define F1(x, y, z) (z ^ (x & (y ^ z)))
-#define F2(x, y, z) F1(z, x, y)
-#define F3(x, y, z) (x ^ y ^ z)
-#define F4(x, y, z) (y ^ (x | ~z))
+//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;
 
-/* This is the central step in the MD5 algorithm. */
-#define MD5STEP(f, w, x, y, z, data, s) \
-    ( w += f(x, y, z) + data,  w =( w<<s | w>>(32-s))&0xffffffff,  w += x )
+	pCtx->LenInBitCount[0] = 0;
+	pCtx->LenInBitCount[1] = 0;
+}
 
 /*
- * The core of the MD5 algorithm, this alters an existing MD5 hash to
- * reflect the addition of 16 longwords of new data.  MD5Update blocks
- * the data and converts bytes into longwords for this routine.
+ *  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)
  */
-void MD5Transform(u32 buf[4], u32 in[16])
+UCHAR SHAUpdate(SHA_CTX * pCtx, UCHAR * pData, ULONG LenInBytes)
 {
-    register u32 a, b, c, d;
+	ULONG TfTimes;
+	ULONG temp1, temp2;
+	unsigned int i;
+	UCHAR err = 1;
+
+	temp1 = pCtx->LenInBitCount[0];
+	temp2 = pCtx->LenInBitCount[1];
+
+	pCtx->LenInBitCount[0] =
+	    (ULONG) (pCtx->LenInBitCount[0] + (LenInBytes << 3));
+	if (pCtx->LenInBitCount[0] < temp1)
+		pCtx->LenInBitCount[1]++;	//carry in
+
+	pCtx->LenInBitCount[1] =
+	    (ULONG) (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) {
+			memcpy(pAds, (UCHAR *) pData, LenInBytes);
+			return (0);
+		}
+
+		memcpy(pAds, (UCHAR *) pData, 64 - temp1);
+		byteReverse((UCHAR *) pCtx->Input, 16);
+
+		memset((UCHAR *) pCtx->Input + 64, 0, 16);
+		SHATransform(pCtx->Buf, (ULONG *) pCtx->Input);
+
+		pData += 64 - temp1;
+		LenInBytes -= 64 - temp1;
+	}			// end of if (temp1)
+
+	TfTimes = (LenInBytes >> 6);
+
+	for (i = TfTimes; i > 0; i--) {
+		memcpy(pCtx->Input, (UCHAR *) pData, 64);
+		byteReverse((UCHAR *) pCtx->Input, 16);
+
+		memset((UCHAR *) pCtx->Input + 64, 0, 16);
+		SHATransform(pCtx->Buf, (ULONG *) pCtx->Input);
+		pData += 64;
+		LenInBytes -= 64;
+	}			// end of for
+
+	// buffering lacks of 64-byte data
+	if (LenInBytes)
+		memcpy(pCtx->Input, (UCHAR *) pData, LenInBytes);
 
-    a = buf[0];
-    b = buf[1];
-    c = buf[2];
-    d = buf[3];
-
-    MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);
-    MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);
-    MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);
-    MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);
-    MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);
-    MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);
-    MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);
-    MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);
-    MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);
-    MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);
-    MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);
-    MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);
-    MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);
-    MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);
-    MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);
-    MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);
-
-    MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);
-    MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);
-    MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);
-    MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);
-    MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);
-    MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);
-    MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);
-    MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);
-    MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);
-    MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);
-    MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);
-    MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);
-    MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);
-    MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);
-    MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);
-    MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);
-
-    MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);
-    MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);
-    MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);
-    MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);
-    MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);
-    MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);
-    MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);
-    MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);
-    MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);
-    MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);
-    MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);
-    MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);
-    MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);
-    MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);
-    MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);
-    MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);
-
-    MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);
-    MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);
-    MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);
-    MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);
-    MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);
-    MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);
-    MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);
-    MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);
-    MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);
-    MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);
-    MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);
-    MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);
-    MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);
-    MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);
-    MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);
-    MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);
-
-    buf[0] += a;
-    buf[1] += b;
-    buf[2] += c;
-    buf[3] += d;
+	return (0);
 }
-#endif
 
-void SHAInit(SHA_CTX *ctx) {
-    int i;
- 
-    ctx->lenW = 0;
-    ctx->sizeHi = ctx->sizeLo = 0;
- 
-    /* Initialize H with the magic constants (see FIPS180 for constants)
-     */
-    ctx->H[0] = 0x67452301L;
-    ctx->H[1] = 0xefcdab89L;
-    ctx->H[2] = 0x98badcfeL;
-    ctx->H[3] = 0x10325476L;
-    ctx->H[4] = 0xc3d2e1f0L;
- 
-    for (i = 0; i < 80; i++)
-        ctx->W[i] = 0;
- }
-
-#define SHA_ROTL(X,n) ((((X) << (n)) | ((X) >> (32-(n)))) & 0xffffffffL)
- 
-void SHAHashBlock(SHA_CTX *ctx) {
-    int t;
-    unsigned long A,B,C,D,E,TEMP;
- 
-    for (t = 16; t <= 79; t++)
-        ctx->W[t] = SHA_ROTL(ctx->W[t-3] ^ ctx->W[t-8] ^ ctx->W[t-14] ^ ctx->W[t-16], 1);
- 
-    A = ctx->H[0];
-    B = ctx->H[1];
-    C = ctx->H[2];
-    D = ctx->H[3];
-    E = ctx->H[4];
- 
-    for (t = 0; t <= 19; t++) {
-        TEMP = (SHA_ROTL(A,5) + (((C^D)&B)^D)     + E + ctx->W[t] + 0x5a827999L) & 0xffffffffL;
-        E = D; D = C; C = SHA_ROTL(B, 30); B = A; A = TEMP;
-    }
-    for (t = 20; t <= 39; t++) {
-        TEMP = (SHA_ROTL(A,5) + (B^C^D)           + E + ctx->W[t] + 0x6ed9eba1L) & 0xffffffffL;
-        E = D; D = C; C = SHA_ROTL(B, 30); B = A; A = TEMP;
-    }
-    for (t = 40; t <= 59; t++) {
-        TEMP = (SHA_ROTL(A,5) + ((B&C)|(D&(B|C))) + E + ctx->W[t] + 0x8f1bbcdcL) & 0xffffffffL;
-        E = D; D = C; C = SHA_ROTL(B, 30); B = A; A = TEMP;
-    }
-    for (t = 60; t <= 79; t++) {
-        TEMP = (SHA_ROTL(A,5) + (B^C^D)           + E + ctx->W[t] + 0xca62c1d6L) & 0xffffffffL;
-        E = D; D = C; C = SHA_ROTL(B, 30); B = A; A = TEMP;
-    }
- 
-    ctx->H[0] += A;
-    ctx->H[1] += B;
-    ctx->H[2] += C;
-    ctx->H[3] += D;
-    ctx->H[4] += E;
+// 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--;
+
+		memset((UCHAR *) pCtx->Input + Remainder + 1, 0,
+			       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);
+		memset((UCHAR *) pCtx->Input + 64, 0, 14);
+		SHATransform(pCtx->Buf, (ULONG *) pCtx->Input);
+	}			// end of if
+
+	// padding bits with crossing block(64-byte based) boundary
+	else {
+		// the first block ===
+		*pAppend = 0x80;
+		PadLenInBytes--;
+
+		memset((UCHAR *) pCtx->Input + Remainder + 1, 0,
+			       (64 - Remainder - 1));
+		PadLenInBytes -= (64 - Remainder - 1);
+
+		byteReverse((UCHAR *) pCtx->Input, 16);
+		memset((UCHAR *) pCtx->Input + 64, 0, 16);
+		SHATransform(pCtx->Buf, (ULONG *) pCtx->Input);
+
+		// the second block ===
+		memset((UCHAR *) pCtx->Input, 0, 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);
+		memset((UCHAR *) pCtx->Input + 64, 0, 16);
+		SHATransform(pCtx->Buf, (ULONG *) pCtx->Input);
+	}			// end of else
+
+	//Output, bytereverse
+	for (i = 0; i < 20; i++) {
+		Digest[i] = (UCHAR) (pCtx->Buf[i >> 2] >> 8 * (3 - (i & 0x3)));
+	}
+
+	memset(pCtx, 0, sizeof(pCtx));	// memory free
 }
 
-void SHAUpdate(SHA_CTX *ctx, unsigned char *dataIn, int len) 
+// The central algorithm of SHA-1, consists of four rounds and
+// twenty steps per round
+VOID SHATransform(ULONG Buf[5], ULONG Mes[20])
 {
-    int i;
- 
-    /* Read the data into W and process blocks as they get full
-     */
-    for (i = 0; i < len; i++) {
-        ctx->W[ctx->lenW / 4] <<= 8;
-        ctx->W[ctx->lenW / 4] |= (unsigned long)dataIn[i];
-        if ((++ctx->lenW) % 64 == 0) {
-            SHAHashBlock(ctx);
-            ctx->lenW = 0;
-        }
-        ctx->sizeLo += 8;
-        ctx->sizeHi += (ctx->sizeLo < 8);
-    }
+	ULONG Reg[5], Temp;
+	unsigned int i;
+	ULONG W[80];
+
+	static ULONG 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];
 }
 
-
-void SHAFinal(SHA_CTX *ctx, unsigned char hashout[20]) {
-    unsigned char pad0x80 = 0x80;
-    unsigned char pad0x00 = 0x00;
-    unsigned char padlen[8];
-    int i;
- 
-    /* Pad with a binary 1 (e.g. 0x80), then zeroes, then length
-     */
-    padlen[0] = (unsigned char)((ctx->sizeHi >> 24) & 255);
-    padlen[1] = (unsigned char)((ctx->sizeHi >> 16) & 255);
-    padlen[2] = (unsigned char)((ctx->sizeHi >> 8) & 255);
-    padlen[3] = (unsigned char)((ctx->sizeHi >> 0) & 255);
-    padlen[4] = (unsigned char)((ctx->sizeLo >> 24) & 255);
-    padlen[5] = (unsigned char)((ctx->sizeLo >> 16) & 255);
-    padlen[6] = (unsigned char)((ctx->sizeLo >> 8) & 255);
-    padlen[7] = (unsigned char)((ctx->sizeLo >> 0) & 255);
-    SHAUpdate(ctx, &pad0x80, 1);
-    while (ctx->lenW != 56)
-        SHAUpdate(ctx, &pad0x00, 1);
-    SHAUpdate(ctx, padlen, 8);
- 
-    /* Output hash
-     */
-    for (i = 0; i < 20; i++) {
-        hashout[i] = (unsigned char)(ctx->H[i / 4] >> 24);
-        ctx->H[i / 4] <<= 8;
-    }
- 
-    /*
-     *  Re-initialize the context (also zeroizes contents)
-     */
-    SHAInit(ctx); 
-}
+/* =========================  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
+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 \
+#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)
+	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
+#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
+#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
+#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
+#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
+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 \
+#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)
+	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
+#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
+#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
+#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
+#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
+static uint32 RCON[10] = {
+	0x01000000, 0x02000000, 0x04000000, 0x08000000,
+	0x10000000, 0x20000000, 0x40000000, 0x80000000,
+	0x1B000000, 0x36000000
 };
 
-/* key schedule tables */
+/* key schedule	tables */
 
 static int KT_init = 1;
 
@@ -750,451 +953,445 @@
 static uint32 KT2[256];
 static uint32 KT3[256];
 
-/* platform-independant 32-bit integer manipulation macros */
+/* 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 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)       );       \
+#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 aes_set_key( aes_context *ctx, uint8 *key, int nbits )
+int 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 */
+	int i;
+	uint32 *RK, *SK;
 
-    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] ];
-        }
+	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++;
 
-        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 );
+	return (0);
 }
 
-/* AES 128-bit block encryption routine */
+/* AES 128-bit block encryption	routine	*/
 
-void aes_encrypt(aes_context *ctx, uint8 input[16], uint8 output[16] )
+void aes_encrypt(aes_context * ctx, uint8 input[16], uint8 output[16])
 {
-    uint32 *RK, X0, X1, X2, X3, Y0, Y1, Y2, Y3;
+	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;
+	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		 ) ];	\
+}
 
-    X0 = RK[0] ^ ( FSb[ (uint8) ( Y0 >> 24 ) ] << 24 ) ^
-                 ( FSb[ (uint8) ( Y1 >> 16 ) ] << 16 ) ^
-                 ( FSb[ (uint8) ( Y2 >>  8 ) ] <<  8 ) ^
-                 ( FSb[ (uint8) ( Y3       ) ]       );
+	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);
+}
 
-    X1 = RK[1] ^ ( FSb[ (uint8) ( Y1 >> 24 ) ] << 24 ) ^
-                 ( FSb[ (uint8) ( Y2 >> 16 ) ] << 16 ) ^
-                 ( FSb[ (uint8) ( Y3 >>  8 ) ] <<  8 ) ^
-                 ( FSb[ (uint8) ( Y0       ) ]       );
+/* AES 128-bit block decryption	routine	*/
 
-    X2 = RK[2] ^ ( FSb[ (uint8) ( Y2 >> 24 ) ] << 24 ) ^
-                 ( FSb[ (uint8) ( Y3 >> 16 ) ] << 16 ) ^
-                 ( FSb[ (uint8) ( Y0 >>  8 ) ] <<  8 ) ^
-                 ( FSb[ (uint8) ( Y1       ) ]       );
+void aes_decrypt(aes_context * ctx, uint8 input[16], uint8 output[16])
+{
+	uint32 *RK, X0, X1, X2, X3, Y0, Y1, Y2, Y3;
 
-    X3 = RK[3] ^ ( FSb[ (uint8) ( Y3 >> 24 ) ] << 24 ) ^
-                 ( FSb[ (uint8) ( Y0 >> 16 ) ] << 16 ) ^
-                 ( FSb[ (uint8) ( Y1 >>  8 ) ] <<  8 ) ^
-                 ( FSb[ (uint8) ( Y2       ) ]       );
+	RK = ctx->drk;
 
-    PUT_UINT32( X0, output,  0 );
-    PUT_UINT32( X1, output,  4 );
-    PUT_UINT32( X2, output,  8 );
-    PUT_UINT32( X3, output, 12 );
+	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 128-bit block decryption routine */
+	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);
+}
 
-void aes_decrypt( aes_context *ctx, uint8 input[16], uint8 output[16] )
+void hmac_sha1(unsigned char *text, int text_len, unsigned char *key,
+	       int key_len, unsigned char *digest)
 {
-    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 */
-    }
+	SHA_CTX context;
+	unsigned char k_ipad[65];	/* inner padding - key XORd with ipad */
+	unsigned char 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;
+	}
+
+	/*
+	 * the HMAC_SHA1 transform looks like:
+	 *
+	 * SHA1(K XOR opad, SHA1(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 */
+	memset(k_ipad, 0, sizeof k_ipad);
+	memset(k_opad, 0, sizeof k_opad);
+	memcpy(k_ipad, key, key_len);
+	memcpy(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 */
+}
 
-    /* last round */
+/*
+* 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)
+*/
 
-    RK += 4;
+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;
 
-    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 );
-}
-
-void hmac_sha1(unsigned char *text, int text_len, unsigned char *key, int key_len, unsigned char *digest) 
-{ 
-    SHA_CTX context; 
-    unsigned char k_ipad[65]; /* inner padding - key XORd with ipad */ 
-    unsigned char 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; 
-    } 
-
-    /* 
-    * the HMAC_SHA1 transform looks like: 
-    * 
-    * SHA1(K XOR opad, SHA1(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 */ 
-    memset(k_ipad, 0, sizeof k_ipad); 
-    memset(k_opad, 0, sizeof k_opad); 
-    memcpy(k_ipad, key, key_len); 
-    memcpy(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 */ 
-} 
+	/* 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];
+		}
+	}
+}
 
 /*
-* 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; 
+* 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;
 }
diff -Nur rt2500-1.1.0-b4/Module/md5.h rt2500-cvs-2007061011/Module/md5.h
--- rt2500-1.1.0-b4/Module/md5.h	2006-06-17 22:12:58.000000000 +0200
+++ rt2500-cvs-2007061011/Module/md5.h	2007-05-29 05:49:17.000000000 +0200
@@ -1,94 +1,96 @@
-/*************************************************************************** 
- * RT2400/RT2500 SourceForge Project - http://rt2x00.serialmonkey.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.                          * 
- *                                                                         * 
- *   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.             * 
- *                                                                         * 
- *   Licensed under the GNU GPL                                            * 
- *   Original code supplied under license from RaLink Inc, 2004.           * 
+/***************************************************************************
+ * RT2400/RT2500 SourceForge Project - http://rt2x00.serialmonkey.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.                          *
+ *                                                                         *
+ *   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.             *
+ *                                                                         *
+ *   Licensed under the GNU GPL                                            *
+ *   Original code supplied under license from RaLink Inc, 2004.           *
  *   This MD5 code is based on code from Dynamics -- HUT Mobile IP         *
  *   Copyright (C) 1998-2001, Dynamics group                               *
- ***************************************************************************/ 
+ ***************************************************************************/
 
- /*************************************************************************** 
+ /***************************************************************************
  *      Module Name: md5.h
- *              
+ *
  *      Abstract: contain MD5 and AES cipher algorithm
- *              
- *      Revision History: 
- *      Who             When            What 
- *      --------        -----------     ----------------------------- 
- *      MarkW           8th  Dec 04     Baseline code  
- ***************************************************************************/ 
+ *
+ *      Revision History:
+ *      Who             When            What
+ *      --------        -----------     -----------------------------
+ *      MarkW           8th  Dec 04     Baseline code
+ ***************************************************************************/
 
-#ifndef MD5_H
-#define MD5_H
+#ifndef	__MD5_H__
+#define	__MD5_H__
 
 #define MD5_MAC_LEN 16
 #define SHA_DIGEST_LEN 20
 
-struct MD5Context {
-    u32 buf[4];
-    u32 bits[2];
-    u8 in[64];
-};
+typedef struct _MD5_CTX {
+	ULONG Buf[4];		// buffers of four states
+	UCHAR Input[64];	// input message
+	ULONG 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, ULONG LenInBytes);
+VOID MD5Final(UCHAR Digest[16], MD5_CTX * pCtx);
+VOID MD5Transform(ULONG Buf[4], ULONG Mes[16]);
+
+void md5_mac(UCHAR * key, ULONG key_len, UCHAR * data, ULONG data_len,
+	     UCHAR * mac);
+void hmac_md5(UCHAR * key, ULONG key_len, UCHAR * data, ULONG data_len,
+	      UCHAR * mac);
+
+#endif				// __MD5_H__
+
+/******************************************************************************/
+
+VOID SHAInit(SHA_CTX * pCtx);
+UCHAR SHAUpdate(SHA_CTX * pCtx, UCHAR * pData, ULONG LenInBytes);
+VOID SHAFinal(SHA_CTX * pCtx, UCHAR Digest[20]);
+VOID SHATransform(ULONG Buf[5], ULONG Mes[20]);
+
+void hmac_sha1(unsigned char *text, int text_len, unsigned char *key,
+	       int key_len, unsigned char *digest);
+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);
+
+/******************************************************************************/
+#ifndef	_AES_H
+#define	_AES_H
 
-void MD5Init(struct MD5Context *context);
-void MD5Update(struct MD5Context *context, unsigned char *buf, unsigned len);
-void MD5Final(unsigned char digest[16], struct MD5Context *context);
-void MD5Transform(u32 buf[4], u32 in[16]);
-
-typedef struct MD5Context MD5_CTX;
-
-
-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);
-
-#endif /* MD5_H */
-
-#ifndef _AES_H
-#define _AES_H
-
-#ifndef uint8
-#define uint8  unsigned char
+#ifndef	uint8
+#define	uint8  unsigned	char
 #endif
 
-#ifndef uint32
-#define uint32 unsigned long int
+#ifndef	uint32
+#define	uint32 unsigned	long int
 #endif
 
-typedef struct
-{
-    uint32 erk[64];     /* encryption round keys */
-    uint32 drk[64];     /* decryption round keys */
-    int nr;             /* number of rounds */
-}
-aes_context;
-
-int  aes_set_key( aes_context *ctx, uint8 *key, int nbits );
-void aes_encrypt( aes_context *ctx, uint8 input[16], uint8 output[16] );
-void aes_decrypt( aes_context *ctx, uint8 input[16], uint8 output[16] );
-
-
-void SHAInit(SHA_CTX *ctx);
-void SHAUpdate(SHA_CTX *ctx, unsigned char *dataIn, int len);
-void SHAFinal(SHA_CTX *ctx, unsigned char hashout[20]);
-void SHAHashBlock(SHA_CTX *ctx);
-void hmac_sha1(unsigned char *text, int text_len, unsigned char *key, int key_len, unsigned char *digest);
-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 */
+typedef struct {
+	uint32 erk[64];		/* encryption round     keys */
+	uint32 drk[64];		/* decryption round     keys */
+	int nr;			/* number of rounds     */
+} aes_context;
+
+int aes_set_key(aes_context * ctx, uint8 * key, int nbits);
+void aes_encrypt(aes_context * ctx, uint8 input[16], uint8 output[16]);
+void aes_decrypt(aes_context * ctx, uint8 input[16], uint8 output[16]);
 
+#endif				/* aes.h */
diff -Nur rt2500-1.1.0-b4/Module/mlme.c rt2500-cvs-2007061011/Module/mlme.c
--- rt2500-1.1.0-b4/Module/mlme.c	2006-06-17 22:12:58.000000000 +0200
+++ rt2500-cvs-2007061011/Module/mlme.c	2007-05-15 21:41:34.000000000 +0200
@@ -1,54 +1,54 @@
-/*************************************************************************** 
- * RT2400/RT2500 SourceForge Project - http://rt2x00.serialmonkey.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.                          * 
- *                                                                         * 
- *   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.             * 
- *                                                                         * 
- *   Licensed under the GNU GPL                                            * 
- *   Original code supplied under license from RaLink Inc, 2004.           * 
- ***************************************************************************/ 
+/***************************************************************************
+ * RT2400/RT2500 SourceForge Project - http://rt2x00.serialmonkey.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.                          *
+ *                                                                         *
+ *   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.             *
+ *                                                                         *
+ *   Licensed under the GNU GPL                                            *
+ *   Original code supplied under license from RaLink Inc, 2004.           *
+ ***************************************************************************/
 
- /*************************************************************************** 
+ /***************************************************************************
  *      Module Name: mlme.c
- *              
- *      Abstract: 
- *              
- *      Revision History: 
- *      Who             When            What 
- *      --------        -----------     ----------------------------- 
- *      MarkW           8th  Dec 04     Baseline code  
+ *
+ *      Abstract:
+ *
+ *      Revision History:
+ *      Who             When            What
+ *      --------        -----------     -----------------------------
+ *      MarkW           8th  Dec 04     Baseline code
  *      MarkW           8th  Dec 04     kmalloc ATOMIC fixes
- *      RobinC          10th Dec 04     RFMON Support 
- *      MarkW           10th Dec 04     Rolled in Ralink 1.4.5.0 
- *      Ivo (rt2400)    15th Dec 04     Uninitialised timer 
+ *      RobinC          10th Dec 04     RFMON Support
+ *      MarkW           10th Dec 04     Rolled in Ralink 1.4.5.0
+ *      Ivo (rt2400)    15th Dec 04     Uninitialised timer
  *      MarkW           17th Dec 04     Monitor mode through iwconfig
  *      BrunoH			3rd  Feb 04     Fix for 802.11b adhoc association
- *      JohnC           19th Mar 04     Fixes for quality reporting     
+ *      JohnC           19th Mar 04     Fixes for quality reporting
  * 		MarkW			13th Jun 05		Fix to allow adhoc network creation
- ***************************************************************************/ 
+ ***************************************************************************/
 
 #include "rt_config.h"
 #include <stdarg.h>
 
-// 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 
+// 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 };
 
-                                  //  1      2       5.5      11  
+                                  //  1      2       5.5      11
 UCHAR Phy11BNextRateDownward[] = {RATE_1, RATE_1,   RATE_2,  RATE_5_5};
 UCHAR Phy11BNextRateUpward[]   = {RATE_2, RATE_5_5, RATE_11, RATE_11};
 
@@ -68,10 +68,10 @@
 
 USHORT OldRateUpPER[]   = {    40,  40,  40, 40, 30, 30, 30, 30, 20, 20, 10, 10 }; // in percentage
 USHORT OldRateDownPER[] = {    45,  45,  45, 45, 35, 35, 35, 35, 25, 25, 25, 12 }; // in percentage
-    
+
 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};
-    
+
 RTMP_RF_REGS RF2522RegTable[] = {
 //      ch   R1          R2          R3(TX0~4=0) R4
         {1,  0x94002050, 0x940c1fda, 0x94000101, 0},
@@ -144,10 +144,10 @@
         {14, 0x94032020, 0x94000d1a, 0x94000101, 0x94000a03}
 };
 #define	NUM_OF_2524_CHNL	(sizeof(RF2524RegTable) / sizeof(RTMP_RF_REGS))
-            
+
 RTMP_RF_REGS RF2525RegTable[] = {
 //      ch   R1          R2          R3(TX0~4=0) R4
-        {1,  0x94022020, 0x94080c9e, 0x94060111, 0x94000a1b}, // {1,  0x94022010, 0x9408062e, 0x94060111, 0x94000a23}, 
+        {1,  0x94022020, 0x94080c9e, 0x94060111, 0x94000a1b}, // {1,  0x94022010, 0x9408062e, 0x94060111, 0x94000a23},
         {2,  0x94022020, 0x94080ca2, 0x94060111, 0x94000a1b},
         {3,  0x94022020, 0x94080ca6, 0x94060111, 0x94000a1b},
         {4,  0x94022020, 0x94080caa, 0x94060111, 0x94000a1b},
@@ -157,15 +157,15 @@
         {8,  0x94022020, 0x94080cba, 0x94060111, 0x94000a1b},
         {9,  0x94022020, 0x94080cbe, 0x94060111, 0x94000a1b},
         {10, 0x94022020, 0x94080d02, 0x94060111, 0x94000a1b},
-        {11, 0x94022020, 0x94080d06, 0x94060111, 0x94000a1b}, // {11, 0x94022010, 0x94080682, 0x94060111, 0x94000a23}, 
+        {11, 0x94022020, 0x94080d06, 0x94060111, 0x94000a1b}, // {11, 0x94022010, 0x94080682, 0x94060111, 0x94000a23},
         {12, 0x94022020, 0x94080d0a, 0x94060111, 0x94000a1b},
-        {13, 0x94022020, 0x94080d0e, 0x94060111, 0x94000a1b}, // {13, 0x94022010, 0x94080686, 0x94060111, 0x94000a23}, 
+        {13, 0x94022020, 0x94080d0e, 0x94060111, 0x94000a1b}, // {13, 0x94022010, 0x94080686, 0x94060111, 0x94000a23},
         {14, 0x94022020, 0x94080d1a, 0x94060111, 0x94000a03}
 };
 #define	NUM_OF_2525_CHNL	(sizeof(RF2525RegTable) / sizeof(RTMP_RF_REGS))
 
 RTMP_RF_REGS RF2525HBOffsetRegTable[] = {
-        {1,  0x94022020, 0x94080cbe, 0x94060111, 0x94000a1b},  
+        {1,  0x94022020, 0x94080cbe, 0x94060111, 0x94000a1b},
         {2,  0x94022020, 0x94080d02, 0x94060111, 0x94000a1b},
         {3,  0x94022020, 0x94080d06, 0x94060111, 0x94000a1b},
         {4,  0x94022020, 0x94080d0a, 0x94060111, 0x94000a1b},
@@ -175,9 +175,9 @@
         {8,  0x94022020, 0x94080d1a, 0x94060111, 0x94000a1b},
         {9,  0x94022020, 0x94080d1e, 0x94060111, 0x94000a1b},
         {10, 0x94022020, 0x94080d22, 0x94060111, 0x94000a1b},
-        {11, 0x94022020, 0x94080d26, 0x94060111, 0x94000a1b}, 
+        {11, 0x94022020, 0x94080d26, 0x94060111, 0x94000a1b},
         {12, 0x94022020, 0x94080d2a, 0x94060111, 0x94000a1b},
-        {13, 0x94022020, 0x94080d2e, 0x94060111, 0x94000a1b}, 
+        {13, 0x94022020, 0x94080d2e, 0x94060111, 0x94000a1b},
         {14, 0x94022020, 0x94080d3a, 0x94060111, 0x94000a03}
 };
 
@@ -195,7 +195,7 @@
         {8,  0x94022020, 0x94081192, 0x94060111, 0x94000a0b},
         {9,  0x94022020, 0x94081196, 0x94060111, 0x94000a0b},
         {10, 0x94022020, 0x9408119a, 0x94060111, 0x94000a0b},
-        {11, 0x94022020, 0x9408119e, 0x94060111, 0x94000a0b}, 
+        {11, 0x94022020, 0x9408119e, 0x94060111, 0x94000a0b},
         {12, 0x94022020, 0x940811a2, 0x94060111, 0x94000a0b},
         {13, 0x94022020, 0x940811a6, 0x94060111, 0x94000a0b},
         {14, 0x94022020, 0x940811ae, 0x94060111, 0x94000a1b}
@@ -212,7 +212,7 @@
         {8,  0x94022010, 0x940808aa, 0x94060111, 0x94000a07},
         {9,  0x94022010, 0x940808aa, 0x94060111, 0x94000a1b},
         {10, 0x94022010, 0x940808ae, 0x94060111, 0x94000a07},
-        {11, 0x94022010, 0x940808ae, 0x94060111, 0x94000a1b}, 
+        {11, 0x94022010, 0x940808ae, 0x94060111, 0x94000a1b},
         {12, 0x94022010, 0x940808b2, 0x94060111, 0x94000a07},
         {13, 0x94022010, 0x940808b2, 0x94060111, 0x94000a1b},
         {14, 0x94022010, 0x940808b6, 0x94060111, 0x94000a23}
@@ -238,7 +238,7 @@
         {14, 0x94022020, 0x940011ae, 0x94000101, 0x94000a1b},
 
         // still lack of MMAC(Japan) ch 34,38,42,46
-        
+
         {36, 0x94022010, 0x94018896, 0x94000101, 0x94000a1f},
         {40, 0x94022010, 0x9401889a, 0x94000101, 0x94000a1f},
         {44, 0x94022010, 0x9401889e, 0x94000101, 0x94000a1f},
@@ -247,7 +247,7 @@
         {66, 0x94022010, 0x940188aa, 0x94000101, 0x94000a1f},
         {60, 0x94022010, 0x940188ae, 0x94000101, 0x94000a1f},
         {64, 0x94022010, 0x940188b2, 0x94000101, 0x94000a1f},
-        
+
         {100, 0x94022010, 0x94008802, 0x94000101, 0x94000a0f},
         {104, 0x94022010, 0x94008806, 0x94000101, 0x94000a0f},
         {108, 0x94022010, 0x9400880a, 0x94000101, 0x94000a0f},
@@ -259,7 +259,7 @@
         {132, 0x94022010, 0x94008822, 0x94000101, 0x94000a0f},
         {136, 0x94022010, 0x94008826, 0x94000101, 0x94000a0f},
         {140, 0x94022010, 0x9400882a, 0x94000101, 0x94000a0f},
-        
+
         {149, 0x94022020, 0x940090a6, 0x94000101, 0x94000a07},
         {153, 0x94022020, 0x940090ae, 0x94000101, 0x94000a07},
         {157, 0x94022020, 0x940090b6, 0x94000101, 0x94000a07},
@@ -270,14 +270,14 @@
 /*
     ==========================================================================
     Description:
-        initialize the MLME task and its data structure (queue, spinlock, 
+        initialize the MLME task and its data structure (queue, spinlock,
         timer, state machines).
     Return:
         always return NDIS_STATUS_SUCCESS
     ==========================================================================
 */
 NDIS_STATUS MlmeInit(
-    IN PRTMP_ADAPTER pAd) 
+    IN PRTMP_ADAPTER pAd)
 {
     NDIS_STATUS Status = NDIS_STATUS_SUCCESS;
 
@@ -285,8 +285,8 @@
     	return Status;
 
     DBGPRINT(RT_DEBUG_TRACE, "--> MLME Initialize\n");
-    
-    do 
+
+    do
     {
         pAd->Mlme.Running = FALSE;
         spin_lock_init(&pAd->Mlme.TaskLock);
@@ -298,10 +298,10 @@
         // init state machines
         ASSERT(ASSOC_FUNC_SIZE == MAX_ASSOC_MSG * MAX_ASSOC_STATE);
         AssocStateMachineInit(pAd, &pAd->Mlme.AssocMachine, pAd->Mlme.AssocFunc);
-        
+
         ASSERT(AUTH_FUNC_SIZE == MAX_AUTH_MSG * MAX_AUTH_STATE);
         AuthStateMachineInit(pAd, &pAd->Mlme.AuthMachine, pAd->Mlme.AuthFunc);
-        
+
         ASSERT(AUTH_RSP_FUNC_SIZE == MAX_AUTH_RSP_MSG * MAX_AUTH_RSP_STATE);
         AuthRspStateMachineInit(pAd, &pAd->Mlme.AuthRspMachine, pAd->Mlme.AuthRspFunc);
 
@@ -310,8 +310,8 @@
 
 		ASSERT(WPA_PSK_FUNC_SIZE == MAX_WPA_PSK_MSG * MAX_WPA_PSK_STATE);
         WpaPskStateMachineInit(pAd,&pAd->Mlme.WpaPskMachine,pAd->Mlme.WpaPskFunc);
-		
-        // Since we are using switch/case to implement it, the init is different from the above 
+
+        // 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);
 
@@ -332,7 +332,7 @@
     } while (FALSE);
 
     RTMP_SET_FLAG(pAd, fRTMP_ADAPTER_MLME_INITIALIZED);
-   
+
     DBGPRINT(RT_DEBUG_TRACE, "<-- MLME Initialize\n");
 
     return Status;
@@ -347,83 +347,70 @@
         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. 
+        This task guarantee only one MlmeHandler will run.
     ==========================================================================
  */
 VOID MlmeHandler(
-    IN PRTMP_ADAPTER pAd) 
-{
-#if (LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,0))
-    schedule_work(&pAd->mlme_work);
-}
-
-VOID MlmeWork(void *vpAd)
+    IN PRTMP_ADAPTER pAd)
 {
-    PRTMP_ADAPTER pAd = vpAd;
-#endif
     MLME_QUEUE_ELEM        *Elem = NULL;
     unsigned long flags;
-    int loops = 0;
 
     // Only accept MLME and Frame from peer side, no other (control/data) frame should
     // get into this state machine
 
-    spin_lock_irqsave(&pAd->Mlme.TaskLock,flags);
-    if(pAd->Mlme.Running) 
+    spin_lock_irqsave(&pAd->Mlme.TaskLock, flags);
+    if(pAd->Mlme.Running)
     {
-        spin_unlock_irqrestore(&pAd->Mlme.TaskLock,flags);
+        spin_unlock_irqrestore(&pAd->Mlme.TaskLock, flags);
         return;
-    } 
-    else 
+    }
+    else
     {
         pAd->Mlme.Running = TRUE;
     }
-    spin_unlock_irqrestore(&pAd->Mlme.TaskLock,flags);
+    spin_unlock_irqrestore(&pAd->Mlme.TaskLock, flags);
+
+    while (TRUE) {
+	    spin_lock_irqsave(&pAd->Mlme.Queue.Lock, flags);
+    	if (!MlmeDequeue(&pAd->Mlme.Queue, &Elem)) {
+    		spin_unlock_irqrestore(&pAd->Mlme.Queue.Lock, flags);
+    		break;
+    	}
+   		spin_unlock_irqrestore(&pAd->Mlme.Queue.Lock, flags);
+
+        if (pAd->PortCfg.BssType == BSS_MONITOR)
+        	continue;
 
-    while (MlmeDequeue(&pAd->Mlme.Queue, &Elem)) 
-    {
         //From message type, determine which state machine I should drive
-        if (pAd->PortCfg.BssType != BSS_MONITOR) 
+        switch (Elem->Machine)
         {
-            // if dequeue success
-            switch (Elem->Machine) 
-            {
-                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;
-                default:
-                    DBGPRINT(RT_DEBUG_TRACE, "ERROR: Illegal machine in MlmeHandler()\n");
-                    break;
-            } // end of switch
+            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;
+            default:
+                DBGPRINT(RT_DEBUG_TRACE, "ERROR: Illegal machine in MlmeHandler()\n");
+                break;
+        } // end of switch
 
-            // free MLME element
-            Elem->Occupied = FALSE;
-            Elem->MsgLen = 0;
-            
-        }
-        else
-        {
-            printk(KERN_ERR DRV_NAME "ERROR: empty Elem in MlmeQueue\n");
-        }
-	loops++;
-	if (loops > 50)
-		/* something wrong - avoid locking up the computer solid */
-		break;
+        // free MLME element
+        Elem->Occupied = FALSE;
+        Elem->MsgLen = 0;
     }
 
     spin_lock_irqsave(&pAd->Mlme.TaskLock,flags);
@@ -442,7 +429,7 @@
     ==========================================================================
  */
 VOID MlmeHalt(
-    IN PRTMP_ADAPTER pAd) 
+    IN PRTMP_ADAPTER pAd)
 {
     MLME_DISASSOC_REQ_STRUCT DisReq;
     MLME_QUEUE_ELEM *MsgElem;
@@ -455,8 +442,8 @@
 		return;
 
     DBGPRINT(RT_DEBUG_TRACE, "==> MlmeHalt\n");
-    
-    if (INFRA_ON(pAd) && !RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_NIC_NOT_EXIST)) 
+
+    if (INFRA_ON(pAd) && !RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_NIC_NOT_EXIST))
     {
         COPY_MAC_ADDR(&DisReq.Addr, &pAd->PortCfg.Bssid);
         DisReq.Reason =  REASON_DISASSOC_STA_LEAVING;
@@ -476,7 +463,7 @@
     	// disable BEACON generation and other BEACON related hardware timers
     	AsicDisableSync(pAd);
 	}
-    
+
     // Cancel pending timers
     RTMPCancelTimer(&pAd->Mlme.AssocAux.AssocTimer);
     RTMPCancelTimer(&pAd->Mlme.AssocAux.ReassocTimer);
@@ -496,7 +483,7 @@
 
     RTMPCancelTimer(&pAd->PortCfg.RxAnt.RxAntDiversityTimer);
     udelay(1000);
-    
+
     MlmeQueueDestroy(&pAd->Mlme.Queue);
     StateMachineDestroy(&pAd->Mlme.AssocMachine);
     StateMachineDestroy(&pAd->Mlme.AuthMachine);
@@ -506,11 +493,11 @@
     //NdisFreeSpinLock(&pAd->Mlme.Queue.Lock);
     //NdisFreeSpinLock(&pAd->Mlme.TaskLock);
     // NdisFreeSpinLock(&pAd->PortCfg.MacTab.Lock);
-  
+
     MlmeFreeMemoryHandler(pAd); //Free MLME memory handler
 
     RTMP_CLEAR_FLAG(pAd, fRTMP_ADAPTER_MLME_INITIALIZED);
-   
+
 	DBGPRINT(RT_DEBUG_TRACE, "<== MlmeHalt\n");
 	kfree(MsgElem);
 }
@@ -519,42 +506,33 @@
     ==========================================================================
     Description:
         This routine is executed periodically to -
-        1. Decide if it's a right time to turn on PwrMgmt bit of all 
+        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 
+           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 
+        3. If the calculated ChannelQuality indicated current connection not
            healthy, then a ROAMing attempt is tried here.
     ==========================================================================
  */
 #define ADHOC_BEACON_LOST_TIME      (10*HZ)  // 4 sec
 VOID MlmePeriodicExec(
-    IN  unsigned long data) 
+    IN  unsigned long data)
 {
     RTMP_ADAPTER *pAd = (RTMP_ADAPTER *)data;
     ULONG Now32;
     CSR15_STRUC Csr15;
 
-    if (pAd->PortCfg.BssType == BSS_MONITOR)
-    {
-        RTMPSetTimer(pAd, &pAd->Mlme.PeriodicTimer, MLME_TASK_EXEC_INTV);
-        return;
-    }
-
-	if (RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_RADIO_OFF))
-	{
-	    RTMPSetTimer(pAd, &pAd->Mlme.PeriodicTimer, MLME_TASK_EXEC_INTV);
-		return;
-	}
-
-	if (RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_RESET_IN_PROGRESS))
-	{
-	    RTMPSetTimer(pAd, &pAd->Mlme.PeriodicTimer, MLME_TASK_EXEC_INTV);
+	if ((pAd->PortCfg.BssType == BSS_MONITOR)
+			|| RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_RADIO_OFF)
+			|| RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_RESET_IN_PROGRESS)
+			|| RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_BSS_SCAN_IN_PROGRESS)
+			) {  
+		RTMPSetTimer(pAd, &pAd->Mlme.PeriodicTimer, MLME_TASK_EXEC_INTV);
 		return;
 	}
 
-	// check every 2 second. If rcv-beacon less than 5 in the past 2 second, then AvgRSSI is no longer a 
+	// 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 (pAd->MediaState == NdisMediaStateConnected)
     {
@@ -568,7 +546,7 @@
         else
             pAd->PortCfg.NumOfAvgRssiSample = 0;
     }
-	
+
     Now32 = jiffies;
 
 	if (pAd->RalinkCounters.MgmtRingFullCount >= 2)
@@ -579,7 +557,7 @@
 	{
 		pAd->RalinkCounters.MgmtRingFullCount = 0;
 	}
-    
+
 	if ((pAd->PortCfg.bBlockAssoc == TRUE) && (pAd->PortCfg.LastMicErrorTime + (60 * HZ) < Now32))
 	{
 		pAd->PortCfg.bBlockAssoc = FALSE;
@@ -600,11 +578,11 @@
 	}
 
 
-#ifndef	WIFI_TEST        
+#ifndef	WIFI_TEST
     // danamic tune BBP R17 to find a balance between sensibility and noise isolation
-    // 2003-12-05 For 2560C and before, to avoid collision with MAC ASIC, limit 
+    // 2003-12-05 For 2560C and before, to avoid collision with MAC ASIC, limit
     //   BBP R17 tuning to be within 20 seconds after LINK UP. 2560D (R0=4) and
-    //   after can always enable R17 tuning 
+    //   after can always enable R17 tuning
     if (pAd->PortCfg.Rt2560Version >= RT2560_VER_D)
         AsicBbpTuning(pAd);
     else if ((pAd->MediaState == NdisMediaStateConnected) && (pAd->Mlme.PeriodicRound <= 20))
@@ -642,23 +620,23 @@
 		if (pAd->PortCfg.MicErrCnt >= 3)
 		{
 			MLME_DISASSOC_REQ_STRUCT	DisassocReq;
-			
+
             // disassoc from current AP first
         	DBGPRINT(RT_DEBUG_TRACE, "MLME - disassociate with current AP after sending second continuous EAPOL frame\n");
             DisassocParmFill(pAd, &DisassocReq, &pAd->PortCfg.Bssid, REASON_MIC_FAILURE);
-            MlmeEnqueue(&pAd->Mlme.Queue, ASSOC_STATE_MACHINE, MT2_MLME_DISASSOC_REQ, 
+            MlmeEnqueue(&pAd->Mlme.Queue, ASSOC_STATE_MACHINE, MT2_MLME_DISASSOC_REQ,
                         sizeof(MLME_DISASSOC_REQ_STRUCT), &DisassocReq);
 
             pAd->Mlme.CntlMachine.CurrState = CNTL_WAIT_DISASSOC;
 			pAd->PortCfg.bBlockAssoc = TRUE;
 		}
-		
-        else 
+
+        else
         {
             // send out a NULL frame every 10 sec. for what??? inform "PwrMgmt" bit?
             if ((pAd->Mlme.PeriodicRound % 10) == 8)
                 EnqueueNullFrame(pAd, pAd->PortCfg.TxRate);
-    
+
        		if (CQI_IS_BAD(pAd->Mlme.ChannelQuality))
        		{
            		pAd->RalinkCounters.BadCQIAutoRecoveryCount ++;
@@ -669,7 +647,7 @@
        		else if (CQI_IS_FAIR(pAd->Mlme.ChannelQuality) || CQI_IS_POOR(pAd->Mlme.ChannelQuality))
         	{
    	        	// perform aggresive roaming only when SECURITY OFF or WEP64/128;
-   	        	// WPA and WPA-PSK has no aggresive roaming because re-negotiation 
+   	        	// WPA and WPA-PSK has no aggresive roaming because re-negotiation
    	        	// between 802.1x supplicant and authenticator/AAA server is required
    	        	// but can't be guaranteed.
    	        	if (pAd->PortCfg.AuthMode < Ndis802_11AuthModeWPA)
@@ -686,7 +664,7 @@
             // minimum BEACON to tell the peer I'm alive.
             // drawback is that this BEACON won't well align at TBTT boundary.
             RTMP_IO_READ32(pAd, CSR15, &Csr15.word);  // read-n-clear "BcnSent" bit
-            if (Csr15.field.BeaconSent == 0)  
+            if (Csr15.field.BeaconSent == 0)
                 EnqueueBeaconFrame(pAd);              // software send BEACON
         }
         else
@@ -697,14 +675,14 @@
                 (pAd->PortCfg.MaxDesiredRate > RATE_11)  &&
                 ((pAd->PortCfg.Last11bBeaconRxTime + (5 * HZ)) < Now32))
             {
-                DBGPRINT(RT_DEBUG_TRACE, "last 11B peer left, update Tx rates\n"); 
+                DBGPRINT(RT_DEBUG_TRACE, "last 11B peer left, update Tx rates\n");
                 memcpy(pAd->PortCfg.SupportedRates, pAd->PortCfg.IbssConfig.SupportedRates, MAX_LEN_OF_SUPPORTED_RATES);
                 pAd->PortCfg.SupportedRatesLen = pAd->PortCfg.IbssConfig.SupportedRatesLen;
                 MlmeUpdateTxRates(pAd, FALSE);
                 MakeIbssBeacon(pAd);    // supported rates changed
             }
         }
-        
+
 #ifndef	SINGLE_ADHOC_LINKUP
         // 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
@@ -712,7 +690,7 @@
         if ((pAd->PortCfg.LastBeaconRxTime + ADHOC_BEACON_LOST_TIME < Now32) &&
             (pAd->MediaState == NdisMediaStateConnected))
         {
-            DBGPRINT(RT_DEBUG_TRACE, "MMCHK - excessive BEACON lost, last STA in this IBSS, MediaState=Disconnected\n"); 
+            DBGPRINT(RT_DEBUG_TRACE, "MMCHK - excessive BEACON lost, last STA in this IBSS, MediaState=Disconnected\n");
 
             pAd->MediaState = NdisMediaStateDisconnected;
 			// clean up previous SCAN result, add current BSS back to table if any
@@ -731,7 +709,7 @@
 			if ((pAd->PortCfg.BssTab.BssNr==0) && (pAd->Mlme.CntlMachine.CurrState == CNTL_IDLE))
 			{
 				MLME_SCAN_REQ_STRUCT	   ScanReq;
-			
+
 				if ((pAd->PortCfg.LastScanTime + 10 * HZ) < Now32)
 				{
 					DBGPRINT(RT_DEBUG_TRACE, "CNTL - No matching BSS, start a new scan\n");
@@ -745,7 +723,7 @@
 				}
 				else if (pAd->PortCfg.BssType == BSS_INDEP)	// Quit the forever scan when in a very clean room
 					MlmeAutoRecoverNetwork(pAd);
-					//MlmeAutoReconnectLastSSID(pAd);					
+					//MlmeAutoReconnectLastSSID(pAd);
 			}
 			else if (pAd->Mlme.CntlMachine.CurrState == CNTL_IDLE)
 			{
@@ -759,7 +737,7 @@
 				}
 				else
 					MlmeAutoReconnectLastSSID(pAd);
-				
+
 				DBGPRINT(RT_DEBUG_INFO, "pAd->PortCfg.AutoReconnect is TRUE\n");
 			}
 		}
@@ -772,7 +750,7 @@
 
 	RTMPSetTimer(pAd, &pAd->Mlme.PeriodicTimer, MLME_TASK_EXEC_INTV);
 }
-	
+
 VOID MlmeAutoScan(
     IN PRTMP_ADAPTER pAd)
 {
@@ -783,17 +761,17 @@
 
         // tell CNTL state machine NOT to call NdisMSetInformationComplete() after completing
         // this request, because this request is initiated by driver itself.
-        pAd->Mlme.CntlAux.CurrReqIsFromNdis = FALSE; 
-                    
-        MlmeEnqueue(&pAd->Mlme.Queue, 
-                    MLME_CNTL_STATE_MACHINE, 
-                    OID_802_11_BSSID_LIST_SCAN, 
-                    0, 
+        pAd->Mlme.CntlAux.CurrReqIsFromNdis = FALSE;
+
+        MlmeEnqueue(&pAd->Mlme.Queue,
+                    MLME_CNTL_STATE_MACHINE,
+                    OID_802_11_BSSID_LIST_SCAN,
+                    0,
                     NULL);
         MlmeHandler(pAd);
     }
 }
-	
+
 VOID MlmeAutoRecoverNetwork(
     IN PRTMP_ADAPTER pAd)
 {
@@ -808,18 +786,18 @@
 
         // tell CNTL state machine NOT to call NdisMSetInformationComplete() after completing
         // this request, because this request is initiated by driver itself.
-        pAd->Mlme.CntlAux.CurrReqIsFromNdis = FALSE; 
-                    
-        MlmeEnqueue(&pAd->Mlme.Queue, 
-                    MLME_CNTL_STATE_MACHINE, 
-                    OID_802_11_SSID, 
-                    sizeof(NDIS_802_11_SSID), 
+        pAd->Mlme.CntlAux.CurrReqIsFromNdis = FALSE;
+
+        MlmeEnqueue(&pAd->Mlme.Queue,
+                    MLME_CNTL_STATE_MACHINE,
+                    OID_802_11_SSID,
+                    sizeof(NDIS_802_11_SSID),
                     &OidSsid);
         MlmeHandler(pAd);
     }
 
 }
-    
+
 VOID MlmeAutoReconnectLastSSID(
     IN PRTMP_ADAPTER pAd)
 {
@@ -833,12 +811,12 @@
         DBGPRINT(RT_DEBUG_TRACE, "Driver auto reconnect to last OID_802_11_SSID setting - %s\n", pAd->Mlme.CntlAux.Ssid);
 
 		// We will only try this attemp once, therefore change the AutoReconnect flag afterwards.
-        pAd->Mlme.CntlAux.CurrReqIsFromNdis = FALSE; 
-                    
-        MlmeEnqueue(&pAd->Mlme.Queue, 
-                    MLME_CNTL_STATE_MACHINE, 
-                    OID_802_11_SSID, 
-                    sizeof(NDIS_802_11_SSID), 
+        pAd->Mlme.CntlAux.CurrReqIsFromNdis = FALSE;
+
+        MlmeEnqueue(&pAd->Mlme.Queue,
+                    MLME_CNTL_STATE_MACHINE,
+                    OID_802_11_SSID,
+                    sizeof(NDIS_802_11_SSID),
                     &OidSsid);
         MlmeHandler(pAd);
     }
@@ -867,17 +845,17 @@
     for (i = 0; i < pBssTab->BssNr; i++)
     {
         pBss = &pBssTab->BssEntry[i];
-        
-        if ((pBssTab->BssEntry[i].LastBeaconRxTime + BEACON_LOST_TIME) < Now32) 
+
+        if ((pBssTab->BssEntry[i].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(&pBssTab->BssEntry[i].Bssid, &pAd->PortCfg.Bssid))
             continue;    // skip current AP
-        if (CQI_IS_FAIR(pAd->Mlme.ChannelQuality) && (pAd->PortCfg.LastRssi + RSSI_DELTA > pBss->Rssi)) 
+        if (CQI_IS_FAIR(pAd->Mlme.ChannelQuality) && (pAd->PortCfg.LastRssi + RSSI_DELTA > pBss->Rssi))
             continue;    // we're still okay, only AP with stronger RSSI is eligible for roaming
 
-        // AP passing all above rules is put into roaming candidate table        
+        // AP passing all above rules is put into roaming candidate table
         memcpy(&pRoamTab->BssEntry[pRoamTab->BssNr], pBss, sizeof(BSS_ENTRY));
         pRoamTab->BssNr += 1;
     }
@@ -889,23 +867,23 @@
         {
             // tell CNTL state machine NOT to call NdisMSetInformationComplete() after completing
             // this request, because this request is initiated by driver itself, not from NDIS.
-            pAd->Mlme.CntlAux.CurrReqIsFromNdis = FALSE; 
-        
+            pAd->Mlme.CntlAux.CurrReqIsFromNdis = FALSE;
+
           	pAd->RalinkCounters.PoorCQIRoamingCount ++;
             DBGPRINT(RT_DEBUG_TRACE, "MMCHK - Roaming attempt #%d\n", pAd->RalinkCounters.PoorCQIRoamingCount);
             MlmeEnqueue(&pAd->Mlme.Queue, MLME_CNTL_STATE_MACHINE, MT2_MLME_ROAMING_REQ, 0, NULL);
             MlmeHandler(pAd);
         }
     }
-    
+
 }
 
 /*
     ==========================================================================
     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. 
+        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:
@@ -923,11 +901,11 @@
     //
     // monitor TX counters change for the past period
     //
-    TxFailCnt     = pAd->WlanCounters.FailedCount.vv.LowPart - 
+    TxFailCnt     = pAd->WlanCounters.FailedCount.vv.LowPart -
                     pAd->Mlme.PrevWlanCounters.FailedCount.vv.LowPart;
-    TxRetryCnt    = pAd->WlanCounters.RetryCount.vv.LowPart - 
+    TxRetryCnt    = pAd->WlanCounters.RetryCount.vv.LowPart -
                     pAd->Mlme.PrevWlanCounters.RetryCount.vv.LowPart;
-    TxOkCnt       = pAd->WlanCounters.TransmittedFragmentCount.vv.LowPart - 
+    TxOkCnt       = pAd->WlanCounters.TransmittedFragmentCount.vv.LowPart -
                     pAd->Mlme.PrevWlanCounters.TransmittedFragmentCount.vv.LowPart;
     TxCnt = TxOkCnt + TxFailCnt;
 
@@ -947,16 +925,16 @@
     pAd->WlanCounters.FCSErrorCount.vv.LowPart += ((Cnt0 & 0x0000ffff) >> 7);
     if (pAd->WlanCounters.FCSErrorCount.vv.LowPart < OldFcsCount)
        	pAd->WlanCounters.FCSErrorCount.vv.HighPart++;
-            
+
     // Add FCS error count to private counters
     OldFcsCount = pAd->RalinkCounters.RealFcsErrCount.vv.LowPart;
     pAd->RalinkCounters.RealFcsErrCount.vv.LowPart += Cnt0;
     if (pAd->RalinkCounters.RealFcsErrCount.vv.LowPart < OldFcsCount)
     	pAd->RalinkCounters.RealFcsErrCount.vv.HighPart++;
-	
-    RxOkCnt   = pAd->WlanCounters.ReceivedFragmentCount.vv.LowPart - 
+
+    RxOkCnt   = pAd->WlanCounters.ReceivedFragmentCount.vv.LowPart -
                 pAd->Mlme.PrevWlanCounters.ReceivedFragmentCount.vv.LowPart;
-    RxFailCnt = pAd->RalinkCounters.RealFcsErrCount.vv.LowPart - 
+    RxFailCnt = pAd->RalinkCounters.RealFcsErrCount.vv.LowPart -
                 pAd->Mlme.PrevWlanCounters.FCSErrorCount.vv.LowPart;
     RxCnt = RxOkCnt + RxFailCnt;
 
@@ -966,8 +944,8 @@
     //
     // decide ChannelQuality based on: 1)last BEACON received time, 2)last RSSI, 3)TxPER, and 4)RxPER
     //
-    // This value also decides when all roaming fails (or no roaming candidates at 
-    // all), should this STA stay with original AP, or a LinkDown signal 
+    // This value also decides when all roaming fails (or no roaming candidates at
+    // all), should this STA stay with original AP, or a LinkDown signal
     // is indicated to NDIS
     //
     if (INFRA_ON(pAd) &&
@@ -977,7 +955,7 @@
     	// Ignore lost beacon if traffic still goes well
     	if (!RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_RESET_IN_PROGRESS) && (TxOkCnt < 2))
     	{
-        	DBGPRINT(RT_DEBUG_TRACE, "BEACON lost for more than %d sec with TxOkCnt=%d, let CQI = 0\n", BEACON_LOST_TIME/HZ, TxOkCnt); 
+        	DBGPRINT(RT_DEBUG_TRACE, "BEACON lost for more than %d sec with TxOkCnt=%d, let CQI = 0\n", BEACON_LOST_TIME/HZ, TxOkCnt);
         	pAd->Mlme.ChannelQuality = 0;
         	// Lost AP, send disconnect & link down event
 			LinkDown(pAd);
@@ -986,19 +964,19 @@
     else
     {
         // ChannelQuality = W1*RSSI + W2*TxPRR + W3*RxPER    (RSSI 0..100), (TxPER 100..0), (RxPER 100..0)
-        pAd->Mlme.ChannelQuality = (RSSI_WEIGHTING * pAd->PortCfg.LastRssi + 
-                             TX_WEIGHTING * (100 - TxPRR) + 
+        pAd->Mlme.ChannelQuality = (RSSI_WEIGHTING * pAd->PortCfg.LastRssi +
+                             TX_WEIGHTING * (100 - TxPRR) +
                              RX_WEIGHTING* (100 - RxPER)) / 100;
         if (pAd->Mlme.ChannelQuality >= 100)
             pAd->Mlme.ChannelQuality = 100;
     }
-    
+
     // latch current WLAN counters for next check-for-roaming usage
     memcpy(&pAd->Mlme.PrevWlanCounters, &pAd->WlanCounters, sizeof(COUNTER_802_11));
 	// make sure copy the real FCS counts into previous mlme counter structure.
 	pAd->Mlme.PrevWlanCounters.FCSErrorCount = pAd->RalinkCounters.RealFcsErrCount;
-	
-    DBGPRINT(RT_DEBUG_INFO, "MMCHK - CQI= %d, (Tx Fail=%d/Retry=%d/Total=%d, Rx Fail=%d/Total=%d, RSSI=%d dbm)\n", 
+
+    DBGPRINT(RT_DEBUG_INFO, "MMCHK - CQI= %d, (Tx Fail=%d/Retry=%d/Total=%d, Rx Fail=%d/Total=%d, RSSI=%d dbm)\n",
     pAd->Mlme.ChannelQuality, TxFailCnt, TxRetryCnt, TxCnt, RxFailCnt, RxCnt, pAd->PortCfg.LastRssi - pAd->PortCfg.RssiToDbm);
 
 }
@@ -1006,13 +984,13 @@
 /*
     ==========================================================================
     Description:
-        This routine calculates the acumulated TxPER of eaxh TxRate. And 
-        according to the calculation result, change PortCfg.TxRate which 
-        is the stable TX Rate we expect the Radio situation could sustained. 
+        This routine calculates the acumulated TxPER of eaxh TxRate. And
+        according to the calculation result, change PortCfg.TxRate which
+        is the stable TX Rate we expect the Radio situation could sustained.
 
-        PortCfg.TxRate will change dynamically within {RATE_1/RATE_6, MaxTxRate} 
+        PortCfg.TxRate will change dynamically within {RATE_1/RATE_6, MaxTxRate}
     Output:
-        PortCfg.TxRate - 
+        PortCfg.TxRate -
     NOTE:
         call this routine every second
     ==========================================================================
@@ -1032,9 +1010,9 @@
     {
         if (pAd->PortCfg.EnableAutoRateSwitching == FALSE)
             break;
-            
+
         // 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 
+        // but clear all bad history. because the bad history may affect the next
         // Chariot throughput test
         if (TxTotalCnt == 0)
         {
@@ -1043,7 +1021,7 @@
             memset(pAd->DrsCounters.PER, 0, MAX_LEN_OF_SUPPORTED_RATES);
             break;
         }
-        
+
         // decide the next upgrade rate and downgrade rate, if any
         if (pAd->PortCfg.PhyMode == PHY_11BG_MIXED)
         {
@@ -1062,7 +1040,7 @@
         }
         else // PHY_11ABG_MIXED
         {
-            if (pAd->PortCfg.Channel > 14)  
+            if (pAd->PortCfg.Channel > 14)
             {
                 UpRate = Phy11ANextRateUpward[CurrRate];
                 DownRate = Phy11ANextRateDownward[CurrRate];
@@ -1081,7 +1059,7 @@
         if (TxTotalCnt > 15)
         {
             TxErrorRatio = ((pAd->DrsCounters.OneSecTxRetryOkCount + pAd->DrsCounters.OneSecTxFailCount) *100) / TxTotalCnt;
-           
+
             // 2560D and after has implemented ASIC-based OFDM rate switching,
             // but not 2560C & before. thus software use different PER for rate switching
             if (pAd->PortCfg.Rt2560Version >= RT2560_VER_D)
@@ -1106,20 +1084,20 @@
                 fUpgradeQuality = TRUE;
                 if (pAd->DrsCounters.TxQuality[CurrRate])
                     pAd->DrsCounters.TxQuality[CurrRate] --;  // quality very good in CurrRate
-                    
+
                 if (pAd->DrsCounters.TxRateUpPenalty)
                     pAd->DrsCounters.TxRateUpPenalty --;
                 else if (pAd->DrsCounters.TxQuality[UpRate])
                     pAd->DrsCounters.TxQuality[UpRate] --;    // may improve next UP rate's quality
             }
-            
+
         }
-        
+
         // if not enough TX samples, decide by heuristic rules
         else
         {
             TxErrorRatio = 0;
-            
+
             // Downgrade TX quality upon any TX failure in the past second
             if (pAd->DrsCounters.OneSecTxFailCount)
             {
@@ -1155,22 +1133,22 @@
 
         if (pAd->DrsCounters.fNoisyEnvironment)
         {
-            DBGPRINT(RT_DEBUG_TRACE,"DRS(noisy):"); 
+            DBGPRINT(RT_DEBUG_TRACE,"DRS(noisy):");
         }
         else
         {
-            DBGPRINT(RT_DEBUG_TRACE,"DRS:"); 
+            DBGPRINT(RT_DEBUG_TRACE,"DRS:");
         }
-        DBGPRINT(RT_DEBUG_TRACE, "Qty[%d]=%d PER=%d%% %d-sec, Qty[%d]=%d, Pty=%d\n", 
+        DBGPRINT(RT_DEBUG_TRACE, "Qty[%d]=%d PER=%d%% %d-sec, Qty[%d]=%d, Pty=%d\n",
             RateIdToMbps[CurrRate], pAd->DrsCounters.TxQuality[CurrRate],
             TxErrorRatio,
             pAd->DrsCounters.CurrTxRateStableTime,
             RateIdToMbps[UpRate], pAd->DrsCounters.TxQuality[UpRate],
             pAd->DrsCounters.TxRateUpPenalty);
-        
+
         // 2004-3-13 special case: Claim noisy environment
-        //   decide if there was a false "rate down" in the past 2 sec due to noisy 
-        //   environment. if so, we would rather switch back to the higher TX rate. 
+        //   decide if there was a false "rate down" in the past 2 sec due to noisy
+        //   environment. if so, we would rather switch back to the higher TX rate.
         //   criteria -
         //     1. there's a higher rate available, AND
         //     2. there was a rate-down happened, AND
@@ -1179,8 +1157,8 @@
         if ((UpRate != CurrRate)                              &&
             (pAd->DrsCounters.LastSecTxRateChangeAction == 2) &&
             (TxTotalCnt > 15) &&  // this line is to prevent the case that not enough TX sample causing PER=0%
-            (pAd->DrsCounters.PER[CurrRate] < 75) && 
-            ((pAd->DrsCounters.PER[CurrRate] > 20) || (pAd->DrsCounters.fNoisyEnvironment)) && 
+            (pAd->DrsCounters.PER[CurrRate] < 75) &&
+            ((pAd->DrsCounters.PER[CurrRate] > 20) || (pAd->DrsCounters.fNoisyEnvironment)) &&
             ((pAd->DrsCounters.PER[CurrRate]+5) > pAd->DrsCounters.PER[UpRate]))
         {
             // we believe this is a noisy environment. better stay at UpRate
@@ -1218,12 +1196,12 @@
 
             if (JumpUpRate > pAd->PortCfg.MaxTxRate)
                 JumpUpRate = pAd->PortCfg.MaxTxRate;
-            
+
             DBGPRINT(RT_DEBUG_TRACE,"DRS: #### leave Noisy environment ####, RSSI=%d, JumpUpRate=%d\n",
 
             pAd->PortCfg.AvgRssi - RSSI_TO_DBM_OFFSET, RateIdToMbps[JumpUpRate]);
 
-            
+
             if (JumpUpRate > CurrRate)
             {
                 pAd->PortCfg.TxRate = JumpUpRate;
@@ -1231,15 +1209,15 @@
             }
         }
 
-        // we're going to upgrade CurrRate to UpRate at next few seconds, 
-        // but before that, we'd better try a NULL frame @ UpRate and 
+        // we're going to upgrade CurrRate to UpRate at next few seconds,
+        // but before that, we'd better try a NULL frame @ UpRate and
         // see if UpRate is stable or not. If this NULL frame fails, it will
         // downgrade TxQuality[CurrRate], so that STA won't switch to
         // to UpRate in the next second
         // 2004-04-07 requested by David Tung - sent test frames only in OFDM rates
-        if (fUpgradeQuality      && 
-            INFRA_ON(pAd)        && 
-            (UpRate != CurrRate) && 
+        if (fUpgradeQuality      &&
+            INFRA_ON(pAd)        &&
+            (UpRate != CurrRate) &&
             (UpRate > RATE_11)   &&
             (pAd->DrsCounters.TxQuality[CurrRate] <= 1) &&
             (pAd->DrsCounters.TxQuality[UpRate] <= 1))
@@ -1260,16 +1238,16 @@
 #endif
            	pAd->PortCfg.TxRate = DownRate;
         }
-        else if ((pAd->DrsCounters.TxQuality[CurrRate] <= 0) && 
+        else if ((pAd->DrsCounters.TxQuality[CurrRate] <= 0) &&
             (pAd->DrsCounters.TxQuality[UpRate] <=0)         &&
             (CurrRate != UpRate))
         {
             pAd->PortCfg.TxRate = UpRate;
         }
-        
+
     }while (FALSE);
 
-    
+
     // if rate-up happen, clear all bad history of all TX rates
     if (pAd->PortCfg.TxRate > CurrRate)
     {
@@ -1291,7 +1269,7 @@
        	    pAd->DrsCounters.TxRateUpPenalty = 2;           // add 2 sec penalty
        	else                                                // >= 8 sec
        	    pAd->DrsCounters.TxRateUpPenalty = 0;           // no penalty
-       	    
+
         pAd->DrsCounters.CurrTxRateStableTime = 0;
         pAd->DrsCounters.LastSecTxRateChangeAction = 2; // rate DOWN
        	pAd->DrsCounters.TxQuality[pAd->PortCfg.TxRate] = 0;
@@ -1299,7 +1277,7 @@
     }
     else
         pAd->DrsCounters.LastSecTxRateChangeAction = 0; // rate no change
-    
+
     // reset all OneSecxxx counters
     pAd->DrsCounters.OneSecTxFailCount = 0;
     pAd->DrsCounters.OneSecTxOkCount = 0;
@@ -1309,10 +1287,10 @@
 /*
     ==========================================================================
     Description:
-        This routine is executed periodically inside MlmePeriodicExec() after 
+        This routine is executed periodically inside MlmePeriodicExec() after
         association with an AP.
         It checks if PortCfg.Psm is consistent with user policy (recorded in
-        PortCfg.WindowsPowerMode). If not, enforce user policy. However, 
+        PortCfg.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
@@ -1334,7 +1312,7 @@
     // 4. CNTL state machine is not doing SCANning
     // 5. no TX SUCCESS event for the past period
     PowerMode = pAd->PortCfg.WindowsPowerMode;
-    
+
     if (INFRA_ON(pAd) &&
         (PowerMode != Ndis802_11PowerModeCAM) &&
         (pAd->PortCfg.Psm == PWR_ACTIVE) &&
@@ -1344,21 +1322,21 @@
         MlmeSetPsmBit(pAd, PWR_SAVE);
         EnqueueNullFrame(pAd, pAd->PortCfg.TxRate);
     }
-    
+
     // latch current count for next-time comparison
     pAd->Mlme.PrevTxCnt = pAd->WlanCounters.TransmittedFragmentCount.vv.LowPart;
 
 }
 
 VOID MlmeSetPsmBit(
-    IN PRTMP_ADAPTER pAd, 
+    IN PRTMP_ADAPTER pAd,
     IN USHORT psm)
 {
     TXCSR7_STRUC txcsr7;
-    
+
     txcsr7.word = 0;
-    pAd->PortCfg.Psm = psm;    
-    
+    pAd->PortCfg.Psm = psm;
+
     DBGPRINT(RT_DEBUG_TRACE, "MMCHK - change PSM bit to %d <<<\n", psm);
     if (psm == PWR_SAVE)
     {
@@ -1373,14 +1351,14 @@
 }
 
 VOID MlmeSetTxPreamble(
-    IN PRTMP_ADAPTER pAd, 
+    IN PRTMP_ADAPTER pAd,
     IN USHORT TxPreamble)
 {
     ULONG Plcp1MCsr = 0x00700400;     // 0x13c, ACK/CTS PLCP at 1 Mbps
     ULONG Plcp2MCsr = 0x00380401;     // 0x140, ACK/CTS PLCP at 2 Mbps
     ULONG Plcp5MCsr = 0x00150402;     // 0x144, ACK/CTS PLCP at 5.5 Mbps
     ULONG Plcp11MCsr = 0x000b8403;     // 0x148, ACK/CTS PLCP at 11 Mbps
-    
+
     if (TxPreamble == Rt802_11PreambleShort)
     {
         DBGPRINT(RT_DEBUG_TRACE, "MlmeSetTxPreamble (= SHORT PREAMBLE)\n");
@@ -1401,7 +1379,7 @@
     RTMP_IO_WRITE32(pAd, PLCP5MCSR, Plcp5MCsr);
     RTMP_IO_WRITE32(pAd, PLCP11MCSR, Plcp11MCsr);
 }
-    
+
 VOID MlmeUpdateTxRates(
     IN PRTMP_ADAPTER pAd,
     IN BOOLEAN		 bLinkUp)
@@ -1436,14 +1414,14 @@
 
     // 2003-12-10 802.11g WIFI spec disallow OFDM rates in 802.11g ADHOC mode
     if ((pAd->PortCfg.BssType == BSS_INDEP)        &&
-        (pAd->PortCfg.PhyMode == PHY_11BG_MIXED)   && 
+        (pAd->PortCfg.PhyMode == PHY_11BG_MIXED)   &&
         (pAd->PortCfg.AdhocMode == 0) &&
         (MaxDesire > RATE_11))
         MaxDesire = RATE_11;
-    
+
     pAd->PortCfg.MaxDesiredRate = MaxDesire;
-    
-    // Auto rate switching is enabled only if more than one DESIRED RATES are 
+
+    // Auto rate switching is enabled only if more than one DESIRED RATES are
     // specified; otherwise disabled
     if (num <= 1)
         pAd->PortCfg.EnableAutoRateSwitching = FALSE;
@@ -1455,66 +1433,66 @@
     {
         switch (pAd->PortCfg.SupportedRates[i] & 0x7f)
         {
-            case 2: Rate = RATE_1;   
-                    if (pAd->PortCfg.SupportedRates[i] & 0x80) 
-                        BasicRateBitmap |= 0x0001;  
+            case 2: Rate = RATE_1;
+                    if (pAd->PortCfg.SupportedRates[i] & 0x80)
+                        BasicRateBitmap |= 0x0001;
                     break;
-            case 4: Rate = RATE_2;   
-                    if (pAd->PortCfg.SupportedRates[i] & 0x80) 
-                        BasicRateBitmap |= 0x0002;  
+            case 4: Rate = RATE_2;
+                    if (pAd->PortCfg.SupportedRates[i] & 0x80)
+                        BasicRateBitmap |= 0x0002;
                     break;
-            case 11: 
-                    Rate = RATE_5_5; 
-                    if (pAd->PortCfg.SupportedRates[i] & 0x80) 
-                        BasicRateBitmap |= 0x0004;  
+            case 11:
+                    Rate = RATE_5_5;
+                    if (pAd->PortCfg.SupportedRates[i] & 0x80)
+                        BasicRateBitmap |= 0x0004;
                     break;
-            case 22: 
-                    Rate = RATE_11;  
-                    if (pAd->PortCfg.SupportedRates[i] & 0x80) 
-                        BasicRateBitmap |= 0x0008;  
+            case 22:
+                    Rate = RATE_11;
+                    if (pAd->PortCfg.SupportedRates[i] & 0x80)
+                        BasicRateBitmap |= 0x0008;
                     break;
-            case 12: 
-                    Rate = RATE_6;   
-//                  if (pAd->PortCfg.SupportedRates[i] & 0x80) 
-                        BasicRateBitmap |= 0x0010;  
+            case 12:
+                    Rate = RATE_6;
+//                  if (pAd->PortCfg.SupportedRates[i] & 0x80)
+                        BasicRateBitmap |= 0x0010;
                     break;
-            case 18: 
-                    Rate = RATE_9;   
-                    if (pAd->PortCfg.SupportedRates[i] & 0x80) 
-                        BasicRateBitmap |= 0x0020;  
+            case 18:
+                    Rate = RATE_9;
+                    if (pAd->PortCfg.SupportedRates[i] & 0x80)
+                        BasicRateBitmap |= 0x0020;
                     break;
-            case 24: 
-                    Rate = RATE_12;  
-//                  if (pAd->PortCfg.SupportedRates[i] & 0x80) 
-                        BasicRateBitmap |= 0x0040;  
+            case 24:
+                    Rate = RATE_12;
+//                  if (pAd->PortCfg.SupportedRates[i] & 0x80)
+                        BasicRateBitmap |= 0x0040;
                     break;
-            case 36: 
-                    Rate = RATE_18;  
-                    if (pAd->PortCfg.SupportedRates[i] & 0x80) 
-                        BasicRateBitmap |= 0x0080;  
+            case 36:
+                    Rate = RATE_18;
+                    if (pAd->PortCfg.SupportedRates[i] & 0x80)
+                        BasicRateBitmap |= 0x0080;
                     break;
-            case 48: 
-                    Rate = RATE_24;  
-//                  if (pAd->PortCfg.SupportedRates[i] & 0x80) 
-                        BasicRateBitmap |= 0x0100;  
+            case 48:
+                    Rate = RATE_24;
+//                  if (pAd->PortCfg.SupportedRates[i] & 0x80)
+                        BasicRateBitmap |= 0x0100;
                     break;
-            case 72: 
-                    Rate = RATE_36;  
-                    if (pAd->PortCfg.SupportedRates[i] & 0x80) 
-                        BasicRateBitmap |= 0x0200;  
+            case 72:
+                    Rate = RATE_36;
+                    if (pAd->PortCfg.SupportedRates[i] & 0x80)
+                        BasicRateBitmap |= 0x0200;
                     break;
-            case 96: 
-                    Rate = RATE_48;  
-                    if (pAd->PortCfg.SupportedRates[i] & 0x80) 
-                        BasicRateBitmap |= 0x0400;  
+            case 96:
+                    Rate = RATE_48;
+                    if (pAd->PortCfg.SupportedRates[i] & 0x80)
+                        BasicRateBitmap |= 0x0400;
                     break;
-            case 108: 
-                    Rate = RATE_54; 
-                    if (pAd->PortCfg.SupportedRates[i] & 0x80) 
-                        BasicRateBitmap |= 0x0800;  
+            case 108:
+                    Rate = RATE_54;
+                    if (pAd->PortCfg.SupportedRates[i] & 0x80)
+                        BasicRateBitmap |= 0x0800;
                     break;
-            default:  
-                    Rate = RATE_1;   
+            default:
+                    Rate = RATE_1;
                     break;
         }
         if (MaxSupport < Rate)  MaxSupport = Rate;
@@ -1530,7 +1508,7 @@
         pAd->PortCfg.ExpectedACKRate[i] = CurrBasicRate;
         DBGPRINT(RT_DEBUG_INFO,"Expected ACK rate[%d] = %d Mbps\n", RateIdToMbps[i], RateIdToMbps[CurrBasicRate]);
     }
-        
+
     // max tx rate = min {max desire rate, max supported rate}
     if (MaxSupport < MaxDesire)
         pAd->PortCfg.MaxTxRate = MaxSupport;
@@ -1547,13 +1525,13 @@
     {
         if (pAd->PortCfg.Channel > 14)
             pAd->PortCfg.TxRate = RATE_6; // 802.11a
-        else 
+        else
         {
             short dbm = pAd->PortCfg.AvgRssi - pAd->PortCfg.RssiToDbm;
 			if (bLinkUp == TRUE && pAd->PortCfg.MaxTxRate >= RATE_24)
 				pAd->PortCfg.TxRate = RATE_24;
 			else
-            	pAd->PortCfg.TxRate = pAd->PortCfg.MaxTxRate; 
+            	pAd->PortCfg.TxRate = pAd->PortCfg.MaxTxRate;
             if (dbm < -75)
                 pAd->PortCfg.TxRate = RATE_11;
             else if ((dbm < -70) && (pAd->PortCfg.TxRate > RATE_24))
@@ -1568,7 +1546,7 @@
         case PHY_11BG_MIXED:
         case PHY_11B:
             pAd->PortCfg.MlmeRate = RATE_2;
-#ifdef	WIFI_TEST			
+#ifdef	WIFI_TEST
             pAd->PortCfg.RtsRate = RATE_11;
 #else
             pAd->PortCfg.RtsRate = RATE_2;
@@ -1595,10 +1573,10 @@
             pAd->PortCfg.RtsRate = RATE_2;
             break;
     }
-    
-    DBGPRINT(RT_DEBUG_TRACE, " MlmeUpdateTxRates (MaxDesire=%d, MaxSupport=%d, MaxTxRate=%d, Rate Switching =%d)\n", 
+
+    DBGPRINT(RT_DEBUG_TRACE, " MlmeUpdateTxRates (MaxDesire=%d, MaxSupport=%d, MaxTxRate=%d, Rate Switching =%d)\n",
              RateIdToMbps[MaxDesire], RateIdToMbps[MaxSupport], RateIdToMbps[pAd->PortCfg.MaxTxRate], pAd->PortCfg.EnableAutoRateSwitching);
-    DBGPRINT(RT_DEBUG_TRACE, " MlmeUpdateTxRates (TxRate=%d, RtsRate=%d, BasicRateBitmap=0x%04x)\n", 
+    DBGPRINT(RT_DEBUG_TRACE, " MlmeUpdateTxRates (TxRate=%d, RtsRate=%d, BasicRateBitmap=0x%04x)\n",
              RateIdToMbps[pAd->PortCfg.TxRate], RateIdToMbps[pAd->PortCfg.RtsRate], BasicRateBitmap);
 }
 
@@ -1623,14 +1601,14 @@
 	{
 		ASIC_LED_ACT_OFF(pAd);
 	}
-	
+
 	// Clean up old bss table
 	BssTableInit(&pAd->PortCfg.BssTab);
 }
 
 VOID MlmeRadioOn(
     IN PRTMP_ADAPTER pAd)
-{	
+{
 	// Turn on radio
 	RTMP_IO_WRITE32(pAd, PWRCSR0, 0x3f3b3100);
 
@@ -1665,12 +1643,12 @@
  *  \post
  */
 VOID BssTableInit(
-    IN BSS_TABLE *Tab) 
+    IN BSS_TABLE *Tab)
 {
     int i;
 
     Tab->BssNr = 0;
-    for (i = 0; i < MAX_LEN_OF_BSS_TABLE; i++) 
+    for (i = 0; i < MAX_LEN_OF_BSS_TABLE; i++)
     {
         memset(&Tab->BssEntry[i], 0, sizeof(BSS_ENTRY));
     }
@@ -1678,23 +1656,23 @@
 
 /*! \brief search the BSS table by SSID
  *  \param p_tab pointer to the bss table
- *  \param ssid SSID string 
+ *  \param ssid SSID string
  *  \return index of the table, BSS_NOT_FOUND if not in the table
  *  \pre
  *  \post
  *  \note search by sequential search
  */
 ULONG BssTableSearch(
-    IN BSS_TABLE *Tab, 
-    IN PMACADDR Bssid) 
+    IN BSS_TABLE *Tab,
+    IN PMACADDR Bssid)
 {
     UCHAR i;
-    
-    for (i = 0; i < Tab->BssNr; i++) 
+
+    for (i = 0; i < Tab->BssNr; i++)
     {
         //printf("comparing %s and %s\n", p_tab->bss[i].ssid, ssid);
-        if (MAC_ADDR_EQUAL(&(Tab->BssEntry[i].Bssid), Bssid)) 
-        { 
+        if (MAC_ADDR_EQUAL(&(Tab->BssEntry[i].Bssid), Bssid))
+        {
             return i;
         }
     }
@@ -1702,15 +1680,15 @@
 }
 
 VOID BssTableDeleteEntry(
-    IN OUT	BSS_TABLE *Tab, 
-    IN		PMACADDR Bssid) 
+    IN OUT	BSS_TABLE *Tab,
+    IN		PMACADDR Bssid)
 {
     UCHAR i, j;
-    
-    for (i = 0; i < Tab->BssNr; i++) 
+
+    for (i = 0; i < Tab->BssNr; i++)
     {
         //printf("comparing %s and %s\n", p_tab->bss[i].ssid, ssid);
-        if (MAC_ADDR_EQUAL(&(Tab->BssEntry[i].Bssid), Bssid)) 
+        if (MAC_ADDR_EQUAL(&(Tab->BssEntry[i].Bssid), Bssid))
         {
         	for (j = i; j < Tab->BssNr - 1; j++)
         	{
@@ -1724,36 +1702,63 @@
 
 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};
+
+static NDIS_802_11_WEP_STATUS setWepStatus(
+		IN USHORT mask,							// Peer cipher capability set
+		IN NDIS_802_11_WEP_STATUS WepStatus)	// local cipher selection
+{
+	static const unsigned char transtoieee[] = {
+		CIPHER_TYPE_WEP104,0,0,0,CIPHER_TYPE_TKIP,0,CIPHER_TYPE_CCMP,0
+	};
+	static const unsigned char transtondis[] = {
+		Ndis802_11EncryptionDisabled, Ndis802_11WEPEnabled,
+		Ndis802_11Encryption2Enabled, Ndis802_11WEPKeyAbsent,
+		Ndis802_11Encryption3Enabled, Ndis802_11WEPEnabled
+	};
+	NDIS_802_11_WEP_STATUS	wepstatus = Ndis802_11WEPDisabled;
+	USHORT					suite = transtoieee[WepStatus];
+
+	DBGPRINT(RT_DEBUG_TRACE, " - (%s) mask 0x%04x wepstatus %d ieee %d\n",
+			__FUNCTION__, mask, WepStatus, suite);
+
+	if (suite && (mask & 0x01 << suite)) {
+		wepstatus = transtondis[suite];
+	}
+	return wepstatus;
+
+} /* End setWepStatus () */
+
 /*! \brief
- *  \param 
+ *  \param
  *  \return
  *  \pre
  *  \post
  */
 VOID BssEntrySet(
-    IN	PRTMP_ADAPTER	pAd, 
-    OUT BSS_ENTRY *pBss, 
-    IN MACADDR *pBssid, 
-    IN CHAR Ssid[], 
-    IN UCHAR SsidLen, 
-    IN UCHAR BssType, 
-    IN USHORT BeaconPeriod, 
+    IN	PRTMP_ADAPTER	pAd,
+    OUT BSS_ENTRY *pBss,
+    IN MACADDR *pBssid,
+    IN CHAR Ssid[],
+    IN UCHAR SsidLen,
+    IN UCHAR BssType,
+    IN USHORT BeaconPeriod,
     IN BOOLEAN CfExist,
-    IN CF_PARM *pCfParm, 
-    IN USHORT AtimWin, 
-    IN USHORT CapabilityInfo, 
-    IN UCHAR Rates[], 
+    IN CF_PARM *pCfParm,
+    IN USHORT AtimWin,
+    IN USHORT CapabilityInfo,
+    IN UCHAR Rates[],
     IN UCHAR RatesLen,
     IN BOOLEAN ExtendedRateIeExist,
     IN UCHAR Channel,
     IN UCHAR Rssi,
     IN UCHAR Noise,
     IN LARGE_INTEGER TimeStamp,
-    IN PNDIS_802_11_VARIABLE_IEs pVIE) 
+    IN USHORT VarIELen,               // Length of all saved IEs.
+    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;	
+	pBss->Hidden = 1;
 	if (SsidLen > 0)
 	{
 		// For hidden SSID AP, it might send beacon with SSID len equal to 0
@@ -1769,17 +1774,17 @@
 	}
     pBss->BssType = BssType;
     pBss->BeaconPeriod = BeaconPeriod;
-    if (BssType == BSS_INFRA) 
+    if (BssType == BSS_INFRA)
     {
-        if (CfExist) 
+        if (CfExist)
         {
             pBss->CfpCount = pCfParm->CfpCount;
             pBss->CfpPeriod = pCfParm->CfpPeriod;
             pBss->CfpMaxDuration = pCfParm->CfpMaxDuration;
             pBss->CfpDurRemaining = pCfParm->CfpDurRemaining;
         }
-    } 
-    else 
+    }
+    else
     {
         pBss->AtimWin = AtimWin;
     }
@@ -1801,15 +1806,23 @@
 	pBss->FixIEs.Capabilities = CapabilityInfo;
 
 	// New for microsoft Variable IEs
-	if (pVIE->Length != 0)
+	pBss->VarIELen = VarIELen;
+	if (VarIELen != 0)
 	{
-		pBss->VarIELen = pVIE->Length + 2;
-		memcpy(pBss->VarIEs, pVIE, pBss->VarIELen);
-		pBss->WepStatus = BssCipherParse(pBss->VarIEs);
+		memcpy(pBss->VarIEs, pVIE, VarIELen);
+		pBss->CipherCap = BssCipherParse((PBEACON_EID_STRUCT)pBss->VarIEs,
+										VarIELen);
+		if (pBss->CipherCap & (0x01 << CIPHER_TYPE_GRP)) {
+			pBss->WepStatus = setWepStatus(pBss->CipherCap >> 8,
+											pAd->PortCfg.WepStatus);
+		}
+		else {
+			pBss->WepStatus = setWepStatus(pBss->CipherCap,
+											pAd->PortCfg.WepStatus);
+		}
 	}
 	else
 	{
-		pBss->VarIELen = 0;
 		// No SSN ID, if security is on, this is WEP algorithm
 		if  (pBss->Privacy)
 			pBss->WepStatus = Ndis802_11WEPEnabled;
@@ -1817,9 +1830,11 @@
 		else
 			pBss->WepStatus = Ndis802_11WEPDisabled;
 	}
+	DBGPRINT(RT_DEBUG_TRACE, "%s: Ndis WepStatus (Local=%d, Remote=%d)\n",
+			__FUNCTION__, pAd->PortCfg.WepStatus, pBss->WepStatus);
 }
 
-/*! 
+/*!
  *  \brief insert an entry into the bss table
  *  \param p_tab The BSS table
  *  \param Bssid BSSID
@@ -1840,17 +1855,17 @@
  *  \note If SSID is identical, the old entry will be replaced by the new one
  */
 ULONG BssTableSetEntry(
-    IN	PRTMP_ADAPTER	pAd, 
-    OUT BSS_TABLE *Tab, 
-    IN MACADDR *Bssid, 
-    IN CHAR Ssid[], 
-    IN UCHAR SsidLen, 
-    IN UCHAR BssType, 
-    IN USHORT BeaconPeriod, 
-    IN BOOLEAN CfExist, 
-    IN CF_PARM *CfParm, 
-    IN USHORT AtimWin, 
-    IN USHORT CapabilityInfo, 
+    IN	PRTMP_ADAPTER	pAd,
+    OUT BSS_TABLE *Tab,
+    IN MACADDR *Bssid,
+    IN CHAR Ssid[],
+    IN UCHAR SsidLen,
+    IN UCHAR BssType,
+    IN USHORT BeaconPeriod,
+    IN BOOLEAN CfExist,
+    IN CF_PARM *CfParm,
+    IN USHORT AtimWin,
+    IN USHORT CapabilityInfo,
     IN UCHAR Rates[],
     IN UCHAR RatesLen,
     IN BOOLEAN ExtendedRateIeExist,
@@ -1858,50 +1873,52 @@
     IN UCHAR Rssi,
     IN UCHAR Noise,
     IN LARGE_INTEGER TimeStamp,
+    IN USHORT VarIELen,          // Length of all saved IEs.
     IN PNDIS_802_11_VARIABLE_IEs pVIE)
 {
     ULONG   Idx;
+
     Idx = BssTableSearch(Tab, Bssid);
-    if (Idx == BSS_NOT_FOUND) 
+    if (Idx == BSS_NOT_FOUND)
     {
         if (Tab->BssNr >= MAX_LEN_OF_BSS_TABLE)
             return BSS_NOT_FOUND;
-            
+
         Idx = Tab->BssNr;
         BssEntrySet(pAd, &Tab->BssEntry[Idx], Bssid, Ssid, SsidLen, BssType, BeaconPeriod,
                     CfExist, CfParm, AtimWin, CapabilityInfo, Rates, RatesLen, ExtendedRateIeExist,
-                    ChannelNo, Rssi, Noise, TimeStamp, pVIE);
+                    ChannelNo, Rssi, Noise, TimeStamp, VarIELen, pVIE);
         Tab->BssNr++;
-    } 
+    }
     else
     {
         BssEntrySet(pAd, &Tab->BssEntry[Idx], Bssid, Ssid, SsidLen, BssType, BeaconPeriod,
                     CfExist, CfParm, AtimWin, CapabilityInfo, Rates, RatesLen, ExtendedRateIeExist,
-                    ChannelNo, Rssi, Noise, TimeStamp, pVIE);
+                    ChannelNo, Rssi, Noise, TimeStamp, VarIELen, pVIE);
     }
-    
+
     return Idx;
 }
 
 VOID BssTableSsidSort(
-    IN	PRTMP_ADAPTER	pAd, 
-    OUT BSS_TABLE *OutTab, 
-    IN  CHAR Ssid[], 
-    IN  UCHAR SsidLen) 
+    IN	PRTMP_ADAPTER	pAd,
+    OUT BSS_TABLE *OutTab,
+    IN  CHAR Ssid[],
+    IN  UCHAR SsidLen)
 {
     INT i;
     BssTableInit(OutTab);
 
-    for (i = 0; i < pAd->PortCfg.BssTab.BssNr; i++) 
+    for (i = 0; i < pAd->PortCfg.BssTab.BssNr; i++)
     {
         BSS_ENTRY *pInBss = &pAd->PortCfg.BssTab.BssEntry[i];
-        
-        if ((pInBss->BssType == pAd->PortCfg.BssType) && 
+
+        if ((pInBss->BssType == pAd->PortCfg.BssType) &&
 			((pInBss->SsidLen==SsidLen) && RTMPEqualMemory(pInBss->Ssid, Ssid, (ULONG) SsidLen)))
         {
             BSS_ENTRY *pOutBss = &OutTab->BssEntry[OutTab->BssNr];
 
-			// Bss Type matched, SSID matched. 
+			// Bss Type matched, SSID matched.
 			// We will check wepstatus for qualification Bss
 			if (pAd->PortCfg.WepStatus != pInBss->WepStatus)
 					continue;
@@ -1911,24 +1928,24 @@
 			// CCX also require not even try to connect it!!
 			if (SsidLen == 0)
 				continue;
-			
+
             // copy matching BSS from InTab to OutTab
             memcpy(pOutBss, pInBss, sizeof(BSS_ENTRY));
-            
+
             OutTab->BssNr++;
         }
         else if ((pInBss->BssType == pAd->PortCfg.BssType) && (SsidLen == 0))
         {
             BSS_ENTRY *pOutBss = &OutTab->BssEntry[OutTab->BssNr];
 
-			// Bss Type matched, SSID matched. 
+			// Bss Type matched, SSID matched.
 			// We will check wepstatus for qualification Bss
 			if (pAd->PortCfg.WepStatus != pInBss->WepStatus)
 					continue;
-			
+
             // copy matching BSS from InTab to OutTab
             memcpy(pOutBss, pInBss, sizeof(BSS_ENTRY));
-            
+
             OutTab->BssNr++;
         }
 #if 0
@@ -1937,36 +1954,36 @@
 			// Add for hidden SSID. But we have to verify the security suite too.
             BSS_ENTRY *pOutBss = &OutTab->BssEntry[OutTab->BssNr];
 
-			// Bss Type matched, SSID matched. 
+			// Bss Type matched, SSID matched.
 			// We will check wepstatus for qualification Bss
 			if (pAd->PortCfg.WepStatus != pInBss->WepStatus)
 					continue;
-			
+
             // copy matching BSS from InTab to OutTab
             memcpy(pOutBss, pInBss, sizeof(BSS_ENTRY));
-            
-            OutTab->BssNr++;			
+
+            OutTab->BssNr++;
 		}
-#endif		
+#endif
 		if (OutTab->BssNr >= MAX_LEN_OF_BSS_TABLE)
 			break;
-		
+
     }
-    
+
     BssTableSortByRssi(OutTab);
 }
 
 VOID BssTableSortByRssi(
-    IN OUT BSS_TABLE *OutTab) 
+    IN OUT BSS_TABLE *OutTab)
 {
     INT       i, j;
     BSS_ENTRY TmpBss;
 
-    for (i = 0; i < OutTab->BssNr - 1; i++) 
+    for (i = 0; i < OutTab->BssNr - 1; i++)
     {
-        for (j = i+1; j < OutTab->BssNr; j++) 
+        for (j = i+1; j < OutTab->BssNr; j++)
         {
-            if (OutTab->BssEntry[j].Rssi > OutTab->BssEntry[i].Rssi) 
+            if (OutTab->BssEntry[j].Rssi > OutTab->BssEntry[i].Rssi)
             {
                 memcpy(&TmpBss, &OutTab->BssEntry[j], sizeof(BSS_ENTRY));
                 memcpy(&OutTab->BssEntry[j], &OutTab->BssEntry[i], sizeof(BSS_ENTRY));
@@ -1976,34 +1993,178 @@
     }
 }
 
-NDIS_802_11_WEP_STATUS	BssCipherParse(
-	IN	PUCHAR	pCipher)
+/*
+ * ============================================================================
+ * Description:
+ * 		Scan cipher suite list and return cipher capability set.
+ * ============================================================================
+ */
+static USHORT scan_csl(
+		IN suite_list_t *psl,
+		IN USHORT curtype)
 {
-	PBEACON_EID_STRUCT	pEid;
-	PUCHAR				pTmp;
+	USHORT	ciphertype = curtype;	// Cipher "capability set"
+	int		i, j;
+
+	DBGPRINT(RT_DEBUG_TRACE, " -  scan %d pair cipher(s)\n", psl->count);
+
+	for (i = 0, j = psl->count; i < j; i++) {
 
-	pEid = (PBEACON_EID_STRUCT) pCipher;
+		if (psl->suite[i].type < NUM_CIPHER_TYPES) {
+			ciphertype |= 0x01 << psl->suite[i].type;
+		}
+		else {
+			DBGPRINT(RT_DEBUG_ERROR, " -  invalid pair cipher type %d\n",
+					psl->suite[i].type);
+		}
+		DBGPRINT(RT_DEBUG_TRACE, " -  (pair) CipherType now=0x%04x\n",
+				ciphertype);
+	}
+	return ciphertype;
 
-	// Double check sanity information, although it should be done at peer beacon sanity check already.
-	if (pEid->Eid != IE_WPA)
-		return (Ndis802_11WEPDisabled);
-
-	// Double check Var IE length, it must be no less than 0x16
-	if (pEid->Len < 0x16)
-		return (Ndis802_11WEPDisabled);
-	
-	// 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 += 9;
-
-	if (*pTmp == 4)			// AES
-		return (Ndis802_11Encryption3Enabled);
-	else if (*pTmp == 2)	// TKIP
-		return (Ndis802_11Encryption2Enabled);
+} /* End scan_csl () */
+
+USHORT	BssCipherParse(
+	IN	PBEACON_EID_STRUCT	pEid,
+    IN USHORT           VarIELen)	// Length of all saved IEs.
+{
+	USHORT				ciphertype = 0;
+	PBEACON_EID_STRUCT	ptEid;
+	USHORT              len;
+
+	DBGPRINT(RT_DEBUG_TRACE, "%s: using VarIELen=%d\n", __FUNCTION__, VarIELen);
+
+	// Handle the stinerman problem (a too-short WPA IE followed by
+	// a long-enough WPA IE from an AP), the onishin/dacull problem
+	// (a RSN - WPA2 - IE followed by a WPA1 IE from an AP), and the
+	// holtzmichel problem (a WPA1 IE followed by a WPA2 IE). We end
+	// up using the *last* one we find. This may (or may not) really
+	// be the thing to do. - bb
+	for (ptEid = pEid, len = 0; len < VarIELen;
+			len += ptEid->Len + 2,
+			ptEid = (PBEACON_EID_STRUCT)((UCHAR *)pEid + len)) {
+
+		DBGPRINT(RT_DEBUG_TRACE, " - examining IE=%d, Len=%d\n",
+				ptEid->Eid, ptEid->Len);
+
+		switch (ptEid->Eid) {
+			default:
+				DBGPRINT(RT_DEBUG_ERROR, " -  Not a WPA/WPA2 IE=%d, Len=%d\n",
+						ptEid->Eid, ptEid->Len);
+				break;
+
+			case IE_WPA: {
+				#define p ((PRSN_EID_STRUCT)ptEid)
+
+				// Double check Var IE length, it must be no less than 0x16
+				// Silently ignore if not
+				if (ptEid->Len < 0x16) {
+					DBGPRINT(RT_DEBUG_ERROR, " -  Len %d too short\n",
+							ptEid->Len);
+					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.
+				// (The future is now - bb)
+				if (p->Multicast[3] < NUM_CIPHER_TYPES) {
+					ciphertype |= 0x100 << p->Multicast[3];
+				}
+				else {
+					DBGPRINT(RT_DEBUG_ERROR,
+							" -  IE_WPA invalid group cipher %d\n",
+							p->Multicast[3]);
+				}
+				DBGPRINT(RT_DEBUG_TRACE, " -  WPA CipherType now=0x%04x\n",
+						ciphertype);
 
-	return (Ndis802_11WEPDisabled);
+				if (p->Length >= sizeof(RSN_EID_STRUCT) -
+					offsetof(RSN_EID_STRUCT, Oui)) {
+					suite_list_p psl = (suite_list_p)((UCHAR *)p +
+							offsetof(RSN_EID_STRUCT, Count));
+
+					if (psl->count * sizeof(suite_sel_t) +
+						offsetof(RSN_EID_STRUCT,Count) -
+						offsetof(RSN_EID_STRUCT,Oui) >
+						p->Length) {
+						DBGPRINT(RT_DEBUG_ERROR,
+								" -  malformed WPA pair cipher count "
+								"(needs %d bytes, %d bytes avail)\n",
+								psl->count*sizeof(suite_sel_t) +
+								offsetof(RSN_EID_STRUCT,Count) -
+								offsetof(RSN_EID_STRUCT,Oui),
+								p->Length);
+						break;
+					}
+					ciphertype = scan_csl(psl, ciphertype);
+				}
+				else {
+					ciphertype |= 0x01;		// Indicate use group cipher
+				}
+				#undef p
+				break;
+			}
+			case IE_RSN: {			// 802.11i pp. 27 - 32
+				#define p ((rsn_ie_p)ptEid)
+
+				if (p->length == sizeof(p->version)) {
+					ciphertype = 0x01 | 0x100 << CIPHER_TYPE_CCMP;
+					break;
+				}
+				if (p->length >= sizeof(p->version) + sizeof(p->gcsuite)) {
+
+					// Right now, we use the group cipher suite since it
+					// appears (to me, at any rate) that that's what is
+					// being used from the WPA IE.
+					// (SWAG - cf. RSN_EID_STRUCT - is that WPA_IE is RSN_IE
+					// with 4 bytes in front of the version tag. So we
+					// use the group cipher suite ala case IE_WPA above.)
+					// cf. the Holtzmichel problem: Looks like the Sinus 154
+					// Basic 3 includes either 3 pairwise cipher suites, or
+					// 1 pairwise cipher suite, 1 AKM suite, and an RSN
+					// capabilities field, because the len is 20.
+					if (p->gcsuite.type < NUM_CIPHER_TYPES) {
+						ciphertype |= 0x100 << p->gcsuite.type;
+					}
+					else {
+						DBGPRINT(RT_DEBUG_ERROR,
+								" -  IE_RSN invalid group cipher %d\n",
+								p->gcsuite.type);
+					}
+					DBGPRINT(RT_DEBUG_TRACE,
+							" -  (grp) CipherType now=0x%04x\n", ciphertype);
+				}
+				if (p->length > sizeof(p->version) + sizeof(p->gcsuite)) {
+					suite_list_p psl = (suite_list_p)((UCHAR *)p +
+							offsetof(rsn_ie_t, version) +
+							sizeof(ie_version_t) + sizeof(suite_sel_t));
+
+					if (psl->count * sizeof(suite_sel_t) +
+						sizeof(ie_version_t) + sizeof(suite_sel_t) >
+						p->length) {
+						DBGPRINT(RT_DEBUG_ERROR,
+								" -  malformed RSN pair cipher count "
+								"(needs %d bytes, %d bytes avail)\n",
+								psl->count*sizeof(suite_sel_t) +
+								sizeof(ie_version_t) + sizeof(suite_sel_t),
+								p->length);
+						break;
+					}
+					ciphertype = scan_csl(psl, ciphertype);
+				}
+				else {
+					ciphertype |= 0x01;		// Indicate use group cipher
+				}
+				#undef p
+				break;
+			} /* End case IE_RSN */
+		} /* End switch EID */
+	} /* End for () */
+
+	DBGPRINT(RT_DEBUG_TRACE, "%s: return CipherType=0x%04x\n",
+			__FUNCTION__, ciphertype);
+	return ciphertype;
 }
 
 // ===========================================================================================
@@ -2017,16 +2178,16 @@
  *  \post
  */
 VOID MacAddrRandomBssid(
-    IN PRTMP_ADAPTER pAd, 
-    OUT MACADDR *Addr) 
+    IN PRTMP_ADAPTER pAd,
+    OUT MACADDR *Addr)
 {
     INT i;
 
-    for (i = 0; i < ETH_ALEN; i++) 
+    for (i = 0; i < ETH_ALEN; i++)
     {
         Addr->Octet[i] = RandomByte(pAd);
     }
-    
+
     Addr->Octet[0] = (Addr->Octet[0] & 0xfe) | 0x02;  // the first 2 bits must be 01xxxxxxxx
 }
 
@@ -2042,12 +2203,12 @@
  *  \note this function initializes the following field
  */
 VOID MgtMacHeaderInit(
-    IN	PRTMP_ADAPTER	pAd, 
-    IN OUT PMACHDR Hdr, 
-    IN UCHAR Subtype, 
-    IN UCHAR ToDs, 
-    IN PMACADDR Ds, 
-    IN PMACADDR Bssid) 
+    IN	PRTMP_ADAPTER	pAd,
+    IN OUT PMACHDR Hdr,
+    IN UCHAR Subtype,
+    IN UCHAR ToDs,
+    IN PMACADDR Ds,
+    IN PMACADDR Bssid)
 {
     memset(Hdr, 0, sizeof(MACHDR));
     Hdr->Type = BTYPE_MGMT;
@@ -2063,8 +2224,8 @@
 // ===========================================================================================
 
 /*!***************************************************************************
- * 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 
+ * 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
@@ -2073,12 +2234,12 @@
  *                         function will FAIL!!!
  * return:
  *      Size of the buffer
- * usage:  
+ * usage:
  *      MakeOutgoingFrame(Buffer, output_length, 2, &fc, 2, &dur, 6, p_addr1, 6,p_addr2, END_OF_ARGS);
  ****************************************************************************/
 ULONG MakeOutgoingFrame(
-    OUT CHAR *Buffer, 
-    OUT ULONG *FrameLen, ...) 
+    OUT CHAR *Buffer,
+    OUT ULONG *FrameLen, ...)
 {
     CHAR   *p;
     int     leng;
@@ -2088,10 +2249,10 @@
     // calculates the total length
     TotLeng = 0;
     va_start(Args, FrameLen);
-    do 
+    do
     {
         leng = va_arg(Args, int);
-        if (leng == END_OF_ARGS) 
+        if (leng == END_OF_ARGS)
         {
             break;
         }
@@ -2117,7 +2278,7 @@
  *  \note   Because this is done only once (at the init stage), no need to be locked
  */
 NDIS_STATUS MlmeQueueInit(
-    IN MLME_QUEUE *Queue) 
+    IN MLME_QUEUE *Queue)
 {
     INT i;
 
@@ -2127,7 +2288,7 @@
     Queue->Head = 0;
     Queue->Tail = 0;
 
-    for (i = 0; i < MAX_LEN_OF_MLME_QUEUE; i++) 
+    for (i = 0; i < MAX_LEN_OF_MLME_QUEUE; i++)
     {
         Queue->Entry[i].Occupied = FALSE;
         Queue->Entry[i].MsgLen = 0;
@@ -2150,11 +2311,11 @@
  *  \note    The message has to be initialized
  */
 BOOLEAN MlmeEnqueue(
-    OUT MLME_QUEUE *Queue, 
-    IN ULONG Machine, 
-    IN ULONG MsgType, 
-    IN ULONG MsgLen, 
-    IN VOID *Msg) 
+    OUT MLME_QUEUE *Queue,
+    IN ULONG Machine,
+    IN ULONG MsgType,
+    IN ULONG MsgLen,
+    IN VOID *Msg)
 {
     INT Tail;
     unsigned long flags;
@@ -2164,30 +2325,25 @@
         DBGPRINT(RT_DEBUG_ERROR, "MlmeEnqueueForRecv mlme frame too large, size = %d \n", MsgLen);
 		return FALSE;
 	}
-	
-    spin_lock_irqsave(&(Queue->Lock), flags);
-    if (MlmeQueueFull(Queue)) 
-    {
+
+    spin_lock_irqsave(&Queue->Lock, flags);
+    if (Queue->Num == MAX_LEN_OF_MLME_QUEUE) {
+		spin_unlock_irqrestore(&Queue->Lock, flags);
         printk(KERN_ERR DRV_NAME "MlmeEnqueue full, msg dropped and may corrupt MLME\n");
-	spin_unlock_irqrestore(&(Queue->Lock), flags);
         return FALSE;
     }
-
-    Tail = Queue->Tail;
-    Queue->Tail++;
+    Tail = Queue->Tail++;
+    Queue->Tail %= MAX_LEN_OF_MLME_QUEUE;
     Queue->Num++;
-    if (Queue->Tail == MAX_LEN_OF_MLME_QUEUE) 
-    {
-        Queue->Tail = 0;
-    }
+    spin_unlock_irqrestore(&Queue->Lock, flags);
     DBGPRINT(RT_DEBUG_INFO, "MlmeEnqueue, num=%d\n",Queue->Num);
- 
+
     Queue->Entry[Tail].Occupied = TRUE;
     Queue->Entry[Tail].Machine = Machine;
     Queue->Entry[Tail].MsgType = MsgType;
     Queue->Entry[Tail].MsgLen  = MsgLen;
-    memcpy(Queue->Entry[Tail].Msg, Msg, MsgLen);
-    spin_unlock_irqrestore(&(Queue->Lock), flags);
+    if (Msg != NULL)
+	memcpy(Queue->Entry[Tail].Msg, Msg, MsgLen);
     return TRUE;
 }
 
@@ -2203,14 +2359,14 @@
  *  \post
  */
 BOOLEAN MlmeEnqueueForRecv(
-    IN	PRTMP_ADAPTER	pAd, 
-    OUT MLME_QUEUE *Queue, 
-    IN ULONG TimeStampHigh, 
+    IN	PRTMP_ADAPTER	pAd,
+    OUT MLME_QUEUE *Queue,
+    IN ULONG TimeStampHigh,
     IN ULONG TimeStampLow,
     IN UCHAR Rssi,
-    IN UCHAR Noise, 
-    IN ULONG MsgLen, 
-    IN VOID *Msg) 
+    IN UCHAR Noise,
+    IN ULONG MsgLen,
+    IN VOID *Msg)
 {
     INT          Tail, Machine;
     MACFRAME    *Fr = (MACFRAME *)Msg;
@@ -2225,31 +2381,25 @@
 	}
 
 
-    if (!MsgTypeSubst(Fr, &Machine, &MsgType)) 
+    if (!MsgTypeSubst(Fr, &Machine, &MsgType))
     {
         DBGPRINT(RT_DEBUG_ERROR, "MlmeEnqueueForRecv (drop mgmt->subtype=%d)\n",Fr->Hdr.SubType);
         return FALSE;
     }
 
-    spin_lock_irqsave(&(Queue->Lock), flags);
-    if (MlmeQueueFull(Queue)) 
-    {
+    spin_lock_irqsave(&Queue->Lock, flags);
+    if (Queue->Num == MAX_LEN_OF_MLME_QUEUE) {
+		spin_unlock_irqrestore(&Queue->Lock, flags);
         DBGPRINT(RT_DEBUG_ERROR, "MlmeEnqueueForRecv (queue full error) \n");
-	spin_unlock_irqrestore(&(Queue->Lock), flags);
         return FALSE;
     }
-    
-    // OK, we got all the informations, it is time to put things into queue
-    Tail = Queue->Tail;
-    Queue->Tail++;
+    Tail = Queue->Tail++;
+    Queue->Tail %= MAX_LEN_OF_MLME_QUEUE;
     Queue->Num++;
-    if (Queue->Tail == MAX_LEN_OF_MLME_QUEUE) 
-    {
-        Queue->Tail = 0;
-    }
-
+    spin_unlock_irqrestore(&Queue->Lock, flags);
     DBGPRINT(RT_DEBUG_INFO, "MlmeEnqueueForRecv, num=%d\n",Queue->Num);
-    
+
+    // OK, we got all the informations, it is time to put things into queue
     Queue->Entry[Tail].Occupied = TRUE;
     Queue->Entry[Tail].Machine = Machine;
     Queue->Entry[Tail].MsgType = MsgType;
@@ -2258,8 +2408,8 @@
     Queue->Entry[Tail].TimeStamp.vv.HighPart = TimeStampHigh;
     Queue->Entry[Tail].Rssi = Rssi;
     Queue->Entry[Tail].Noise = (Noise > BBP_R17_DYNAMIC_UP_BOUND) ? BBP_R17_DYNAMIC_UP_BOUND : ((ULONG) Noise);
-    memcpy(Queue->Entry[Tail].Msg, Msg, MsgLen);
-    spin_unlock_irqrestore(&(Queue->Lock), flags);
+    if (Msg != NULL)
+	memcpy(Queue->Entry[Tail].Msg, Msg, MsgLen);
 
     MlmeHandler(pAd);
 
@@ -2267,6 +2417,7 @@
 }
 
 /*! \brief   Dequeue a message from the MLME Queue
+ * 			WARNING: Must be call with Mlme.Queue.Lock held
  *  \param  *Queue    The MLME Queue
  *  \param  *Elem     The message dequeued from MLME Queue
  *  \return  TRUE if the Elem contains something, FALSE otherwise
@@ -2274,23 +2425,14 @@
  *  \post
  */
 BOOLEAN MlmeDequeue(
-    IN MLME_QUEUE *Queue, 
-    OUT MLME_QUEUE_ELEM **Elem) 
+    IN MLME_QUEUE *Queue,
+    OUT MLME_QUEUE_ELEM **Elem)
 {
-    unsigned long flags;
-    spin_lock_irqsave(&(Queue->Lock), flags);
-    if (Queue->Num == 0) {
-	    spin_unlock_irqrestore(&(Queue->Lock),flags);
+    if (Queue->Num == 0)
 	    return FALSE;
-    }
-    *Elem = &(Queue->Entry[Queue->Head]);
+    *Elem = &Queue->Entry[Queue->Head++];
+    Queue->Head %= MAX_LEN_OF_MLME_QUEUE;
     Queue->Num--;
-    Queue->Head++;
-    if (Queue->Head == MAX_LEN_OF_MLME_QUEUE) 
-    {
-        Queue->Head = 0;
-    }
-    spin_unlock_irqrestore(&(Queue->Lock), flags);
     DBGPRINT(RT_DEBUG_INFO, "MlmeDequeue, num=%d\n",Queue->Num);
 
     return TRUE;
@@ -2308,29 +2450,27 @@
 		DBGPRINT(RT_DEBUG_ERROR, "Failure to initialize mlme.\n");
 	// Continue the reset procedure...
     }
-   
+
     spin_lock_irqsave(&pAd->Mlme.TaskLock, flags);
-    if(pAd->Mlme.Running) 
+    if(pAd->Mlme.Running)
     {
         spin_unlock_irqrestore(&pAd->Mlme.TaskLock, flags);
         return;
-    } 
-    else 
+    }
+    else
     {
         pAd->Mlme.Running = TRUE;
     }
     spin_unlock_irqrestore(&pAd->Mlme.TaskLock, flags);
 
 	// Remove all Mlme queues elements
-    while (MlmeDequeue(&pAd->Mlme.Queue, &Elem)) 
-    {
-        //From message type, determine which state machine I should drive
-
-            // free MLME element
-            Elem->Occupied = FALSE;
-            Elem->MsgLen = 0;
-            
-        }
+    spin_lock_irqsave(&pAd->Mlme.Queue.Lock, flags);
+    while (MlmeDequeue(&pAd->Mlme.Queue, &Elem)) {
+        // free MLME element
+        Elem->Occupied = FALSE;
+        Elem->MsgLen = 0;
+    }
+	spin_unlock_irqrestore(&pAd->Mlme.Queue.Lock, flags);
 
 	// Cancel all timer events
 	// Be careful to cancel new added timer
@@ -2356,54 +2496,22 @@
 	pAd->Mlme.AuthMachine.CurrState    = AUTH_REQ_IDLE;
 	pAd->Mlme.AuthRspMachine.CurrState = AUTH_RSP_IDLE;
 	pAd->Mlme.SyncMachine.CurrState    = SYNC_IDLE;
-	
+
 	// Remove running state
     spin_lock_irqsave(&pAd->Mlme.TaskLock, flags);
     pAd->Mlme.Running = FALSE;
     spin_unlock_irqrestore(&pAd->Mlme.TaskLock, flags);
 }
 
-/*! \brief  test if the MLME Queue is empty
- *  \param  *Queue    The MLME Queue
- *  \return TRUE if the Queue is empty, FALSE otherwise
- *  \pre
- *  \post
- */
-BOOLEAN MlmeQueueEmpty(
-    IN MLME_QUEUE *Queue) 
-{
-    BOOLEAN Ans;
-
-    Ans = (Queue->Num == 0);
-
-    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
- */
-BOOLEAN MlmeQueueFull(
-    IN MLME_QUEUE *Queue) 
-{
-    BOOLEAN Ans;
-
-    Ans = (Queue->Num == MAX_LEN_OF_MLME_QUEUE);
-
-    return Ans;
-}
-
 /*! \brief   The destructor of MLME Queue
- *  \param 
+ *  \param
  *  \return
  *  \pre
  *  \post
  *  \note   Clear Mlme Queue, Set Queue->Num to Zero.
  */
 VOID MlmeQueueDestroy(
-    IN MLME_QUEUE *Queue) 
+    IN MLME_QUEUE *Queue)
 {
     unsigned long flags;
     spin_lock_irqsave(&(Queue->Lock), flags);
@@ -2422,22 +2530,22 @@
  *  \post
  */
 BOOLEAN MsgTypeSubst(
-    IN MACFRAME *Fr, 
-    OUT INT *Machine, 
-    OUT INT *MsgType) 
+    IN MACFRAME *Fr,
+    OUT INT *Machine,
+    OUT INT *MsgType)
 {
     USHORT Seq;
 	UCHAR	EAPType;
 
 	// The only data type will pass to this function is EAPOL frame
-    if (Fr->Hdr.Type == BTYPE_DATA) 
-    {    
+    if (Fr->Hdr.Type == BTYPE_DATA)
+    {
        	*Machine = WPA_PSK_STATE_MACHINE;
        	EAPType = *((UCHAR*)Fr + LENGTH_802_11 + LENGTH_802_1_H + 1);
        	return(WpaMsgTypeSubst(EAPType, MsgType));
     }
 
-    switch (Fr->Hdr.SubType) 
+    switch (Fr->Hdr.SubType)
     {
         case SUBTYPE_ASSOC_REQ:
             *Machine = ASSOC_STATE_MACHINE;
@@ -2478,17 +2586,17 @@
         case SUBTYPE_AUTH:
             // get the sequence number from payload 24 Mac Header + 2 bytes algorithm
             memcpy(&Seq, &Fr->Octet[2], sizeof(USHORT));
-            if (Seq == 1 || Seq == 3) 
+            if (Seq == 1 || Seq == 3)
             {
                 *Machine = AUTH_RSP_STATE_MACHINE;
                 *MsgType = MT2_PEER_AUTH_ODD;
-            } 
-            else if (Seq == 2 || Seq == 4) 
+            }
+            else if (Seq == 2 || Seq == 4)
             {
                 *Machine = AUTH_STATE_MACHINE;
                 *MsgType = MT2_PEER_AUTH_EVEN;
-            } 
-            else 
+            }
+            else
             {
                 return FALSE;
             }
@@ -2510,25 +2618,25 @@
 // ===========================================================================================
 
 /*! \brief Initialize the state machine.
- *  \param *S           pointer to 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  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
  */
 
 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) 
+    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;
 
@@ -2538,22 +2646,22 @@
     S->Base    = Base;
 
     S->TransFunc  = Trans;
-    
+
     // init all state transition to default function
-    for (i = 0; i < StNr; i++) 
+    for (i = 0; i < StNr; i++)
     {
-        for (j = 0; j < MsgNr; j++) 
+        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 
+/*! \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
@@ -2562,20 +2670,20 @@
  *  \post
  */
 VOID StateMachineSetAction(
-    IN STATE_MACHINE *S, 
-    IN ULONG St, 
-    IN ULONG Msg, 
-    IN STATE_MACHINE_FUNC Func) 
+    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) 
+    if (St < S->NrState && MsgIdx < S->NrMsg)
     {
         // boundary checking before setting the action
         S->TransFunc[St * S->NrMsg + MsgIdx] = Func;
-    } 
+    }
 }
 
 /*! \brief   The destructor of the state machine
@@ -2583,7 +2691,7 @@
  *  \note    doing nothing at this moment, may need to do something if the implementation changed
  */
 VOID
-StateMachineDestroy(IN STATE_MACHINE *S) 
+StateMachineDestroy(IN STATE_MACHINE *S)
 {
 }
 
@@ -2594,9 +2702,9 @@
  *  \return   None
  */
 VOID StateMachinePerformAction(
-    IN	PRTMP_ADAPTER	pAd, 
-    IN STATE_MACHINE *S, 
-    IN MLME_QUEUE_ELEM *Elem) 
+    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);
 }
@@ -2604,14 +2712,14 @@
 /*
     ==========================================================================
     Description:
-        The drop function, when machine executes this, the message is simply 
-        ignored. This function does nothing, the message is freed in 
+        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) 
+    IN PRTMP_ADAPTER pAd,
+    IN MLME_QUEUE_ELEM *Elem)
 {
 #if 0
     if ((Elem->MsgType == MT2_PEER_BEACON) ||
@@ -2622,7 +2730,7 @@
     {
         DBGPRINT(RT_DEBUG_TRACE, ("Warn:>>Drop Msg=%d<<\n",Elem->MsgType));
     }
-#endif    
+#endif
 }
 
 // ===========================================================================================
@@ -2635,12 +2743,12 @@
     ==========================================================================
  */
 VOID LfsrInit(
-    IN PRTMP_ADAPTER pAd, 
-    IN ULONG Seed) 
+    IN PRTMP_ADAPTER pAd,
+    IN ULONG Seed)
 {
-    if (Seed == 0) 
+    if (Seed == 0)
         pAd->Mlme.ShiftReg = 1;
-    else 
+    else
         pAd->Mlme.ShiftReg = Seed;
 }
 
@@ -2650,21 +2758,21 @@
     ==========================================================================
  */
 UCHAR RandomByte(
-    IN PRTMP_ADAPTER pAd) 
+    IN PRTMP_ADAPTER pAd)
 {
     ULONG i;
     UCHAR R, Result;
 
     R = 0;
 
-    for (i = 0; i < 8; i++) 
+    for (i = 0; i < 8; i++)
     {
-        if (pAd->Mlme.ShiftReg & 0x00000001) 
+        if (pAd->Mlme.ShiftReg & 0x00000001)
         {
             pAd->Mlme.ShiftReg = ((pAd->Mlme.ShiftReg ^ LFSR_MASK) >> 1) | 0x80000000;
             Result = 1;
-        } 
-        else 
+        }
+        else
         {
             pAd->Mlme.ShiftReg = pAd->Mlme.ShiftReg >> 1;
             Result = 0;
@@ -2681,17 +2789,17 @@
     ==========================================================================
  */
 VOID AsicSwitchChannel(
-    IN PRTMP_ADAPTER pAd, 
-    IN UCHAR Channel) 
+    IN PRTMP_ADAPTER pAd,
+    IN UCHAR Channel)
 {
     ULONG R3;
     UCHAR index;
     int Value;
 
     // TODO: need to update E2PROM format to add 802.11a channel's TX power calibration values
-    if (Channel <= 14)    
+    if (Channel <= 14)
         R3 = pAd->PortCfg.ChannelTxPower[Channel - 1];
-    else 
+    else
         R3 = pAd->PortCfg.ChannelTxPower[0];
 
     if (R3 > 31)  R3 = 31;
@@ -2706,10 +2814,10 @@
     Value = (Value > 31) ? 31 : Value;
     Value = (Value <  0) ?  0 : Value;
     R3 = Value;
-    
+
 	 // Krellan: Save value for readout to user
 	 pAd->PortCfg.TxPowerDriver = R3;
-	 
+
     R3 = R3 << 9; // shift TX power control to correct RF R3 bit position
 
     switch (pAd->PortCfg.RfType)
@@ -2772,7 +2880,7 @@
                 }
             }
             break;
-            
+
         case RFIC_2525:
             for (index = 0; index < NUM_OF_2525_CHNL; index++)
             {
@@ -2800,7 +2908,7 @@
                 }
             }
             break;
-            
+
         case RFIC_2525E:
             for (index = 0; index < NUM_OF_2525E_CHNL; index++)
             {
@@ -2820,7 +2928,7 @@
                 }
             }
             break;
-            
+
         case RFIC_5222:
             for (index = 0; index < NUM_OF_5222_CHNL; index++)
             {
@@ -2846,12 +2954,12 @@
     }
 
     DBGPRINT(RT_DEBUG_INFO, "AsicSwitchChannel(RF=%d) to #%d, TXPwr=%d, R1=0x%08x, R2=0x%08x, R3=0x%08x, R4=0x%08x\n",
-        pAd->PortCfg.RfType, 
-        pAd->PortCfg.LatchRfRegs.Channel, 
+        pAd->PortCfg.RfType,
+        pAd->PortCfg.LatchRfRegs.Channel,
         pAd->PortCfg.TxPower,
-        pAd->PortCfg.LatchRfRegs.R1, 
-        pAd->PortCfg.LatchRfRegs.R2, 
-        pAd->PortCfg.LatchRfRegs.R3, 
+        pAd->PortCfg.LatchRfRegs.R1,
+        pAd->PortCfg.LatchRfRegs.R2,
+        pAd->PortCfg.LatchRfRegs.R3,
         pAd->PortCfg.LatchRfRegs.R4);
 }
 
@@ -2865,8 +2973,8 @@
     ==========================================================================
  */
 VOID AsicLockChannel(
-    IN PRTMP_ADAPTER pAd, 
-    IN UCHAR Channel) 
+    IN PRTMP_ADAPTER pAd,
+    IN UCHAR Channel)
 {
     UCHAR   r70;
 	ULONG   FcsCnt;
@@ -2899,14 +3007,14 @@
         case RFIC_2525E:
             pAd->PortCfg.LatchRfRegs.R1 &= 0xfffdffff;  // RF R1.bit17 "tune_en1" OFF
             pAd->PortCfg.LatchRfRegs.R3 &= 0xfffffeff;   // RF R3.bit8 "tune_en2" OFF
-            RTMP_RF_IO_WRITE32(pAd, pAd->PortCfg.LatchRfRegs.R1); 
-            RTMP_RF_IO_WRITE32(pAd, pAd->PortCfg.LatchRfRegs.R3); 
+            RTMP_RF_IO_WRITE32(pAd, pAd->PortCfg.LatchRfRegs.R1);
+            RTMP_RF_IO_WRITE32(pAd, pAd->PortCfg.LatchRfRegs.R3);
             DBGPRINT(RT_DEBUG_INFO, "AsicRfTuningExec(R1=0x%x,R3=0x%x)\n",pAd->PortCfg.LatchRfRegs.R1,pAd->PortCfg.LatchRfRegs.R3);
             break;
-            
+
         case RFIC_2523:
             pAd->PortCfg.LatchRfRegs.R3 &= 0xfffffeff;   // RF R3.bit8 "tune_en2" OFF
-            RTMP_RF_IO_WRITE32(pAd, pAd->PortCfg.LatchRfRegs.R3); 
+            RTMP_RF_IO_WRITE32(pAd, pAd->PortCfg.LatchRfRegs.R3);
             DBGPRINT(RT_DEBUG_INFO, "AsicRfTuningExec(R3=0x%x)\n",pAd->PortCfg.LatchRfRegs.R3);
             break;
 
@@ -2929,16 +3037,16 @@
     ==========================================================================
  */
 VOID AsicAdjustTxPower(
-    IN PRTMP_ADAPTER pAd) 
+    IN PRTMP_ADAPTER pAd)
 {
     ULONG R3, Channel, CurrTxPwr;
     int Value;
 
     if ((pAd->PortCfg.Channel >= 1) && (pAd->PortCfg.Channel <= 14))
         Channel = pAd->PortCfg.Channel;
-    else 
+    else
         Channel = 1;  // don't have calibration info for 11A, temporarily use Channel 1
-    
+
     // get TX Power base from E2PROM
     R3 = pAd->PortCfg.ChannelTxPower[Channel - 1];
     if (R3 > 31)  R3 = 31;
@@ -2948,7 +3056,7 @@
     Value = (Value > 31) ? 31 : Value;
     Value = (Value <  0) ?  0 : Value;
     R3 = Value;
-    
+
     // 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->PortCfg.TxPowerAuto == TRUE)       // AUTO TX POWER control
@@ -2959,10 +3067,10 @@
             // low TX power upon very-short distance to AP to solve some vendor's AP RX problem
             // in this case, no TSSI compensation is required.
 
-            if ((pAd->DrsCounters.fNoisyEnvironment == FALSE) && 
+            if ((pAd->DrsCounters.fNoisyEnvironment == FALSE) &&
                 (pAd->PortCfg.AvgRssi > (pAd->PortCfg.RssiToDbm - RSSI_FOR_LOWEST_TX_POWER)))
                 R3 -= LOWEST_TX_POWER_DELTA;
-            else if ((pAd->DrsCounters.fNoisyEnvironment == FALSE) && 
+            else if ((pAd->DrsCounters.fNoisyEnvironment == FALSE) &&
                 (pAd->PortCfg.AvgRssi > (pAd->PortCfg.RssiToDbm - RSSI_FOR_LOW_TX_POWER)))
                 R3 -= LOW_TX_POWER_DELTA;
 
@@ -2973,7 +3081,7 @@
                 R3 +=2;
                 if (R3 > 31) R3 = 31;
             }
-            
+
             // 2 exclusive rules applied on CCK rates only -
             //    1. always plus 2 db for CCK
             //    2. adjust TX Power based on TSSI
@@ -2986,10 +3094,10 @@
    	                R3 += 2;  // plus 2 db
    	                if (R3 > 31) R3 = 31;
     	        }
-    	        
-        	    // Auto calibrate Tx AGC if bAutoTxAgc is TRUE and TX rate is CCK, 
+
+        	    // Auto calibrate Tx AGC if bAutoTxAgc is TRUE and TX rate is CCK,
         	    // because E2PROM's TSSI reference is valid only in CCK range.
-    	        else  
+    	        else
     	        {
     		        UCHAR	R1,TxPowerRef, TssiRef;
 
@@ -3005,7 +3113,7 @@
 			                // Need R3 adjustment. However, we have to make sure there is only
 			                // plus / minus 5 variation allowed
 			                if (TssiRef > R1)
-			                {				
+			                {
 				                R3 = (R3 < (ULONG) (TxPowerRef + 5)) ? (R3 + 1) : R3;
 				                if (R3 > 31)
 				                    R3 = 31;
@@ -3020,7 +3128,7 @@
 	    	        }
     	        }
     	    }
-    	    
+
         }
     }
     else // fixed AUTO TX power
@@ -3035,7 +3143,7 @@
 
 	 // Krellan: Save value for readout to user
 	 pAd->PortCfg.TxPowerDriver = R3;
-	     
+
     // compare the desired R3.TxPwr value with current R3, if not equal
     // set new R3.TxPwr
     CurrTxPwr = (pAd->PortCfg.LatchRfRegs.R3 >> 9) & 0x0000001f;
@@ -3058,8 +3166,8 @@
     ==========================================================================
  */
 VOID AsicSleepThenAutoWakeup(
-    IN PRTMP_ADAPTER pAd, 
-    IN USHORT TbttNumToNextWakeUp) 
+    IN PRTMP_ADAPTER pAd,
+    IN USHORT TbttNumToNextWakeUp)
 {
     CSR20_STRUC Csr20;
     PWRCSR1_STRUC Pwrcsr1;
@@ -3067,9 +3175,9 @@
     // we have decided to SLEEP, so at least do it for a BEACON period.
     if (TbttNumToNextWakeUp==0)
         TbttNumToNextWakeUp=1;
-    
+
     // PWRCSR0 remains untouched
-    
+
     // set CSR20 for next wakeup
     Csr20.word = 0;
     Csr20.field.NumBcnBeforeWakeup = TbttNumToNextWakeUp - 1;
@@ -3141,17 +3249,17 @@
     ==========================================================================
  */
 VOID AsicSetBssid(
-    IN PRTMP_ADAPTER pAd, 
-    IN MACADDR *Bssid) 
+    IN PRTMP_ADAPTER pAd,
+    IN MACADDR *Bssid)
 {
     ULONG         Addr4;
 
-    Addr4 = (ULONG)(Bssid->Octet[0]) | 
-            (ULONG)(Bssid->Octet[1] << 8) | 
+    Addr4 = (ULONG)(Bssid->Octet[0]) |
+            (ULONG)(Bssid->Octet[1] << 8) |
             (ULONG)(Bssid->Octet[2] << 16) |
             (ULONG)(Bssid->Octet[3] << 24);
     RTMP_IO_WRITE32(pAd, CSR5, Addr4);
-    
+
     Addr4 = (ULONG)(Bssid->Octet[4]) | (ULONG)(Bssid->Octet[5] << 8);
     RTMP_IO_WRITE32(pAd, CSR6, Addr4);
 }
@@ -3162,7 +3270,7 @@
     ==========================================================================
  */
 VOID AsicDisableSync(
-    IN PRTMP_ADAPTER pAd) 
+    IN PRTMP_ADAPTER pAd)
 {
     // TIMECSR_STRUC TimeCsr;
     DBGPRINT(RT_DEBUG_TRACE, "--->Disable TSF synchronization\n");
@@ -3174,7 +3282,7 @@
     RTMP_IO_WRITE32(pAd, CSR14, 0x00000000);
 #endif
 
-#if 0    
+#if 0
     RTMP_IO_READ32(pAd, TIMECSR, &TimeCsr.word);
 
     // restore to 33 PCI-tick-per-Usec. for 2560a only where PCI-clock is used as TSF timing source
@@ -3192,7 +3300,7 @@
     ==========================================================================
  */
 VOID AsicEnableBssSync(
-    IN PRTMP_ADAPTER pAd) 
+    IN PRTMP_ADAPTER pAd)
 {
     CSR12_STRUC Csr12;
     CSR13_STRUC Csr13;
@@ -3201,14 +3309,14 @@
     BOOLEAN IsApPc;
 
     DBGPRINT(RT_DEBUG_TRACE, "--->AsicEnableBssSync(INFRA mode)\n");
-    
+
     RTMP_IO_WRITE32(pAd, CSR14, 0x00000000);
-    
+
     Csr12.word = 0;
     Csr12.field.BeaconInterval = pAd->PortCfg.BeaconPeriod << 4; // ASIC register in units of 1/16 TU
     Csr12.field.CfpMaxDuration = pAd->PortCfg.CfpMaxDuration << 4; // ASIC register in units of 1/16 TU
     RTMP_IO_WRITE32(pAd, CSR12, Csr12.word);
-    
+
     Csr13.word = 0;
     Csr13.field.CfpPeriod = pAd->PortCfg.CfpDurRemain << 4; // ASIC register in units of 1/16 TU
     RTMP_IO_WRITE32(pAd, CSR13, Csr13.word);
@@ -3218,14 +3326,14 @@
     Bcncsr1.field.BeaconCwMin = 5;
     RTMP_IO_WRITE32(pAd, BCNCSR1, Bcncsr1.word);
 
-    IsApPc = (CAP_IS_CF_POLLABLE_ON(pAd->PortCfg.CapabilityInfo) && 
+    IsApPc = (CAP_IS_CF_POLLABLE_ON(pAd->PortCfg.CapabilityInfo) &&
               CAP_IS_CF_POLL_REQ_ON(pAd->PortCfg.CapabilityInfo));
     IsApPc = FALSE; // TODO: not support so far
-    
+
     Csr14.word = 0;
     Csr14.field.TsfCount = 1;
     Csr14.field.TsfSync = 1; // sync TSF in INFRASTRUCTURE mode
-    if (IsApPc) 
+    if (IsApPc)
     {
         Csr14.field.CfpCntPreload = pAd->PortCfg.CfpCount;
         Csr14.field.Tcfp = 1;
@@ -3234,13 +3342,13 @@
 //  Csr14.field.TbcnPreload = (pAd->PortCfg.BeaconPeriod - 30) << 4; // TODO: ???? 1 TU ???
     Csr14.field.Tbcn = 1;
     RTMP_IO_WRITE32(pAd, CSR14, Csr14.word);
-    
+
 }
 
 /*
     ==========================================================================
     Description:
-    Note: 
+    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.
@@ -3254,7 +3362,7 @@
     CSR14_STRUC Csr14;
     // BCNCSR_STRUC Bcncsr;
     BCNCSR1_STRUC Bcncsr1;
-    
+
     DBGPRINT(RT_DEBUG_TRACE, "--->AsicEnableIbssSync(ADHOC mode)\n");
 
     RTMP_IO_WRITE32(pAd, CSR14, 0x00000000);
@@ -3279,7 +3387,7 @@
         Bcncsr1.field.Preload = 700;   // 24 + ((MAC_HDR_LEN << 4) / RateIdTo500Kbps[pAd->PortCfg.MlmeRate]);
     }
     RTMP_IO_WRITE32(pAd, BCNCSR1, Bcncsr1.word);
-    
+
     Csr14.word = 0;
     Csr14.field.TsfCount = 1;
     Csr14.field.TsfSync = 2; // sync TSF in IBSS mode
@@ -3289,16 +3397,16 @@
 }
 
 VOID AsicLedPeriodicExec(
-    IN  unsigned long data) 
+    IN  unsigned long data)
 {
     RTMP_ADAPTER *pAd = (RTMP_ADAPTER *)data;
     ULONG LedCsr = 0x0000461E; // 0x0000461E;
-    
+
     pAd->PortCfg.LedCntl.fOdd = ! pAd->PortCfg.LedCntl.fOdd;
 
-    if (INFRA_ON(pAd) || ADHOC_ON(pAd))   
+    if (INFRA_ON(pAd) || ADHOC_ON(pAd))
         LedCsr |= 0x00010000; // enable hardwired TX activity LED
-    if (pAd->PortCfg.LedCntl.fOdd && pAd->PortCfg.LedCntl.fRxActivity) 
+    if (pAd->PortCfg.LedCntl.fOdd && pAd->PortCfg.LedCntl.fRxActivity)
         LedCsr |= 0x00020000; // turn on software-based RX activity LED
     pAd->PortCfg.LedCntl.fRxActivity = FALSE;
 
@@ -3315,17 +3423,17 @@
 // pAd->PortCfg.CurrentRxAntenna
 // 0xff: diversity, 0:antenna A, 1:antenna B
 VOID AsicSetRxAnt(
-    IN PRTMP_ADAPTER pAd) 
+    IN PRTMP_ADAPTER pAd)
 {
     UCHAR   RxValue, TxValue;
     ULONG   Bbpcsr1;
-    
+
     RTMPCancelTimer(&pAd->PortCfg.RxAnt.RxAntDiversityTimer);
     pAd->PortCfg.RxAnt.AvgRssi[0] = (-95 + 120) << 3;  // reset Ant-A's RSSI history
     pAd->PortCfg.RxAnt.AvgRssi[1] = (-95 + 120) << 3;  // reset Ant-B's RSSI history
 
    	pAd->PortCfg.RxAnt.PrimaryInUsed  = TRUE;
-    
+
     if (pAd->PortCfg.CurrentRxAntenna == 0xff)     // Diversity
     {
        	pAd->PortCfg.RxAnt.PrimaryRxAnt   = 1;  // assume ant-B
@@ -3344,7 +3452,7 @@
 
     DBGPRINT(RT_DEBUG_TRACE,"AntDiv - set RxAnt=%d, primary=%d, second=%d\n",
         pAd->PortCfg.CurrentRxAntenna, pAd->PortCfg.RxAnt.PrimaryRxAnt, pAd->PortCfg.RxAnt.SecondaryRxAnt);
-    
+
     // use primary antenna
     RTMP_IO_READ32(pAd, BBPCSR1, &Bbpcsr1);
     TxValue = pAd->PortCfg.BbpWriteLatch[BBP_Tx_Configure];
@@ -3352,34 +3460,34 @@
     if (pAd->PortCfg.RxAnt.PrimaryRxAnt == 0) // ant-A
     {
         TxValue = (TxValue & 0xFC) | 0x00;
-        RxValue = 0x1c; 
+        RxValue = 0x1c;
         Bbpcsr1 = (Bbpcsr1 & 0xFFFCFFFC) | 0x00000000;
     }
     else                                      // ant-B
     {
 		TxValue = (TxValue & 0xFC) | 0x02;
-		RxValue = 0x1e; 
+		RxValue = 0x1e;
         Bbpcsr1 = (Bbpcsr1 & 0xFFFCFFFC) | 0x00020002;
     }
     RTMP_IO_WRITE32(pAd, BBPCSR1, Bbpcsr1);
    	//RTMP_BBP_IO_WRITE32_BY_REG_ID(pAd, BBP_Tx_Configure, TxValue);
    	RTMP_BBP_IO_WRITE32_BY_REG_ID(pAd, BBP_Rx_Configure, RxValue);
-        
+
 }
 
 // switch to secondary RxAnt for a while to collect it's average RSSI
-// also set a timeout routine to DO the actual evaluation. If evaluation 
+// also set a timeout routine to DO the actual evaluation. If evaluation
 // result shows a much better RSSI using secondary RxAnt, then a official
 // RX antenna switch is performed.
 VOID AsicEvaluateSecondaryRxAnt(
-    IN PRTMP_ADAPTER pAd) 
+    IN PRTMP_ADAPTER pAd)
 {
     UCHAR  RxValue, TxValue;
     ULONG  Bbpcsr1;
 
     if (pAd->PortCfg.CurrentRxAntenna != 0xff)
         return;
-    
+
    	pAd->PortCfg.RxAnt.PrimaryInUsed  = FALSE;
    	pAd->PortCfg.RxAnt.FirstPktArrivedWhenEvaluate = FALSE;
    	pAd->PortCfg.RxAnt.RcvPktNumWhenEvaluate = 0;
@@ -3387,16 +3495,16 @@
 //  pAd->PortCfg.RxAnt.AvgRssi[pAd->PortCfg.RxAnt.SecondaryRxAnt] = 0;
 
     DBGPRINT(RT_DEBUG_TRACE,"AntDiv - evaluate Ant #%d\n", pAd->PortCfg.RxAnt.SecondaryRxAnt);
-    
+
     // temporarily switch to secondary antenna
     RxValue = pAd->PortCfg.BbpWriteLatch[BBP_Rx_Configure];
     TxValue = pAd->PortCfg.BbpWriteLatch[BBP_Tx_Configure];
     RTMP_IO_READ32(pAd, BBPCSR1, &Bbpcsr1);
-    
+
     if (pAd->PortCfg.RxAnt.SecondaryRxAnt == 0) // ant-A
     {
         TxValue = (TxValue & 0xFC) | 0x00;
-        RxValue = 0x1c; 
+        RxValue = 0x1c;
         Bbpcsr1 = (Bbpcsr1 & 0xFFFCFFFC) | 0x00000000;
     }
     else                                        // ant-B
@@ -3411,7 +3519,7 @@
 
     // a one-shot timer to end the evalution
     if (pAd->MediaState == NdisMediaStateConnected)
-        RTMPSetTimer(pAd, &pAd->PortCfg.RxAnt.RxAntDiversityTimer, 150);	
+        RTMPSetTimer(pAd, &pAd->PortCfg.RxAnt.RxAntDiversityTimer, 150);
     else
    	RTMPSetTimer(pAd, &pAd->PortCfg.RxAnt.RxAntDiversityTimer, 300);
 }
@@ -3419,17 +3527,17 @@
 // this timeout routine collect AvgRssi[SecondaryRxAnt] and decide if
 // SecondaryRxAnt is much better than PrimaryRxAnt
 VOID AsicRxAntEvalTimeout(
-    IN  unsigned long data) 
+    IN  unsigned long data)
 {
     RTMP_ADAPTER *pAd = (RTMP_ADAPTER *)data;
 
- 
+
     DBGPRINT(RT_DEBUG_TRACE,"AntDiv - AsicRxAntEvalTimeout, \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;
-	
+
    if (pAd->PortCfg.RxAnt.PrimaryInUsed == TRUE)
 
         return;
@@ -3445,7 +3553,7 @@
         pAd->PortCfg.RxAnt.PrimaryRxAnt = pAd->PortCfg.RxAnt.SecondaryRxAnt;
         pAd->PortCfg.RxAnt.SecondaryRxAnt = temp;
         pAd->PortCfg.LastAvgRssi = (pAd->PortCfg.RxAnt.AvgRssi[pAd->PortCfg.RxAnt.SecondaryRxAnt] >> 3) - pAd->PortCfg.RssiToDbm;
-        
+
         DBGPRINT(RT_DEBUG_TRACE,"AntDiv - Switch to Ant #%d, RSSI[0,1]=<%d, %d>\n",
             pAd->PortCfg.RxAnt.PrimaryRxAnt, pAd->PortCfg.RxAnt.AvgRssi[0], pAd->PortCfg.RxAnt.AvgRssi[1]);
     }
@@ -3453,7 +3561,7 @@
     {
         UCHAR RxValue, TxValue;
         ULONG Bbpcsr1;
-        
+
         // end of evaluation, swicth back to primary antenna
         RxValue = pAd->PortCfg.BbpWriteLatch[BBP_Rx_Configure];
         TxValue = pAd->PortCfg.BbpWriteLatch[BBP_Tx_Configure];
@@ -3461,7 +3569,7 @@
         if (pAd->PortCfg.RxAnt.PrimaryRxAnt == 0) // ant-A
         {
             TxValue = (TxValue & 0xFC) | 0x00;
-            RxValue = 0x1c; 
+            RxValue = 0x1c;
             Bbpcsr1 = (Bbpcsr1 & 0xFFFCFFFC) | 0x00000000;
         }
         else                                      // ant-B
@@ -3491,7 +3599,7 @@
  */
 VOID AsicSetSlotTime(
     IN PRTMP_ADAPTER pAd,
-    IN BOOLEAN UseShortSlotTime) 
+    IN BOOLEAN UseShortSlotTime)
 {
     CSR11_STRUC Csr11;
     CSR18_STRUC Csr18;
@@ -3499,7 +3607,7 @@
     UCHAR PhyMode;
 
     pAd->PortCfg.ShortSlotInUsed = UseShortSlotTime;
-    
+
     PhyMode = pAd->PortCfg.PhyMode;
     if (PhyMode == PHY_11ABG_MIXED)
     {
@@ -3527,7 +3635,7 @@
     else
         Csr19.field.EIFS = 60;   // roughly = SIFS + ACK @6Mbps
     RTMP_IO_WRITE32(pAd, CSR19, Csr19.word);
-    
+
 #if 1
     // force using short SLOT time for FAE to demo performance only
     if (pAd->PortCfg.EnableTxBurst == 1)
@@ -3543,7 +3651,7 @@
     ==========================================================================
     Description:
        This routine is used for 2560a only where 2560a still use non-accurate
-       PCI-clock as TSF 1-usec source. we have to dynamically change tick-per-usec 
+       PCI-clock as TSF 1-usec source. we have to dynamically change tick-per-usec
        to avoid ADHOC synchronization issue with SYMBOL 11b card
     ==========================================================================
  */
@@ -3575,7 +3683,7 @@
 /*
     ==========================================================================
     Description:
-        danamic tune BBP R17 to find a balance between sensibility and 
+        danamic tune BBP R17 to find a balance between sensibility and
         noise isolation
     ==========================================================================
  */
@@ -3586,13 +3694,13 @@
     UCHAR R17;
     ULONG FalseCcaUpperThreshold = pAd->PortCfg.BbpTuning.FalseCcaUpperThreshold << 7;
     int dbm = pAd->PortCfg.AvgRssi - pAd->PortCfg.RssiToDbm;
-    
+
     if ((! pAd->PortCfg.BbpTuningEnable) || (pAd->PortCfg.BbpTuning.VgcDelta==0))
         return;
-    
+
     R17 = pAd->PortCfg.BbpWriteLatch[17];
 
-	if ((pAd->PortCfg.Rt2560Version >= RT2560_VER_D) && 
+	if ((pAd->PortCfg.Rt2560Version >= RT2560_VER_D) &&
 	    (pAd->MediaState == NdisMediaStateConnected))
 	{
         // Rule 0.
@@ -3609,7 +3717,7 @@
             return;
         }
         // Rule 1. "special big-R17 for short-distance" when not SCANNING
-	    else if ((dbm >= RSSI_FOR_LOW_SENSIBILITY) && 
+	    else if ((dbm >= RSSI_FOR_LOW_SENSIBILITY) &&
 	        (pAd->Mlme.CntlMachine.CurrState == CNTL_IDLE))
 	    {
 	        if (R17 != BBP_R17_LOW_SENSIBILITY)
@@ -3621,7 +3729,7 @@
             return;
 	    }
         // Rule 2. "special mid-R17 for mid-distance" when not SCANNING
-	    else if ((dbm >= RSSI_FOR_MID_SENSIBILITY) && 
+	    else if ((dbm >= RSSI_FOR_MID_SENSIBILITY) &&
 	        (pAd->Mlme.CntlMachine.CurrState == CNTL_IDLE))
 	    {
 	        if (R17 != BBP_R17_MID_SENSIBILITY)
@@ -3632,7 +3740,7 @@
             DBGPRINT(RT_DEBUG_INFO, "RSSI = %d dbm, fixed R17 at 0x%x\n", dbm, R17);
             return;
 	    }
-        // Rule 3. leave "short or mid-distance" condition, restore R17 to the 
+        // Rule 3. leave "short or mid-distance" condition, restore R17 to the
         //    dynamic tuning range <E2PROM-6, BBP_R17_DYNAMIC_UP_BOUND>
 	    else if (R17 >= BBP_R17_MID_SENSIBILITY)
 	    {
@@ -3642,13 +3750,13 @@
             return;
 	    }
 	}
-	
+
     // Rule 3. otherwise, R17 is currenly in dyanmic tuning range: <E2PROM-6, BBP_R17_DYNAMIC_UP_BOUND>.
     //    Keep dynamic tuning based on False CCA conter
-    
+
 	RTMP_IO_READ32(pAd, CNT3, &Value);
 	pAd->PrivateInfo.CCAErrCnt = (Value & 0x0000ffff);
-	DBGPRINT(RT_DEBUG_INFO, "CCA flase alarm = %d, Avg RSSI= %d dbm\n", 
+	DBGPRINT(RT_DEBUG_INFO, "CCA flase alarm = %d, Avg RSSI= %d dbm\n",
 	    pAd->PrivateInfo.CCAErrCnt, dbm);
 
 	if ((pAd->PrivateInfo.CCAErrCnt > FalseCcaUpperThreshold) &&
@@ -3697,7 +3805,7 @@
 
     Return Value:
         None
-	
+
     Note:
 
     ========================================================================
@@ -3714,7 +3822,7 @@
     DBGPRINT(RT_DEBUG_INFO, "==> MlmeFreeMemory\n");
     spin_lock(&pAd->MemLock);
     if (pAd->Mlme.MemHandler.MemRunning)
-    { 
+    {
         //Mlme memory handler is busy.
         //Move it to the Pending array for later free
         pAd->Mlme.MemHandler.MemFreePending[pAd->Mlme.MemHandler.PendingCount++] = (PULONG) AllocVa;
@@ -3738,7 +3846,7 @@
         while (pMlmeMemoryStruct)
         {
             if (pMlmeMemoryStruct->AllocVa == (PVOID) pAd->Mlme.MemHandler.MemFreePending[Index])
-            { 
+            {
                 //Found virtual address in the in-used link list
                 //Remove it from the memory in-used link list, and move it to the unused link list
                 if (pPrevious == NULL)
@@ -3865,7 +3973,7 @@
     pAd->Mlme.MemHandler.MemRunning = FALSE;
     spin_unlock(&pAd->MemLock);
 
-    DBGPRINT(RT_DEBUG_INFO, "<== MlmeFreeMemory [IN:%d][UN:%d][Pending:%d]\n", 
+    DBGPRINT(RT_DEBUG_INFO, "<== MlmeFreeMemory [IN:%d][UN:%d][Pending:%d]\n",
                 pAd->Mlme.MemHandler.InUseCount, pAd->Mlme.MemHandler.UnUseCount, pAd->Mlme.MemHandler.PendingCount);
 }
 
@@ -3883,7 +3991,7 @@
         NDIS_STATUS_SUCCESS
         NDIS_STATUS_FAILURE
         NDIS_STATUS_RESOURCES
-	
+
     Note:
 
     ========================================================================
@@ -3911,7 +4019,7 @@
     }
 
     if (pAd->Mlme.MemHandler.pUnUseHead == NULL)
-    { //There are no available memory for caller use 
+    { //There are no available memory for caller use
         Status = NDIS_STATUS_RESOURCES;
         pAd->Mlme.MemHandler.MemRunning = FALSE;
         spin_unlock(&pAd->MemLock);
@@ -3963,7 +4071,7 @@
     Return Value:
         NDIS_STATUS_SUCCESS
         NDIS_STATUS_RESOURCES
-        
+
     Note:
 
     ========================================================================
@@ -3994,7 +4102,7 @@
     //
     if (Number > MAX_MLME_HANDLER_MEMORY)
         Number = MAX_MLME_HANDLER_MEMORY;
-        
+
     for (i = 0; i < Number; i++)
     {
         //Allocate a nonpaged memory for link list use.
diff -Nur rt2500-1.1.0-b4/Module/mlme.h rt2500-cvs-2007061011/Module/mlme.h
--- rt2500-1.1.0-b4/Module/mlme.h	2006-06-17 22:12:58.000000000 +0200
+++ rt2500-cvs-2007061011/Module/mlme.h	2007-03-21 05:25:34.000000000 +0100
@@ -1,43 +1,43 @@
-/*************************************************************************** 
- * RT2400/RT2500 SourceForge Project - http://rt2x00.serialmonkey.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.                          * 
- *                                                                         * 
- *   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.             * 
- *                                                                         * 
- *   Licensed under the GNU GPL                                            * 
- *   Original code supplied under license from RaLink Inc, 2004.           * 
- ***************************************************************************/ 
+/***************************************************************************
+ * RT2400/RT2500 SourceForge Project - http://rt2x00.serialmonkey.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.                          *
+ *                                                                         *
+ *   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.             *
+ *                                                                         *
+ *   Licensed under the GNU GPL                                            *
+ *   Original code supplied under license from RaLink Inc, 2004.           *
+ ***************************************************************************/
 
- /*************************************************************************** 
+ /***************************************************************************
  *      Module Name: mlme.h
- *              
- *      Abstract: 
- *              
- *      Revision History: 
- *      Who             When            What 
- *      --------        -----------     ----------------------------- 
- *      John            28th Aug 03     Initial code     
- *      MarkW           8th  Dec 04     Baseline code  
- ***************************************************************************/ 
+ *
+ *      Abstract:
+ *
+ *      Revision History:
+ *      Who             When            What
+ *      --------        -----------     -----------------------------
+ *      John            28th Aug 03     Initial code
+ *      MarkW           8th  Dec 04     Baseline code
+ ***************************************************************************/
 
 #ifndef __MLME_H__
 #define __MLME_H__
 
 #include "oid.h"
 
-// maximum supported capability information - 
+// maximum supported capability information -
 // ESS, IBSS, Privacy, Short Preamble, Short Slot
 #define SUPPORTED_CAPABILITY_INFO 0x0433
 
@@ -61,7 +61,7 @@
 
 #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 
+#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   // -3 db from full TX power upon mid-distance to AP
@@ -212,7 +212,7 @@
 #define TX_FER_TOO_HIGH(TxFER)          ((TxFER) > 15)   // consider rate down if FER>15%
 #define TX_FER_VERY_LOW(TxFER)          ((TxFER) < 7)    // consider rate up if FER<7%
 #define FAIR_FER                        10               // any value between TOO_HIGH and VERY_LOW
-#define DRS_TX_QUALITY_WORST_BOUND      3 
+#define DRS_TX_QUALITY_WORST_BOUND      3
 #define DRS_PENALTY                     8
 
 // Ralink timer control block
@@ -329,13 +329,14 @@
     USHORT  CfpDurRemaining;
     UCHAR   SsidLen;
     CHAR    Ssid[MAX_LEN_OF_SSID];
-    
+
     ULONG   LastBeaconRxTime; // OS's timestamp
 
     // New for microsoft WPA support
+	USHORT					CipherCap;	// Pair (0:7), Group (8:15) cipher cap
     NDIS_802_11_FIXED_IEs   FixIEs;
     NDIS_802_11_WEP_STATUS  WepStatus;
-    UCHAR                   VarIELen;               // Length of next VIE include EID & Length
+    USHORT                  VarIELen;	// Length of all saved IEs.
     UCHAR                   VarIEs[MAX_VIE_LEN];
 } BSS_ENTRY, *PBSS_ENTRY;
 
@@ -384,7 +385,7 @@
     ULONG               BssIdx;
     ULONG               RoamIdx;
     BOOLEAN             CurrReqIsFromNdis; // TRUE - then we should call NdisMSetInformationComplete()
-                                           // FALSE - req is from driver itself. 
+                                           // FALSE - req is from driver itself.
                                            // no NdisMSetInformationComplete() is required
 } CNTL_AUX, *PCNTL_AUX;
 
@@ -394,7 +395,7 @@
     USHORT              CapabilityInfo;
     USHORT              ListenIntv;
     CHAR                Ssid[MAX_LEN_OF_SSID];
-    UCHAR               SsidLen;    
+    UCHAR               SsidLen;
     RALINK_TIMER_STRUCT AssocTimer, ReassocTimer, DisassocTimer;
 } ASSOC_AUX, *PASSOC_AUX;
 
@@ -482,10 +483,10 @@
 typedef struct PACKED _BEACON_EID_STRUCT {
     UCHAR   Eid;
     UCHAR   Len;
-    CHAR   Octet[1];
+    UCHAR   Octet[1];
 } BEACON_EID_STRUCT,*PBEACON_EID_STRUCT;
 
-// New for WPA cipher suite 
+// New for WPA cipher suite
 typedef struct PACKED _RSN_EID_STRUCT {
     UCHAR   Eid;
     UCHAR   Length;
@@ -497,6 +498,98 @@
         UCHAR   Oui[4];
     }   Unicast[1];
 }   RSN_EID_STRUCT, *PRSN_EID_STRUCT;
+#define MIN_WPA_KEYDATA_LEN	(4 + sizeof(ie_version_t) + sizeof(suite_sel_t) + \
+							2*sizeof(suite_list_t))
+
+
+/* Country Information Element (802.11d pp. 4, 5) */
+
+typedef struct country_subelement {
+	unsigned char	first_chan,
+					num_chans;
+	signed char		max_tx_pwr;		// in dBm
+} PACKED country_subelement_t, *country_subelement_p;
+
+typedef struct country_string {	// (all alpha)
+	UCHAR	co[2];				// ISO/IEC 3166-1 country code
+	UCHAR	env;				// ' '/'O'/'I' - 802.11d pp. 19
+} PACKED country_string_t, *country_string_p;
+
+typedef struct country_ie {
+	UCHAR					eid;
+	UCHAR					length;
+	country_string_t		cs;
+	country_subelement_t	chans[1];
+	UCHAR					pad[0];	// may or may not be present
+} PACKED country_ie_t, *country_ie_p;
+
+
+/* WPA2 (cf. 802.11i pp. 27 ff.) */
+
+// access
+#define wtohs(x)	(le16_to_cpu(x))// sic (802.11 is "native" little-endian)
+#define htows(x)	(cpu_to_le16(x))// i.e. opposite of internet byte order
+
+// primitives
+typedef USHORT	ie_version_t;
+typedef USHORT	ie_count_t;
+typedef UCHAR	ie_oui_t[3];		// Organizationally Unique Identifier
+typedef UCHAR pmkid_t[16], *pmkid_p;// 802.11i pp. 76
+
+typedef struct rsncap {
+#ifdef BIG_ENDIAN
+	USHORT	Reserved:10;
+	USHORT	GTKSAReplayCounter:2;	// 0/2/4/16 replay counters
+	USHORT	PTKSAReplayCounter:2;
+	USHORT	NoPairwise:1;			// WEP key 0 and pairwise key n/a
+	USHORT	PreAuth:1;				// AP STA supports pre-authentication
+#else
+	USHORT	PreAuth:1;				// AP STA supports pre-authentication
+	USHORT	NoPairwise:1;			// WEP key 0 and pairwise key n/a
+	USHORT	PTKSAReplayCounter:2;
+	USHORT	GTKSAReplayCounter:2;	// 0/2/4/16 replay counters
+	USHORT	Reserved:10;
+#endif
+} PACKED rsncap_t, *rsncap_p;
+
+typedef struct suite_sel {
+	ie_oui_t	oui;
+	UCHAR		type;
+} PACKED suite_sel_t, *suite_sel_p;
+
+/* Cipher suite selectors - 802.11i pp. 28, 29 */
+#define CIPHER_TYPE_GRP		0
+#define CIPHER_TYPE_WEP40	1
+#define CIPHER_TYPE_TKIP	2
+#define CIPHER_TYPE_RES		3
+#define CIPHER_TYPE_CCMP	4
+#define CIPHER_TYPE_WEP104	5
+#define NUM_CIPHER_TYPES	6
+
+/* Authentication and Key Management suite selectors - 802.11i pp. 30 */
+#define AKM_TYPE_802_1X		1
+#define AKM_TYPE_PSK		2
+
+typedef struct suite_list {
+	ie_count_t	count;
+	suite_sel_t	suite[1];
+} PACKED suite_list_t, *suite_list_p;
+
+typedef struct pmkid_list {
+	ie_count_t	count;
+	pmkid_t		list[1];
+} PACKED pmkid_list_t, *pmkid_list_p;
+
+typedef struct rsn_ie {
+	UCHAR  			eid;
+	UCHAR  			length;
+	ie_version_t	version;
+
+	// Optional fields
+	suite_sel_t	gcsuite;		// Group Cipher Suite
+}  PACKED rsn_ie_t, *rsn_ie_p;
+#define MIN_RSN_KEYDATA_LEN	(sizeof(ie_version_t) + sizeof(suite_sel_t) + \
+							2*sizeof(suite_list_t))
 
 extern UCHAR  RateIdToMbps[];
 extern USHORT RateIdTo500Kbps[];
diff -Nur rt2500-1.1.0-b4/Module/oid.h rt2500-cvs-2007061011/Module/oid.h
--- rt2500-1.1.0-b4/Module/oid.h	2006-06-17 22:12:58.000000000 +0200
+++ rt2500-cvs-2007061011/Module/oid.h	2007-03-21 05:25:34.000000000 +0100
@@ -1,36 +1,37 @@
-/*************************************************************************** 
- * RT2400/RT2500 SourceForge Project - http://rt2x00.serialmonkey.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.                          * 
- *                                                                         * 
- *   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.             * 
- *                                                                         * 
- *   Licensed under the GNU GPL                                            * 
- *   Original code supplied under license from RaLink Inc, 2004.           * 
- ***************************************************************************/ 
+/***************************************************************************
+ * RT2400/RT2500 SourceForge Project - http://rt2x00.serialmonkey.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.                          *
+ *                                                                         *
+ *   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.             *
+ *                                                                         *
+ *   Licensed under the GNU GPL                                            *
+ *   Original code supplied under license from RaLink Inc, 2004.           *
+ ***************************************************************************/
 
- /*************************************************************************** 
+ /***************************************************************************
  *      Module Name: oid.h
- *              
- *      Abstract: 
- *              
- *      Revision History: 
- *      Who             When            What 
- *      --------        -----------     ----------------------------- 
- *      MarkW           8th  Dec 04     Baseline code  
- *      RobinC          10th Dec 04     RFMON Support 
- ***************************************************************************/ 
+ *
+ *      Abstract:
+ *
+ *      Revision History:
+ *      Who             When            What
+ *      --------        -----------     -----------------------------
+ *      MarkW           8th  Dec 04     Baseline code
+ *      RobinC          10th Dec 04     RFMON Support
+ *      RomainB         31st Dec 06     RFMON getter
+ ***************************************************************************/
 
 #ifndef _OID_H_
 #define _OID_H_
@@ -56,7 +57,8 @@
 #define RTPRIV_IOCTL_BBP                            SIOCIWFIRSTPRIV + 0x03
 #define RTPRIV_IOCTL_MAC                            SIOCIWFIRSTPRIV + 0x05
 #define RTPRIV_IOCTL_E2P                            SIOCIWFIRSTPRIV + 0x07
-#define RTPRIV_IOCTL_RFMONTX                        SIOCIWFIRSTPRIV + 0x0D
+#define RTPRIV_IOCTL_SET_RFMONTX                    SIOCIWFIRSTPRIV + 0x0C
+#define RTPRIV_IOCTL_GET_RFMONTX                    SIOCIWFIRSTPRIV + 0x0D
 
 #define OID_GET_SET_TOGGLE                          0x8000
 
@@ -168,8 +170,8 @@
 // Added new types for OFDM 5G and 2.4G
 typedef enum _NDIS_802_11_NETWORK_TYPE
 {
-   Ndis802_11FH, 
-   Ndis802_11DS, 
+   Ndis802_11FH,
+   Ndis802_11DS,
     Ndis802_11OFDM5,
     Ndis802_11OFDM24,
     Ndis802_11NetworkTypeMax    // not a real type, defined as an upper bound
@@ -199,7 +201,7 @@
 typedef struct _NDIS_802_11_CONFIGURATION_FH
 {
    ULONG           Length;            // Length of structure
-   ULONG           HopPattern;        // As defined by 802.11, MSB set 
+   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;
@@ -237,7 +239,7 @@
 typedef struct _NDIS_802_11_KEY
 {
     ULONG           Length;             // Length of this structure
-    ULONG           KeyIndex;           
+    ULONG           KeyIndex;
     ULONG           KeyLength;          // length of key in bytes
     NDIS_802_11_MAC_ADDRESS BSSID;
     NDIS_802_11_KEY_RSC KeyRSC;
@@ -247,8 +249,8 @@
 typedef struct _NDIS_802_11_REMOVE_KEY
 {
     ULONG                   Length;        // Length of this structure
-    ULONG                   KeyIndex;           
-    NDIS_802_11_MAC_ADDRESS BSSID;      
+    ULONG                   KeyIndex;
+    NDIS_802_11_MAC_ADDRESS BSSID;
 } NDIS_802_11_REMOVE_KEY, *PNDIS_802_11_REMOVE_KEY;
 
 typedef struct PACKED _NDIS_802_11_WEP
@@ -285,7 +287,7 @@
 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 
+typedef struct PACKED _NDIS_802_11_SSID
 {
     ULONG   SsidLength;         // length of SSID field below, in bytes;
                                 // this can be zero.
@@ -338,14 +340,14 @@
     NDIS_WLAN_BSSID_EX      Bssid[1];
 } NDIS_802_11_BSSID_LIST_EX, *PNDIS_802_11_BSSID_LIST_EX;
 
-typedef struct _NDIS_802_11_FIXED_IEs 
+typedef struct _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 
+typedef struct _NDIS_802_11_VARIABLE_IEs
 {
     UCHAR ElementID;
     UCHAR Length;    // Number of bytes in data field
@@ -428,7 +430,7 @@
     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;
diff -Nur rt2500-1.1.0-b4/Module/rt2560.h rt2500-cvs-2007061011/Module/rt2560.h
--- rt2500-1.1.0-b4/Module/rt2560.h	2006-06-17 22:12:58.000000000 +0200
+++ rt2500-cvs-2007061011/Module/rt2560.h	2007-03-21 05:25:34.000000000 +0100
@@ -1,36 +1,36 @@
-/*************************************************************************** 
- * RT2400/RT2500 SourceForge Project - http://rt2x00.serialmonkey.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.                          * 
- *                                                                         * 
- *   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.             * 
- *                                                                         * 
- *   Licensed under the GNU GPL                                            * 
- *   Original code supplied under license from RaLink Inc, 2004.           * 
- ***************************************************************************/ 
+/***************************************************************************
+ * RT2400/RT2500 SourceForge Project - http://rt2x00.serialmonkey.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.                          *
+ *                                                                         *
+ *   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.             *
+ *                                                                         *
+ *   Licensed under the GNU GPL                                            *
+ *   Original code supplied under license from RaLink Inc, 2004.           *
+ ***************************************************************************/
 
- /*************************************************************************** 
+ /***************************************************************************
  *      Module Name: rt2560.h
- *              
+ *
  *      Abstract: RT2560 ASIC related definition & structures
- *              
- *      Revision History: 
- *      Who             When            What 
- *      --------        -----------     ----------------------------- 
- *      MarkW           8th  Dec 04     Baseline code  
- *      MarkW           10th Dec 04     Rolled in Ralink 1.4.5.0 
- ***************************************************************************/ 
+ *
+ *      Revision History:
+ *      Who             When            What
+ *      --------        -----------     -----------------------------
+ *      MarkW           8th  Dec 04     Baseline code
+ *      MarkW           10th Dec 04     Rolled in Ralink 1.4.5.0
+ ***************************************************************************/
 
 #ifndef __RT2560_H__
 #define __RT2560_H__
@@ -370,10 +370,10 @@
 
     // Word 5
     ULONG       Eiv;
-    
+
     // Word 6-9
     UCHAR       Key[16];
-    
+
     // Word 10 - 11 Reserved,   not necessary to put into the structure.
 #ifdef BIG_ENDIAN
     ULONG       Rsv2:31;
@@ -676,7 +676,7 @@
 #endif
     }   field;
     ULONG           word;
-}   CSR11_STRUC, *PCSR11_STRUC; 
+}   CSR11_STRUC, *PCSR11_STRUC;
 
 //
 // CSR12: Synchronization configuration register 0
@@ -869,7 +869,7 @@
 // =================================================================================
 
 //
-// TXCSR0 <0x0060> : TX Control Register 
+// TXCSR0 <0x0060> : TX Control Register
 //
 typedef union   _TXCSR0_STRUC   {
     struct  {
@@ -880,13 +880,13 @@
         ULONG		KickAtim:1;		// Kick ATIM ring
 		ULONG		KickTx:1;		// Kick Tx ring
 #else
-        ULONG       KickTx:1;       // Kick Tx ring 
+        ULONG       KickTx:1;       // Kick Tx ring
         ULONG       KickAtim:1;     // Kick ATIM ring
         ULONG       KickPrio:1;     // Kick priority ring
         ULONG       Abort:1;        // Abort all transmit related ring operation
         ULONG       Rsvd:28;
 #endif
-    }   field;  
+    }   field;
     ULONG           word;
 }   TXCSR0_STRUC, *PTXCSR0_STRUC;
 
@@ -1184,7 +1184,7 @@
         ULONG		BbpDesireState:2;
 		ULONG		SetState:1;
 #else
-        ULONG       SetState:1; 
+        ULONG       SetState:1;
         ULONG       BbpDesireState:2;
         ULONG       RfDesireState:2;
         ULONG       BbpCurrState:2;
@@ -1304,13 +1304,13 @@
 #ifdef BIG_ENDIAN
         ULONG		Rsvd:15;
         ULONG		WriteControl:1;		// 1: Write	BBP, 0:	Read BBP
-        ULONG		Busy:1;				// 1: ASIC is busy execute BBP programming.	
+        ULONG		Busy:1;				// 1: ASIC is busy execute BBP programming.
         ULONG		RegNum:7;			// Selected	BBP	register
 		ULONG		Value:8;			// Register	value to program into BBP
 #else
         ULONG       Value:8;            // Register value to program into BBP
         ULONG       RegNum:7;           // Selected BBP register
-        ULONG       Busy:1;             // 1: ASIC is busy execute BBP programming. 
+        ULONG       Busy:1;             // 1: ASIC is busy execute BBP programming.
         ULONG       WriteControl:1;     // 1: Write BBP, 0: Read BBP
         ULONG       Rsvd:15;
 #endif
diff -Nur rt2500-1.1.0-b4/Module/rt2x00debug.h rt2500-cvs-2007061011/Module/rt2x00debug.h
--- rt2500-1.1.0-b4/Module/rt2x00debug.h	1970-01-01 01:00:00.000000000 +0100
+++ rt2500-cvs-2007061011/Module/rt2x00debug.h	2007-02-20 20:02:18.000000000 +0100
@@ -0,0 +1,76 @@
+/*
+	Copyright (C) 2004 - 2007 rt2x00 SourceForge Project
+	<http://rt2x00.serialmonkey.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.
+
+	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: rt2x00debug
+	Abstract: Data structures for the rt2x00debug module.
+	Supported chipsets: RT2460, RT2560, RT2570,
+	rt2561, rt2561s, rt2661 & rt2573.
+ */
+
+typedef void (debug_access_t)(void *dev, const unsigned long word, void *data);
+
+struct rt2x00debug_reg {
+	debug_access_t *read;
+	debug_access_t *write;
+
+	unsigned int word_size;
+	unsigned int length;
+};
+
+struct rt2x00debug {
+	/*
+	 * Name of the interface.
+	 */
+	char intf_name[16];
+
+	/*
+	 * Reference to the modules structure.
+	 */
+	struct module *owner;
+
+	/*
+	 * Driver module information
+	 */
+	char *mod_name;
+	char *mod_version;
+
+	/*
+	 * Register access information.
+	 */
+	struct rt2x00debug_reg reg_csr;
+	struct rt2x00debug_reg reg_eeprom;
+	struct rt2x00debug_reg reg_bbp;
+
+	/*
+	 * Pointer to driver structure where
+	 * this debugfs entry belongs to.
+	 */
+	void *dev;
+
+	/*
+	 * Pointer to rt2x00debug private data,
+	 * individual driver should not touch this.
+	 */
+	void *priv;
+};
+
+extern int rt2x00debug_register(struct rt2x00debug *debug);
+extern void rt2x00debug_deregister(struct rt2x00debug *debug);
diff -Nur rt2500-1.1.0-b4/Module/rt_config.h rt2500-cvs-2007061011/Module/rt_config.h
--- rt2500-1.1.0-b4/Module/rt_config.h	2006-06-17 22:12:58.000000000 +0200
+++ rt2500-cvs-2007061011/Module/rt_config.h	2007-06-10 18:35:24.000000000 +0200
@@ -1,36 +1,36 @@
-/*************************************************************************** 
- * RT2400/RT2500 SourceForge Project - http://rt2x00.serialmonkey.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.                          * 
- *                                                                         * 
- *   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.             * 
- *                                                                         * 
- *   Licensed under the GNU GPL                                            * 
- *   Original code supplied under license from RaLink Inc, 2004.           * 
- ***************************************************************************/ 
+/***************************************************************************
+ * RT2400/RT2500 SourceForge Project - http://rt2x00.serialmonkey.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.                          *
+ *                                                                         *
+ *   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.             *
+ *                                                                         *
+ *   Licensed under the GNU GPL                                            *
+ *   Original code supplied under license from RaLink Inc, 2004.           *
+ ***************************************************************************/
 
- /*************************************************************************** 
+ /***************************************************************************
  *      Module Name: rt_config.h
- *              
+ *
  *      Abstract: Central header file for all includes
- *              
- *      Revision History: 
- *      Who             When            What 
- *      --------        -----------     ----------------------------- 
- *      RoryC           21st Dec 02     Initial code   
- *      MarkW           8th  Dec 04     Baseline code  
- ***************************************************************************/ 
+ *
+ *      Revision History:
+ *      Who             When            What
+ *      --------        -----------     -----------------------------
+ *      RoryC           21st Dec 02     Initial code
+ *      MarkW           8th  Dec 04     Baseline code
+ ***************************************************************************/
 
 #ifndef __RT_CONFIG_H__
 #define __RT_CONFIG_H__
@@ -39,14 +39,14 @@
 #define NIC_DEVICE_NAME             "RT2500STA"
 
 #define	DRV_NAME	"rt2500"
-#define DRV_VERSION	"1.1.0 BETA4"
-#define DRV_RELDATE	"2006/06/18"
+#define DRV_VERSION	"1.1.0 CVS"
+#define DRV_RELDATE	"2007061011"
 #define DRV_VERSION_MAJOR 1
-#define DRV_VERSION_MINOR 1 
+#define DRV_VERSION_MINOR 1
 #define DRV_VERSION_SUB 0
-#define DRV_BUILD_YEAR 2006
-#define DRV_BUILD_MONTH 06
-#define DRV_BUILD_DAY 18 
+#define DRV_BUILD_YEAR 2007
+#define DRV_BUILD_MONTH 05
+#define DRV_BUILD_DAY 13
 
 /* Operational parameters that are set at compile time. */
 #if !defined(__OPTIMIZE__)  ||  !defined(__KERNEL__)
@@ -55,7 +55,6 @@
 #error  You must compile this driver with "-O".
 #endif
 
-#include <linux/config.h>  //can delete
 #include <linux/module.h>
 #include <linux/version.h>
 #include <linux/kernel.h>
@@ -71,7 +70,6 @@
 #include <linux/skbuff.h>
 #include <linux/init.h>  //can delete
 #include <linux/delay.h> // can delete
-#include <linux/ethtool.h>
 #include <linux/wireless.h>
 #include <linux/proc_fs.h>
 #include <linux/delay.h>
@@ -90,9 +88,9 @@
 
 // The type definition has to be placed before including rt2460.h
 #ifndef ULONG
-#define CHAR            char
+#define CHAR            signed char
 #define INT             int
-#define SHORT           int
+#define SHORT           short
 #define UINT            u32
 #define ULONG           u32
 #define USHORT          u16
@@ -144,6 +142,7 @@
 #include    "rtmp_type.h"
 #include    "rtmp_def.h"
 #include    "rt2560.h"
+#include    "rt2x00debug.h"
 #include    "rtmp.h"
 #include    "mlme.h"
 #include    "oid.h"
@@ -156,7 +155,7 @@
     RT2560A = 0,
 };
 
-#ifdef RTMP_EMBEDDED
+#if 1				//#ifdef RTMP_EMBEDDED
 #undef GFP_KERNEL
 #define GFP_KERNEL      (GFP_DMA | GFP_ATOMIC)
 #endif
diff -Nur rt2500-1.1.0-b4/Module/rtmp.h rt2500-cvs-2007061011/Module/rtmp.h
--- rt2500-1.1.0-b4/Module/rtmp.h	2006-06-17 22:12:58.000000000 +0200
+++ rt2500-cvs-2007061011/Module/rtmp.h	2007-06-08 20:09:53.000000000 +0200
@@ -1,43 +1,44 @@
-/*************************************************************************** 
- * RT2400/RT2500 SourceForge Project - http://rt2x00.serialmonkey.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.                          * 
- *                                                                         * 
- *   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.             * 
- *                                                                         * 
- *   Licensed under the GNU GPL                                            * 
- *   Original code supplied under license from RaLink Inc, 2004.           * 
- ***************************************************************************/ 
+/***************************************************************************
+ * RT2400/RT2500 SourceForge Project - http://rt2x00.serialmonkey.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.                          *
+ *                                                                         *
+ *   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.             *
+ *                                                                         *
+ *   Licensed under the GNU GPL                                            *
+ *   Original code supplied under license from RaLink Inc, 2004.           *
+ ***************************************************************************/
 
- /*************************************************************************** 
+ /***************************************************************************
  *      Module Name: rt_config.h
- *              
+ *
  *      Abstract: Central header file for all includes
- *              
- *      Revision History: 
- *      Who             When            What 
- *      --------        -----------     ----------------------------- 
- *      RoryC           21st Dec 02     Initial code   
- *      MarkW           8th  Dec 04     Baseline code  
+ *
+ *      Revision History:
+ *      Who             When            What
+ *      --------        -----------     -----------------------------
+ *      RoryC           21st Dec 02     Initial code
+ *      MarkW           8th  Dec 04     Baseline code
  *      MarkW (rt2400)  8th  Dec 04     Promisc mode support
  *      Flavio (rt2400) 8th  Dec 04     Elegant irqreturn_t handling
  *      RobinC          10th Dec 04     RFMON Support
- *      MarkW           10th Dec 04     Rolled in Ralink 1.4.5.0 
- *      MarkW (rt2400)  15th Dec 04     Spinlock fix 
+ *      MarkW           10th Dec 04     Rolled in Ralink 1.4.5.0
+ *      MarkW (rt2400)  15th Dec 04     Spinlock fix
  *      Ivo (rt2400)    15th Dec 04     Debug level switching
  *      GregorG         29th Mar 05     Big endian fixes
- ***************************************************************************/ 
+ *      RomainB         31st Dec 06     RFMON getter
+ ***************************************************************************/
 
 #ifndef __RTMP_H__
 #define __RTMP_H__
@@ -62,6 +63,13 @@
 #endif /*(LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,0)) */
 #endif /* pci_name */
 
+#if (LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,22))
+#define pci_module_init	pci_register_driver
+#endif
+
+#if (LINUX_VERSION_CODE < KERNEL_VERSION(2,6,22))
+#define skb_reset_mac_header(skb) (skb->mac.raw = skb->data)
+#endif
 
 // Krellan: Limit range of user TxPower settings from -31 to +0 dBm.
 // We could accept -31 to +31 dBm, relative to 0 dBm which is defined
@@ -87,21 +95,40 @@
 //
 //  MACRO for debugging information
 //
-extern int    debug;
 #ifdef RT2500_DBG
-#define DBGPRINT(Level, fmt, args...) 					\
-	if(debug){printk(Level DRV_NAME ": " fmt, ## args);}
+extern VOID rt2500_setdbg(long);
+extern INT rt2500_dbgprint(int, const char *, ...);
+#define DBGPRINT(mask, fmt, args...) 					\
+	(rt2500_dbgprint(mask, KERN_DEBUG DRV_NAME ": " fmt, ## args))
+
+/* Do not enclose in parentheses ()! */
+#define DBGENTER	DBGPRINT(RT_DEBUG_TRACE, "==> %s\n", __FUNCTION__)
+#define DBGRETURN	DBGPRINT(RT_DEBUG_TRACE, "<== %s\n", __FUNCTION__)
+
+#define DBGHEXSTR(level, prefix, src, len)							\
+	{																\
+	    char			buf[128];	/* allows 64 bytes/512 bits */	\
+		int				i, j;										\
+		unsigned char	*p;											\
+																	\
+		if (len > 0) {												\
+			j = len < sizeof(buf)/2? len: sizeof(buf)/2 - 1;		\
+																	\
+			for (p = (unsigned char *)(src), i = 0; i < j; i++) {	\
+				sprintf(&buf[i*2], "%02x", *p++);					\
+			}														\
+			DBGPRINT(level, prefix "%s\n", buf);					\
+		}															\
+	}
 #else
+#define DBGENTER
+#define DBGRETURN
 #define DBGPRINT(Level, fmt, args...)					\
 	while(0){}
+#define DBGHEXSTR(level, prefix, src, len)							\
+	while(0){}
 #endif
 
-//
-//  spin_lock enhanced for Nested spin lock
-//
-
-extern unsigned long IrqFlags;
-
 //  Assert MACRO to make sure program running
 //
 #undef  ASSERT
@@ -145,12 +172,12 @@
 //              ULONG Register_Offset,
 //              ULONG Value)
 //
-#ifdef RTMP_EMBEDDED
+#if 0				//#ifdef RTMP_EMBEDDED
 #define RTMP_IO_READ32(_A, _R, _pV)     (*_pV = PCIMemRead32(__mem_pci(_A->CSRBaseAddress+_R)))
 #define RTMP_IO_WRITE32(_A, _R, _V)     (PCIMemWrite32(__mem_pci(_A->CSRBaseAddress+_R),_V))
 #else
-#define RTMP_IO_READ32(_A, _R, _pV)	(*_pV = readl( (void*) (_A->CSRBaseAddress + _R) ) )
-#define RTMP_IO_WRITE32(_A, _R, _V)	(writel(_V, (void*) (_A->CSRBaseAddress + _R) ) )
+#define RTMP_IO_READ32(_A, _R, _pV)	(*_pV = readl((void*)(_A->CSRBaseAddress + _R) ) )
+#define RTMP_IO_WRITE32(_A, _R, _V)	(writel(_V, (void*)(_A->CSRBaseAddress + _R) ) )
 #endif
 
 //
@@ -363,7 +390,7 @@
     ULONG           RxRingErrCount;
     ULONG           EncryptCount;
     ULONG           KickTxCount;
-    ULONG           TxRingErrCount; 
+    ULONG           TxRingErrCount;
     LARGE_INTEGER	RealFcsErrCount;
 } COUNTER_RALINK, *PCOUNTER_RALINK;
 
@@ -400,10 +427,10 @@
 typedef struct  _WPA_KEY {
     UCHAR   KeyLen;             // Key length for each key, 0: entry is invalid
     UCHAR   Key[16];            // right now we implement 4 keys, 128 bits max
-    UCHAR   RxMic[8];
-    UCHAR   TxMic[8];
+    UCHAR   RxMic[8];		// Message Integrity Code
+    UCHAR   TxMic[8];		// MIC
     NDIS_802_11_MAC_ADDRESS BssId;  // For pairwise key only
-    UCHAR   TxTsc[6];           // 48bit TSC value
+    UCHAR   TxTsc[6];           // 48bit TKIP Sequence Counter value
     UCHAR   RxTsc[6];           // 48bit TSC value
     UCHAR   Type;               // Indicate Pairwise / Group
 }   WPA_KEY, *PWPA_KEY;
@@ -413,7 +440,7 @@
 {
 	union
 	{
-		struct 
+		struct
 		{
 			UCHAR		rc0;
 			UCHAR		rc1;
@@ -436,38 +463,36 @@
 				UCHAR		Byte;
 			}	CONTROL;
 		}	field;
-		
+
 		ULONG	word;
 	}	IV16;
-	
+
 	ULONG	IV32;
 }	TKIP_IV, *PTKIP_IV;
 #endif
 
-typedef	struct	_IV_CONTROL_
+typedef	struct PACKED _IV_CONTROL_
 {
-		union
-		{
-			struct
-			{
+	union PACKED {
+		struct PACKED {
 #ifdef BIG_ENDIAN
-				ULONG	KeyID:2;
-				ULONG	ExtIV:1;
-				ULONG	Rsvd:5;
-				ULONG	rc2:8;
-				ULONG	rc1:8;
-				ULONG	rc0:8;
+			ULONG	KeyID:2;
+			ULONG	ExtIV:1;
+			ULONG	Rsvd:5;
+			ULONG	rc2:8;
+			ULONG	rc1:8;
+			ULONG	rc0:8;
 #else
-				ULONG	rc0:8;
-				ULONG	rc1:8;
-				ULONG	rc2:8;
-				ULONG	Rsvd:5;
-				ULONG	ExtIV:1;
-				ULONG	KeyID:2;
+			ULONG	rc0:8;
+			ULONG	rc1:8;
+			ULONG	rc2:8;
+			ULONG	Rsvd:5;
+			ULONG	ExtIV:1;
+			ULONG	KeyID:2;
 #endif
-			}field;
-			ULONG	word;
-		}IV16;
+		}field;
+		ULONG	word;
+	}IV16;
 
 	ULONG	IV32;
 }	TKIP_IV, *PTKIP_IV;
@@ -499,7 +524,7 @@
 
 typedef struct _SOFT_RX_ANT_DIVERSITY_STRUCT {
     BOOLEAN   PrimaryInUsed;
-    BOOLEAN   FirstPktArrivedWhenEvaluate;     
+    BOOLEAN   FirstPktArrivedWhenEvaluate;
     UCHAR     PrimaryRxAnt;     // 0:Ant-A, 1:Ant-B
     UCHAR     SecondaryRxAnt;   // 0:Ant-A, 1:Ant-B
     UCHAR     CurrentRxAnt;     // 0:Ant-A, 1:Ant-B
@@ -535,7 +560,7 @@
 
     NDIS_802_11_AUTHENTICATION_MODE     AuthMode;   // This should match to whatever microsoft defined
     NDIS_802_11_WEP_STATUS              WepStatus;
-    
+
     // MIB:ieee802dot11.dot11smt(1).dot11WEPDefaultKeysTable(3)
     WEP_KEY   SharedKey[SHARE_KEY_NO];      // Keep for backward compatiable
     WPA_KEY   PairwiseKey[PAIRWISE_KEY_NO];
@@ -566,8 +591,8 @@
     // MIB:ieee802dot11.dot11mac(2).dot11OperationTable(1)
     USHORT    RtsThreshold;       // in units of BYTE
     USHORT    FragmentThreshold;
-    BOOLEAN   bFragmentZeroDisable;     // Microsoft use 0 as disable 
-    
+    BOOLEAN   bFragmentZeroDisable;     // Microsoft use 0 as disable
+
     // MIB:ieee802dot11.dot11phy(4).dot11PhyAntennaTable(2)
     UCHAR     CurrentTxAntenna;
     UCHAR     CurrentRxAntenna;
@@ -582,19 +607,19 @@
     UCHAR     TxPowerDriver;	// Driver's last TxPower setting written to hardware, in raw units
     int       TxPowerUser;		// User's desired fixed TxPower setting, in dBm
     BOOLEAN   TxPowerAuto;    // 1 - enable auto TxPower; 0 - fixed
-    
+
     // MIB:ieee802dot11.dot11phy(4).dot11PhyDSSSTable(5)
     UCHAR     Channel;        // current (I)BSS channel used in the station
     UCHAR     CountryRegion;    // Enum of country region, 0:FCC, 1:IC, 2:ETSI, 3:SPAIN, 4:France, 5:MKK, 6:MKK1, 7:Israel
-    
+
     // MIB:ieee802dot11.dot11phy(4).dot11AntennasListTable(8)
     BOOLEAN AntennaSupportTx;
     BOOLEAN AntennaSupportRx;
     BOOLEAN AntennaSupportDiversityRx;
 
     // Use user changed MAC
-    BOOLEAN bLocalAdminMAC;                           
-    
+    BOOLEAN bLocalAdminMAC;
+
     // MIB:ieee802dot11.dot11phy(4).dot11SupportedDataRatesTxTable(9)
     // MIB:ieee802dot11.dot11phy(4).dot11SupportedDataRatesRxTable(10)
     UCHAR     SupportedRates[MAX_LEN_OF_SUPPORTED_RATES];    // Supported rates
@@ -661,7 +686,7 @@
     UCHAR     ChannelList[MAX_LEN_OF_CHANNELS];         // list all supported channels for site survey
     UCHAR     ChannelListNum;                           // number of channel in ChannelList[]
     BOOLEAN   bShowHiddenSSID;
-    
+
     // configuration to be used when this STA starts a new ADHOC network
     IBSS_CONFIG IbssConfig;
 
@@ -679,7 +704,7 @@
     UCHAR                   LedMode;
     RALINK_TIMER_STRUCT       RfTuningTimer;
     STA_WITH_ETHER_BRIDGE               StaWithEtherBridge;
-    
+
     // New for WPA, windows want us to to keep association information and
     // Fixed IEs from last association response
     NDIS_802_11_ASSOCIATION_INFORMATION     AssocInfo;
@@ -700,7 +725,7 @@
     ULONG     BGProtectionInUsed;   // 0: not in-used, 1: in-used
     ULONG     ShortSlotInUsed;      // 0: not in-used, 1: in-used
     USHORT    TxPreambleInUsed;     // Rt802_11PreambleLong, Rt802_11PreambleShort
-    
+
     // PCI clock adjustment round
     UCHAR       PciAdjustmentRound;
 
@@ -718,8 +743,8 @@
 
 
     ULONG                         SystemErrorBitmap;  // b0: E2PROM version error
-    
-    // This soft Rx Antenna Diversity mechanism is used only when user set 
+
+    // This soft Rx Antenna Diversity mechanism is used only when user set
     // RX Antenna = DIVERSITY ON
     SOFT_RX_ANT_DIVERSITY         RxAnt;
 
@@ -753,13 +778,13 @@
     STATE_MACHINE_FUNC      CntlFunc[CNTL_FUNC_SIZE], AssocFunc[ASSOC_FUNC_SIZE];
     STATE_MACHINE_FUNC      AuthFunc[AUTH_FUNC_SIZE], AuthRspFunc[AUTH_RSP_FUNC_SIZE];
     STATE_MACHINE_FUNC      SyncFunc[SYNC_FUNC_SIZE], WpaPskFunc[WPA_PSK_FUNC_SIZE];
-    
+
     ASSOC_AUX               AssocAux;
     AUTH_AUX                AuthAux;
     AUTH_RSP_AUX            AuthRspAux;
     SYNC_AUX                SyncAux;
     CNTL_AUX                CntlAux;
-    
+
     COUNTER_802_11          PrevWlanCounters;
     ULONG                   ChannelQuality;  // 0..100, Channel Quality Indication for Roaming
 
@@ -770,7 +795,7 @@
     UINT                    ShiftReg;
     PSPOLL_FRAME            PsFr;
     MACHDR                  NullFr;
-    
+
     RALINK_TIMER_STRUCT     PeriodicTimer;
     ULONG                   PeriodicRound;
     ULONG                   PrevTxCnt;
@@ -849,7 +874,7 @@
 typedef struct PACKED _TUPLE_CACHE    {
     BOOLEAN         Valid;
     MACADDR         MAC;
-    USHORT          Sequence; 
+    USHORT          Sequence;
     USHORT          Frag;
 }   TUPLE_CACHE, *PTUPLE_CACHE;
 
@@ -872,7 +897,7 @@
 typedef struct PACKED _TKIP_KEY_INFO  {
     UINT        nBytesInM;  // # bytes in M for MICKEY
     ULONG       IV16;
-    ULONG       IV32;   
+    ULONG       IV32;
     ULONG       K0;         // for MICKEY Low
     ULONG       K1;         // for MICKEY Hig
     ULONG       L;          // Current state for MICKEY
@@ -937,12 +962,14 @@
 //
 typedef struct _RTMP_ADAPTER
 {
-    char nickn[IW_ESSID_MAX_SIZE+1]; // nickname, only used in the iwconfig i/f 
+    char nickn[IW_ESSID_MAX_SIZE+1]; // nickname, only used in the iwconfig i/f
     int chip_id;
 
     unsigned long           CSRBaseAddress;     // PCI MMIO Base Address, all access will use
                                                 // NdisReadRegisterXx or NdisWriteRegisterXx
 
+	struct rt2x00debug debug;
+
     // configuration
     UCHAR                   PermanentAddress[ETH_ALEN];    // Factory default MAC address
     UCHAR                   CurrentAddress[ETH_ALEN];      // User changed MAC address
@@ -958,7 +985,7 @@
     struct ring_desc        BeaconRing;                 // Beacon Ring, only one
 
     MGMT_STRUC              MgmtRing[MGMT_RING_SIZE];   // management ring size
-    
+
     ULONG                   CurRxIndex;                 // Next RxD read pointer
     ULONG                   CurDecryptIndex;            // Next RxD decrypt read pointer
     ULONG                   CurTxIndex;                 // Next TxD write pointer
@@ -985,17 +1012,17 @@
     struct sk_buff_head            TxSwQueue0;                 // Tx software priority queue 0 mapped to 0.1
     struct sk_buff_head            TxSwQueue1;                 // Tx software priority queue 1 mapped to 2.3
     struct sk_buff_head            TxSwQueue2;                 // Tx software priority queue 2 mapped to 4.5
-    struct sk_buff_head            TxSwQueue3; 
+    struct sk_buff_head            TxSwQueue3;
 
     USHORT                  Sequence;                   // Current sequence number
 
     TUPLE_CACHE             TupleCache[MAX_CLIENT];     // Maximum number of tuple caches, only useful in Ad-Hoc
     UCHAR                   TupleCacheLastUpdateIndex;  // 0..MAX_CLIENT-1
     FRAGMENT_FRAME          FragFrame;                  // Frame storage for fragment frame
-    
+
     // For MiniportTransferData
     PUCHAR                  pRxData;                    // Pointer to current RxRing offset / fragment frame offset
-    
+
     // Counters for 802.3 & generic.
     // Add 802.11 specific counters later
     COUNTER_802_3           Counters;                   // 802.3 counters
@@ -1021,11 +1048,11 @@
     BOOLEAN                 bAcceptBroadcast;
     BOOLEAN                 bAcceptAllMulticast;
     BOOLEAN                 bAcceptPromiscuous;
-    
+
     // Control to check Tx hang
     BOOLEAN                 bTxBusy;
     //PQUEUE_ENTRY            FirstEntryInQueue;      // The first packet in Tx queue
-    
+
     // Control disconnect / connect event generation
     ULONG                   LinkDownTime;
     ULONG                   LastRxRate;
@@ -1044,7 +1071,7 @@
 
     BOOLEAN                 bNetDeviceStopQueue;
     BOOLEAN                 NeedSwapToLittleEndian;
-    
+
 #if WIRELESS_EXT >= 12
     struct iw_statistics iw_stats;
 #endif
@@ -1054,9 +1081,6 @@
 	ATE_INFO				ate;
 #endif	//#ifdef RALINK_ATE
 
-#if (LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,0))
-    struct work_struct mlme_work;
-#endif
 }   RTMP_ADAPTER, *PRTMP_ADAPTER;
 
 //
@@ -1064,10 +1088,9 @@
 //
 typedef struct _SHA_CTX
 {
-    ULONG       H[5];
-    ULONG       W[80];
-    INT         lenW;
-    ULONG       sizeHi, sizeLo;
+    ULONG Buf[5];		// buffers of five states
+    UCHAR Input[80];		// input message
+    ULONG LenInBitCount[2];	// length counter for input message, 0 up to 64 bits
 }   SHA_CTX;
 
 //
@@ -1085,7 +1108,7 @@
     IN  PRTMP_ADAPTER   pAd)
 {
     // 0xFF37 : Txdone & Rxdone, 0xFF07: Txdonw, Rxdone, PrioDone, AtimDone,
-    RTMP_IO_WRITE32(pAd, CSR8, 0xFE14);     
+    RTMP_IO_WRITE32(pAd, CSR8, 0xFE14);
     RTMP_SET_FLAG(pAd, fRTMP_ADAPTER_INTERRUPT_ACTIVE);
 }
 
@@ -1096,10 +1119,16 @@
 INT     RT2500_close(
     IN  struct net_device *net_dev);
 
+#if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,19)
 irqreturn_t RTMPIsr(
-    IN  INT             irq, 
-    IN  VOID            *dev_instance, 
+    IN  INT             irq,
+    IN  VOID            *dev_instance,
     IN  struct pt_regs  *rgs);
+#else
+irqreturn_t RTMPIsr(
+    IN  INT             irq,
+    IN  VOID            *dev_instance);
+#endif
 
 VOID    RT2500_timer(
     IN  unsigned long data);
@@ -1108,16 +1137,16 @@
     IN  struct net_device *net_dev);
 
 INT     RTMPSendPackets(
-    IN  struct sk_buff *skb, 
+    IN  struct sk_buff *skb,
     IN  struct net_device *net_dev);
 
 INT     RT2500_probe(
-    IN  struct pci_dev              *pPci_Dev, 
+    IN  struct pci_dev              *pPci_Dev,
     IN  const struct pci_device_id  *ent);
 
 INT     RT2500_ioctl(
-    IN  struct net_device   *net_dev, 
-    IN  OUT struct ifreq    *rq, 
+    IN  struct net_device   *net_dev,
+    IN  OUT struct ifreq    *rq,
     IN  INT                 cmd);
 
 VOID    RTMPRingCleanUp(
@@ -1179,7 +1208,7 @@
 INT RTMPGetKeyParameter(
     IN  PUCHAR  section,
     IN  PCHAR   key,
-    OUT PCHAR   dest,   
+    OUT PCHAR   dest,
     IN  INT     destsize,
     IN  PCHAR   buffer);
 
@@ -1187,7 +1216,7 @@
     IN  PRTMP_ADAPTER   pAd);
 
 #define RTMPEqualMemory(p1,p2,n) (memcmp((p1),(p2),(n)) == 0)
-    
+
 ULONG   RTMPCompareMemory(
     IN  PVOID   pSrc1,
     IN  PVOID   pSrc2,
@@ -1244,7 +1273,7 @@
 NDIS_STATUS RTMPSendPacket(
     IN  PRTMP_ADAPTER   pAdapter,
     IN  struct sk_buff *skb);
-    
+
 //VOID  RTMPDeQueuePacket(
 //    IN    PRTMP_ADAPTER   pAdapter,
 //    IN    PQUEUE_HEADER   pQueue);
@@ -1320,8 +1349,8 @@
     IN  UCHAR           TxRate);
 
 NDIS_STATUS RTMPApplyPacketFilter(
-    IN  PRTMP_ADAPTER   pAdapter, 
-    IN  PRXD_STRUC      pRxD, 
+    IN  PRTMP_ADAPTER   pAdapter,
+    IN  PRXD_STRUC      pRxD,
     IN  PHEADER_802_11  pHeader);
 
 struct sk_buff_head* RTMPCheckTxSwQueue(
@@ -1329,20 +1358,20 @@
     OUT UCHAR           *AccessCategory);
 
 VOID    RTMPReportMicError(
-    IN  PRTMP_ADAPTER   pAdapter, 
+    IN  PRTMP_ADAPTER   pAdapter,
     IN  PWPA_KEY        pWpaKey);
 //
 // Private routines in rtmp_wep.c
 //
 VOID    RTMPInitWepEngine(
-    IN  PRTMP_ADAPTER   pAdapter,   
+    IN  PRTMP_ADAPTER   pAdapter,
     IN  PUCHAR          pKey,
     IN  UCHAR           KeyId,
-    IN  UCHAR           KeyLen, 
+    IN  UCHAR           KeyLen,
     IN  PUCHAR          pDest);
 
 VOID    RTMPEncryptData(
-    IN  PRTMP_ADAPTER   pAdapter,   
+    IN  PRTMP_ADAPTER   pAdapter,
     IN  PUCHAR          pSrc,
     IN  PUCHAR          pDest,
     IN  UINT            Len);
@@ -1366,7 +1395,7 @@
 
 VOID    ARCFOUR_DECRYPT(
     IN  PARCFOURCONTEXT Ctx,
-    IN  PUCHAR          pDest, 
+    IN  PUCHAR          pDest,
     IN  PUCHAR          pSrc,
     IN  UINT            Len);
 
@@ -1394,18 +1423,18 @@
     IN PRTMP_ADAPTER pAd);
 
 VOID    AsicSwitchChannel(
-    IN  PRTMP_ADAPTER   pAdapter, 
+    IN  PRTMP_ADAPTER   pAdapter,
     IN UCHAR Channel);
 
 VOID    AsicLockChannel(
-    IN PRTMP_ADAPTER pAd, 
+    IN PRTMP_ADAPTER pAd,
     IN UCHAR Channel) ;
 
 VOID AsicRfTuningExec(
     IN unsigned long data);
 
 VOID    AsicSleepThenAutoWakeup(
-    IN  PRTMP_ADAPTER   pAdapter, 
+    IN  PRTMP_ADAPTER   pAdapter,
     IN  USHORT TbttNumToNextWakeUp);
 
 VOID    AsicForceSleep(
@@ -1415,7 +1444,7 @@
     IN PRTMP_ADAPTER pAdapter);
 
 VOID    AsicSetBssid(
-    IN  PRTMP_ADAPTER   pAdapter, 
+    IN  PRTMP_ADAPTER   pAdapter,
     IN  MACADDR *Bssid);
 
 VOID    AsicDisableSync(
@@ -1453,16 +1482,16 @@
     IN PRTMP_ADAPTER pAd);
 
 VOID    MacAddrRandomBssid(
-    IN  PRTMP_ADAPTER   pAdapter, 
+    IN  PRTMP_ADAPTER   pAdapter,
     OUT PMACADDR Addr);
 
 VOID    MgtMacHeaderInit(
-    IN  PRTMP_ADAPTER   pAdapter, 
-    IN OUT PMACHDR Hdr, 
-    IN UCHAR Subtype, 
-    IN UCHAR ToDs, 
-//  IN UCHAR AddrType, 
-    IN PMACADDR Ds, 
+    IN  PRTMP_ADAPTER   pAdapter,
+    IN OUT PMACHDR Hdr,
+    IN UCHAR Subtype,
+    IN UCHAR ToDs,
+//  IN UCHAR AddrType,
+    IN PMACADDR Ds,
     IN PMACADDR Bssid);
 
 VOID MlmeRadioOff(
@@ -1475,66 +1504,69 @@
     IN BSS_TABLE *Tab);
 
 ULONG BssTableSearch(
-    IN BSS_TABLE *Tab, 
+    IN BSS_TABLE *Tab,
     IN PMACADDR Bssid);
 
 VOID BssTableDeleteEntry(
-    IN OUT  BSS_TABLE *Tab, 
+    IN OUT  BSS_TABLE *Tab,
     IN      PMACADDR Bssid);
 
 VOID  BssEntrySet(
-    IN  PRTMP_ADAPTER   pAdapter, 
-    OUT BSS_ENTRY *Bss, 
-    IN MACADDR *Bssid, 
-    IN CHAR Ssid[], 
-    IN UCHAR SsidLen, 
-    IN UCHAR BssType, 
+    IN  PRTMP_ADAPTER   pAdapter,
+    OUT BSS_ENTRY *Bss,
+    IN MACADDR *Bssid,
+    IN CHAR Ssid[],
+    IN UCHAR SsidLen,
+    IN UCHAR BssType,
     IN USHORT BeaconPeriod,
-    IN BOOLEAN CfExist, 
-    IN CF_PARM *CfParm, 
-    IN USHORT AtimWin, 
-    IN USHORT CapabilityInfo, 
-    IN UCHAR Rates[], 
+    IN BOOLEAN CfExist,
+    IN CF_PARM *CfParm,
+    IN USHORT AtimWin,
+    IN USHORT CapabilityInfo,
+    IN UCHAR Rates[],
     IN UCHAR RatesLen,
     IN BOOLEAN ExtendedRateIeExist,
     IN UCHAR Channel,
     IN UCHAR Rssi,
     IN UCHAR Noise,
     IN LARGE_INTEGER TimeStamp,
+    IN USHORT VarIELen,          // Length of all saved IEs.
     IN PNDIS_802_11_VARIABLE_IEs pVIE);
 
 ULONG  BssTableSetEntry(
-    IN  PRTMP_ADAPTER   pAdapter, 
-    OUT BSS_TABLE *Tab, 
-    IN MACADDR *Bssid, 
-    IN CHAR Ssid[], 
-    IN UCHAR SsidLen, 
-    IN UCHAR BssType, 
-    IN USHORT BeaconPeriod, 
-    IN BOOLEAN CfExist, 
-    IN CF_PARM *CfParm, 
-    IN USHORT AtimWin, 
-    IN USHORT CapabilityInfo, 
-    IN UCHAR Rates[], 
+    IN  PRTMP_ADAPTER   pAdapter,
+    OUT BSS_TABLE *Tab,
+    IN MACADDR *Bssid,
+    IN CHAR Ssid[],
+    IN UCHAR SsidLen,
+    IN UCHAR BssType,
+    IN USHORT BeaconPeriod,
+    IN BOOLEAN CfExist,
+    IN CF_PARM *CfParm,
+    IN USHORT AtimWin,
+    IN USHORT CapabilityInfo,
+    IN UCHAR Rates[],
     IN UCHAR RatesLen,
     IN BOOLEAN ExtendedRateIeExist,
     IN UCHAR Channel,
     IN UCHAR Rssi,
     IN UCHAR Noise,
     IN LARGE_INTEGER TimeStamp,
+    IN USHORT VarIELen,          // Length of all saved IEs.
     IN PNDIS_802_11_VARIABLE_IEs pVIE);
 
 VOID  BssTableSsidSort(
-    IN  PRTMP_ADAPTER   pAd, 
-    OUT BSS_TABLE *OutTab, 
-    IN  CHAR Ssid[], 
+    IN  PRTMP_ADAPTER   pAd,
+    OUT BSS_TABLE *OutTab,
+    IN  CHAR Ssid[],
     IN  UCHAR SsidLen);
 
 VOID  BssTableSortByRssi(
     IN OUT BSS_TABLE *OutTab);
 
-NDIS_802_11_WEP_STATUS  BssCipherParse(
-    IN  PUCHAR  pCipher);
+USHORT  BssCipherParse(
+    IN  PBEACON_EID_STRUCT	pEid,
+    IN  USHORT              VarIELen); // Length of all saved IEs.
 
 NDIS_STATUS  MlmeQueueInit(
     IN MLME_QUEUE *Queue);
@@ -1543,70 +1575,64 @@
     IN MLME_QUEUE *Queue);
 
 BOOLEAN MlmeEnqueue(
-    OUT MLME_QUEUE *Queue, 
-    IN ULONG Machine, 
-    IN ULONG MsgType, 
-    IN ULONG MsgLen, 
+    OUT MLME_QUEUE *Queue,
+    IN ULONG Machine,
+    IN ULONG MsgType,
+    IN ULONG MsgLen,
     IN VOID *Msg);
 
 BOOLEAN MlmeEnqueueForRecv(
-    IN  PRTMP_ADAPTER   pAdapter, 
-    OUT MLME_QUEUE *Queue, 
-    IN ULONG TimeStampHigh, 
-    IN ULONG TimeStampLow, 
-    IN UCHAR Rssi, 
+    IN  PRTMP_ADAPTER   pAdapter,
+    OUT MLME_QUEUE *Queue,
+    IN ULONG TimeStampHigh,
+    IN ULONG TimeStampLow,
+    IN UCHAR Rssi,
     IN UCHAR Noise,
-    IN ULONG MsgLen, 
+    IN ULONG MsgLen,
     IN PVOID Msg);
 
 BOOLEAN MlmeDequeue(
-    IN MLME_QUEUE *Queue, 
+    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 MACFRAME *Fr, 
-    OUT INT *Machine, 
+    IN MACFRAME *Fr,
+    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 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 *S,
+    IN ULONG St,
+    ULONG Msg,
     IN STATE_MACHINE_FUNC F);
 
 VOID StateMachinePerformAction(
-    IN  PRTMP_ADAPTER   pAdapter, 
-    IN STATE_MACHINE *S, 
+    IN  PRTMP_ADAPTER   pAdapter,
+    IN STATE_MACHINE *S,
     IN MLME_QUEUE_ELEM *Elem);
 
 VOID Drop(
-    IN  PRTMP_ADAPTER   pAdapter, 
+    IN  PRTMP_ADAPTER   pAdapter,
     IN MLME_QUEUE_ELEM *Elem);
 
 VOID StateMachineDestroy(
     IN STATE_MACHINE *Sm);
 
 VOID  AssocStateMachineInit(
-    IN  PRTMP_ADAPTER   pAdapter, 
-    IN  STATE_MACHINE *Sm, 
+    IN  PRTMP_ADAPTER   pAdapter,
+    IN  STATE_MACHINE *Sm,
     OUT STATE_MACHINE_FUNC Trans[]);
 
 VOID  ReassocTimeout(
@@ -1620,43 +1646,43 @@
 
 //----------------------------------------------
 VOID  MlmeDisassocReqAction(
-    IN  PRTMP_ADAPTER   pAdapter, 
+    IN  PRTMP_ADAPTER   pAdapter,
     IN  MLME_QUEUE_ELEM *Elem);
 
 VOID  MlmeAssocReqAction(
-    IN  PRTMP_ADAPTER   pAdapter, 
+    IN  PRTMP_ADAPTER   pAdapter,
     IN  MLME_QUEUE_ELEM *Elem);
 
 VOID  MlmeReassocReqAction(
-    IN  PRTMP_ADAPTER   pAdapter, 
+    IN  PRTMP_ADAPTER   pAdapter,
     IN  MLME_QUEUE_ELEM *Elem);
 
 VOID  MlmeDisassocReqAction(
-    IN  PRTMP_ADAPTER   pAdapter, 
+    IN  PRTMP_ADAPTER   pAdapter,
     IN  MLME_QUEUE_ELEM *Elem);
 
 VOID  PeerAssocRspAction(
-    IN  PRTMP_ADAPTER   pAdapter, 
+    IN  PRTMP_ADAPTER   pAdapter,
     IN  MLME_QUEUE_ELEM *Elem);
 
 VOID  PeerReassocRspAction(
-    IN  PRTMP_ADAPTER   pAdapter, 
+    IN  PRTMP_ADAPTER   pAdapter,
     IN  MLME_QUEUE_ELEM *Elem);
 
 VOID  PeerDisassocAction(
-    IN  PRTMP_ADAPTER   pAdapter, 
+    IN  PRTMP_ADAPTER   pAdapter,
     IN  MLME_QUEUE_ELEM *Elem);
 
 VOID  DisassocTimeoutAction(
-    IN  PRTMP_ADAPTER   pAdapter, 
+    IN  PRTMP_ADAPTER   pAdapter,
     IN  MLME_QUEUE_ELEM *Elem);
 
 VOID  AssocTimeoutAction(
-    IN  PRTMP_ADAPTER   pAdapter, 
+    IN  PRTMP_ADAPTER   pAdapter,
     IN  MLME_QUEUE_ELEM *Elem);
 
 VOID  ReassocTimeoutAction(
-    IN  PRTMP_ADAPTER   pAdapter, 
+    IN  PRTMP_ADAPTER   pAdapter,
     IN  MLME_QUEUE_ELEM *Elem);
 
 VOID  Cls3errAction(
@@ -1682,60 +1708,60 @@
     IN  PRTMP_ADAPTER   pAdapter);
 
 VOID  AssocPostProc(
-    IN  PRTMP_ADAPTER   pAdapter, 
-    IN  MACADDR *Addr2, 
-    IN  USHORT CapabilityInfo, 
-    IN  USHORT Aid, 
-    IN  UCHAR Rates[], 
+    IN  PRTMP_ADAPTER   pAdapter,
+    IN  MACADDR *Addr2,
+    IN  USHORT CapabilityInfo,
+    IN  USHORT Aid,
+    IN  UCHAR Rates[],
     IN  UCHAR RatesLen,
     IN  BOOLEAN ExtendedRateIeExist);
 
 VOID AuthStateMachineInit(
-    IN  PRTMP_ADAPTER   pAdapter, 
-    IN PSTATE_MACHINE sm, 
+    IN  PRTMP_ADAPTER   pAdapter,
+    IN PSTATE_MACHINE sm,
     OUT STATE_MACHINE_FUNC Trans[]);
 
 VOID AuthTimeout(
     IN  unsigned long data);
 
 VOID MlmeAuthReqAction(
-    IN  PRTMP_ADAPTER   pAdapter, 
+    IN  PRTMP_ADAPTER   pAdapter,
     IN  MLME_QUEUE_ELEM *Elem);
 
 VOID PeerAuthRspAtSeq2Action(
-    IN  PRTMP_ADAPTER   pAdapter, 
+    IN  PRTMP_ADAPTER   pAdapter,
     IN  MLME_QUEUE_ELEM *Elem);
 
 VOID PeerAuthRspAtSeq4Action(
-    IN  PRTMP_ADAPTER   pAdapter, 
+    IN  PRTMP_ADAPTER   pAdapter,
     IN  MLME_QUEUE_ELEM *Elem);
 
 VOID AuthTimeoutAction(
-    IN  PRTMP_ADAPTER   pAdapter, 
+    IN  PRTMP_ADAPTER   pAdapter,
     IN  MLME_QUEUE_ELEM *Elem);
 
 VOID Cls2errAction(
-    IN  PRTMP_ADAPTER   pAdapter, 
+    IN  PRTMP_ADAPTER   pAdapter,
     IN  PMACADDR pAddr);
 
 VOID MlmeDeauthReqAction(
-    IN  PRTMP_ADAPTER   pAdapter, 
+    IN  PRTMP_ADAPTER   pAdapter,
     IN  MLME_QUEUE_ELEM *Elem);
 
 VOID InvalidStateWhenAuth(
-    IN  PRTMP_ADAPTER   pAdapter, 
+    IN  PRTMP_ADAPTER   pAdapter,
     IN  MLME_QUEUE_ELEM *Elem);
 
 //VOID MlmeDeauthReqProc(
-//    IN    PRTMP_ADAPTER   pAdapter, 
-//    IN  MACADDR *Addr, 
+//    IN    PRTMP_ADAPTER   pAdapter,
+//    IN  MACADDR *Addr,
 //    IN  USHORT Reason);
 
 //=============================================
 
 VOID AuthRspStateMachineInit(
-    IN  PRTMP_ADAPTER   pAdapter, 
-    IN  PSTATE_MACHINE Sm, 
+    IN  PRTMP_ADAPTER   pAdapter,
+    IN  PSTATE_MACHINE Sm,
     IN  STATE_MACHINE_FUNC Trans[]);
 
 
@@ -1743,34 +1769,34 @@
     IN  unsigned long data);
 
 VOID AuthRspChallengeTimeoutAction(
-    IN  PRTMP_ADAPTER   pAdapter, 
+    IN  PRTMP_ADAPTER   pAdapter,
     IN  MLME_QUEUE_ELEM *Elem);
 
 VOID PeerAuthAtAuthRspIdleAction(
-    IN  PRTMP_ADAPTER   pAdapter, 
+    IN  PRTMP_ADAPTER   pAdapter,
     IN  MLME_QUEUE_ELEM *Elem);
 
 VOID PeerAuthAtAuthRspWaitAction(
-    IN  PRTMP_ADAPTER   pAdapter, 
+    IN  PRTMP_ADAPTER   pAdapter,
     IN  MLME_QUEUE_ELEM *Elem);
 
 VOID PeerDeauthAction(
-    IN  PRTMP_ADAPTER   pAdaptor, 
+    IN  PRTMP_ADAPTER   pAdaptor,
     IN  MLME_QUEUE_ELEM *Elem);
 
 VOID PeerAuthSimpleRspGenAndSend(
-    IN  PRTMP_ADAPTER pAdapter, 
-    IN  PMACHDR Hdr, 
-    IN  USHORT Alg, 
-    IN  USHORT Seq, 
-    IN  USHORT Reason, 
+    IN  PRTMP_ADAPTER pAdapter,
+    IN  PMACHDR Hdr,
+    IN  USHORT Alg,
+    IN  USHORT Seq,
+    IN  USHORT Reason,
     IN  USHORT Status);
 
 //========================================
 
 VOID SyncStateMachineInit(
-    IN  PRTMP_ADAPTER   pAdapter, 
-    IN  STATE_MACHINE *Sm, 
+    IN  PRTMP_ADAPTER   pAdapter,
+    IN  STATE_MACHINE *Sm,
     OUT STATE_MACHINE_FUNC Trans[]);
 
 VOID BeaconTimeout(
@@ -1783,23 +1809,23 @@
     IN  unsigned long data);
 
 VOID MlmeScanReqAction(
-    IN  PRTMP_ADAPTER   pAdapter, 
+    IN  PRTMP_ADAPTER   pAdapter,
     IN  MLME_QUEUE_ELEM *Elem);
 
 VOID InvalidStateWhenScan(
-    IN  PRTMP_ADAPTER   pAdapter, 
+    IN  PRTMP_ADAPTER   pAdapter,
     IN  MLME_QUEUE_ELEM *Elem);
 
 VOID InvalidStateWhenJoin(
-    IN  PRTMP_ADAPTER   pAdapter, 
+    IN  PRTMP_ADAPTER   pAdapter,
     IN  MLME_QUEUE_ELEM *Elem);
 
 VOID InvalidStateWhenStart(
-    IN  PRTMP_ADAPTER   pAdapter, 
+    IN  PRTMP_ADAPTER   pAdapter,
     IN  MLME_QUEUE_ELEM *Elem);
 
 VOID PeerBeacon(
-    IN  PRTMP_ADAPTER   pAdapter, 
+    IN  PRTMP_ADAPTER   pAdapter,
     IN  MLME_QUEUE_ELEM *Elem);
 
 VOID EnqueueProbeRequest(
@@ -1808,61 +1834,61 @@
 //=========================================
 
 VOID MlmeCntlInit(
-    IN  PRTMP_ADAPTER   pAdapter, 
-    IN  STATE_MACHINE *S, 
+    IN  PRTMP_ADAPTER   pAdapter,
+    IN  STATE_MACHINE *S,
     OUT STATE_MACHINE_FUNC Trans[]);
 
 VOID MlmeCntlMachinePerformAction(
-    IN  PRTMP_ADAPTER   pAdapter, 
-    IN  STATE_MACHINE *S, 
+    IN  PRTMP_ADAPTER   pAdapter,
+    IN  STATE_MACHINE *S,
     IN  MLME_QUEUE_ELEM *Elem);
 
 VOID CntlIdleProc(
-    IN PRTMP_ADAPTER pAdapter, 
+    IN PRTMP_ADAPTER pAdapter,
     IN MLME_QUEUE_ELEM *Elem);
 
 VOID CntlOidScanProc(
-    IN  PRTMP_ADAPTER   pAdapter, 
+    IN  PRTMP_ADAPTER   pAdapter,
     IN  MLME_QUEUE_ELEM *Elem);
 
 VOID CntlOidSsidProc(
-    IN  PRTMP_ADAPTER   pAdapter, 
+    IN  PRTMP_ADAPTER   pAdapter,
     IN  MLME_QUEUE_ELEM * Elem);
 
 VOID CntlOidRTBssidProc(
-    IN  PRTMP_ADAPTER   pAdapter, 
+    IN  PRTMP_ADAPTER   pAdapter,
     IN  MLME_QUEUE_ELEM *Elem);
 
 VOID CntlMlmeRoamingProc(
-    IN  PRTMP_ADAPTER   pAdapter, 
+    IN  PRTMP_ADAPTER   pAdapter,
     IN  MLME_QUEUE_ELEM *Elem);
 
 VOID CntlWaitDisassocProc(
-    IN  PRTMP_ADAPTER   pAdapter, 
+    IN  PRTMP_ADAPTER   pAdapter,
     IN  MLME_QUEUE_ELEM *Elem);
 
 VOID CntlWaitJoinProc(
-    IN  PRTMP_ADAPTER   pAdapter, 
+    IN  PRTMP_ADAPTER   pAdapter,
     IN  MLME_QUEUE_ELEM *Elem);
 
 VOID CntlWaitReassocProc(
-    IN  PRTMP_ADAPTER   pAdapter, 
+    IN  PRTMP_ADAPTER   pAdapter,
     IN  MLME_QUEUE_ELEM *Elem);
 
 VOID CntlWaitStartProc(
-    IN  PRTMP_ADAPTER   pAdapter, 
+    IN  PRTMP_ADAPTER   pAdapter,
     IN  MLME_QUEUE_ELEM *Elem);
 
 VOID CntlWaitAuthProc(
-    IN  PRTMP_ADAPTER   pAdapter, 
+    IN  PRTMP_ADAPTER   pAdapter,
     IN  MLME_QUEUE_ELEM *Elem);
 
 VOID CntlWaitAuthProc2(
-    IN  PRTMP_ADAPTER pAdapter, 
+    IN  PRTMP_ADAPTER pAdapter,
     IN  MLME_QUEUE_ELEM *Elem);
 
 VOID CntlWaitAssocProc(
-    IN  PRTMP_ADAPTER   pAdapter, 
+    IN  PRTMP_ADAPTER   pAdapter,
     IN  MLME_QUEUE_ELEM *Elem);
 
 VOID LinkUp(
@@ -1873,8 +1899,8 @@
     IN  PRTMP_ADAPTER   pAdapter);
 
 VOID MlmeCntlConfirm(
-    IN  PRTMP_ADAPTER   pAdapter, 
-    IN  ULONG MsgType, 
+    IN  PRTMP_ADAPTER   pAdapter,
+    IN  ULONG MsgType,
     IN  USHORT Msg);
 
 VOID IterateOnBssTab(
@@ -1884,42 +1910,42 @@
     IN  PRTMP_ADAPTER   pAdapter);;
 
 VOID JoinParmFill(
-    IN  PRTMP_ADAPTER   pAdapter, 
-    IN  OUT MLME_JOIN_REQ_STRUCT *JoinReq, 
+    IN  PRTMP_ADAPTER   pAdapter,
+    IN  OUT MLME_JOIN_REQ_STRUCT *JoinReq,
     IN  ULONG BssIdx);
 
 VOID AssocParmFill(
-    IN  PRTMP_ADAPTER   pAdapter, 
-    IN OUT MLME_ASSOC_REQ_STRUCT *AssocReq, 
-    IN  MACADDR *Addr, 
-    IN  USHORT CapabilityInfo, 
-    IN  ULONG Timeout, 
+    IN  PRTMP_ADAPTER   pAdapter,
+    IN OUT MLME_ASSOC_REQ_STRUCT *AssocReq,
+    IN  MACADDR *Addr,
+    IN  USHORT CapabilityInfo,
+    IN  ULONG Timeout,
     IN  USHORT ListenIntv);
 
 VOID ScanParmFill(
-    IN  PRTMP_ADAPTER   pAdapter, 
-    IN  OUT MLME_SCAN_REQ_STRUCT *ScanReq, 
-    IN  CHAR Ssid[], 
-    IN  UCHAR SsidLen, 
-    IN  UCHAR BssType, 
-    IN  UCHAR ScanType); 
+    IN  PRTMP_ADAPTER   pAdapter,
+    IN  OUT MLME_SCAN_REQ_STRUCT *ScanReq,
+    IN  CHAR Ssid[],
+    IN  UCHAR SsidLen,
+    IN  UCHAR BssType,
+    IN  UCHAR ScanType);
 
 VOID DisassocParmFill(
-    IN  PRTMP_ADAPTER   pAdapter, 
-    IN  OUT MLME_DISASSOC_REQ_STRUCT *DisassocReq, 
-    IN  MACADDR *Addr, 
+    IN  PRTMP_ADAPTER   pAdapter,
+    IN  OUT MLME_DISASSOC_REQ_STRUCT *DisassocReq,
+    IN  MACADDR *Addr,
     IN  USHORT Reason);
 
 VOID StartParmFill(
-    IN  PRTMP_ADAPTER   pAdapter, 
-    IN  OUT MLME_START_REQ_STRUCT *StartReq, 
-    IN  CHAR Ssid[], 
+    IN  PRTMP_ADAPTER   pAdapter,
+    IN  OUT MLME_START_REQ_STRUCT *StartReq,
+    IN  CHAR Ssid[],
     IN  UCHAR SsidLen);
 
 VOID AuthParmFill(
-    IN  PRTMP_ADAPTER   pAdapter, 
-    IN  OUT MLME_AUTH_REQ_STRUCT *AuthReq, 
-    IN  MACADDR *Addr, 
+    IN  PRTMP_ADAPTER   pAdapter,
+    IN  OUT MLME_AUTH_REQ_STRUCT *AuthReq,
+    IN  MACADDR *Addr,
     IN  USHORT Alg);
 
 VOID EnqueuePsPoll(
@@ -1933,39 +1959,39 @@
     IN  UCHAR         TxRate);
 
 VOID MlmeJoinReqAction(
-    IN  PRTMP_ADAPTER   pAdapter, 
+    IN  PRTMP_ADAPTER   pAdapter,
     IN  MLME_QUEUE_ELEM *Elem);
 
 VOID MlmeScanReqAction(
-    IN  PRTMP_ADAPTER   pAdapter, 
+    IN  PRTMP_ADAPTER   pAdapter,
     IN  MLME_QUEUE_ELEM *Elem);
 
 VOID MlmeStartReqAction(
-    IN  PRTMP_ADAPTER   pAdapter, 
+    IN  PRTMP_ADAPTER   pAdapter,
     IN  MLME_QUEUE_ELEM *Elem);
 
 VOID ScanTimeoutAction(
-    IN  PRTMP_ADAPTER   pAdapter, 
+    IN  PRTMP_ADAPTER   pAdapter,
     IN  MLME_QUEUE_ELEM *Elem);
 
 VOID BeaconTimeoutAtJoinAction(
-    IN  PRTMP_ADAPTER   pAdapter, 
+    IN  PRTMP_ADAPTER   pAdapter,
     IN  MLME_QUEUE_ELEM *Elem);
 
 VOID PeerBeaconAtScanAction(
-    IN  PRTMP_ADAPTER   pAdapter, 
+    IN  PRTMP_ADAPTER   pAdapter,
     IN  MLME_QUEUE_ELEM *Elem);
 
 VOID PeerBeaconAtJoinAction(
-    IN  PRTMP_ADAPTER   pAdapter, 
+    IN  PRTMP_ADAPTER   pAdapter,
     IN  MLME_QUEUE_ELEM *Elem);
 
 VOID PeerBeacon(
-    IN  PRTMP_ADAPTER   pAdapter, 
+    IN  PRTMP_ADAPTER   pAdapter,
     IN  MLME_QUEUE_ELEM *Elem);
 
 VOID PeerProbeReqAction(
-    IN  PRTMP_ADAPTER pAd, 
+    IN  PRTMP_ADAPTER pAd,
     IN  MLME_QUEUE_ELEM *Elem);
 
 VOID ScanNextChannel(
@@ -1975,142 +2001,143 @@
     IN  PRTMP_ADAPTER pAdapter);
 
 BOOLEAN MlmeScanReqSanity(
-    IN  PRTMP_ADAPTER   pAdapter, 
-    IN  VOID *Msg, 
-    IN  ULONG MsgLen, 
-    OUT UCHAR *BssType, 
-    OUT CHAR ssid[], 
-    OUT UCHAR *SsidLen, 
+    IN  PRTMP_ADAPTER   pAdapter,
+    IN  VOID *Msg,
+    IN  ULONG MsgLen,
+    OUT UCHAR *BssType,
+    OUT CHAR ssid[],
+    OUT UCHAR *SsidLen,
     OUT UCHAR *ScanType);
 
 BOOLEAN PeerBeaconAndProbeRspSanity(
-    IN  PRTMP_ADAPTER   pAdapter, 
-    IN  VOID *Msg, 
-    IN  ULONG MsgLen, 
-    OUT MACADDR *Addr2, 
-    OUT MACADDR *Bssid, 
-    OUT CHAR Ssid[], 
-    OUT UCHAR *SsidLen, 
-    OUT UCHAR *BssType, 
-    OUT USHORT *BeaconPeriod, 
-    OUT UCHAR *Channel, 
-    OUT LARGE_INTEGER *Timestamp, 
-    OUT BOOLEAN *CfExist, 
-    OUT CF_PARM *Cf, 
-    OUT USHORT *AtimWin, 
-    OUT USHORT *CapabilityInfo, 
-    OUT UCHAR Rate[], 
+    IN  PRTMP_ADAPTER   pAdapter,
+    IN  VOID *Msg,
+    IN  ULONG MsgLen,
+    OUT MACADDR *Addr2,
+    OUT MACADDR *Bssid,
+    OUT CHAR Ssid[],
+    OUT UCHAR *SsidLen,
+    OUT UCHAR *BssType,
+    OUT USHORT *BeaconPeriod,
+    OUT UCHAR *Channel,
+    OUT LARGE_INTEGER *Timestamp,
+    OUT BOOLEAN *CfExist,
+    OUT CF_PARM *Cf,
+    OUT USHORT *AtimWin,
+    OUT USHORT *CapabilityInfo,
+    OUT UCHAR Rate[],
     OUT UCHAR *RateLen,
     OUT BOOLEAN *ExtendedRateIeExist,
     OUT UCHAR *Erp,
-    OUT UCHAR *DtimCount, 
-    OUT UCHAR *DtimPeriod, 
-    OUT UCHAR *BcastFlag, 
-    OUT UCHAR *MessageToMe, 
+    OUT UCHAR *DtimCount,
+    OUT UCHAR *DtimPeriod,
+    OUT UCHAR *BcastFlag,
+    OUT UCHAR *MessageToMe,
     OUT UCHAR *Legacy,
     OUT UCHAR SupRate[],
 	OUT UCHAR *SupRateLen,
 	OUT UCHAR ExtRate[],
 	OUT UCHAR *ExtRateLen,
+    OUT USHORT *VarIELen,	// Length of all saved IEs.
     OUT	PNDIS_802_11_VARIABLE_IEs pVIE);
 
 //BOOLEAN JoinParmSanity(
-//    IN    PRTMP_ADAPTER   pAdapter, 
-//    IN  VOID *Msg, 
-//    IN  ULONG MsgLen, 
+//    IN    PRTMP_ADAPTER   pAdapter,
+//    IN  VOID *Msg,
+//    IN  ULONG MsgLen,
 //    OUT ULONG *BssIdx,
-//    OUT UCHAR SupportedRates[], 
+//    OUT UCHAR SupportedRates[],
 //    OUT UCHAR *SupportedRatesLen);
 
 BOOLEAN MlmeAssocReqSanity(
     IN  PRTMP_ADAPTER   pAdapter,
-    IN  VOID *Msg, 
-    IN  ULONG MsgLen, 
-    OUT MACADDR *ApAddr, 
-    OUT USHORT *CapabilityInfo, 
-    OUT ULONG *Timeout, 
+    IN  VOID *Msg,
+    IN  ULONG MsgLen,
+    OUT MACADDR *ApAddr,
+    OUT USHORT *CapabilityInfo,
+    OUT ULONG *Timeout,
     OUT USHORT *ListenIntv);
 
 BOOLEAN MlmeAuthReqSanity(
-    IN  PRTMP_ADAPTER   pAdapter, 
-    IN  VOID *Msg, 
-    IN  ULONG MsgLen, 
-    OUT MACADDR *Addr, 
-    OUT ULONG *Timeout, 
+    IN  PRTMP_ADAPTER   pAdapter,
+    IN  VOID *Msg,
+    IN  ULONG MsgLen,
+    OUT MACADDR *Addr,
+    OUT ULONG *Timeout,
     OUT USHORT *Alg);
 
 BOOLEAN MlmeStartReqSanity(
-    IN  PRTMP_ADAPTER   pAdapter, 
-    IN  VOID *Msg, 
-    IN  ULONG MsgLen, 
-    OUT CHAR Ssid[], 
+    IN  PRTMP_ADAPTER   pAdapter,
+    IN  VOID *Msg,
+    IN  ULONG MsgLen,
+    OUT CHAR Ssid[],
     OUT UCHAR *Ssidlen);
 
 BOOLEAN PeerAuthSanity(
-    IN  PRTMP_ADAPTER   pAdapter, 
-    IN  VOID *Msg, 
-    IN  ULONG MsgLen, 
-    OUT MACADDR *Addr, 
-    OUT USHORT *Alg, 
-    OUT USHORT *Seq, 
-    OUT USHORT *Status, 
+    IN  PRTMP_ADAPTER   pAdapter,
+    IN  VOID *Msg,
+    IN  ULONG MsgLen,
+    OUT MACADDR *Addr,
+    OUT USHORT *Alg,
+    OUT USHORT *Seq,
+    OUT USHORT *Status,
     OUT CHAR ChlgText[]);
 
 BOOLEAN PeerAssocRspSanity(
-    IN  PRTMP_ADAPTER   pAdapter, 
-    IN  VOID *Msg, 
-    IN  ULONG MsgLen, 
-    OUT MACADDR *Addr2, 
-    OUT USHORT *CapabilityInfo, 
-    OUT USHORT *Status, 
-    OUT USHORT *Aid, 
-    OUT UCHAR Rates[], 
+    IN  PRTMP_ADAPTER   pAdapter,
+    IN  VOID *Msg,
+    IN  ULONG MsgLen,
+    OUT MACADDR *Addr2,
+    OUT USHORT *CapabilityInfo,
+    OUT USHORT *Status,
+    OUT USHORT *Aid,
+    OUT UCHAR Rates[],
     OUT UCHAR *RatesLen,
     OUT BOOLEAN *ExtendedRateIeExist);
 
 BOOLEAN PeerDisassocSanity(
-    IN  PRTMP_ADAPTER   pAdapter, 
-    IN  VOID *Msg, 
-    IN  ULONG MsgLen, 
-    OUT MACADDR *Addr2, 
+    IN  PRTMP_ADAPTER   pAdapter,
+    IN  VOID *Msg,
+    IN  ULONG MsgLen,
+    OUT MACADDR *Addr2,
     OUT USHORT *Reason);
 
 BOOLEAN PeerDeauthSanity(
-    IN  PRTMP_ADAPTER   pAdapter, 
-    IN  VOID *Msg, 
-    IN  ULONG MsgLen, 
-    OUT MACADDR *Addr2, 
+    IN  PRTMP_ADAPTER   pAdapter,
+    IN  VOID *Msg,
+    IN  ULONG MsgLen,
+    OUT MACADDR *Addr2,
     OUT USHORT *Reason);
 
 BOOLEAN PeerProbeReqSanity(
-    IN  PRTMP_ADAPTER   pAdapter, 
-    IN  VOID *Msg, 
-    IN  ULONG MsgLen, 
+    IN  PRTMP_ADAPTER   pAdapter,
+    IN  VOID *Msg,
+    IN  ULONG MsgLen,
     OUT MACADDR *Addr2,
-    OUT CHAR Ssid[], 
-    OUT UCHAR *SsidLen); 
-//    OUT UCHAR Rates[], 
+    OUT CHAR Ssid[],
+    OUT UCHAR *SsidLen);
+//    OUT UCHAR Rates[],
 //    OUT UCHAR *RatesLen);
 
 BOOLEAN GetTimBit(
-    IN  CHAR *Ptr, 
-    IN  USHORT Aid, 
-    OUT UCHAR *TimLen, 
-    OUT UCHAR *BcastFlag, 
-    OUT UCHAR *DtimCount, 
-    OUT UCHAR *DtimPeriod, 
+    IN  CHAR *Ptr,
+    IN  USHORT Aid,
+    OUT UCHAR *TimLen,
+    OUT UCHAR *BcastFlag,
+    OUT UCHAR *DtimCount,
+    OUT UCHAR *DtimPeriod,
     OUT UCHAR *MessageToMe);
 
 BOOLEAN GetLegacy(
-    IN  CHAR *Ptr, 
+    IN  CHAR *Ptr,
     OUT UCHAR *Legacy);
 
 ULONG MakeOutgoingFrame(
-    OUT CHAR *Buffer, 
+    OUT CHAR *Buffer,
     OUT ULONG *Length, ...);
 
 VOID  LfsrInit(
-    IN  PRTMP_ADAPTER   pAdapter, 
+    IN  PRTMP_ADAPTER   pAdapter,
     IN  ULONG Seed);
 
 UCHAR RandomByte(
@@ -2129,26 +2156,26 @@
     IN PRTMP_ADAPTER pAdapter);
 
 VOID MlmeCheckForRoaming(
-    IN  PRTMP_ADAPTER   pAdapter, 
+    IN  PRTMP_ADAPTER   pAdapter,
     IN ULONG    Now32);
 
 VOID MlmeCheckDynamicTxRateSwitching(
     IN PRTMP_ADAPTER pAd);
 
 VOID MlmeCheckChannelQuality(
-    IN  PRTMP_ADAPTER   pAdapter, 
+    IN  PRTMP_ADAPTER   pAdapter,
     IN ULONG Now);
 
 VOID MlmeCheckForPsmChange(
-    IN  PRTMP_ADAPTER   pAdapter, 
+    IN  PRTMP_ADAPTER   pAdapter,
     IN ULONG    Now32);
 
 VOID MlmeSetPsmBit(
-    IN  PRTMP_ADAPTER   pAdapter, 
+    IN  PRTMP_ADAPTER   pAdapter,
     IN USHORT psm);
 
 VOID MlmeSetTxPreamble(
-    IN  PRTMP_ADAPTER   pAdapter, 
+    IN  PRTMP_ADAPTER   pAdapter,
     IN USHORT TxPreamble);
 
 VOID MlmeUpdateTxRates(
@@ -2214,7 +2241,7 @@
 
 VOID EWEN(
     IN  PRTMP_ADAPTER   pAd);
-    
+
 USHORT RTMP_EEPROM_READ16(
     IN  PRTMP_ADAPTER   pAd,
     IN  USHORT Offset);
@@ -2223,16 +2250,16 @@
     IN  PRTMP_ADAPTER   pAd,
     IN  USHORT Offset,
     IN  USHORT Data);
-    
+
 UCHAR ChannelSanity(
-    IN PRTMP_ADAPTER pAd, 
+    IN PRTMP_ADAPTER pAd,
     IN UCHAR channel);
 
 //
 // Prototypes of function definition in rtmp_tkip.c
 //
 VOID    RTMPInitTkipEngine(
-    IN  PRTMP_ADAPTER   pAdapter, 
+    IN  PRTMP_ADAPTER   pAdapter,
     IN  PUCHAR          pTKey,
     IN  UCHAR           KeyId,
     IN  PUCHAR          pTA,
@@ -2242,14 +2269,14 @@
     OUT PULONG          pIV32);
 
 VOID    RTMPInitMICEngine(
-    IN  PRTMP_ADAPTER   pAdapter,   
+    IN  PRTMP_ADAPTER   pAdapter,
     IN  PUCHAR          pKey,
     IN  PUCHAR          pDA,
     IN  PUCHAR          pSA,
     IN  PUCHAR          pMICKey);
 
 BOOLEAN RTMPTkipCompareMICValue(
-    IN  PRTMP_ADAPTER   pAdapter, 
+    IN  PRTMP_ADAPTER   pAdapter,
     IN  PUCHAR          pSrc,
     IN  PUCHAR          pDA,
     IN  PUCHAR          pSA,
@@ -2272,12 +2299,12 @@
     IN  PUCHAR          pMICKey,
     IN  UINT            Len);
 
-VOID    RTMPTkipAppend( 
-    IN  PTKIP_KEY_INFO  pTkip,  
+VOID    RTMPTkipAppend(
+    IN  PTKIP_KEY_INFO  pTkip,
     IN  PUCHAR          pSrc,
     IN  UINT            nBytes);
 
-VOID    RTMPTkipGetMIC( 
+VOID    RTMPTkipGetMIC(
     IN  PTKIP_KEY_INFO  pTkip);
 
 NDIS_STATUS RTMPWPAAddKeyProc(
@@ -2292,7 +2319,7 @@
     IN PRTMP_ADAPTER pAdapter);
 
 VOID    RTMPSetPhyMode(
-    IN PRTMP_ADAPTER pAdapter, 
+    IN PRTMP_ADAPTER pAdapter,
     IN  ULONG phymode);
 
 VOID    RTMPSetDesiredRates(
@@ -2313,102 +2340,102 @@
 // Prototypes of function definition for *iwpriv* in rtmp_info.c
 //
 INT Set_CountryRegion_Proc(
-    IN  PRTMP_ADAPTER   pAdapter, 
+    IN  PRTMP_ADAPTER   pAdapter,
     IN  PUCHAR          arg);
 
 INT Set_SSID_Proc(
-    IN  PRTMP_ADAPTER   pAdapter, 
+    IN  PRTMP_ADAPTER   pAdapter,
     IN  PUCHAR          arg);
 
 INT Set_WirelessMode_Proc(
-    IN  PRTMP_ADAPTER   pAdapter, 
+    IN  PRTMP_ADAPTER   pAdapter,
     IN  PUCHAR          arg);
 
 INT Set_TxRate_Proc(
-    IN  PRTMP_ADAPTER   pAdapter, 
+    IN  PRTMP_ADAPTER   pAdapter,
     IN  PUCHAR          arg);
 
 INT Set_AdhocModeRate_Proc(
-    IN  PRTMP_ADAPTER   pAdapter, 
+    IN  PRTMP_ADAPTER   pAdapter,
     IN  PUCHAR          arg);
 
 INT Set_Channel_Proc(
-    IN  PRTMP_ADAPTER   pAdapter, 
-    IN  PUCHAR  
+    IN  PRTMP_ADAPTER   pAdapter,
+    IN  PUCHAR
     arg);
 
 #ifdef RT2500_DBG
 INT Set_Debug_Proc(
-    IN  PRTMP_ADAPTER   pAdapter, 
+    IN  PRTMP_ADAPTER   pAdapter,
     IN  PUCHAR          arg);
 #endif
 
 INT Set_BGProtection_Proc(
-    IN  PRTMP_ADAPTER   pAdapter, 
+    IN  PRTMP_ADAPTER   pAdapter,
     IN  PUCHAR          arg);
 
 INT Set_TxPreamble_Proc(
-    IN  PRTMP_ADAPTER   pAdapter, 
+    IN  PRTMP_ADAPTER   pAdapter,
     IN  PUCHAR          arg);
 
 INT Set_StaWithEtherBridge_Proc(
-    IN  PRTMP_ADAPTER   pAdapter, 
+    IN  PRTMP_ADAPTER   pAdapter,
     IN  PUCHAR          arg);
 
 INT Set_RTSThreshold_Proc(
-    IN  PRTMP_ADAPTER   pAdapter, 
+    IN  PRTMP_ADAPTER   pAdapter,
     IN  PUCHAR          arg);
 
 INT Set_FragThreshold_Proc(
-    IN  PRTMP_ADAPTER   pAdapter, 
+    IN  PRTMP_ADAPTER   pAdapter,
     IN  PUCHAR          arg);
 
 INT Set_TxBurst_Proc(
-    IN  PRTMP_ADAPTER   pAdapter, 
+    IN  PRTMP_ADAPTER   pAdapter,
     IN  PUCHAR          arg);
 
 INT Set_TurboRate_Proc(
-    IN  PRTMP_ADAPTER   pAdapter, 
+    IN  PRTMP_ADAPTER   pAdapter,
     IN  PUCHAR          arg);
 
 INT Set_NetworkType_Proc(
-    IN  PRTMP_ADAPTER   pAdapter, 
+    IN  PRTMP_ADAPTER   pAdapter,
     IN  PUCHAR          arg);
-    
+
 INT Set_AuthMode_Proc(
-    IN  PRTMP_ADAPTER   pAdapter, 
+    IN  PRTMP_ADAPTER   pAdapter,
     IN  PUCHAR          arg);
 
 INT Set_EncrypType_Proc(
-    IN  PRTMP_ADAPTER   pAdapter, 
+    IN  PRTMP_ADAPTER   pAdapter,
     IN  PUCHAR          arg);
 
 INT Set_DefaultKeyID_Proc(
-    IN  PRTMP_ADAPTER   pAdapter, 
+    IN  PRTMP_ADAPTER   pAdapter,
     IN  PUCHAR          arg);
 
 INT Set_Key1_Proc(
-    IN  PRTMP_ADAPTER   pAdapter, 
+    IN  PRTMP_ADAPTER   pAdapter,
     IN  PUCHAR          arg);
 
 INT Set_Key2_Proc(
-    IN  PRTMP_ADAPTER   pAdapter, 
+    IN  PRTMP_ADAPTER   pAdapter,
     IN  PUCHAR          arg);
 
 INT Set_Key3_Proc(
-    IN  PRTMP_ADAPTER   pAdapter, 
+    IN  PRTMP_ADAPTER   pAdapter,
     IN  PUCHAR          arg);
 
 INT Set_Key4_Proc(
-    IN  PRTMP_ADAPTER   pAdapter, 
+    IN  PRTMP_ADAPTER   pAdapter,
     IN  PUCHAR          arg);
 
 INT Set_WPAPSK_Proc(
-    IN  PRTMP_ADAPTER   pAdapter, 
+    IN  PRTMP_ADAPTER   pAdapter,
     IN  PUCHAR          arg);
 
 INT Set_WPANONE_Proc(
-    IN  PRTMP_ADAPTER   pAdapter, 
+    IN  PRTMP_ADAPTER   pAdapter,
     IN  PUCHAR          arg);
 
 VOID RTMPIoctlBBP(
@@ -2425,10 +2452,14 @@
     IN  struct iwreq    *wrq);
 #endif
 
-int RTMPIoctlRFMONTX(
-    IN OUT PRTMP_ADAPTER   pAdapter,
+int RTMPIoctlSetRFMONTX(
+    IN PRTMP_ADAPTER   pAdapter,
     IN  struct iwreq    *wrq);
 
+int RTMPIoctlGetRFMONTX(
+    IN PRTMP_ADAPTER   pAdapter,
+    OUT  struct iwreq    *wrq);
+
 //
 // prototype in wpa.c
 //
@@ -2437,31 +2468,31 @@
     OUT ULONG   *MsgType);
 
 VOID WpaPskStateMachineInit(
-    IN  PRTMP_ADAPTER       pAd, 
-    IN  STATE_MACHINE       *S, 
+    IN  PRTMP_ADAPTER       pAd,
+    IN  STATE_MACHINE       *S,
     OUT STATE_MACHINE_FUNC Trans[]);
 
 VOID WpaEAPOLKeyAction(
-    IN  PRTMP_ADAPTER   pAdapter, 
+    IN  PRTMP_ADAPTER   pAdapter,
     IN  MLME_QUEUE_ELEM *Elem);
 
 VOID    WpaPairMsg1Action(
-    IN  PRTMP_ADAPTER   pAdapter, 
+    IN  PRTMP_ADAPTER   pAdapter,
     IN  MLME_QUEUE_ELEM *Elem);
 
 VOID    WpaPairMsg3Action(
-    IN  PRTMP_ADAPTER   pAdapter, 
-    IN  MLME_QUEUE_ELEM *Elem); 
+    IN  PRTMP_ADAPTER   pAdapter,
+    IN  MLME_QUEUE_ELEM *Elem);
 
 VOID    WpaGroupMsg1Action(
-    IN  PRTMP_ADAPTER   pAdapter, 
+    IN  PRTMP_ADAPTER   pAdapter,
     IN  MLME_QUEUE_ELEM *Elem);
 
 VOID    WpaMacHeaderInit(
-    IN      PRTMP_ADAPTER   pAd, 
-    IN OUT  PHEADER_802_11  Hdr, 
-    IN      UCHAR           wep, 
-    IN      PMACADDR        pAddr1); 
+    IN      PRTMP_ADAPTER   pAd,
+    IN OUT  PHEADER_802_11  Hdr,
+    IN      UCHAR           wep,
+    IN      PMACADDR        pAddr1);
 
 VOID    WpaHardEncrypt(
     IN  PRTMP_ADAPTER   pAdapter,
@@ -2495,15 +2526,15 @@
     IN  UINT    len);
 
 VOID    GenRandom(
-    IN  PRTMP_ADAPTER   pAd, 
+    IN  PRTMP_ADAPTER   pAd,
     OUT UCHAR           *random);
 
-VOID    AES_GTK_KEY_UNWRAP( 
+VOID    AES_GTK_KEY_UNWRAP(
     IN  UCHAR   *key,
     OUT UCHAR   *plaintext,
     IN  UCHAR   *ciphertext);
 
-ULONG	RTMPTkipGetUInt32( 	
+ULONG	RTMPTkipGetUInt32(
 	IN	PUCHAR	pMICKey);
 
 char * rtstrstr(
@@ -2512,39 +2543,39 @@
 
 #ifdef RALINK_ATE
 INT	Set_ATE_Proc(
-	IN	PRTMP_ADAPTER	pAdapter, 
+	IN	PRTMP_ADAPTER	pAdapter,
 	IN	PUCHAR			arg);
 
 INT	Set_ATE_DA_Proc(
-	IN	PRTMP_ADAPTER	pAdapter, 
+	IN	PRTMP_ADAPTER	pAdapter,
 	IN	PUCHAR			arg);
 
 INT	Set_ATE_SA_Proc(
-	IN	PRTMP_ADAPTER	pAdapter, 
+	IN	PRTMP_ADAPTER	pAdapter,
 	IN	PUCHAR			arg);
 
 INT	Set_ATE_BSSID_Proc(
-	IN	PRTMP_ADAPTER	pAdapter, 
+	IN	PRTMP_ADAPTER	pAdapter,
 	IN	PUCHAR			arg);
 
 INT	Set_ATE_CHANNEL_Proc(
-	IN	PRTMP_ADAPTER	pAdapter, 
+	IN	PRTMP_ADAPTER	pAdapter,
 	IN	PUCHAR			arg);
 
 INT	Set_ATE_TX_POWER_Proc(
-	IN	PRTMP_ADAPTER	pAdapter, 
+	IN	PRTMP_ADAPTER	pAdapter,
 	IN	PUCHAR			arg);
 
 INT	Set_ATE_TX_LENGTH_Proc(
-	IN	PRTMP_ADAPTER	pAdapter, 
+	IN	PRTMP_ADAPTER	pAdapter,
 	IN	PUCHAR			arg);
 
 INT	Set_ATE_TX_COUNT_Proc(
-	IN	PRTMP_ADAPTER	pAdapter, 
+	IN	PRTMP_ADAPTER	pAdapter,
 	IN	PUCHAR			arg);
 
 INT	Set_ATE_TX_RATE_Proc(
-	IN	PRTMP_ADAPTER	pAdapter, 
+	IN	PRTMP_ADAPTER	pAdapter,
 	IN	PUCHAR			arg);
 
 VOID RTMPStationStop(
@@ -2559,11 +2590,15 @@
 
 #ifdef BIG_ENDIAN
 VOID   RTMPFrameEndianChange(
-       IN  PRTMP_ADAPTER   pAdapter, 
-       IN  PUCHAR          pData, 
+       IN  PRTMP_ADAPTER   pAdapter,
+       IN  PUCHAR          pData,
        IN  ULONG           Dir,
        IN  BOOLEAN         FromRxDoneInt);
 
+VOID WriteBackToDescriptor(IN PUCHAR Dest,
+			   IN PUCHAR Src,
+			   IN BOOLEAN DoEncrypt, IN ULONG DescriptorType);
+
 VOID    RTMPDescriptorEndianChange(
        IN      PUCHAR                  pData,
        IN      ULONG                   DescriptorType);
diff -Nur rt2500-1.1.0-b4/Module/rtmp_data.c rt2500-cvs-2007061011/Module/rtmp_data.c
--- rt2500-1.1.0-b4/Module/rtmp_data.c	2006-06-17 22:12:58.000000000 +0200
+++ rt2500-cvs-2007061011/Module/rtmp_data.c	2007-06-08 20:09:53.000000000 +0200
@@ -1,42 +1,42 @@
-/*************************************************************************** 
- * RT2400/RT2500 SourceForge Project - http://rt2x00.serialmonkey.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.                          * 
- *                                                                         * 
- *   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.             * 
- *                                                                         * 
- *   Licensed under the GNU GPL                                            * 
- *   Original code supplied under license from RaLink Inc, 2004.           * 
- ***************************************************************************/ 
+/***************************************************************************
+ * RT2400/RT2500 SourceForge Project - http://rt2x00.serialmonkey.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.                          *
+ *                                                                         *
+ *   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.             *
+ *                                                                         *
+ *   Licensed under the GNU GPL                                            *
+ *   Original code supplied under license from RaLink Inc, 2004.           *
+ ***************************************************************************/
 
- /*************************************************************************** 
+ /***************************************************************************
  *      Module Name: rtmp_data.c
- *              
+ *
  *      Abstract: Data path subroutines
- *              
- *      Revision History: 
- *      Who             When            What 
- *      --------        -----------     ----------------------------- 
+ *
+ *      Revision History:
+ *      Who             When            What
+ *      --------        -----------     -----------------------------
  *      John            25th Feb 03     Modify for rt2560
- *      MarkW           8th  Dec 04     Baseline code  
+ *      MarkW           8th  Dec 04     Baseline code
  *      MarkW (rt2400)  8th  Dec 04     Promisc mode support
  *      RobinC          10th Dec 04     RFMON Support
- *      MarkW           10th Dec 04     Rolled in Ralink 1.4.5.0 
+ *      MarkW           10th Dec 04     Rolled in Ralink 1.4.5.0
  *      MarkW           17th Dec 04     Monitor mode through iwconfig
  *      MarkW           19th Feb 05     Fixes to incoming byte count
  *      GregorG         29th Mar 05     Big endian fixes
- ***************************************************************************/ 
+ ***************************************************************************/
 
 #include "rt_config.h"
 
@@ -46,12 +46,12 @@
 
 static	UCHAR	IPX[] = {0x81, 0x37};
 static	UCHAR	APPLE_TALK[] = {0x80, 0xf3};
-static  UCHAR   PlcpSignal[12] = { 
+static  UCHAR   PlcpSignal[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
 static	UINT	_11G_RATES[12] = { 0, 0, 0, 0, 6, 9, 12, 18, 24, 36, 48, 54 };
-	 
+
 #define COLLECT_RX_ANTENNA_AVERAGE_RSSI(_pAd, _RxAnt, _rssi)      \
 {                                                           \
     USHORT AvgRssi;                                         \
@@ -84,16 +84,16 @@
 
 	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:
-	
+
 	========================================================================
 */
 inline NDIS_STATUS	RTMPCheckRxDescriptor(
@@ -102,7 +102,7 @@
 	// Phy errors
 	if (pRxD->PhyErr)
 		return(NDIS_STATUS_FAILURE);
-	
+
 	// CRC errors
 	if (pRxD->Crc)
 		return(NDIS_STATUS_FAILURE);
@@ -120,15 +120,15 @@
 
 	Routine	Description:
 		Endian conversion of Tx/Rx descriptor .
-		
+
 	Arguments:
 		pAdapter		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
 	========================================================================
@@ -143,12 +143,26 @@
     *(ULONG *)pData = SWAP32(*(ULONG *)pData);                          // Byte 0; this must be swapped last
 }
 
+VOID WriteBackToDescriptor(IN PUCHAR Dest,
+			   IN PUCHAR Src,
+			   IN BOOLEAN DoEncrypt, IN ULONG DescriptorType)
+{
+	PULONG p1, p2;
+	UCHAR i;
+
+	p1 = ((PULONG) Dest) + 1;
+	p2 = ((PULONG) Src) + 1;
+	for (i = 1; i < RING_DESCRIPTOR_SIZE / 4; i++)
+		*p1++ = *p2++;
+	*(PULONG) Dest = *(PULONG) Src;
+}
+
 /*
 	========================================================================
 
 	Routine	Description:
 		Endian conversion of all kinds of 802.11 frames .
-		
+
 	Arguments:
 		pAdapter		Pointer	to our adapter
 		pData			Pointer	to the 802.11 frame structure
@@ -157,14 +171,14 @@
 
 	Return Value:
 		None
-		
+
 	Note:
 	    Call this function when read or update buffer data
 	========================================================================
 */
 VOID	RTMPFrameEndianChange(
-	IN  PRTMP_ADAPTER   pAdapter, 
-	IN  PUCHAR          pData, 
+	IN  PRTMP_ADAPTER   pAdapter,
+	IN  PUCHAR          pData,
 	IN  ULONG           Dir,
 	IN  BOOLEAN         FromRxDoneInt)
 {
@@ -182,7 +196,7 @@
 
     // 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));
 
@@ -210,7 +224,7 @@
                 // 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);
@@ -271,6 +285,7 @@
         *(USHORT *)pData = SWAP16(*(USHORT *)pData);
     }
 }
+
 #endif
 
 /*
@@ -353,14 +368,14 @@
 			pAdapter->RalinkCounters.RxRingErrCount++;
 			break;
 		}
-		
+
 #ifdef RALINK_ATE
 		if(pAdapter->ate.Mode == ATE_RXFRAME)
 		{
 			bDropFrame = TRUE;
 		}
 #endif	//#ifdef RALINK_ATE
-		
+
 		// Point to Rx ring buffer where stores the real data frame
 		pData	= (PUCHAR) (pAdapter->RxRing[pAdapter->CurRxIndex].va_data_addr);
 		// Cast to 802.11 header for flags checking
@@ -372,11 +387,11 @@
 
 		// Check for all RxD errors
 		Status = RTMPCheckRxDescriptor(pRxD);
-		
+
 	    // Apply packet filtering rule based on microsoft requirements.
 		if (Status == NDIS_STATUS_SUCCESS)
 			Status = RTMPApplyPacketFilter(pAdapter, pRxD, pHeader);
-		
+
 		// Add receive counters
 		if (Status == NDIS_STATUS_SUCCESS)
 		{
@@ -394,7 +409,7 @@
 			// Increase general counters
 			pAdapter->Counters.RxErrors++;
 		}
-		
+
 		// Check for retry bit, if this bit is on, search the cache with SA & sequence
 		// as index, if matched, discard this frame, otherwise, update cache
 		// This check only apply to unicast data & management frames
@@ -453,7 +468,7 @@
 							bDropFrame = TRUE;
 							break;
 						}
-						
+
 						// Drop frame from AP while we are in Ad-hoc mode or not associated
 						if (pHeader->Controlhead.Frame.FrDs)
 						{
@@ -471,11 +486,11 @@
 						bDropFrame = TRUE;
 						break;
 					}
-				
+
                                         // Good data frame appears, increase the counters
                                         INC_COUNTER(pAdapter->WlanCounters.ReceivedFragmentCount);
-                                        pAdapter->RalinkCounters.ReceivedByteCount +=  pRxD->DataByteCnt;	
-	
+                                        pAdapter->RalinkCounters.ReceivedByteCount +=  pRxD->DataByteCnt;
+
 					// Process Multicast data frame
 					if (pRxD->Mcast)
 					{
@@ -486,18 +501,18 @@
 
 					// Init WPA Key to NULL
 					pWpaKey = (PWPA_KEY) NULL;
-					
+
 					// Find the WPA key, either Group or Pairwise Key
 					if ((pAdapter->PortCfg.AuthMode >= Ndis802_11AuthModeWPA) && (pHeader->Controlhead.Frame.Wep))
 					{
 						INT 	idx;
-						
+
 						// First lookup the DA, if it's a group address, use GROUP key
 						if (pRxD->Bcast || pRxD->Mcast)
 						{
-							
+
 							idx = (*(pData + 3) & 0xc0) >> 6;
-							if ((pAdapter->PortCfg.GroupKey[idx].KeyLen != 0) && 
+							if ((pAdapter->PortCfg.GroupKey[idx].KeyLen != 0) &&
 								((INFRA_ON(pAdapter) && (NdisEqualMemory(&pHeader->Controlhead.Addr2, &pAdapter->PortCfg.Bssid, 6))) ||
 								(ADHOC_ON(pAdapter) && (NdisEqualMemory(&pHeader->Addr3, &pAdapter->PortCfg.Bssid, 6)))))
 							{
@@ -520,15 +535,15 @@
 									break;
 								}
 							}
-#if 1							
+#if 1
 							// Use default Group Key if there is no Pairwise key present
 							if ((pWpaKey == NULL) && (pAdapter->PortCfg.GroupKey[pAdapter->PortCfg.DefaultKeyId].KeyLen != 0))
 							{
-								pWpaKey = (PWPA_KEY) &pAdapter->PortCfg.GroupKey[pAdapter->PortCfg.DefaultKeyId];				
+								pWpaKey = (PWPA_KEY) &pAdapter->PortCfg.GroupKey[pAdapter->PortCfg.DefaultKeyId];
 								pWpaKey->Type = GROUP_KEY;
 								DBGPRINT(RT_DEBUG_INFO, "Rx Use Group Key\n");
 							}
-#endif							
+#endif
 						}
 					}
 
@@ -542,16 +557,16 @@
 							Status = NDIS_STATUS_FAILURE;
 							bDropFrame = TRUE;
 							break;
-						}	
-							
+						}
+
 						// Filter out Bcast frame which AP relayed for us
 						if (pHeader->Controlhead.Frame.FrDs && RTMPEqualMemory(&pHeader->Addr3, pAdapter->CurrentAddress, 6))
 						{
 							Status = NDIS_STATUS_FAILURE;
 							bDropFrame = TRUE;
 							break;
-						}	
-						
+						}
+
 						// WEP encrypted frame
 						if (pHeader->Controlhead.Frame.Wep)
 						{
@@ -560,27 +575,27 @@
 							{
                                 KeyIdx = (*(pData + 3) & 0xc0) >> 6;
 									memcpy((PUCHAR) &pRxD->Iv, pData, 4);	//Get WEP IV
-									memcpy(pRxD->Key, pAdapter->PortCfg.SharedKey[KeyIdx].Key, pAdapter->PortCfg.SharedKey[KeyIdx].KeyLen);									
+									memcpy(pRxD->Key, pAdapter->PortCfg.SharedKey[KeyIdx].Key, pAdapter->PortCfg.SharedKey[KeyIdx].KeyLen);
 									if (pAdapter->PortCfg.SharedKey[KeyIdx].KeyLen == 5)
 										pRxD->CipherAlg = CIPHER_WEP64;
 									else
-										pRxD->CipherAlg = CIPHER_WEP128;									
+										pRxD->CipherAlg = CIPHER_WEP128;
 							}
 							else if ((pAdapter->PortCfg.WepStatus == Ndis802_11Encryption2Enabled) && (pWpaKey != NULL))	// TKIP
 							{
 								UCHAR	Eiv_Tmp[4];
-								
+
 								memcpy((PUCHAR) &pRxD->Iv, pData, 4);	//Get WEP IV
 								// Swap EIV byte order, due to ASIC's bug.
 								Eiv_Tmp[0] = *(pData + 7);
 								Eiv_Tmp[1] = *(pData + 6);
 								Eiv_Tmp[2] = *(pData + 5);
-								Eiv_Tmp[3] = *(pData + 4);								
+								Eiv_Tmp[3] = *(pData + 4);
 								memcpy((PUCHAR) &pRxD->Eiv, Eiv_Tmp, 4);	//Get WEP EIV
 								// Copy TA into RxD
 								memcpy(pRxD->TA, &pHeader->Controlhead.Addr2, 6);
 								KeyIdx = (*(pData + 3) & 0xc0) >> 6;
-								memcpy(pRxD->Key, pWpaKey->Key, 16);									
+								memcpy(pRxD->Key, pWpaKey->Key, 16);
 								pRxD->CipherAlg = CIPHER_TKIP;
 							}
 							else if ((pAdapter->PortCfg.WepStatus == Ndis802_11Encryption3Enabled) && (pWpaKey != NULL))	// AES
@@ -588,9 +603,9 @@
 								memcpy((PUCHAR) &pRxD->Iv, pData, 4);			//Get WEP IV
 								memcpy((PUCHAR) &pRxD->Eiv, (pData + 4), 4);	//Get WEP EIV
 								// Copy TA into RxD
-								memcpy(pRxD->TA, &pHeader->Controlhead.Addr2, 6);								
+								memcpy(pRxD->TA, &pHeader->Controlhead.Addr2, 6);
 								KeyIdx = (*(pData + 3) & 0xc0) >> 6;
-								memcpy(pRxD->Key, pWpaKey->Key, 16);									
+								memcpy(pRxD->Key, pWpaKey->Key, 16);
 								pRxD->CipherAlg = CIPHER_AES;
 							}
 							else
@@ -606,17 +621,17 @@
 							pRxD->CipherAlg = CIPHER_NONE;
 						}
 					}
-					
+
 					// Begin process unicast to	me frame
 					else if	(pRxD->U2M || pAdapter->bAcceptPromiscuous == TRUE)
 					{
-						// Send PS-Poll for AP to send next data frame					
+						// Send PS-Poll for AP to send next data frame
 						if ((pHeader->Controlhead.Frame.MoreData) && INFRA_ON(pAdapter) && (pAdapter->PortCfg.Psm == PWR_SAVE))
 						{
 							EnqueuePsPoll(pAdapter);
 							DBGPRINT(RT_DEBUG_TRACE, "Sending PS-POLL\n");
 						}
-						
+
 						//
 						// Begin frame processing
 						//
@@ -634,11 +649,11 @@
                                 KeyIdx = (*(pData + 3) & 0xc0) >> 6;
 
 									memcpy((PUCHAR) &pRxD->Iv, pData, 4);	//Get WEP IV
-									memcpy(pRxD->Key, pAdapter->PortCfg.SharedKey[KeyIdx].Key, pAdapter->PortCfg.SharedKey[KeyIdx].KeyLen);									
+									memcpy(pRxD->Key, pAdapter->PortCfg.SharedKey[KeyIdx].Key, pAdapter->PortCfg.SharedKey[KeyIdx].KeyLen);
 									if (pAdapter->PortCfg.SharedKey[KeyIdx].KeyLen == 5)
 										pRxD->CipherAlg = CIPHER_WEP64;
 									else
-										pRxD->CipherAlg = CIPHER_WEP128;									
+										pRxD->CipherAlg = CIPHER_WEP128;
 							}
 							else if ((pAdapter->PortCfg.PrivacyFilter == Ndis802_11PrivFilter8021xWEP) &&
 								(pHeader->Frag == 0))
@@ -659,18 +674,18 @@
 							if (pHeader->Controlhead.Frame.Wep)
 							{
 								UCHAR	Eiv_Tmp[4];
-								
+
 								memcpy((PUCHAR) &pRxD->Iv, pData, 4);	//Get WEP IV
 								// Swap EIV byte order, due to ASIC's bug.
 								Eiv_Tmp[0] = *(pData + 7);
 								Eiv_Tmp[1] = *(pData + 6);
 								Eiv_Tmp[2] = *(pData + 5);
-								Eiv_Tmp[3] = *(pData + 4);								
+								Eiv_Tmp[3] = *(pData + 4);
 								memcpy((PUCHAR) &pRxD->Eiv, Eiv_Tmp, 4);	//Get WEP EIV
 								KeyIdx = (*(pData + 3) & 0xc0) >> 6;
 								// Copy TA into RxD
 								memcpy(pRxD->TA, &pHeader->Controlhead.Addr2, 6);
-								memcpy(pRxD->Key, pWpaKey->Key, 16);									
+								memcpy(pRxD->Key, pWpaKey->Key, 16);
 								pRxD->CipherAlg = CIPHER_TKIP;
 							}
 							else if ((pAdapter->PortCfg.PrivacyFilter == Ndis802_11PrivFilter8021xWEP) &&
@@ -694,9 +709,9 @@
 								memcpy((PUCHAR) &pRxD->Iv, pData, 4);			//Get WEP IV
 								memcpy((PUCHAR) &pRxD->Eiv, (pData + 4), 4);	//Get WEP EIV
 								// Copy TA into RxD
-								memcpy(pRxD->TA, &pHeader->Controlhead.Addr2, 6);								
+								memcpy(pRxD->TA, &pHeader->Controlhead.Addr2, 6);
 								KeyIdx = (*(pData + 3) & 0xc0) >> 6;
-								memcpy(pRxD->Key, pWpaKey->Key, 16);									
+								memcpy(pRxD->Key, pWpaKey->Key, 16);
 								pRxD->CipherAlg = CIPHER_AES;
 							}
 							else if ((pAdapter->PortCfg.PrivacyFilter == Ndis802_11PrivFilter8021xWEP) &&
@@ -719,7 +734,7 @@
 							Status = NDIS_STATUS_FAILURE;
 							bDropFrame = TRUE;
 							break;
-						}						
+						}
 						else	// Not encryptrd frames
 						{
 							pRxD->CipherAlg = CIPHER_NONE;
@@ -756,13 +771,14 @@
 			pRxD->Drop      = 0;
 			pRxD->IvOffset = LENGTH_802_11;
 		}
-		
+
 		pRxD->CipherOwner = DESC_OWN_NIC;
 
 #ifdef BIG_ENDIAN
         RTMPFrameEndianChange(pAdapter, (PUCHAR)pHeader, DIR_WRITE, TRUE);
         RTMPDescriptorEndianChange((PUCHAR)pRxD, TYPE_RXD);
-        *pDestRxD = RxD;
+        //*pDestRxD = RxD;
+	WriteBackToDescriptor((PUCHAR)pDestRxD, (PUCHAR)pRxD, TRUE, TYPE_RXD);
 #endif
 
 		pAdapter->CurRxIndex++;
@@ -771,9 +787,9 @@
 			pAdapter->CurRxIndex = 0;
 		}
 		Count++;
-		
+
 		pAdapter->RalinkCounters.RxCount ++;
-		
+
 	}	while (Count < MAX_RX_PROCESS);
 
 	// Kick Decrypt Control Register, based on ASIC's implementation
@@ -810,10 +826,10 @@
 #endif
 	UCHAR			Count;
         unsigned long           irqflag;
-	
+
 	// Make sure Tx ring resource won't be used by other threads
 	spin_lock_irqsave(&pAdapter->TxRingLock, irqflag);
-	
+
 	Count = 0;
 	do
 	{
@@ -832,22 +848,22 @@
 		}
 
 		RTMPHardTransmitDone(
-			pAdapter, 
-			pTxD, 
+			pAdapter,
+			pTxD,
 			pAdapter->TxRing[pAdapter->NextTxDoneIndex].FrameType);
-		
+
 		// It might happend with no Ndis packet to indicate back to upper layer
 		// Clear for NdisSendComplete request
 		pTxD->Valid = FALSE;
-		
+
 		// Increase Total transmit byte counter after real data sent out
 		pAdapter->RalinkCounters.TransmittedByteCount +=  pTxD->DataByteCnt;
-		
+
 #ifdef BIG_ENDIAN
         RTMPDescriptorEndianChange((PUCHAR)pTxD, TYPE_TXD);
         *pDestTxD = TxD;
 #endif
-		
+
 		pAdapter->NextTxDoneIndex++;
 		if (pAdapter->NextTxDoneIndex >= TX_RING_SIZE)
 		{
@@ -885,16 +901,16 @@
 
 	// Make sure to release Tx ring resource
 	spin_unlock_irqrestore(&pAdapter->TxRingLock, irqflag);
-	
+
 	if(pAdapter->bNetDeviceStopQueue)
         {
                 DBGPRINT(RT_DEBUG_TRACE, "NetDevice start queue!!!\n\n");
                 pAdapter->bNetDeviceStopQueue = FALSE;
                 netif_start_queue(pAdapter->net_dev);
         }
-	
+
 	// Some Tx ring resource freed, check for pending send frame for hard transmit
-	if ((!RTMP_TEST_FLAG(pAdapter, fRTMP_ADAPTER_BSS_SCAN_IN_PROGRESS)) && 
+	if ((!RTMP_TEST_FLAG(pAdapter, fRTMP_ADAPTER_BSS_SCAN_IN_PROGRESS)) &&
 		(!RTMP_TEST_FLAG(pAdapter, fRTMP_ADAPTER_RADIO_OFF)) &&
 		(!RTMP_TEST_FLAG(pAdapter, fRTMP_ADAPTER_RESET_IN_PROGRESS)))
 	{
@@ -932,10 +948,10 @@
 	UCHAR			Count;
 	PMGMT_STRUC		pMgmt;
         unsigned long           irqflag;
-	
+
 	// Make sure Prio ring resource won't be used by other threads
-	spin_lock_irqsave(&pAdapter->PrioRingLock, irqflag);	
-	
+	spin_lock_irqsave(&pAdapter->PrioRingLock, irqflag);
+
 	Count = 0;
 	do
 	{
@@ -957,16 +973,16 @@
 #endif
 			break;
 		}
-		
+
 		// No need to put in reply for MLME
 		RTMPHardTransmitDone(
-			pAdapter, 
-			pTxD, 
+			pAdapter,
+			pTxD,
 			pAdapter->PrioRing[pAdapter->NextPrioDoneIndex].FrameType);
-		
+
 		// It might happend with no Ndis packet to indicate back to upper layer
-		pTxD->Valid = FALSE;		
-		
+		pTxD->Valid = FALSE;
+
 		// Increase Total transmit byte counter after real data sent out
 		pAdapter->RalinkCounters.TransmittedByteCount +=  pTxD->DataByteCnt;
 
@@ -983,11 +999,11 @@
 	}	while (++Count < MAX_TX_PROCESS);
 
 	// Make sure to release Prio ring resource
-	spin_unlock_irqrestore(&pAdapter->PrioRingLock, irqflag);	
-	
+	spin_unlock_irqrestore(&pAdapter->PrioRingLock, irqflag);
+
 	if (RTMP_TEST_FLAG(pAdapter, fRTMP_ADAPTER_RADIO_OFF))
 		return;
-	
+
 
 	spin_lock_irqsave(&pAdapter->PrioRingLock, irqflag);
 	if (pAdapter->PushMgmtIndex != pAdapter->PopMgmtIndex)
@@ -1008,7 +1024,7 @@
 				}
 			}
 		}
-	}	
+	}
 	spin_unlock_irqrestore(&pAdapter->PrioRingLock, irqflag);
 }
 
@@ -1033,12 +1049,12 @@
 {
 	// PTXD_STRUC		pTxD;
 	// UCHAR			Count;
-	
+
 	// Make sure Atim ring resource won't be used by other threads
 	//spin_lock_irqsave(&pAdapter->AtimRingLock);
-	
+
 	// Did not support ATIM, remove everything.
-	
+
 	// Make sure to release Atim ring resource
 	//spin_unlock_irqrestore(&pAdapter->AtimRingLock);
 }
@@ -1083,10 +1099,10 @@
 	ULONG			i;
 	struct sk_buff  *skb;
         unsigned long           irqflag;
-	
+
 	// Make sure Rx ring resource won't be used by other threads
 	spin_lock_irqsave(&pAdapter->RxRingLock, irqflag);
-	
+
 	RTMP_IO_READ32(pAdapter, SECCSR0, &RegValue);
         HwDecryptIndex = RegValue - pAdapter->RxRing[0].pa_addr;
         do_div(HwDecryptIndex, RING_DESCRIPTOR_SIZE);
@@ -1104,11 +1120,11 @@
         pRxD = &RxD;
         RTMPDescriptorEndianChange((PUCHAR)pRxD, TYPE_RXD);
 #endif
-	
+
 		// In case of false alarm or processed at last instance
 		if ((pRxD->Owner != DESC_OWN_HOST) || (pRxD->CipherOwner != DESC_OWN_HOST))
 			break;
-	
+
 		// Point to Rx ring buffer where stores the real data frame
 		pData	= (PUCHAR) (pAdapter->RxRing[pAdapter->CurDecryptIndex].va_data_addr);
 		// Cast to 802.11 header for flags checking
@@ -1117,15 +1133,18 @@
 #ifdef BIG_ENDIAN
         RTMPFrameEndianChange(pAdapter, (PUCHAR)pHeader, DIR_READ, FALSE);
 #endif
-		// Driver will check the decrypt algorithm and decide whether this ICV is true or not		
+		// Driver will check the decrypt algorithm and decide whether this ICV is true or not
 		if ((pRxD->IcvError == 1) && (pRxD->CipherAlg == CIPHER_NONE))
 				pRxD->IcvError = 0;
-		
+
 		// Since we already process header at RxDone interrupt, there is no need to proces
 		// header sanity again, the only thing we have to check is icv_err bit
-		if (pRxD->IcvError == 1)
+		//if (pRxD->IcvError == 1)
+		if ((pRxD->IcvError == 1) && (pRxD->CipherAlg != CIPHER_NONE))
 		{
-   		    DBGPRINT(RT_DEBUG_TRACE,"Rx DecryptDone - ICV error (len %d)\n", pRxD->DataByteCnt);
+   		    DBGPRINT(RT_DEBUG_TRACE,
+					"Rx DecryptDone - ICV error (CipherAlg=%d) (len %d)\n",
+					pRxD->CipherAlg, pRxD->DataByteCnt);
 			pRxD->Drop =1;			// Drop frame with icv error
 		}
 		// Saved data pointer for management frame which will pass to MLME block
@@ -1135,7 +1154,7 @@
          	{
  	            struct sk_buff  *skb;
 		    wlan_ng_prism2_header *ph;
- 	
+
  	            if ((skb = __dev_alloc_skb(2048, GFP_DMA|GFP_ATOMIC)) != NULL)
  	            {
 			if (pAdapter->PortCfg.MallowRFMONTx == TRUE)
@@ -1196,12 +1215,12 @@
 
  	                skb->dev = pAdapter->net_dev;
  	                memcpy(skb_put(skb, pRxD->DataByteCnt), pData, pRxD->DataByteCnt);
- 	                skb->mac.raw = skb->data;
+					skb_reset_mac_header(skb);
  	                skb->pkt_type = PACKET_OTHERHOST;
  	                skb->protocol = htons(ETH_P_802_2);
  	                skb->ip_summed = CHECKSUM_NONE;
  	                netif_rx(skb);
- 	            }	
+ 	            }
                     pRxD->Drop = 1;
          	}
 
@@ -1211,7 +1230,7 @@
 		// The total available payload should exclude 24-byte 802.11 Header
 		// If Security is enabled, IV, EIV, ICV size is excluded by ASIC
 		PacketSize = (USHORT) pRxD->DataByteCnt - LENGTH_802_11;
-	
+
 		// Find the WPA key, either Group or Pairwise Key
 		// Although the data has been decrypted by ASIC,
 		// driver has to calculate the RxMIC which required the key.
@@ -1221,7 +1240,7 @@
         if ((pAdapter->PortCfg.AuthMode >= Ndis802_11AuthModeWPA) && (pHeader->Controlhead.Frame.Wep))
 		{
 			INT 	idx;
-				
+
 			// First lookup the DA, if it's a group address, use GROUP key
 			if (pRxD->Bcast || pRxD->Mcast)
 			{
@@ -1231,7 +1250,7 @@
 #else
                 idx = (pRxD->Iv & 0xc0000000) >> 30;
 #endif
-				if ((pAdapter->PortCfg.GroupKey[idx].KeyLen != 0) && 
+				if ((pAdapter->PortCfg.GroupKey[idx].KeyLen != 0) &&
 					((INFRA_ON(pAdapter) && (NdisEqualMemory(&pHeader->Controlhead.Addr2, &pAdapter->PortCfg.Bssid, 6))) ||
 					(ADHOC_ON(pAdapter) && (NdisEqualMemory(&pHeader->Addr3, &pAdapter->PortCfg.Bssid, 6)))))
 				{
@@ -1254,22 +1273,22 @@
 						break;
 					}
 				}
-#if 1				
+#if 1
 				// Use default Group Key if there is no Pairwise key present
 				if ((pWpaKey == NULL) && (pAdapter->PortCfg.GroupKey[pAdapter->PortCfg.DefaultKeyId].KeyLen != 0))
 				{
-					pWpaKey = (PWPA_KEY) &pAdapter->PortCfg.GroupKey[pAdapter->PortCfg.DefaultKeyId];				
+					pWpaKey = (PWPA_KEY) &pAdapter->PortCfg.GroupKey[pAdapter->PortCfg.DefaultKeyId];
 					pWpaKey->Type = GROUP_KEY;
 					DBGPRINT(RT_DEBUG_INFO, "Rx Use Group Key\n");
 				}
-#endif				
+#endif
 			}
 
 			// If there is no WPA key matched, this frame should be dropped
 			if (pWpaKey == NULL)
 				pRxD->Drop = 1;
 		}
-			
+
 		//
 		// Start of main loop to parse receiving frames.
 		// The sequence will be Type first, then subtype...
@@ -1287,10 +1306,10 @@
 						pSrcMac = (PUCHAR) &(pHeader->Addr3);
 					else
 						pSrcMac = (PUCHAR) &(pHeader->Controlhead.Addr2);
-					
+
 					// Process Broadcast & Multicast data frame
 					if (pRxD->Bcast || pRxD->Mcast)
-					{							
+					{
 						// For TKIP frame, calculate the MIC value
 						if (pRxD->CipherAlg == CIPHER_TKIP)
 						{
@@ -1302,7 +1321,7 @@
 								Status = NDIS_STATUS_FAILURE;
 								break;
 							}
-								
+
 							// Minus MIC length
 							PacketSize -= 8;
 							if (RTMPTkipCompareMICValue(
@@ -1313,7 +1332,7 @@
 								pWpaKey->RxMic,
 								PacketSize) == FALSE)
 							{
-								DBGPRINT(RT_DEBUG_ERROR,"Rx MIC Value error\n");							
+								DBGPRINT(RT_DEBUG_ERROR,"Rx MIC Value error\n");
 								RTMPReportMicError(pAdapter, pWpaKey);
 								Status = NDIS_STATUS_FAILURE;
 								break;
@@ -1329,21 +1348,17 @@
 							// Rx TSC has done one full cycle, since re-key is done by transmitter
 							// We did not do anything for Rx path
 						}
-						
+
                         // build 802.3 header and decide if remove the 8-byte LLC/SNAP encapsulation
 						CONVERT_TO_802_3(Header802_3, pDestMac, pSrcMac, pData, PacketSize);
-								
+
 						pAdapter->PortCfg.LedCntl.fRxActivity = TRUE; // for RX ACTIVITY LED
 
 						// For miniportTransferData
 						pAdapter->pRxData = pData;
-			
+
 						// Acknolwdge upper layer the received frame
-#ifdef RTMP_EMBEDDED
                         if ((skb = __dev_alloc_skb(PacketSize + LENGTH_802_3 + 2, GFP_DMA|GFP_ATOMIC)) != NULL)
-#else
-                        if ((skb = dev_alloc_skb(PacketSize + LENGTH_802_3 + 2)) != NULL)
-#endif
                         {
                             skb->dev = pAdapter->net_dev;
                             skb_reserve(skb, 2);    // 16 byte align the IP header
@@ -1354,10 +1369,10 @@
                             pAdapter->net_dev->last_rx = jiffies;
                             pAdapter->stats.rx_packets++;
                         }
-		
+
 						DBGPRINT(RT_DEBUG_INFO, "!!! Broadcast Ethenet rx Indicated !!!\n");
 					}
-						
+
 					// Begin process unicast to me frame
 					else if (pRxD->U2M || pAdapter->bAcceptPromiscuous == TRUE)
 					{
@@ -1383,12 +1398,12 @@
 							else if (pRxD->BBR0 == 110)
 								pAdapter->LastRxRate = 3;
 						}
-						
+
 						if (pHeader->Frag == 0) 	// First or Only fragment
 						{
 							// For TKIP frame, calculate the MIC value
 							if ((pHeader->Controlhead.Frame.MoreFrag == FALSE) &&
-								(pRxD->CipherAlg == CIPHER_TKIP) && 
+								(pRxD->CipherAlg == CIPHER_TKIP) &&
                                 (pHeader->Controlhead.Frame.Wep))
 							{
 								if (pWpaKey == NULL)
@@ -1407,17 +1422,17 @@
 									pWpaKey->RxMic,
 									PacketSize) == FALSE)
 								{
-									DBGPRINT(RT_DEBUG_ERROR,"Rx MIC Value error\n");							
+									DBGPRINT(RT_DEBUG_ERROR,"Rx MIC Value error\n");
 									RTMPReportMicError(pAdapter, pWpaKey);
 									Status = NDIS_STATUS_FAILURE;
 									break;
 								}
 							}
-								
+
 							pAdapter->FragFrame.Flags &= 0xFFFFFFFE;
-								
+
 							// Check for encapsulation other than RFC1042 & Bridge tunnel
-							if ((!RTMPEqualMemory(SNAP_802_1H, pData, 6)) && 
+							if ((!RTMPEqualMemory(SNAP_802_1H, pData, 6)) &&
 							    (!RTMPEqualMemory(SNAP_BRIDGE_TUNNEL, pData, 6)))
 							{
 								LLC_Len[0] = PacketSize / 256;
@@ -1427,13 +1442,13 @@
 							else
 							{
 							    char *pProto = pData + 6;
-							    
+
 								// Remove 802.11 H header & reconstruct 802.3 header
 								// pData += (LENGTH_802_1_H - LENGTH_802_3_TYPE);
 								// Check for EAPOL frame when driver supplicant enabled
 								// TODO: It is not strickly correct. There is no fragment handling. It might damage driver
 								// TODO: But for WPAPSK, it's not likely fragment on EAPOL frame will happen
-								if (RTMPEqualMemory(EAPOL, pProto, 2) && ((pAdapter->PortCfg.WpaState != SS_NOTUSE))) 
+								if (RTMPEqualMemory(EAPOL, pProto, 2) && ((pAdapter->PortCfg.WpaState != SS_NOTUSE)))
 								{
 									RTMP_IO_READ32(pAdapter, CSR17, &High32TSF);		// TSF value
 									RTMP_IO_READ32(pAdapter, CSR16, &Low32TSF); 		// TSF vlaue
@@ -1441,16 +1456,16 @@
 									// Enqueue this frame to MLME engine
 									MlmeEnqueueForRecv(
 										pAdapter,
-										&pAdapter->Mlme.Queue,	
-										High32TSF, 
+										&pAdapter->Mlme.Queue,
+										High32TSF,
 										Low32TSF,
-										(UCHAR)pRxD->BBR1, (UCHAR)pAdapter->PortCfg.LastR17Value, 
-										PacketSize, 
-										pManage);					
+										(UCHAR)pRxD->BBR1, (UCHAR)pAdapter->PortCfg.LastR17Value,
+										PacketSize,
+										pManage);
 									break;
 								}
 
-								if ((RTMPEqualMemory(IPX, pProto, 2) || RTMPEqualMemory(APPLE_TALK, pProto, 2)) && 
+								if ((RTMPEqualMemory(IPX, pProto, 2) || RTMPEqualMemory(APPLE_TALK, pProto, 2)) &&
 								    RTMPEqualMemory(SNAP_802_1H, pData, 6))
 								{
 								    // preserved the LLC/SNAP filed
@@ -1468,21 +1483,17 @@
 									pAdapter->FragFrame.Flags |= 0x01;
 								}
 							}
-									
+
 							// One & The only fragment
 							if (pHeader->Controlhead.Frame.MoreFrag == FALSE)
 							{
 								// For miniportTransferData
 								pAdapter->pRxData = pData;
-								
+
 								pAdapter->PortCfg.LedCntl.fRxActivity = TRUE; // for RX ACTIVITY LED
 
 								// Acknowledge upper layer the received frame
-#ifdef RTMP_EMBEDDED
                                 if ((skb = __dev_alloc_skb(PacketSize + LENGTH_802_3 + 2, GFP_DMA|GFP_ATOMIC)) != NULL)
-#else
-                                if ((skb = dev_alloc_skb(PacketSize + LENGTH_802_3 + 2)) != NULL)
-#endif
                                 {
                                     skb->dev = pAdapter->net_dev;
                                     skb_reserve(skb, 2);    // 16 byte align the IP header
@@ -1499,7 +1510,7 @@
 
 								// Increase general counters
 								pAdapter->Counters.GoodReceives++;
-	
+
 							}
 							// First fragment of fragmented frames
 							else
@@ -1516,7 +1527,7 @@
 						else
 						{
 							// No LLC-SNAP header in except the first fragment frame
-								
+
 							if ((pHeader->Sequence != pAdapter->FragFrame.Sequence) ||
 								(pHeader->Frag != (pAdapter->FragFrame.LastFrag + 1)))
 							{
@@ -1525,7 +1536,7 @@
 								memset(&pAdapter->FragFrame, 0, sizeof(FRAGMENT_FRAME));
 								Status = NDIS_STATUS_FAILURE;
 								break;
-							}	
+							}
 							else if ((pAdapter->FragFrame.RxSize + PacketSize) > MAX_FRAME_SIZE)
 							{
 								// Fragment frame is too large, it exeeds the maximum frame size.
@@ -1535,12 +1546,12 @@
 								Status = NDIS_STATUS_FAILURE;
 								break;
 							}
-							
+
                             // concatenate this fragment into the re-assembly buffer
 							memcpy(&pAdapter->FragFrame.Buffer[LENGTH_802_3 + pAdapter->FragFrame.RxSize], pData, PacketSize);
 							pAdapter->FragFrame.RxSize	+= PacketSize;
 							pAdapter->FragFrame.LastFrag = pHeader->Frag;		// Update fragment number
-									
+
 							// Last fragment
 							if (pHeader->Controlhead.Frame.MoreFrag == FALSE)
 							{
@@ -1555,7 +1566,7 @@
 									}
 									// Minus MIC length
 									pAdapter->FragFrame.RxSize -= 8;
-											
+
 									if (pAdapter->FragFrame.Flags & 0x00000001)
 									{
 									    // originally there's an LLC/SNAP field in the first fragment
@@ -1563,9 +1574,9 @@
 									    // this LLC/SNAP field upon calculating TKIP MIC
 										// Copy LLC data to the position in front of real data for MIC calculation
 										memcpy(&pAdapter->FragFrame.Buffer[LENGTH_802_3 - LENGTH_802_1_H],
-														pAdapter->FragFrame.Header_LLC, 
+														pAdapter->FragFrame.Header_LLC,
 														LENGTH_802_1_H);
-									    pData = (PUCHAR) &pAdapter->FragFrame.Buffer[LENGTH_802_3 - LENGTH_802_1_H];										
+									    pData = (PUCHAR) &pAdapter->FragFrame.Buffer[LENGTH_802_3 - LENGTH_802_1_H];
 									    PacketSize = (USHORT)pAdapter->FragFrame.RxSize + LENGTH_802_1_H;
 									    //cketSize = (USHORT)pAdapter->FragFrame.RxSize + 8;
 									}
@@ -1583,29 +1594,25 @@
 										pWpaKey->RxMic,
  									    PacketSize) == FALSE)
 									{
-										DBGPRINT(RT_DEBUG_ERROR,"Rx MIC Value error 2\n");							
+										DBGPRINT(RT_DEBUG_ERROR,"Rx MIC Value error 2\n");
 										RTMPReportMicError(pAdapter, pWpaKey);
 										Status = NDIS_STATUS_FAILURE;
 										break;
 									}
-							
+
 									// TODO:
 									// Getting RxTSC from Rx descriptor
-								}				
+								}
 
                                 // for RX ACTIVITY LED
-								pAdapter->PortCfg.LedCntl.fRxActivity = TRUE; 
+								pAdapter->PortCfg.LedCntl.fRxActivity = TRUE;
 
 								// For miniportTransferData
 								pAdapter->pRxData = &pAdapter->FragFrame.Buffer[LENGTH_802_3];
 
 								memcpy(pAdapter->FragFrame.Buffer, pAdapter->FragFrame.Header802_3, LENGTH_802_3);
 								// Acknowledge upper layer the received frame
-#ifdef RTMP_EMBEDDED
                                 if ((skb = __dev_alloc_skb(pAdapter->FragFrame.RxSize + LENGTH_802_3 + 2, GFP_DMA|GFP_ATOMIC)) != NULL)
-#else
-                                if ((skb = dev_alloc_skb(pAdapter->FragFrame.RxSize + LENGTH_802_3 + 2)) != NULL)
-#endif
                                 {
                                     skb->dev = pAdapter->net_dev;
                                     skb_reserve(skb, 2);    /* 16 byte align the IP header */
@@ -1619,7 +1626,7 @@
 
 								// Increase general counters
 								pAdapter->Counters.GoodReceives++;
-	
+
 								// Clear Fragment frame contents
 								memset(&pAdapter->FragFrame, 0, sizeof(FRAGMENT_FRAME));
 								DBGPRINT(RT_DEBUG_INFO, "!!! Frame with Fragment Indicated !!!\n");
@@ -1627,42 +1634,42 @@
 						}
 					}
 					break;
-	
+
 				case BTYPE_MGMT:
 					// Read required regsiter for MLME engine
 					RTMP_IO_READ32(pAdapter, CSR17, &High32TSF);		// TSF value
 					RTMP_IO_READ32(pAdapter, CSR16, &Low32TSF); 		// TSF vlaue
-				
+
 					// Enqueue this frame to MLME engine
 					MlmeEnqueueForRecv(
 						pAdapter,
-						&pAdapter->Mlme.Queue,	
-						High32TSF, 
+						&pAdapter->Mlme.Queue,
+						High32TSF,
 						Low32TSF,
 						(UCHAR)pRxD->BBR1,
-						(UCHAR)pAdapter->PortCfg.LastR17Value, 
-						pRxD->DataByteCnt, 
-						pManage);					
+						(UCHAR)pAdapter->PortCfg.LastR17Value,
+						pRxD->DataByteCnt,
+						pManage);
 					break;
-		
+
 				case BTYPE_CNTL:
 					// Ignore ???
 					break;
-	
+
 				default :
 					break;
 			}
 		}
-			
+
 		pAdapter->CurDecryptIndex++;
 		if (pAdapter->CurDecryptIndex >= RX_RING_SIZE)
 		{
 			pAdapter->CurDecryptIndex = 0;
 		}
 		Count++;
-			
+
 		pAdapter->RalinkCounters.DecryptCount ++;
-			
+
 		// Clear Cipherowner bit & Rx Owner bit for all drop & non-drop frames
 		pRxD->CipherOwner = DESC_OWN_HOST;
 		pRxD->Owner       = DESC_OWN_NIC;
@@ -1673,7 +1680,7 @@
 	}
 	//}	while (Count < RX_RING_SIZE);
 	//} while (pAdapter->CurDecryptIndex != HwDecryptIndex);
-		
+
 	// Make sure to release Rx ring resource
 	spin_unlock_irqrestore(&pAdapter->RxRingLock, irqflag);
 }
@@ -1706,10 +1713,10 @@
 	ULONG			RegValue;
 	ULONGLONG		HwEncryptIndex;
         unsigned long           irqflag;
-	
+
 	// Make sure Prio ring resource won't be used by other threads
-	spin_lock_irqsave(&pAdapter->TxRingLock, irqflag);	
-	
+	spin_lock_irqsave(&pAdapter->TxRingLock, irqflag);
+
 	RTMP_IO_READ32(pAdapter, SECCSR1, &RegValue);
         HwEncryptIndex = RegValue - pAdapter->TxRing[0].pa_addr;
         do_div(HwEncryptIndex, RING_DESCRIPTOR_SIZE);
@@ -1749,17 +1756,18 @@
 			*pTmp       = Eiv_Tmp[3];
 			*(pTmp + 1) = Eiv_Tmp[2];
 			*(pTmp + 2) = Eiv_Tmp[1];
-			*(pTmp + 3) = Eiv_Tmp[0];			
+			*(pTmp + 3) = Eiv_Tmp[0];
 		}
 		// Sanity Check, CurTxIndex should equal to NextEncryptDoneIndex
 		// ASSERT(pAdapter->CurTxIndex == pAdapter->NextEncryptDoneIndex);
-		
+
 		pTxD->Valid = TRUE;
 		pTxD->Owner = DESC_OWN_NIC;
 
 #ifdef BIG_ENDIAN
         RTMPDescriptorEndianChange((PUCHAR)pTxD, TYPE_TXD);
-        *pDestTxD = TxD;
+        //*pDestTxD = TxD;
+	WriteBackToDescriptor((PUCHAR)pDestTxD, (PUCHAR)pTxD, FALSE, TYPE_TXD);
 #endif
 
 		pAdapter->NextEncryptDoneIndex++;
@@ -1778,9 +1786,9 @@
 
 	// Kick Tx Control Register at the end of all ring buffer preparation
 	RTMP_IO_WRITE32(pAdapter, TXCSR0, 0x1);
-	
+
 	// Make sure to release Tx ring resource
-	spin_unlock_irqrestore(&pAdapter->TxRingLock, irqflag);	
+	spin_unlock_irqrestore(&pAdapter->TxRingLock, irqflag);
 }
 
 /*
@@ -1854,7 +1862,7 @@
 				INC_COUNTER(pAdapter->WlanCounters.RTSSuccessCount);
 				pTxD->RTS = 0;
 			}
-			
+
 			// Increase general counters
 			pAdapter->Counters.GoodTransmits++;
 			INC_COUNTER(pAdapter->WlanCounters.TransmittedFragmentCount);
@@ -1865,22 +1873,22 @@
                 pAdapter->DrsCounters.OneSecTxOkCount ++;
             }
 			break;
-			  
+
 		case SUCCESS_WITH_RETRY:			// Success with some retry
 			// DBGPRINT(RT_DEBUG_INFO, "TX Success with retry(=%d)<<<\n",pTxD->RetryCount);
 			// Increase 802.11 counters
 			INC_COUNTER(pAdapter->WlanCounters.RetryCount);
 			INC_COUNTER(pAdapter->WlanCounters.ACKFailureCount);
 			INC_COUNTER(pAdapter->WlanCounters.TransmittedFragmentCount);
-			
+
 			// Increase general counters
 			pAdapter->Counters.GoodTransmits++;
-			
+
 			if (pTxD->RetryCount > 1)
 			{
 				// Increase 802.11 counters
 				INC_COUNTER(pAdapter->WlanCounters.MultipleRetryCount);
-				
+
 				// Increase general counters
 				pAdapter->Counters.MoreCollisions++;
 			}
@@ -1889,7 +1897,7 @@
 				// Increase general counters
 				pAdapter->Counters.OneCollision++;
 			}
-			
+
 			if (pTxD->RTS)
 			{
 				INC_COUNTER(pAdapter->WlanCounters.RTSSuccessCount);
@@ -1901,7 +1909,7 @@
             {
                 if (pTxD->TxRate > pAdapter->PortCfg.TxRate)
                 {
-                    // DRS - must be NULL frame retried @ UpRate; downgrade 
+                    // DRS - must be NULL frame retried @ UpRate; downgrade
                     //       TxQuality[UpRate] so that not upgrade TX rate
                     pAdapter->DrsCounters.TxQuality[pTxD->TxRate] += 2;
                     if (pAdapter->DrsCounters.TxQuality[pTxD->TxRate] > DRS_TX_QUALITY_WORST_BOUND)
@@ -1917,10 +1925,10 @@
 			// Increase 802.11 counters
 			INC_COUNTER(pAdapter->WlanCounters.FailedCount);
 			INC_COUNTER(pAdapter->WlanCounters.ACKFailureCount);
-			
+
 			// Increase general counters
 			pAdapter->Counters.TxErrors++;
-			
+
 			if (pTxD->RTS)
 			{
 				INC_COUNTER(pAdapter->WlanCounters.RTSFailureCount);
@@ -1932,7 +1940,7 @@
             {
                 if (pTxD->TxRate > pAdapter->PortCfg.TxRate)
                 {
-                    // DRS - must be NULL frame failed @ UpRate; downgrade 
+                    // DRS - must be NULL frame failed @ UpRate; downgrade
                     //       TxQuality[UpRate] so that not upgrade TX rate
                     pAdapter->DrsCounters.TxQuality[pTxD->TxRate] = DRS_TX_QUALITY_WORST_BOUND;
                 }
@@ -1942,35 +1950,35 @@
                 }
             }
 			break;
-			
+
 		case FAIL_INVALID:
 			// DBGPRINT(RT_DEBUG_WARN, ("TX Failed (INVALID)<<<\n"));
 			// Increase general counters
 			pAdapter->Counters.TxErrors++;
-			
+
 			if (pTxD->RTS)
 			{
 				INC_COUNTER(pAdapter->WlanCounters.RTSFailureCount);
 				pTxD->RTS = 0;
 			}
-			break;			
-			
+			break;
+
 		case FAIL_OTHER:
 		default:
 			// DBGPRINT(RT_DEBUG_ERROR, ("TX Failed (other=%d)<<<\n",pTxD->TxResult));
 			// Increase 802.11 counters
 			INC_COUNTER(pAdapter->WlanCounters.FailedCount);
 			INC_COUNTER(pAdapter->WlanCounters.ACKFailureCount);
-			
+
 			// Increase general counters
 			pAdapter->Counters.TxErrors++;
-			
+
 			if (pTxD->RTS)
 			{
 				INC_COUNTER(pAdapter->WlanCounters.RTSFailureCount);
 				pTxD->RTS = 0;
 			}
-			break;			
+			break;
 	}
 }
 
@@ -1980,19 +1988,19 @@
 	Routine	Description:
 		API for MLME to transmit management frame to AP (BSS Mode)
 	or station (IBSS Mode)
-	
+
 	Arguments:
 		pAdapter	Pointer	to our adapter
 		Buffer		Pointer to  memory of outgoing frame
 		Length		Size of outgoing management frame
-		
+
 	Return Value:
 		NDIS_STATUS_FAILURE
 		NDIS_STATUS_PENDING
 		NDIS_STATUS_SUCCESS
 
 	Note:
-	
+
 	========================================================================
 */
 NDIS_STATUS	MiniportMMRequest(
@@ -2001,28 +2009,28 @@
 	IN	ULONG			Length)
 {
 	PMGMT_STRUC		pMgmt;
-	NDIS_STATUS		Status = NDIS_STATUS_SUCCESS;    
+	NDIS_STATUS		Status = NDIS_STATUS_SUCCESS;
 	unsigned long irqflag;
 
 	DBGPRINT(RT_DEBUG_INFO, "---> MiniportMMRequest\n");
 	// Check management ring free avaliability
 	pMgmt = (PMGMT_STRUC) &pAdapter->MgmtRing[pAdapter->PushMgmtIndex];
-	
+
 	// This management cell has been occupied
-	if (pMgmt->Valid == TRUE)	
+	if (pMgmt->Valid == TRUE)
 	{
 		// No Management ring buffer avaliable
 		MlmeFreeMemory(pAdapter, pBuffer);
-		Status = NDIS_STATUS_FAILURE; 
+		Status = NDIS_STATUS_FAILURE;
 		DBGPRINT(RT_DEBUG_WARN, "<--- MiniportMMRequest (error:: MgmtRing full)\n");
 		pAdapter->RalinkCounters.MgmtRingFullCount++;
 		return (Status);
 	}
-	
+
 	// Insert this request into software managemnet ring
 	if (pBuffer)
 	{
-		pMgmt->pBuffer = pBuffer;		
+		pMgmt->pBuffer = pBuffer;
 		pMgmt->Length  = Length;
 		pMgmt->Valid   = TRUE;
 		pAdapter->PushMgmtIndex++;
@@ -2031,19 +2039,19 @@
 		{
 			pAdapter->PushMgmtIndex = 0;
 		}
-	}	
+	}
 	else
 	{
 		// Null pBuffer, no need to free memory buffer.
 		// This should not happen
 		DBGPRINT(RT_DEBUG_WARN, "<--- MiniportMMRequest (error:: NULL msg)\n");
-		Status = NDIS_STATUS_FAILURE; 
+		Status = NDIS_STATUS_FAILURE;
 		return (Status);
 	}
-	
+
 	if (RTMP_TEST_FLAG(pAdapter, fRTMP_ADAPTER_RADIO_OFF))
 		return (Status);
-	
+
 	// Check Free priority queue
 	spin_lock_irqsave(&pAdapter->PrioRingLock, irqflag);
 	if (RTMPFreeDescriptorRequest(pAdapter, PRIO_RING, 1) == NDIS_STATUS_SUCCESS)
@@ -2076,21 +2084,21 @@
 	========================================================================
 
 	Routine	Description:
-		Copy frame from waiting queue into relative ring buffer and set 
+		Copy frame from waiting queue into relative ring buffer and set
 	appropriate ASIC register to kick hardware transmit function
-	
+
 	Arguments:
 		pAdapter	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
 
 	Note:
-	
+
 	========================================================================
 */
 VOID	MlmeHardTransmit(
@@ -2103,15 +2111,15 @@
     PTXD_STRUC      pDestTxD;
     TXD_STRUC       TxD;
 #endif
-	PUCHAR			pDest;	
+	PUCHAR			pDest;
 	PHEADER_802_11	pHeader_802_11;
 	BOOLEAN         AckRequired, InsertTimestamp;
-	
+
 	DBGPRINT(RT_DEBUG_INFO, "MlmeHardTransmit\n");
-	
+
 	// Make sure Prio ring resource won't be used by other threads
-		
-	pDest = (PUCHAR) pAdapter->PrioRing[pAdapter->CurPrioIndex].va_data_addr;              
+
+	pDest = (PUCHAR) pAdapter->PrioRing[pAdapter->CurPrioIndex].va_data_addr;
 #ifndef BIG_ENDIAN
 	pTxD  = (PTXD_STRUC) pAdapter->PrioRing[pAdapter->CurPrioIndex].va_addr;
 #else
@@ -2120,7 +2128,7 @@
     pTxD = &TxD;
     RTMPDescriptorEndianChange((PUCHAR)pTxD, TYPE_TXD);
 #endif
-		
+
 	if (pTxD->Owner == DESC_OWN_NIC)
 	{
 		// Descriptor owned by NIC. No descriptor avaliable
@@ -2138,10 +2146,10 @@
 		// The buffer shouldn't be NULL
 		return;
 	}
-	
-	// outgoing frame always wakeup PHY to prevent frame lost 
+
+	// outgoing frame always wakeup PHY to prevent frame lost
 	AsicForceWakeup(pAdapter);
-	
+
 	pHeader_802_11           = (PHEADER_802_11) pBuffer;
 	pHeader_802_11->Controlhead.Frame.PwrMgt = 0; // (pAdapter->PortCfg.Psm == PWR_SAVE);
 	InsertTimestamp = FALSE;
@@ -2175,7 +2183,7 @@
     RTMPFrameEndianChange(pAdapter, (PUCHAR)pBuffer, DIR_WRITE, FALSE);
 #endif
 	memcpy(pDest, pBuffer, Length);
-   
+
 	// Initialize Priority 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
@@ -2193,28 +2201,28 @@
 	{
 		pAdapter->CurPrioIndex = 0;
 	}
-		
+
 	// Kick priority ring transmit
 	RTMP_IO_WRITE32(pAdapter,TXCSR0,0x4);
-	
+
 	// Make sure to release Prio ring resource
-}   
+}
 /*
 	========================================================================
 
 	Routine	Description:
 		This routine is	used to	en-queue outgoing packets when
 		there is no	enough shread memory
-		
+
 	Arguments:
 		pAdapter	Pointer	to our adapter
 		pPacket		Pointer to send packet
-		
+
 	Return Value:
 		None
 
 	Note:
-	
+
 	========================================================================
 */
 NDIS_STATUS	RTMPSendPacket(
@@ -2225,51 +2233,42 @@
 	UINT			AllowFragSize;
 	UCHAR			NumberOfFrag;
 	UCHAR			RTSRequired;
-	NDIS_STATUS		Status = NDIS_STATUS_FAILURE;
-	UCHAR			PsMode;
-	
+
 	struct sk_buff_head	*pTxQueue = NULL;
 	ULONG			Priority;
 	UCHAR                   AccessCategory;
         unsigned long           irqflag;
-	
-	DBGPRINT(RT_DEBUG_INFO, "<==== RTMPSendPacket\n");
 
-	// Init priority value
-	Priority = 0;
-	AccessCategory = 0;
-	
-    if (skb)
-    {
-		Priority = skb->priority;
-		// 802.11e/d4.4 June, 2003
-		if (Priority <=2)
-		    AccessCategory = 0;
-		else if (Priority == 3)
-		    AccessCategory = 1;
-		else if (Priority <= 5)
-		    AccessCategory = 2;
-		else
-		    AccessCategory = 3;
-		DBGPRINT(RT_DEBUG_INFO, "Priority = %d, AC = %d\n", Priority, AccessCategory);
-    }
+	DBGPRINT(RT_DEBUG_INFO, "====> RTMPSendPacket\n");
+
+	if (skb == NULL)
+		return NDIS_STATUS_SUCCESS;
+
+	Priority = skb->priority;
+	// 802.11e/d4.4 June, 2003
+	if (Priority <=2)
+	    AccessCategory = 0;
+	else if (Priority == 3)
+	    AccessCategory = 1;
+	else if (Priority <= 5)
+	    AccessCategory = 2;
+	else
+	    AccessCategory = 3;
+	DBGPRINT(RT_DEBUG_INFO, "Priority = %d, AC = %d\n", Priority,
+			AccessCategory);
 
 	// For TKIP, MIC value is treated as payload, it might be fragmented through
 	// different MPDUs.
 	if (pAdapter->PortCfg.WepStatus == Ndis802_11Encryption2Enabled)
-	{
 		skb->data_len += 8;
-	}
 
 	pVirtualAddress = (PVOID)skb->data;
 
 	// Check for virtual address allocation, it might fail !!!
 	if (pVirtualAddress == NULL)
-	{
-		// Resourece is low, system did not allocation virtual address
+		// Resource is low, system did not allocate virtual address
 		// return NDIS_STATUS_FAILURE directly to upper layer
-		return (Status);
-	}
+		return NDIS_STATUS_FAILURE;
 
 	// Store Ethernet MAC address when APClinet mode on
 	if ((pAdapter->PortCfg.StaWithEtherBridge.Enable)
@@ -2296,7 +2295,7 @@
         pAdapter->CurrentAddress[3] = StaMacReg0.field.Byte3;
         pAdapter->CurrentAddress[4] = StaMacReg1.field.Byte4;
         pAdapter->CurrentAddress[5] = StaMacReg1.field.Byte5;
-        
+
         RTMP_IO_WRITE32(pAdapter, CSR3, StaMacReg0.word);
         RTMP_IO_WRITE32(pAdapter, CSR4, StaMacReg1.word);
 
@@ -2304,7 +2303,7 @@
 	        pAdapter->PortCfg.StaWithEtherBridge.EtherMacAddr.Octet[0],pAdapter->PortCfg.StaWithEtherBridge.EtherMacAddr.Octet[1],pAdapter->PortCfg.StaWithEtherBridge.EtherMacAddr.Octet[2],
 	        pAdapter->PortCfg.StaWithEtherBridge.EtherMacAddr.Octet[3],pAdapter->PortCfg.StaWithEtherBridge.EtherMacAddr.Octet[4],pAdapter->PortCfg.StaWithEtherBridge.EtherMacAddr.Octet[5]);
 	}
-	
+
 	//
 	// Check for multicast or broadcast (First byte of DA)
 	//
@@ -2322,37 +2321,30 @@
 		NumberOfFrag = ((skb->data_len - LENGTH_802_3 + LENGTH_802_1_H) / AllowFragSize) + 1;
 		// Minus 1 if the size just match to allowable fragment size
 		if (((skb->data_len - LENGTH_802_3 + LENGTH_802_1_H) % AllowFragSize) == 0)
-		{
 			NumberOfFrag--;
-		}
 	}
 
-	// Check for requirement of RTS 
+	// Check for requirement of RTS
 	if (NumberOfFrag > 1)
-	{
 		// If multiple fragment required, RTS is required only for the first fragment
 		// if the fragment size large than RTS threshold
 		RTSRequired = (pAdapter->PortCfg.FragmentThreshold > pAdapter->PortCfg.RtsThreshold) ? 1 : 0;
-	}
 	else
-	{
 		RTSRequired = (skb->data_len > pAdapter->PortCfg.RtsThreshold) ? 1 : 0;
-	}
-	DBGPRINT(RT_DEBUG_INFO, "Number of fragments include RTS :%d\n", NumberOfFrag + RTSRequired);
+	DBGPRINT(RT_DEBUG_INFO,
+			"Number of fragments include RTS :%d\n",
+			NumberOfFrag + RTSRequired);
+
+	// RTS/CTS may also be required in order to protect OFDM frame
+	if ((pAdapter->PortCfg.TxRate >= RATE_FIRST_OFDM_RATE) && pAdapter->PortCfg.BGProtectionInUsed)
+		RTSRequired = 1;
 
-    // RTS/CTS may also be required in order to protect OFDM frame
-    if ((pAdapter->PortCfg.TxRate >= RATE_FIRST_OFDM_RATE) && pAdapter->PortCfg.BGProtectionInUsed)
-        RTSRequired = 1;
-        
 	// Save framnet number to Ndis packet reserved field
 	RTMP_SET_PACKET_FRAGMENTS(skb, NumberOfFrag);
 
 	// Save RTS requirement to Ndis packet reserved field
 	RTMP_SET_PACKET_RTS(skb, RTSRequired);
 
-	// Make sure SendTxWait queue resource won't be used by other threads
-	spin_lock_irqsave(&pAdapter->TxSwQueueLock, irqflag);
-
 	// Select the right priority queue
 	// There should be no else statement since it should always fall within 0-3
 	if (AccessCategory== 0)
@@ -2363,56 +2355,49 @@
 		pTxQueue = &pAdapter->TxSwQueue2;
 	else if (AccessCategory== 3)
 		pTxQueue = &pAdapter->TxSwQueue3;
-	
+
 	//
 	// For infrastructure mode, enqueue this frame immediately to sendwaitqueue
 	// For Ad-hoc mode, check the DA power state, then decide which queue to enqueue
 	//
-	if (INFRA_ON(pAdapter))
-	{
-	    // In infrastructure mode, simply enqueue the packet into Tx waiting queue.
-	    DBGPRINT(RT_DEBUG_INFO, "Infrastructure -> Enqueue one frame\n");
-		
-	    // Enqueue Ndis packet to end of Tx wait queue
-	    skb_queue_tail(pTxQueue, skb);
-	    Status = NDIS_STATUS_SUCCESS;
-	}
-	else
-	{
-	    // In IBSS mode, power state of destination should be considered.
-	    PsMode = PWR_ACTIVE;		// Faked
-	    if (PsMode == PWR_ACTIVE)
-	    {
-		DBGPRINT(RT_DEBUG_INFO,"Ad-Hoc -> Enqueue one frame\n");
-
+	if (INFRA_ON(pAdapter)) {
+	    	// In infrastructure mode, simply enqueue the packet into Tx waiting queue.
+	    	DBGPRINT(RT_DEBUG_INFO,
+	    		"<=== RTMPSendPacket Infrastructure -> Enqueue one frame\n");
 		// Enqueue Ndis packet to end of Tx wait queue
+		spin_lock_irqsave(&pAdapter->TxSwQueueLock, irqflag);
 		skb_queue_tail(pTxQueue, skb);
-		Status = NDIS_STATUS_SUCCESS;
-	    }
+		spin_unlock_irqrestore(&pAdapter->TxSwQueueLock, irqflag);
+		return NDIS_STATUS_SUCCESS;
 	}
-	
+	// Ad-hoc mode (power state of destination might be considered).
+	DBGPRINT(RT_DEBUG_INFO,
+			"<=== RTMPSendPacket Ad-Hoc -> Enqueue one frame\n");
+	// Enqueue Ndis packet to end of Tx wait queue
+	spin_lock_irqsave(&pAdapter->TxSwQueueLock, irqflag);
+	skb_queue_tail(pTxQueue, skb);
 	spin_unlock_irqrestore(&pAdapter->TxSwQueueLock, irqflag);
-	return (Status);
+	return NDIS_STATUS_SUCCESS;
 }
 
 /*
 	========================================================================
 
 	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 
+		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:
 		pAdapter	Pointer	to our adapter
 		pQueue		Pointer to Waiting Queue
-		
+
 	Return Value:
 		None
 
 	Note:
-	
+
 	========================================================================
 */
 VOID	RTMPDeQueuePacket(
@@ -2424,69 +2409,64 @@
 	struct sk_buff_head	*pQueue;
 	UCHAR           AccessCategory;
 	struct sk_buff  *skb;
-        unsigned long           irqflag;
-	
-	// Make sure SendTxWait queue resource won't be used by other threads
-	spin_lock_irqsave(&pAdapter->TxSwQueueLock, irqflag);
+	unsigned long           irqflag;
 
-	while (Count < MAX_TX_PROCESS)
-	// Check queue before dequeue
-	// while ((pQueue->Head != NULL) && (Count < MAX_TX_PROCESS)) 
-	{
+	while (Count < MAX_TX_PROCESS) {
 		// Reset is in progress, stop immediately
 		if (RTMP_TEST_FLAG(pAdapter, fRTMP_ADAPTER_RESET_IN_PROGRESS))
 			break;
 
 		pQueue = RTMPCheckTxSwQueue(pAdapter, &AccessCategory);
 		if(!pQueue)
-                    break;
+			break;
 
 		// Dequeue the first entry from head of queue list
+		spin_lock_irqsave(&pAdapter->TxSwQueueLock, irqflag);
 		skb = skb_dequeue(pQueue);
+		spin_unlock_irqrestore(&pAdapter->TxSwQueueLock, irqflag);
 
 		if(!skb)
-                    break;
+			break;
 
 		// RTS or CTS-to-self for B/G protection mode has been set already.
-		// There is no need to re-do it here. 
+		// There is no need to re-do it here.
 		// Total fragment required = number of fragment + RST if required
 		FragmentRequired = RTMP_GET_PACKET_FRAGMENTS(skb) + RTMP_GET_PACKET_RTS(skb);
-		
-		if (RTMPFreeDescriptorRequest(pAdapter, TX_RING, FragmentRequired) == NDIS_STATUS_SUCCESS)
-		{
-			// Avaliable ring descriptors are enough for this frame
-			// Call hard transmit
-			Status = RTMPHardEncrypt(pAdapter, skb, FragmentRequired, pAdapter->PortCfg.EnableTxBurst, AccessCategory);
 
-			if (Status == NDIS_STATUS_FAILURE)
-			{
-                // Packet failed due to various Ndis Packet error
-               dev_kfree_skb_irq(skb);
-				break;
-			}
-			else if (Status == NDIS_STATUS_RESOURCES)
-			{
-				// Not enough free tx ring, it might happen due to free descriptor inquery might be not correct
-				// It also might change to NDIS_STATUS_FAILURE to simply drop the frame
-				// Put the frame back into head of queue
-				skb_queue_head(pQueue, skb);
-                break;
-			}			
-			Count++;
-		}	
-		else
-		{
+		if (RTMPFreeDescriptorRequest(pAdapter, TX_RING,
+				FragmentRequired) != NDIS_STATUS_SUCCESS) {
+			spin_lock_irqsave(&pAdapter->TxSwQueueLock, irqflag);
 			skb_queue_head(pQueue, skb);
+			spin_unlock_irqrestore(&pAdapter->TxSwQueueLock, irqflag);
 			pAdapter->PrivateInfo.TxRingFullCnt++;
-			DBGPRINT(RT_DEBUG_INFO,"RTMPDequeuePacket --> Not enough free Tx Ring descriptor (CurEncryptIndex=%d,CurTxIndex=%d, NextTxDoneIndex=%d)!!!\n",
-			    pAdapter->CurEncryptIndex, pAdapter->CurTxIndex, pAdapter->NextTxDoneIndex);
+			DBGPRINT(RT_DEBUG_INFO,
+					"RTMPDequeuePacket --> Not enough free Tx Ring descriptor (CurEncryptIndex=%d,CurTxIndex=%d, NextTxDoneIndex=%d)!!!\n",
+					pAdapter->CurEncryptIndex,
+					pAdapter->CurTxIndex,
+					pAdapter->NextTxDoneIndex);
 			break;
 		}
+		// Available ring descriptors are enough for this frame
+		// Call hard transmit
+		Status = RTMPHardEncrypt(pAdapter, skb, FragmentRequired, pAdapter->PortCfg.EnableTxBurst, AccessCategory);
+		if (Status == NDIS_STATUS_FAILURE) {
+        		// Packet failed due to various Ndis Packet error
+       			dev_kfree_skb_irq(skb);
+			break;
+		} else if (Status == NDIS_STATUS_RESOURCES) {
+			// Not enough free tx ring, it might happen due to free descriptor inquery might be not correct
+			// It also might change to NDIS_STATUS_FAILURE to simply drop the frame
+			// Put the frame back into head of queue
+			spin_lock_irqsave(&pAdapter->TxSwQueueLock, irqflag);
+			skb_queue_head(pQueue, skb);
+			spin_unlock_irqrestore(&pAdapter->TxSwQueueLock, irqflag);
+        		break;
+		}
+
+		Count++;
 	}
 
-	// Release TxSwQueue0 resources
-	spin_unlock_irqrestore(&pAdapter->TxSwQueueLock, irqflag);
-}    
+}
 
 /*
 	========================================================================
@@ -2494,17 +2474,17 @@
 	Routine	Description:
 		This subroutine will scan through releative ring descriptor to find
 		out avaliable free ring descriptor and compare with request size.
-		
+
 	Arguments:
 		pAdapter	Pointer	to our adapter
 		RingType	Selected Ring
-		
+
 	Return Value:
 		NDIS_STATUS_FAILURE		Not enough free descriptor
 		NDIS_STATUS_SUCCESS		Enough free descriptor
 
 	Note:
-	
+
 	========================================================================
 */
 NDIS_STATUS	RTMPFreeDescriptorRequest(
@@ -2557,18 +2537,18 @@
 				{
 					Index = 0;
 				}
-				
+
 			}	while (FreeNumber < NumberRequired);	// Quit here ! Free number is enough !
-			
+
 			if (FreeNumber >= NumberRequired)
 			{
 				Status = NDIS_STATUS_SUCCESS;
 			}
-			
+
 			// Make sure to release Tx ring resource
 			spin_unlock_irqrestore(&pAdapter->TxRingLock, irqflag);
 			break;
-			
+
 		case PRIO_RING:
 			Index = pAdapter->CurPrioIndex;
 			do
@@ -2581,7 +2561,7 @@
                 pTxD = &TxD;
                 RTMPDescriptorEndianChange((PUCHAR)pTxD, TYPE_TXD);
 #endif
-				
+
 				// While Owner bit is NIC, obviously ASIC still need it.
 				// If valid bit is TRUE, indicate that TxDone has not process yet
 				// We should not use it until TxDone finish cleanup job
@@ -2594,26 +2574,26 @@
 				{
 					break;
 				}
-					
+
 				Index++;
 				if (Index >= PRIO_RING_SIZE)			// Wrap around issue
 				{
 					Index = 0;
 				}
-				
+
 			}	while (FreeNumber < NumberRequired);	// Quit here ! Free number is enough !
-			
+
 			if (FreeNumber >= NumberRequired)
 			{
 				Status = NDIS_STATUS_SUCCESS;
 			}
-			
+
 			break;
 
 		default:
 			break;
 	}
-	
+
 	return (Status);
 }
 
@@ -2631,7 +2611,7 @@
     TXD_STRUC       TxD;
 #endif
         unsigned long           irqflag;
-	
+
 	if (pBuffer == NULL)
 	{
 		return;
@@ -2642,19 +2622,19 @@
 		MlmeFreeMemory(pAdapter, pBuffer);
 		return;
 	}
-	
+
 	// WPA 802.1x secured port control
-    if (((pAdapter->PortCfg.AuthMode == Ndis802_11AuthModeWPA) || 
+    if (((pAdapter->PortCfg.AuthMode == Ndis802_11AuthModeWPA) ||
         (pAdapter->PortCfg.AuthMode == Ndis802_11AuthModeWPAPSK)) &&
-       (pAdapter->PortCfg.PortSecured == WPA_802_1X_PORT_NOT_SECURED)) 
+       (pAdapter->PortCfg.PortSecured == WPA_802_1X_PORT_NOT_SECURED))
 	{
 		MlmeFreeMemory(pAdapter, pBuffer);
 		return;
-	}		
-	
+	}
+
 	FrameGap = IFS_BACKOFF;		// Default frame gap mode
 
-	// outgoing frame always wakeup PHY to prevent frame lost and 
+	// outgoing frame always wakeup PHY to prevent frame lost and
 	// turn off PSM bit to improve performance
 	AsicForceWakeup(pAdapter);
 #if 0
@@ -2664,13 +2644,13 @@
 		DBGPRINT(RT_DEBUG_TRACE,("Drop Null frame due to Tx queue not empty!\n"));
 	}
 	else
-#endif	    
+#endif
 	{
 		// Make sure Tx ring resource won't be used by other threads
 		spin_lock_irqsave(&pAdapter->TxRingLock, irqflag);
-	
+
 		// Get the Tx Ring descriptor & Dma Buffer address
-		pDest = (PUCHAR) pAdapter->TxRing[pAdapter->CurEncryptIndex].va_data_addr;              
+		pDest = (PUCHAR) pAdapter->TxRing[pAdapter->CurEncryptIndex].va_data_addr;
 #ifndef BIG_ENDIAN
 		pTxD  = (PTXD_STRUC) pAdapter->TxRing[pAdapter->CurEncryptIndex].va_addr;
 #else
@@ -2679,11 +2659,11 @@
         pTxD = &TxD;
         RTMPDescriptorEndianChange((PUCHAR)pTxD, TYPE_TXD);
 #endif
-		
+
 		if ((pTxD->Owner == DESC_OWN_HOST) && (pTxD->CipherOwn == DESC_OWN_HOST) && (pTxD->Valid == FALSE))
 		{
 			HEADER_802_11	*pHeader_802_11;
-			
+
 			DBGPRINT(RT_DEBUG_TRACE, "SYNC - send NULL Frame @%d Mbps...\n", RateIdToMbps[TxRate]);
 #ifdef BIG_ENDIAN
             RTMPFrameEndianChange(pAdapter, (PUCHAR)pBuffer, DIR_WRITE, FALSE);
@@ -2693,14 +2673,14 @@
 
 			pHeader_802_11 = (PHEADER_802_11) pDest;
 			pHeader_802_11->Controlhead.Frame.PwrMgt = (pAdapter->PortCfg.Psm == PWR_SAVE);
-			
+
 #ifdef BIG_ENDIAN
             RTMPDescriptorEndianChange((PUCHAR)pTxD, TYPE_TXD);
             *pDestTxD = TxD;
             pTxD = pDestTxD;
 #endif
 
-			RTMPWriteTxDescriptor(pTxD, TRUE, CIPHER_NONE, TRUE, FALSE, FALSE, LONG_RETRY, IFS_BACKOFF, 
+			RTMPWriteTxDescriptor(pTxD, TRUE, CIPHER_NONE, TRUE, FALSE, FALSE, LONG_RETRY, IFS_BACKOFF,
 			    TxRate, 4, Length, pAdapter->PortCfg.TxPreambleInUsed, 0);
 
 			// Increase & maintain Tx Ring Index
@@ -2709,13 +2689,13 @@
 			{
 				pAdapter->CurEncryptIndex = 0;
 			}
-			
+
 			pAdapter->RalinkCounters.EncryptCount++;
 
 			// Kick Encrypt Control Register at the end of all ring buffer preparation
 			RTMP_IO_WRITE32(pAdapter, SECCSR1, 0x1);
-			
-		}		
+
+		}
 		spin_unlock_irqrestore(&pAdapter->TxRingLock, irqflag);
 	}
 	MlmeFreeMemory(pAdapter, pBuffer);
@@ -2725,20 +2705,20 @@
 	========================================================================
 
 	Routine	Description:
-		Copy frame from waiting queue into relative ring buffer and set 
+		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:
 		pAdapter		Pointer	to our adapter
 		PNDIS_PACKET	Pointer to outgoing Ndis frame
 		NumberOfFrag	Number of fragment required
-		
+
 	Return Value:
 		None
 
 	Note:
-	
+
 	========================================================================
 */
 NDIS_STATUS	RTMPHardEncrypt(
@@ -2794,7 +2774,7 @@
     if (pAdapter->PortCfg.BssType == BSS_MONITOR && pAdapter->PortCfg.MallowRFMONTx == TRUE)
     {
 	pAdapter->TxRing[pAdapter->CurEncryptIndex].FrameType = BTYPE_DATA;
-	pDest = (PUCHAR) pAdapter->TxRing[pAdapter->CurEncryptIndex].va_data_addr;              
+	pDest = (PUCHAR) pAdapter->TxRing[pAdapter->CurEncryptIndex].va_data_addr;
 	pTxD  = (PTXD_STRUC) pAdapter->TxRing[pAdapter->CurEncryptIndex].va_addr;
 	MlmeSetPsmBit(pAdapter, PWR_ACTIVE);
 	memcpy(pDest,skb->data,skb->len);
@@ -2812,25 +2792,25 @@
 		FrameGap = IFS_SIFS;
 	else
 		FrameGap = IFS_BACKOFF;		// Default frame gap mode
-	
-	// outgoing frame always wakeup PHY to prevent frame lost and 
+
+	// outgoing frame always wakeup PHY to prevent frame lost and
 	// turn off PSM bit to improve performance
 	if (pAdapter->PortCfg.Psm == PWR_SAVE)
 	{
 		MlmeSetPsmBit(pAdapter, PWR_ACTIVE);
 	}
 	AsicForceWakeup(pAdapter);
-	
+
 	// Sequence Number is identical for all fragments belonged to the same frame
 	// Sequence is 0 - 4095
 	pAdapter->Sequence = ((pAdapter->Sequence) + 1) & (MAX_SEQ_NUMBER);
-	
+
 	AckRate = pAdapter->PortCfg.ExpectedACKRate[pAdapter->PortCfg.TxRate];
 	AckDuration = RTMPCalcDuration(pAdapter, AckRate, 14);
 
     pVirtualAddress = skb->data;
     NdisBufferLength = skb->len;
-	
+
 	if ((*((PUCHAR) pVirtualAddress) & 0x01) != 0)	// Multicast or Broadcast
 	{
 		INC_COUNTER(pAdapter->WlanCounters.MulticastTransmittedFrameCount);
@@ -2843,7 +2823,7 @@
 		spin_unlock_irqrestore(&pAdapter->TxRingLock, irqflag);
 		return (NDIS_STATUS_FAILURE);
 	}
-	
+
 	//
 	// Start making 802.11 frame header
 	//
@@ -2855,14 +2835,14 @@
 		memcpy(&Header_802_11.Addr3, (PUCHAR) pVirtualAddress, ETH_ALEN);
 		Header_802_11.Controlhead.Frame.ToDs = 1;
 	}
-	else 
+	else
 	{
 		// Address 1 - DA, Address 2 - this STA, Address 3 - BSSID
 		memcpy(&Header_802_11.Controlhead.Addr1, (PUCHAR) pVirtualAddress, ETH_ALEN);
 		memcpy(&Header_802_11.Addr3, &pAdapter->PortCfg.Bssid, ETH_ALEN);
 	}
 	memcpy(&Header_802_11.Controlhead.Addr2, pAdapter->CurrentAddress, ETH_ALEN);
-	
+
 	Header_802_11.Sequence = pAdapter->Sequence;		// Sequence number
 	Header_802_11.Controlhead.Frame.Type = BTYPE_DATA;	// Frame type
 	Header_802_11.Controlhead.Frame.PwrMgt = (pAdapter->PortCfg.Psm == PWR_SAVE);
@@ -2878,9 +2858,9 @@
 	}
 	else
 		EAPOLFrame = FALSE;
-	
+
 	// WPA 802.1x secured port control
-    if (((pAdapter->PortCfg.AuthMode == Ndis802_11AuthModeWPA) || 
+    if (((pAdapter->PortCfg.AuthMode == Ndis802_11AuthModeWPA) ||
          (pAdapter->PortCfg.AuthMode == Ndis802_11AuthModeWPAPSK)) &&
         ((pAdapter->PortCfg.PortSecured == WPA_802_1X_PORT_NOT_SECURED) || (pAdapter->PortCfg.MicErrCnt >= 2)) &&
         (EAPOLFrame == FALSE))
@@ -2889,28 +2869,28 @@
 		// Make sure to release Tx ring resource
 		spin_unlock_irqrestore(&pAdapter->TxRingLock, irqflag);
 		return (NDIS_STATUS_FAILURE);
-	}		
-	
+	}
+
 	MICFrag = FALSE;	// Flag to indicate MIC shall spread into two MPDUs
 	Encapped = FALSE;
 	pEncap = NULL;
-	
+
 	pSrc = (PUCHAR) pVirtualAddress;
 	Protocol = *(pSrc + 12) * 256 + *(pSrc + 13);
 	if (Protocol > 1500)	// CHeck for LLC encaped
 	{
 		pEncap = SNAP_802_1H;
 		Encapped = TRUE;
-		if (RTMPEqualMemory(IPX, pSrc + 12, 2) || 
+		if (RTMPEqualMemory(IPX, pSrc + 12, 2) ||
 		    RTMPEqualMemory(APPLE_TALK, pSrc + 12, 2))
 		{
 			pEncap = SNAP_BRIDGE_TUNNEL;
 		}
 	}
 
-	if ((pAdapter->PortCfg.WepStatus == Ndis802_11Encryption1Enabled) && 
+	if ((pAdapter->PortCfg.WepStatus == Ndis802_11Encryption1Enabled) &&
 		(pAdapter->PortCfg.SharedKey[pAdapter->PortCfg.DefaultKeyId].KeyLen != 0))
-		EncryptionOverhead = 8;     // WEP: IV + ICV			
+		EncryptionOverhead = 8;     // WEP: IV + ICV
 	else if (pAdapter->PortCfg.WepStatus == Ndis802_11Encryption2Enabled)
 		EncryptionOverhead = 12;    // TKIP: IV + EIV + ICV, MIC already added to TotalPacketLength
 	else if (pAdapter->PortCfg.WepStatus == Ndis802_11Encryption3Enabled)
@@ -2925,11 +2905,11 @@
 	{
 		PCONTROL_HEADER		pControlHeader;
 		ULONG				NextFragSize;
-		
+
         // RTS-protected frame should use LONG_RETRY (=4), other frames use SHORT_RETRY (=7)
         RetryMode = LONG_RETRY;
-        
-		pDest = (PUCHAR) pAdapter->TxRing[pAdapter->CurEncryptIndex].va_data_addr;              
+
+		pDest = (PUCHAR) pAdapter->TxRing[pAdapter->CurEncryptIndex].va_data_addr;
 #ifndef BIG_ENDIAN
 		pTxD  = (PTXD_STRUC) pAdapter->TxRing[pAdapter->CurEncryptIndex].va_addr;
 #else
@@ -2938,7 +2918,7 @@
         pTxD = &TxD;
         RTMPDescriptorEndianChange((PUCHAR)pTxD, TYPE_TXD);
 #endif
-				
+
 		if ((pTxD->Owner == DESC_OWN_NIC) || (pTxD->CipherOwn == DESC_OWN_NIC))
 		{
 			// Descriptor owned by NIC. No descriptor avaliable
@@ -2961,11 +2941,11 @@
             RTMPDescriptorEndianChange((PUCHAR)pTxD, TYPE_TXD);
             *pDestTxD = TxD;
 #endif
-				
+
 			spin_unlock_irqrestore(&pAdapter->TxRingLock, irqflag);
 			return (NDIS_STATUS_RESOURCES);
 		}
-		
+
 		pAdapter->TxRing[pAdapter->CurEncryptIndex].FrameType = BTYPE_CNTL;
 		pControlHeader = (PCONTROL_HEADER) pDest;
 		memset(pControlHeader, 0, sizeof(CONTROL_HEADER));
@@ -2987,27 +2967,32 @@
 		}
 		pControlHeader->Duration = 2 * (pAdapter->PortCfg.Dsifs)
 			+ RTMPCalcDuration(pAdapter, pAdapter->PortCfg.TxRate, NextFragSize + EncryptionOverhead)
-			+ AckDuration; 
+			+ AckDuration;
 
 		// Write Tx descriptor
 		// Don't kick tx start until all frames are prepared
 		// RTS has to set more fragment bit for fragment burst
-		// RTS did not encrypt		
+		// RTS did not encrypt
 		if (pAdapter->PortCfg.BGProtectionInUsed == 1)
 		{
 			DBGPRINT(RT_DEBUG_TRACE,"Making CTS-to-self Frame\n");
-			pControlHeader->Frame.Subtype = SUBTYPE_CTS;		
+			pControlHeader->Frame.Subtype = SUBTYPE_CTS;
 			memcpy(&pControlHeader->Addr1, pAdapter->CurrentAddress, ETH_ALEN);
 
 #ifdef BIG_ENDIAN
-            RTMPFrameEndianChange(pAdapter, (PUCHAR)pControlHeader, DIR_WRITE, FALSE);
-            RTMPDescriptorEndianChange((PUCHAR)pTxD, TYPE_TXD);
-            *pDestTxD = TxD;
-            pTxD = pDestTxD;
+			// Write Tx descriptor
+			// Don't kick tx start until all frames are prepared
+			// CTS has to set more fragment bit for fragment burst
+			// CTS did not encrypt
+			// CTS-to-self will never receive ACK
+			RTMPFrameEndianChange(pAdapter, (PUCHAR)pControlHeader,
+					      DIR_WRITE, FALSE);
+			RTMPDescriptorEndianChange((PUCHAR)pTxD, TYPE_TXD);
+			*pDestTxD = TxD;
+			pTxD = pDestTxD;
 #endif
 
-
-#ifdef	WIFI_TEST			
+#ifdef	WIFI_TEST
 			RTMPWriteTxDescriptor(pTxD, TRUE, CIPHER_NONE, FALSE, FALSE, FALSE, SHORT_RETRY,
 				FrameGap, pAdapter->PortCfg.RtsRate, 4, 10, Rt802_11PreambleShort,
 				AccessCategory);
@@ -3019,42 +3004,51 @@
 		}
 		else
 		{
-            DBGPRINT(RT_DEBUG_TRACE,"Making RTS Frame\n");
-			pControlHeader->Frame.Subtype = SUBTYPE_RTS;        
-		    if (INFRA_ON(pAdapter))
-			    memcpy(&pControlHeader->Addr1, &pAdapter->PortCfg.Bssid, ETH_ALEN);
-		    else
-			    memcpy(&pControlHeader->Addr1, (PUCHAR) pVirtualAddress, ETH_ALEN);
-		    memcpy(&pControlHeader->Addr2, pAdapter->CurrentAddress, ETH_ALEN);
+			DBGPRINT(RT_DEBUG_TRACE,"Making RTS Frame\n");
+			pControlHeader->Frame.Subtype = SUBTYPE_RTS;
+			if (INFRA_ON(pAdapter))
+				memcpy(&pControlHeader->Addr1,
+				       &pAdapter->PortCfg.Bssid, ETH_ALEN);
+			else
+				memcpy(&pControlHeader->Addr1,
+				       (PUCHAR) pVirtualAddress, ETH_ALEN);
+			memcpy(&pControlHeader->Addr2,
+			       pAdapter->CurrentAddress, ETH_ALEN);
+
+			// Write Tx descriptor
+			// Don't kick tx start until all frames are prepared
+			// RTS has to set more fragment bit for fragment burst
+			// RTS did not encrypt
+			pTxD->RTS = 1;
 #ifdef BIG_ENDIAN
-            RTMPFrameEndianChange(pAdapter, (PUCHAR)pControlHeader, DIR_WRITE, FALSE);
-            RTMPDescriptorEndianChange((PUCHAR)pTxD, TYPE_TXD);
-            *pDestTxD = TxD;
-            pTxD = pDestTxD;
+			RTMPFrameEndianChange(pAdapter, (PUCHAR)pControlHeader,
+					      DIR_WRITE, FALSE);
+			RTMPDescriptorEndianChange((PUCHAR)pTxD, TYPE_TXD);
+			*pDestTxD = TxD;
+			pTxD = pDestTxD;
 #endif
 			RTMPWriteTxDescriptor(pTxD, TRUE, CIPHER_NONE, TRUE, TRUE, FALSE, SHORT_RETRY,
 				FrameGap, pAdapter->PortCfg.RtsRate, 4, sizeof(CONTROL_HEADER),
 				pAdapter->PortCfg.TxPreambleInUsed, AccessCategory);
-			pTxD->RTS = 1;
 		}
-		
+
 		FrameGap = IFS_SIFS;		// Init frame gap for coming data after RTS
 		NumberRequired--;
-		
+
 		// Increase & maintain Tx Ring Index
 		pAdapter->CurEncryptIndex++;
 		if (pAdapter->CurEncryptIndex >= TX_RING_SIZE)
 		{
 			pAdapter->CurEncryptIndex = 0;
 		}
-		pAdapter->RalinkCounters.EncryptCount++;		
+		pAdapter->RalinkCounters.EncryptCount++;
 	}
 
 	// Find the WPA key, either Group or Pairwise Key
 	if (pAdapter->PortCfg.AuthMode >= Ndis802_11AuthModeWPA)
 	{
 		INT 	idx;
-			
+
 		pWpaKey = (PWPA_KEY) NULL;
 		// First lookup the DA, if it's a group address, use GROUP key
 		if (Header_802_11.Controlhead.Addr1.Octet[0] & 0x01)
@@ -3101,17 +3095,17 @@
 	{
 		// Get the Tx Ring descriptor & Dma Buffer address
 #ifndef BIG_ENDIAN
-		pDest = (PUCHAR) pAdapter->TxRing[pAdapter->CurEncryptIndex].va_data_addr;              
+		pDest = (PUCHAR) pAdapter->TxRing[pAdapter->CurEncryptIndex].va_data_addr;
 		pTxD  = (PTXD_STRUC) pAdapter->TxRing[pAdapter->CurEncryptIndex].va_addr;
 #else
-        pDest = (PUCHAR) pAdapter->TxRing[pAdapter->CurEncryptIndex].va_data_addr;              
+        pDest = (PUCHAR) pAdapter->TxRing[pAdapter->CurEncryptIndex].va_data_addr;
         pOriginDest = pDest;
         pDestTxD  = (PTXD_STRUC) pAdapter->TxRing[pAdapter->CurEncryptIndex].va_addr;
         TxD = *pDestTxD;
         pTxD = &TxD;
         RTMPDescriptorEndianChange((PUCHAR)pTxD, TYPE_TXD);
 #endif
-		
+
 		if ((pTxD->Owner == DESC_OWN_NIC) || (pTxD->CipherOwn == DESC_OWN_NIC))
 		{
 			// Descriptor owned by NIC. No descriptor avaliable
@@ -3127,12 +3121,14 @@
 			// This should not happen since caller guaranteed.
 			// Make sure to release Tx ring resource
 			pTxD->Valid = FALSE;
-				
+
 #ifdef BIG_ENDIAN
             RTMPDescriptorEndianChange((PUCHAR)pTxD, TYPE_TXD);
-            *pDestTxD = TxD;
+            //*pDestTxD = TxD;
+	    WriteBackToDescriptor((PUCHAR)pDestRxD, (PUCHAR)pRxD, FALSE,
+		    		  TYPE_RXD);
 #endif
-                
+
 			pAdapter->RalinkCounters.TxRingErrCount++;
 			spin_unlock_irqrestore(&pAdapter->TxRingLock, irqflag);
 			return (NDIS_STATUS_RESOURCES);
@@ -3144,7 +3140,7 @@
 			Header_802_11.Frag = 0;			// Start of fragment burst / Single Frame
 		else
 			Header_802_11.Frag++;			// Rest of fragmented frames.
-		
+
 		// Maximum allowable payload with one ring buffer, bound by fragment size
 		FreeFragSize = pAdapter->PortCfg.FragmentThreshold - LENGTH_CRC;
 
@@ -3155,12 +3151,12 @@
 		{
 		    ULONG NextFragSize;
 			Header_802_11.Controlhead.Frame.MoreFrag = 1;
-			
+
 			if (NumberRequired == 2)
     			NextFragSize = RemainSize - pAdapter->PortCfg.FragmentThreshold + LENGTH_802_11 + LENGTH_802_11 + LENGTH_CRC;
 			else
 			    NextFragSize = pAdapter->PortCfg.FragmentThreshold;
-			
+
 			Header_802_11.Controlhead.Duration = 3 * pAdapter->PortCfg.Dsifs
 				+ 2 * AckDuration
 				+ RTMPCalcDuration(pAdapter, pAdapter->PortCfg.TxRate, NextFragSize + EncryptionOverhead);
@@ -3168,7 +3164,7 @@
 		else // this is the last or only fragment
 		{
 			Header_802_11.Controlhead.Frame.MoreFrag = 0;
-			
+
 			if (Header_802_11.Controlhead.Addr1.Octet[0] & 0x01) // multicast/broadcast
 				Header_802_11.Controlhead.Duration = 0;
 			else
@@ -3183,7 +3179,7 @@
 			Header_802_11.Controlhead.Frame.Wep = 1;
 		else if ((pAdapter->PortCfg.WepStatus == Ndis802_11Encryption3Enabled) && (pWpaKey != NULL))
 			Header_802_11.Controlhead.Frame.Wep = 1;
-		
+
 		//
 		// Copy 802.11 header to Tx ring buffer
 		//
@@ -3191,12 +3187,15 @@
 		pDest        += sizeof(Header_802_11);
 		FreeFragSize -= sizeof(Header_802_11);
 
-		DBGPRINT(RT_DEBUG_TRACE,"pWpaKey = %s\n", pWpaKey == NULL ? "NULL" : "not NULL");
+		DBGPRINT(RT_DEBUG_INFO, "pWpaKey = %s\n",
+			 pWpaKey == NULL ? "NULL" : "not NULL");
 
 		if ((pAdapter->PortCfg.WepStatus == Ndis802_11Encryption1Enabled) && (EAPOLFrame == FALSE) &&
 			(pAdapter->PortCfg.SharedKey[pAdapter->PortCfg.DefaultKeyId].KeyLen != 0))
 		{
-			DBGPRINT(RT_DEBUG_TRACE,"Ndis802_11Encryption1Enabled::DefaultKeyId = %d\n", pAdapter->PortCfg.DefaultKeyId);
+			DBGPRINT(RT_DEBUG_INFO,
+				 "Ndis802_11Encryption1Enabled::DefaultKeyId = %d\n",
+				 pAdapter->PortCfg.DefaultKeyId);
                 // Prepare IV, IV offset, Key for Hardware encryption
                 RTMPInitWepEngine(
                 pAdapter,
@@ -3216,12 +3215,14 @@
                 memcpy(
 					pTxD->Key,
 					pAdapter->PortCfg.SharedKey[pAdapter->PortCfg.DefaultKeyId].Key,
-					pAdapter->PortCfg.SharedKey[pAdapter->PortCfg.DefaultKeyId].KeyLen);			
+					pAdapter->PortCfg.SharedKey[pAdapter->PortCfg.DefaultKeyId].KeyLen);
 		}
 		else if ((pAdapter->PortCfg.WepStatus == Ndis802_11Encryption2Enabled) && (pWpaKey != NULL))
 		{
 			INT     i = 0;
-			DBGPRINT(RT_DEBUG_TRACE,"Ndis802_11Encryption2Enabled::DefaultKeyId = %d\n", pAdapter->PortCfg.DefaultKeyId);
+			DBGPRINT(RT_DEBUG_INFO,
+				 "Ndis802_11Encryption2Enabled::DefaultKeyId = %d\n",
+				 pAdapter->PortCfg.DefaultKeyId);
             // Prepare 8 bytes TKIP encapsulation for MPDU
             {
                 TKIP_IV	tkipIv;
@@ -3232,31 +3233,20 @@
                 tkipIv.IV16.field.rc2 = *pWpaKey->TxTsc;
                 tkipIv.IV16.field.ExtIV = 1;// 0: non-extended IV, 1: extended IV
                 tkipIv.IV16.field.KeyID = pAdapter->PortCfg.DefaultKeyId;
-                tkipIv.IV32 = *(PULONG)(pWpaKey->TxTsc + 2);
-#if 0	//jett, 2004-1222 ------------------
-#if BIG_ENDIAN == TRUE
-                pTxD->Iv = (tkipIv.IV16.field.rc0 << 24) | (tkipIv.IV16.field.rc1 << 16) | (tkipIv.IV16.field.rc2 << 8) | (tkipIv.IV16.field.CONTROL.Byte);
-#endif
-
-#ifdef RTMP_EMBEDDED
-                pTxD->Iv = (tkipIv.IV16.field.CONTROL.Byte << 24) | (tkipIv.IV16.field.rc2 << 16) | (tkipIv.IV16.field.rc1 << 8) | (tkipIv.IV16.field.rc0);
-#else
-                pTxD->Iv = tkipIv.IV16.word;
-#endif
-#else	//----------------------------------
+                //tkipIv.IV32 = *(PULONG)(pWpaKey->TxTsc + 2);
+		memcpy(&tkipIv.IV32, &pWpaKey->TxTsc[2], 4);
 #ifdef BIG_ENDIAN
-               pTxD->Iv = SWAP32(tkipIv.IV16.word);
+		pTxD->Iv = SWAP32(tkipIv.IV16.word);
 #else
-                pTxD->Iv = tkipIv.IV16.word;
+		pTxD->Iv = tkipIv.IV16.word;
 #endif
-#endif	//----------------------------------
 
                 *((PUCHAR) &pTxD->Eiv) = *((PUCHAR) &tkipIv.IV32 + 3);
                 *((PUCHAR) &pTxD->Eiv + 1) = *((PUCHAR) &tkipIv.IV32 + 2);
                 *((PUCHAR) &pTxD->Eiv + 2) = *((PUCHAR) &tkipIv.IV32 + 1);
                 *((PUCHAR) &pTxD->Eiv + 3) = *((PUCHAR) &tkipIv.IV32);
             }
-            
+
             // Increase TxTsc value for next transmission
             while (++pWpaKey->TxTsc[i] == 0x0)
             {
@@ -3264,13 +3254,13 @@
                 if (i == 6)
                     break;
             }
-            
+
             // Set IV offset
             pTxD->IvOffset = LENGTH_802_11;
 
             // Copy TKey
             memcpy(pTxD->Key, pWpaKey->Key, 16);
-            
+
             // Set Cipher suite
             CipherAlg = CIPHER_TKIP;
 		}
@@ -3279,15 +3269,20 @@
 			INT		i;
 			PUCHAR	pTmp;
 
+			DBGPRINT(RT_DEBUG_INFO,
+				 "Ndis802_11Encryption3Enabled::DefaultKeyId = %d\n",
+				 pAdapter->PortCfg.DefaultKeyId);
+
 			i = 0;
 			pTmp = (PUCHAR) &Iv16;
 			*pTmp       = pWpaKey->TxTsc[0];
 			*(pTmp + 1) = pWpaKey->TxTsc[1];
 			*(pTmp + 2) = 0;
 			*(pTmp + 3) = (pAdapter->PortCfg.DefaultKeyId << 6) | 0x20;
-			
-			Iv32 = *(PULONG)(&pWpaKey->TxTsc[2]);
-			
+
+			//Iv32 = *(PULONG)(&pWpaKey->TxTsc[2]);
+			memcpy(&Iv32, &pWpaKey->TxTsc[2], 4);
+
 			// Increase TxTsc value for next transmission
 			while (++pWpaKey->TxTsc[i] == 0x0)
 			{
@@ -3300,7 +3295,7 @@
 				// TODO: TSC has done one full cycle, do re-keying stuff follow specs
 				// Should send a special event microsoft defined to request re-key
 			}
-			
+
 			memcpy(&pTxD->Iv, &Iv16, 4);            // Copy IV
 			memcpy(&pTxD->Eiv, &Iv32, 4);           // Copy EIV
 			pTxD->IvOffset = LENGTH_802_11;                 // Set IV offset
@@ -3308,8 +3303,11 @@
 			CipherAlg = CIPHER_AES;                         // Set Cipher suite
 		}
 		else
+		{
+			DBGPRINT(RT_DEBUG_TRACE,"Ndis802_11EncryptionDisabled\n");
 			CipherAlg = CIPHER_NONE;
-		
+		}
+
 		//
 		// Only the first fragment required LLC-SNAP header !!!
 		//
@@ -3332,7 +3330,7 @@
 			pSrc = (PUCHAR) pVirtualAddress;
 			memcpy(pDest, pSrc + 12, 2);
 			pDest += 2;
-			
+
 			// Exclude 802.3 header size, we will recalculate the size at
 			// the end of fragment preparation.
 	    	NdisBufferLength -= LENGTH_802_3;
@@ -3346,11 +3344,11 @@
 				// Calculate MSDU MIC Value
 				RTMPCalculateMICValue(pAdapter, skb, pEncap, 0, pWpaKey);
 			}
-			
+
    			pSrc = (PUCHAR) pVirtualAddress + LENGTH_802_3;
     		NdisBufferLength -= LENGTH_802_3;
 		}
-		
+
 		// Start copying payload
 		BytesCopied = 0;
 		do
@@ -3375,23 +3373,25 @@
 		    	pDest        += NdisBufferLength;
 		    	FreeFragSize -= NdisBufferLength;
 			}
-		
+
 			// No more buffer descriptor
 			// Add MIC value if needed
-			if ((pAdapter->PortCfg.WepStatus == Ndis802_11Encryption2Enabled) && 
+			if ((pAdapter->PortCfg.WepStatus == Ndis802_11Encryption2Enabled) &&
 				(MICFrag == FALSE) &&
 				(pWpaKey != NULL))
 			{
-				INT i;
-
 			    NdisBufferLength = 8;		// Set length to MIC length
-				DBGPRINT(RT_DEBUG_INFO, "Calculated TX MIC value =");  
-				for (i = 0; i < 8; i++)
-				{
-					DBGPRINT(RT_DEBUG_INFO, "%02x:", pAdapter->PrivateInfo.Tx.MIC[i]);  
-				}
-				DBGPRINT(RT_DEBUG_INFO, "\n"); 
-							
+		            DBGPRINT(RT_DEBUG_INFO,
+				"--- TX MIC=%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x\n",
+				pAdapter->PrivateInfo.Tx.MIC[0],
+				pAdapter->PrivateInfo.Tx.MIC[1],
+				pAdapter->PrivateInfo.Tx.MIC[2],
+				pAdapter->PrivateInfo.Tx.MIC[3],
+				pAdapter->PrivateInfo.Tx.MIC[4],
+				pAdapter->PrivateInfo.Tx.MIC[5],
+				pAdapter->PrivateInfo.Tx.MIC[6],
+				pAdapter->PrivateInfo.Tx.MIC[7]);
+
     			if (FreeFragSize >= NdisBufferLength)
 				{
 					memcpy(pDest, pAdapter->PrivateInfo.Tx.MIC, NdisBufferLength);
@@ -3413,7 +3413,7 @@
 				}
 			}
 		}	while (FALSE);		// End of copying payload
-				
+
 		// Real packet size, No 802.1H header for fragments except the first one.
 		if ((StartOfFrame == TRUE) && (Encapped == TRUE))
 		{
@@ -3425,7 +3425,7 @@
 		}
 
 		RemainSize = RemainSize - BytesCopied;
-			
+
 		if ((pAdapter->PortCfg.WepStatus == Ndis802_11Encryption1Enabled) && (Header_802_11.Controlhead.Frame.Wep == 1))
 		{
 			// IV + ICV which ASIC added after encryption done
@@ -3441,7 +3441,7 @@
 			// IV + EIV + HW MIC
 			TxSize += 16;
 		}
-				
+
 		// Prepare Tx descriptors before kicking tx.
 		// The BBP register index in Tx descriptor has to be configured too.
 #ifdef BIG_ENDIAN
@@ -3453,12 +3453,12 @@
 		if (Header_802_11.Controlhead.Addr1.Octet[0] & 0x01)
 		{
 			// Multicast, retry bit is off
-			RTMPWriteTxDescriptor(pTxD, TRUE, CipherAlg, FALSE, FALSE, FALSE, RetryMode, FrameGap, 
+			RTMPWriteTxDescriptor(pTxD, TRUE, CipherAlg, FALSE, FALSE, FALSE, RetryMode, FrameGap,
                 pAdapter->PortCfg.TxRate, 4, TxSize, pAdapter->PortCfg.TxPreambleInUsed, AccessCategory);
 		}
 		else
 		{
-			RTMPWriteTxDescriptor(pTxD, TRUE, CipherAlg, TRUE, FALSE, FALSE, RetryMode, FrameGap, 
+			RTMPWriteTxDescriptor(pTxD, TRUE, CipherAlg, TRUE, FALSE, FALSE, RetryMode, FrameGap,
 			    pAdapter->PortCfg.TxRate, 4, TxSize, pAdapter->PortCfg.TxPreambleInUsed, AccessCategory);
 		}
 
@@ -3467,23 +3467,23 @@
 		StartOfFrame = FALSE;
 		FrameGap     = IFS_SIFS;
 		NumberRequired--;
-		
+
 		// Increase & maintain Tx Ring Index
 		pAdapter->CurEncryptIndex++;
 		if (pAdapter->CurEncryptIndex >= TX_RING_SIZE)
 		{
 			pAdapter->CurEncryptIndex = 0;
 		}
-		
+
 		pAdapter->RalinkCounters.EncryptCount++;
-		
+
 	}	while (NumberRequired > 0);
 
 skip_packet_handling:
-	
+
 	// Kick Encrypt Control Register at the end of all ring buffer preparation
 	RTMP_IO_WRITE32(pAdapter, SECCSR1, 0x1);
-	
+
     // Acknowledge protocol send complete of pending packet.
 	dev_kfree_skb_irq(skb);
 
@@ -3497,19 +3497,19 @@
 	========================================================================
 
 	Routine	Description:
-		Calculates the duration which is required to transmit out frames 
+		Calculates the duration which is required to transmit out frames
 	with given size and specified rate.
-		
+
 	Arguments:
 		pAdapter		Pointer	to our adapter
 		Rate			Transmit rate
 		Size			Frame size in units of byte
-		
+
 	Return Value:
 		Duration number in units of usec
 
 	Note:
-	
+
 	========================================================================
 */
 USHORT	RTMPCalcDuration(
@@ -3525,7 +3525,7 @@
     		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 ++;
@@ -3537,18 +3537,18 @@
 		if ((11 + Size * 4) % RateIdTo500Kbps[Rate])
 			Duration += 4;
 	}
-	
+
 	return (USHORT)Duration;
-	
+
 }
 
 /*
 	========================================================================
-	
+
 	Routine	Description:
-		Calculates the duration which is required to transmit out frames 
+		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
@@ -3560,10 +3560,10 @@
 		Length		Frame length
 		TxPreamble  Short or Long preamble when using CCK rates
 		AccessCategory - 0-3, according to 802.11e/d4.4 June/2003
-		
+
 	Return Value:
 		None
-		
+
 	========================================================================
 */
 VOID	RTMPWriteTxDescriptor(
@@ -3624,7 +3624,7 @@
         	pTxD->Aifs        = 2;
         	break;
 	}
-		
+
 	if (Rate < RATE_FIRST_OFDM_RATE)
 		pTxD->Ofdm = 0;
 	else
@@ -3671,7 +3671,7 @@
 		pTxD->PlcpLengthHigh = Length / 64;  // high 6-bit of total byte count
 		pTxD->PlcpLengthLow = Length % 64;   // low 6-bit of total byte count
 	}
-	
+
 	if (DoEncrypt == TRUE)		// Do encryption only
 	{
 		pTxD->Owner     = DESC_OWN_HOST;
@@ -3687,8 +3687,10 @@
 		pTxD->Owner     = DESC_OWN_NIC;
 	}
 #ifdef BIG_ENDIAN
-    RTMPDescriptorEndianChange((PUCHAR)pTxD, TYPE_TXD);
-    *pSourceTxD = *pTxD;
+	RTMPDescriptorEndianChange((PUCHAR)pTxD, TYPE_TXD);
+	//*pSourceTxD = *pTxD;
+	WriteBackToDescriptor((PUCHAR) pSourceTxD, (PUCHAR) pTxD, FALSE,
+			      TYPE_TXD);
 #endif
 }
 
@@ -3697,17 +3699,17 @@
 
 	Routine	Description:
 		Search tuple cache for receive duplicate frame from unicast frames.
-		
+
 	Arguments:
 		pAdapter		Pointer	to our adapter
 		pHeader			802.11 header of receiving frame
-		
+
 	Return Value:
 		TRUE			found matched tuple cache
 		FALSE			no matched found
 
 	Note:
-	
+
 	========================================================================
 */
 BOOLEAN	RTMPSearchTupleCache(
@@ -3720,12 +3722,12 @@
 	{
 		if (pAdapter->TupleCache[Index].Valid == FALSE)
 		    continue;
-		
+
 		if (RTMPEqualMemory(&pAdapter->TupleCache[Index].MAC, &pHeader->Controlhead.Addr2, 6) &&
 			(pAdapter->TupleCache[Index].Sequence == pHeader->Sequence) &&
 			(pAdapter->TupleCache[Index].Frag == pHeader->Frag))
 		{
-//			DBGPRINT(RT_DEBUG_TRACE,("DUPCHECK - duplicate frame hit entry %d\n", Index)); 
+//			DBGPRINT(RT_DEBUG_TRACE,("DUPCHECK - duplicate frame hit entry %d\n", Index));
 			return (TRUE);
 		}
 	}
@@ -3737,16 +3739,16 @@
 
 	Routine	Description:
 		Update tuple cache for new received unicast frames.
-		
+
 	Arguments:
 		pAdapter		Pointer	to our adapter
 		pHeader			802.11 header of receiving frame
-		
+
 	Return Value:
 		None
-		
+
 	Note:
-	
+
 	========================================================================
 */
 VOID	RTMPUpdateTupleCache(
@@ -3765,7 +3767,7 @@
 			pAdapter->TupleCache[Index].Frag     = pHeader->Frag;
 			pAdapter->TupleCache[Index].Valid    = TRUE;
 			pAdapter->TupleCacheLastUpdateIndex  = Index;
-			DBGPRINT(RT_DEBUG_INFO,"DUPCHECK - Add Entry %d, MAC=%02x:%02x:%02x:%02x:%02x:%02x\n", 
+			DBGPRINT(RT_DEBUG_INFO,"DUPCHECK - Add Entry %d, MAC=%02x:%02x:%02x:%02x:%02x:%02x\n",
 			    Index, pAdapter->TupleCache[Index].MAC.Octet[0], pAdapter->TupleCache[Index].MAC.Octet[1],
 			    pAdapter->TupleCache[Index].MAC.Octet[2], pAdapter->TupleCache[Index].MAC.Octet[3],
 			    pAdapter->TupleCache[Index].MAC.Octet[4], pAdapter->TupleCache[Index].MAC.Octet[5]);
@@ -3794,7 +3796,7 @@
 		pAdapter->TupleCache[Index].Sequence = pHeader->Sequence;
 		pAdapter->TupleCache[Index].Frag     = pHeader->Frag;
 		pAdapter->TupleCache[Index].Valid    = TRUE;
-		DBGPRINT(RT_DEBUG_INFO,"DUPCHECK - replace Entry %d, MAC=%02x:%02x:%02x:%02x:%02x:%02x\n", 
+		DBGPRINT(RT_DEBUG_INFO,"DUPCHECK - replace Entry %d, MAC=%02x:%02x:%02x:%02x:%02x:%02x\n",
 		    Index, pAdapter->TupleCache[Index].MAC.Octet[0], pAdapter->TupleCache[Index].MAC.Octet[1],
 		    pAdapter->TupleCache[Index].MAC.Octet[2], pAdapter->TupleCache[Index].MAC.Octet[3],
 		    pAdapter->TupleCache[Index].MAC.Octet[4], pAdapter->TupleCache[Index].MAC.Octet[5]);
@@ -3806,15 +3808,15 @@
 
 	Routine	Description:
 		Suspend MSDU transmission
-		
+
 	Arguments:
 		pAdapter		Pointer	to our adapter
-		
+
 	Return Value:
 		None
-		
+
 	Note:
-	
+
 	========================================================================
 */
 VOID    RTMPSuspendMsduTransmission(
@@ -3829,15 +3831,15 @@
 
 	Routine	Description:
 		Resume MSDU transmission
-		
+
 	Arguments:
 		pAdapter		Pointer	to our adapter
-		
+
 	Return Value:
 		None
-		
+
 	Note:
-	
+
 	========================================================================
 */
 VOID    RTMPResumeMsduTransmission(
@@ -3863,40 +3865,40 @@
 	Routine	Description:
 		Apply packet filter policy, return NDIS_STATUS_FAILURE if this frame
 		should be dropped.
-		
+
 	Arguments:
 		pAdapter		Pointer	to our adapter
 		pRxD			Pointer	to the Rx descriptor
 		pHeader			Pointer to the 802.11 frame header
-		
+
 	Return Value:
 		NDIS_STATUS_SUCCESS		Accept frame
 		NDIS_STATUS_FAILURE		Drop Frame
-		
+
 	Note:
 		Maganement frame should bypass this filtering rule.
-	
+
 	========================================================================
 */
 NDIS_STATUS	RTMPApplyPacketFilter(
-	IN	PRTMP_ADAPTER	pAdapter, 
-	IN	PRXD_STRUC		pRxD, 
+	IN	PRTMP_ADAPTER	pAdapter,
+	IN	PRXD_STRUC		pRxD,
 	IN	PHEADER_802_11	pHeader)
 {
 	UCHAR	i;
-	
+
 	// 0. Management frame should bypass all these filtering rules.
 	if (pHeader->Controlhead.Frame.Type == BTYPE_MGMT)
 	{
 		return(NDIS_STATUS_SUCCESS);
 	}
-	
+
 	// 0.1	Drop all Rx frames if MIC countermeasures kicks in
 	if (pAdapter->PortCfg.MicErrCnt >= 2)
 	{
 		return(NDIS_STATUS_FAILURE);
 	}
-	
+
 	// 1. Drop unicast to me packet if NDIS_PACKET_TYPE_DIRECTED is FALSE
 	if (pRxD->U2M)
 	{
@@ -3905,7 +3907,7 @@
 			return(NDIS_STATUS_FAILURE);
 		}
 	}
-		
+
 	// 2. Drop broadcast packet if NDIS_PACKET_TYPE_BROADCAST is FALSE
 	else if (pRxD->Bcast)
 	{
@@ -3914,7 +3916,7 @@
 			return(NDIS_STATUS_FAILURE);
 		}
 	}
-			
+
 	// 3. Drop multicast packet if NDIS_PACKET_TYPE_ALL_MULTICAST is false
 	//    and NDIS_PACKET_TYPE_MULTICAST is false.
 	//    If NDIS_PACKET_TYPE_MULTICAST is true, but NDIS_PACKET_TYPE_ALL_MULTICAST is false.
@@ -3964,8 +3966,8 @@
 	{
 		return(NDIS_STATUS_FAILURE);
 	}
-	
-	return(NDIS_STATUS_SUCCESS);	
+
+	return(NDIS_STATUS_SUCCESS);
 }
 
 /*
@@ -3973,15 +3975,15 @@
 
 	Routine	Description:
 		Check and fine the packet waiting in SW queue with highest priority
-		
+
 	Arguments:
 		pAdapter	Pointer	to our adapter
-		
+
 	Return Value:
 		pQueue		Pointer to Waiting Queue
 
 	Note:
-	
+
 	========================================================================
 */
 struct sk_buff_head* RTMPCheckTxSwQueue(
@@ -4019,20 +4021,20 @@
 
 	Routine	Description:
 		Process MIC error indication and record MIC error timer.
-		
+
 	Arguments:
 		pAdapter		Pointer	to our adapter
 		pWpaKey			Pointer	to the WPA key structure
-		
+
 	Return Value:
 		None
-		
+
 	Note:
-	
+
 	========================================================================
 */
 VOID	RTMPReportMicError(
-	IN	PRTMP_ADAPTER	pAdapter, 
+	IN	PRTMP_ADAPTER	pAdapter,
 	IN	PWPA_KEY		pWpaKey)
 {
 	ULONG	Now;
@@ -4044,7 +4046,7 @@
 
 	// 0. Set Status to indicate auth error
 	Report.Status.StatusType = Ndis802_11StatusType_Authentication;
-	
+
 	// 1. Check for Group or Pairwise MIC error
 	if (pWpaKey->Type == PAIRWISE_KEY)
 		Report.Request.Flags = NDIS_802_11_AUTH_REQUEST_PAIRWISE_ERROR;
@@ -4069,13 +4071,13 @@
 		if ((pAdapter->PortCfg.LastMicErrorTime + (60 * HZ)) < Now)
 		{
 			// Update Last MIC error time, this did not violate two MIC errors within 60 seconds
-			pAdapter->PortCfg.LastMicErrorTime = Now;			
+			pAdapter->PortCfg.LastMicErrorTime = Now;
 		}
 		else
 		{
-			pAdapter->PortCfg.LastMicErrorTime = Now;			
+			pAdapter->PortCfg.LastMicErrorTime = Now;
 			// Violate MIC error counts, MIC countermeasures kicks in
-			pAdapter->PortCfg.MicErrCnt++;			
+			pAdapter->PortCfg.MicErrCnt++;
 			// We shall block all reception
 			// We shall clean all Tx ring and disassoicate from AP after next EAPOL frame
 			RTMPRingCleanUp(pAdapter, TX_RING);
diff -Nur rt2500-1.1.0-b4/Module/rtmp_def.h rt2500-cvs-2007061011/Module/rtmp_def.h
--- rt2500-1.1.0-b4/Module/rtmp_def.h	2006-06-17 22:12:58.000000000 +0200
+++ rt2500-cvs-2007061011/Module/rtmp_def.h	2007-03-21 05:25:35.000000000 +0100
@@ -1,36 +1,36 @@
-/*************************************************************************** 
- * RT2400/RT2500 SourceForge Project - http://rt2x00.serialmonkey.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.                          * 
- *                                                                         * 
- *   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.             * 
- *                                                                         * 
- *   Licensed under the GNU GPL                                            * 
- *   Original code supplied under license from RaLink Inc, 2004.           * 
- ***************************************************************************/ 
+/***************************************************************************
+ * RT2400/RT2500 SourceForge Project - http://rt2x00.serialmonkey.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.                          *
+ *                                                                         *
+ *   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.             *
+ *                                                                         *
+ *   Licensed under the GNU GPL                                            *
+ *   Original code supplied under license from RaLink Inc, 2004.           *
+ ***************************************************************************/
 
- /*************************************************************************** 
+ /***************************************************************************
  *      Module Name: rtmp_def.h
- *              
+ *
  *      Abstract: Miniport related definition header
- *              
- *      Revision History: 
- *      Who             When            What 
- *      --------        -----------     ----------------------------- 
- *      PaulL           1st  Aug 02     Initial code     
- *      MarkW           8th  Dec 04     Baseline code  
- ***************************************************************************/ 
+ *
+ *      Revision History:
+ *      Who             When            What
+ *      --------        -----------     -----------------------------
+ *      PaulL           1st  Aug 02     Initial code
+ *      MarkW           8th  Dec 04     Baseline code
+ ***************************************************************************/
 
 #ifndef __RTMP_DEF_H__
 #define __RTMP_DEF_H__
@@ -38,11 +38,12 @@
 //
 //  Debug information verbosity: lower values indicate higher urgency
 //
-#define RT_DEBUG_ERROR      KERN_ERR
-#define RT_DEBUG_WARN       KERN_WARNING
-#define RT_DEBUG_TRACE      KERN_NOTICE
-#define RT_DEBUG_INFO       KERN_INFO
-#define RT_DEBUG_LOUD       KERN_DEBUG
+#define RT_DEBUG_OFF        0
+#define RT_DEBUG_ERROR      1
+#define RT_DEBUG_WARN       2
+#define RT_DEBUG_TRACE      4
+#define RT_DEBUG_INFO       8
+#define RT_DEBUG_LOUD       16
 
 //
 // update the driver version number every time you release a new driver
@@ -190,8 +191,8 @@
 #define HASH_TABLE_SIZE                   256
 #define MAX_LEN_OF_MLME_BUFFER            1024
 #define MAX_FRAME_LEN                     2338
-#define MAX_VIE_LEN                       128   // New for WPA cipher suite variable IE sizes.
-#define MAX_MLME_HANDLER_MEMORY           20    //each them cantains  MAX_LEN_OF_MLME_BUFFER size 
+#define MAX_VIE_LEN                       257	// sum of WPAx IEs
+#define MAX_MLME_HANDLER_MEMORY           20    //each them cantains  MAX_LEN_OF_MLME_BUFFER size
 #define MAX_INI_BUFFER_SIZE               1024
 
 #define MAX_TX_POWER_LEVEL                100   /* mW */
@@ -265,7 +266,7 @@
 #define MLME_SUCCESS                      0
 #define MLME_UNSPECIFY_FAIL               1
 #define MLME_CANNOT_SUPPORT_CAP           10
-#define MLME_REASSOC_DENY_ASSOC_EXIST     11 
+#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
@@ -317,7 +318,7 @@
 
 #define MT2_MLME_ASSOC_REQ          0
 #define MT2_MLME_REASSOC_REQ        1
-#define MT2_MLME_DISASSOC_REQ       2  
+#define MT2_MLME_DISASSOC_REQ       2
 #define MT2_PEER_DISASSOC_REQ       3
 #define MT2_PEER_ASSOC_REQ          4
 #define MT2_PEER_ASSOC_RSP          5
diff -Nur rt2500-1.1.0-b4/Module/rtmp_info.c rt2500-cvs-2007061011/Module/rtmp_info.c
--- rt2500-1.1.0-b4/Module/rtmp_info.c	2006-06-17 22:12:58.000000000 +0200
+++ rt2500-cvs-2007061011/Module/rtmp_info.c	2007-05-31 22:45:43.000000000 +0200
@@ -1,49 +1,50 @@
-/*************************************************************************** 
- * RT2400/RT2500 SourceForge Project - http://rt2x00.serialmonkey.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.                          * 
- *                                                                         * 
- *   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.             * 
- *                                                                         * 
- *   Licensed under the GNU GPL                                            * 
- *   Original code supplied under license from RaLink Inc, 2004.           * 
- ***************************************************************************/ 
+/***************************************************************************
+ * RT2400/RT2500 SourceForge Project - http://rt2x00.serialmonkey.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.                          *
+ *                                                                         *
+ *   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.             *
+ *                                                                         *
+ *   Licensed under the GNU GPL                                            *
+ *   Original code supplied under license from RaLink Inc, 2004.           *
+ ***************************************************************************/
 
- /*************************************************************************** 
+ /***************************************************************************
  *      Module Name: rtmp_info.c
- *              
- *      Abstract: IOCTL related subroutines         
- *              
- *      Revision History: 
- *      Who             When            What 
- *      --------        -----------     ----------------------------- 
- *      RoryC           3rd  Jan 03     Initial code     
- *      MarkW           8th  Dec 04     Baseline code  
+ *
+ *      Abstract: IOCTL related subroutines
+ *
+ *      Revision History:
+ *      Who             When            What
+ *      --------        -----------     -----------------------------
+ *      RoryC           3rd  Jan 03     Initial code
+ *      MarkW           8th  Dec 04     Baseline code
  *      RobinC          10th Dec 04     RFMON Support
- *      MarkW           10th Dec 04     Rolled in Ralink 1.4.5.0 
+ *      MarkW           10th Dec 04     Rolled in Ralink 1.4.5.0
  *      MarkW           15th Dec 04     Removed debug iwpriv
  *      RobinC          16th Dec 04     Fix for range values
  *		RobinC			16th Dec 04     support ifpreup scripts
  *      RobinC          17th Dec 04     Link Quality reporting
  *      MarkW           17th Dec 04     iwconfig frequency fix
- *      MarkW           17th Dec 04     Monitor mode through iwconfig 
+ *      MarkW           17th Dec 04     Monitor mode through iwconfig
  *      MarkW           22nd Dec 04     RSSI reporting for iwlist scanning
  *      MarkW           31st Jan 05     if pre-up fix for RaConfig
  *      LuisCorreia     23rd Feb 05     fix unknown IOCTL's
  *      MarkW           9th  Mar 05     Quality reporting in scan for current
  * 		MarkW			9th  Jun 05		Fix channel change for ADHOC mode
- ***************************************************************************/ 
+ * 		RomainB         31st Dec 06     RFMON getter
+ ***************************************************************************/
 
 #include    "rt_config.h"
 #include <net/iw_handler.h>
@@ -154,7 +155,7 @@
             }
 
 struct iw_priv_args privtab[] = {
-{ RTPRIV_IOCTL_SET, 
+{ RTPRIV_IOCTL_SET,
   IW_PRIV_TYPE_CHAR | 1024, 0,
   "set"},
 { RTPRIV_IOCTL_BBP,
@@ -166,9 +167,12 @@
 { RTPRIV_IOCTL_E2P,
   IW_PRIV_TYPE_CHAR | 1024, IW_PRIV_TYPE_CHAR | 1024,
   "e2p"},
-{ RTPRIV_IOCTL_RFMONTX,
-  IW_PRIV_TYPE_INT | 2, IW_PRIV_TYPE_CHAR | sizeof (char),
-  "rfmontx"}
+{ RTPRIV_IOCTL_SET_RFMONTX,
+  IW_PRIV_TYPE_INT | 2, 0,
+  "rfmontx"},
+{ RTPRIV_IOCTL_GET_RFMONTX,
+  0, IW_PRIV_TYPE_INT | IW_PRIV_SIZE_FIXED | 1,
+  "get_rfmontx"}
 };
 
 static struct {
@@ -198,6 +202,9 @@
     {"Key4", Set_Key4_Proc},
     {"WPAPSK", Set_WPAPSK_Proc},
     {"WPANONE", Set_WPANONE_Proc},
+#ifdef RT2500_DBG
+    {"Debug", Set_Debug_Proc},
+#endif
 
 #ifdef RALINK_ATE
 	{"ATE",       Set_ATE_Proc			},	// set ATE Mode to: STOP, TXCONT, TXCARR, TXFRAME, RXFRAME
@@ -233,7 +240,13 @@
 	u16 val;
 	int i,chan;
 
-	DBGPRINT(RT_DEBUG_TRACE,"0. rtusb_ioctl_giwrange\n");		
+	//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;
+	}
+
+	DBGPRINT(RT_DEBUG_TRACE,"0. rt_ioctl_giwrange\n");
 	data->length = sizeof(struct iw_range);
 	memset(range, 0, sizeof(struct iw_range));
 
@@ -266,7 +279,7 @@
 		{
 			range->freq[val].i = chan;
 			MAP_CHANNEL_ID_TO_KHZ(range->freq[val].i, range->freq[val].m);
-			range->freq[val].m*=100;		
+			range->freq[val].m*=100;
 			range->freq[val].e = 1;
 			val++;
 		}
@@ -335,8 +348,8 @@
 	char *this_char;
 	char *value;
 	int  Status;
-  
-				while ((this_char = strsep(&extra, ",")) != NULL) 
+
+				while ((this_char = strsep(&extra, ",")) != NULL)
 				{
 					if (!*this_char)
 						 continue;
@@ -349,8 +362,8 @@
 
 					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 (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;
@@ -382,6 +395,13 @@
 	PRTMP_ADAPTER pAdapter = (PRTMP_ADAPTER) dev->priv;
 	int Status = NDIS_STATUS_SUCCESS;
 	BOOLEAN 		StateMachineTouched = FALSE;
+
+	//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 (RTMP_TEST_FLAG(pAdapter, fRTMP_ADAPTER_BSS_SCAN_IN_PROGRESS))
 		return 0;
 	if(!RTMP_TEST_FLAG(pAdapter, fRTMP_ADAPTER_MLME_INITIALIZED))
@@ -390,7 +410,7 @@
 		Now = jiffies;
 
             if ((pAdapter->MediaState == NdisMediaStateConnected) &&
-				((pAdapter->PortCfg.AuthMode == Ndis802_11AuthModeWPA) || 
+				((pAdapter->PortCfg.AuthMode == Ndis802_11AuthModeWPA) ||
 				(pAdapter->PortCfg.AuthMode == Ndis802_11AuthModeWPAPSK)) &&
                 (pAdapter->PortCfg.PortSecured == WPA_802_1X_PORT_NOT_SECURED)
                 )
@@ -413,15 +433,17 @@
             pAdapter->PortCfg.IgnoredScanNumber = 0;
             pAdapter->PortCfg.LastScanTime = Now;
 
-            MlmeEnqueue(&pAdapter->Mlme.Queue, 
-                    MLME_CNTL_STATE_MACHINE, 
-                    OID_802_11_BSSID_LIST_SCAN, 
-                    0, 
+            MlmeEnqueue(&pAdapter->Mlme.Queue,
+                    MLME_CNTL_STATE_MACHINE,
+                    OID_802_11_BSSID_LIST_SCAN,
+                    0,
                     NULL);
 
 		Status = NDIS_STATUS_SUCCESS;
 		StateMachineTouched = TRUE;
 	}while(0);
+    if(StateMachineTouched) // Upper layer sent a MLME-related operations
+        MlmeHandler(pAdapter);
 	return 0;
 }
 int
@@ -437,7 +459,19 @@
 	char *current_val;
 	struct iw_event iwe;
 
-	for (i = 0; i < pAdapter->PortCfg.BssTab.BssNr; 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");
+		return -ENETDOWN;
+	}
+	if (RTMP_TEST_FLAG(pAdapter, fRTMP_ADAPTER_BSS_SCAN_IN_PROGRESS)){
+		/*
+		 * Still scanning, indicate the caller should try again.
+		 */
+		DBGPRINT(RT_DEBUG_TRACE, "%s: still scanning\n", __FUNCTION__);
+		return -EAGAIN;
+	}
+	for (i = 0; i < pAdapter->PortCfg.BssTab.BssNr; i++)
 	{
 		if (current_ev >= end_buf)
 			break;
@@ -511,25 +545,25 @@
                     iwe.u.qual.qual = pAdapter->Mlme.ChannelQuality;
                 else
                     iwe.u.qual.qual = 0;
-                iwe.u.qual.level = pAdapter->PortCfg.BssTab.BssEntry[i].Rssi - RSSI_TO_DBM_OFFSET;   // signal level (dBm) 
+                iwe.u.qual.level = pAdapter->PortCfg.BssTab.BssEntry[i].Rssi - RSSI_TO_DBM_OFFSET;   // signal level (dBm)
 		iwe.u.qual.noise = pAdapter->PortCfg.BssTab.BssEntry[i].Noise;
-                //iwe.u.qual.noise = (pAdapter->PortCfg.LastR17Value > BBP_R17_DYNAMIC_UP_BOUND) ? BBP_R17_DYNAMIC_UP_BOUND : ((ULONG) pAdapter->PortCfg.LastR17Value);           // // noise level (dBm) 
+                //iwe.u.qual.noise = (pAdapter->PortCfg.LastR17Value > BBP_R17_DYNAMIC_UP_BOUND) ? BBP_R17_DYNAMIC_UP_BOUND : ((ULONG) pAdapter->PortCfg.LastR17Value);           // // noise level (dBm)
 
-                current_ev = iwe_stream_add_event(current_ev,end_buf, &iwe, IW_EV_QUAL_LEN);                
+                current_ev = iwe_stream_add_event(current_ev,end_buf, &iwe, IW_EV_QUAL_LEN);
 
 
                 //================================
                 memset(&iwe, 0, sizeof(iwe));
 	}
 	data->length = current_ev - extra;
-	DBGPRINT(RT_DEBUG_TRACE,"rtusb_ioctl_giwscan. %d BSS returned\n",pAdapter->PortCfg.BssTab.BssNr);						
+	DBGPRINT(RT_DEBUG_TRACE,"rt_ioctl_giwscan. %d BSS returned\n",pAdapter->PortCfg.BssTab.BssNr);
 	return 0;
 }
 #endif
 static const iw_handler rt_handler[] =
 {
 	(iw_handler) NULL,				/* SIOCSIWCOMMIT */
-	(iw_handler) NULL,			/* SIOCGIWNAME	1 */	 
+	(iw_handler) NULL,			/* SIOCGIWNAME	1 */
 	(iw_handler) NULL,				/* SIOCSIWNWID */
 	(iw_handler) NULL,				/* SIOCGIWNWID */
 	(iw_handler) NULL,		/* SIOCSIWFREQ */
@@ -641,9 +675,11 @@
             }
             break;
         case OID_802_11_BSSID_LIST_SCAN:
+        	if (!RTMP_TEST_FLAG(pAdapter, fRTMP_ADAPTER_MLME_INITIALIZED))
+        		break;
             Now = jiffies;
-			TxTotalCnt = pAdapter->DrsCounters.OneSecTxOkCount + 
-						 pAdapter->DrsCounters.OneSecTxRetryOkCount + 
+			TxTotalCnt = pAdapter->DrsCounters.OneSecTxOkCount +
+						 pAdapter->DrsCounters.OneSecTxRetryOkCount +
 						 pAdapter->DrsCounters.OneSecTxFailCount;
 			DBGPRINT(RT_DEBUG_TRACE, "Set::OID_802_11_BSSID_LIST_SCAN, TxCnt = %d \n", TxTotalCnt);
 			// For XP WZC, we will allow scan every 10 times, roughly 10 minutes.
@@ -657,9 +693,9 @@
 				pAdapter->PortCfg.IgnoredScanNumber++;
 				break;
             }
-            
+
             if ((pAdapter->MediaState == NdisMediaStateConnected) &&
-				((pAdapter->PortCfg.AuthMode == Ndis802_11AuthModeWPA) || 
+				((pAdapter->PortCfg.AuthMode == Ndis802_11AuthModeWPA) ||
 				(pAdapter->PortCfg.AuthMode == Ndis802_11AuthModeWPAPSK)) &&
                 (pAdapter->PortCfg.PortSecured == WPA_802_1X_PORT_NOT_SECURED)
                 )
@@ -682,10 +718,10 @@
             pAdapter->PortCfg.IgnoredScanNumber = 0;
             pAdapter->PortCfg.LastScanTime = Now;
 
-            MlmeEnqueue(&pAdapter->Mlme.Queue, 
-                    MLME_CNTL_STATE_MACHINE, 
-                    OID_802_11_BSSID_LIST_SCAN, 
-                    0, 
+            MlmeEnqueue(&pAdapter->Mlme.Queue,
+                    MLME_CNTL_STATE_MACHINE,
+                    OID_802_11_BSSID_LIST_SCAN,
+                    0,
                     NULL);
 
             Status = NDIS_STATUS_SUCCESS;
@@ -710,13 +746,13 @@
                     {
                         MlmeRestartStateMachine(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->Mlme.CntlAux.CurrReqIsFromNdis = FALSE; 
+                    pAdapter->Mlme.CntlAux.CurrReqIsFromNdis = FALSE;
 
-                    MlmeEnqueue(&pAdapter->Mlme.Queue, 
-                            MLME_CNTL_STATE_MACHINE, 
+                    MlmeEnqueue(&pAdapter->Mlme.Queue,
+                            MLME_CNTL_STATE_MACHINE,
                             OID_802_11_SSID,
                             sizeof(NDIS_802_11_SSID),
                             (VOID *)pSsid
@@ -746,11 +782,11 @@
 
                 // tell CNTL state machine to call NdisMSetInformationComplete() after completing
                 // this request, because this request is initiated by NDIS.
-                pAdapter->Mlme.CntlAux.CurrReqIsFromNdis = FALSE; 
+                pAdapter->Mlme.CntlAux.CurrReqIsFromNdis = FALSE;
 
-                MlmeEnqueue(&pAdapter->Mlme.Queue, 
-                            MLME_CNTL_STATE_MACHINE, 
-                            OID_802_11_BSSID, 
+                MlmeEnqueue(&pAdapter->Mlme.Queue,
+                            MLME_CNTL_STATE_MACHINE,
+                            OID_802_11_BSSID,
                             sizeof(NDIS_802_11_MAC_ADDRESS),
                             (VOID *)&Bssid);
                 Status = NDIS_STATUS_SUCCESS;
@@ -906,7 +942,7 @@
             }
             break;
         case OID_802_11_AUTHENTICATION_MODE:
-            if (wrq->u.data.length != sizeof(NDIS_802_11_AUTHENTICATION_MODE)) 
+            if (wrq->u.data.length != sizeof(NDIS_802_11_AUTHENTICATION_MODE))
                 Status  = -EINVAL;
             else
             {
@@ -941,7 +977,7 @@
 			Status = -EINVAL;
 			break;
 		}
-                if (BssType == Ndis802_11IBSS) 
+                if (BssType == Ndis802_11IBSS)
                 {
                     if (pAdapter->PortCfg.BssType != BSS_INDEP)
                     {
@@ -951,7 +987,7 @@
                     pAdapter->PortCfg.BssType = BSS_INDEP;
                     DBGPRINT(RT_DEBUG_TRACE, "Set::OID_802_11_INFRASTRUCTURE_MODE (AD-HOC)\n");
                 }
-                else if (BssType == Ndis802_11Infrastructure) 
+                else if (BssType == Ndis802_11Infrastructure)
                 {
                     if (pAdapter->PortCfg.BssType != BSS_INFRA)
                     {
@@ -1028,7 +1064,7 @@
 			break;
 		}
                 // save user's policy here, but not change PortCfg.Psm immediately
-                if (PowerMode == Ndis802_11PowerModeCAM) 
+                if (PowerMode == Ndis802_11PowerModeCAM)
                 {
                     // clear PSM bit immediately
                     MlmeSetPsmBit(pAdapter, PWR_ACTIVE);
@@ -1037,7 +1073,7 @@
                         pAdapter->PortCfg.WindowsPowerMode = PowerMode;
                     pAdapter->PortCfg.WindowsBatteryPowerMode = PowerMode;
                 }
-                else if (PowerMode == Ndis802_11PowerModeMAX_PSP) 
+                else if (PowerMode == Ndis802_11PowerModeMAX_PSP)
                 {
                     // do NOT turn on PSM bit here, wait until MlmeCheckForPsmChange()
                     // to exclude certain situations.
@@ -1048,7 +1084,7 @@
                     pAdapter->PortCfg.RecvDtim = TRUE;  // FALSE;
                     pAdapter->PortCfg.DefaultListenCount = 5;
                 }
-                else if (PowerMode == Ndis802_11PowerModeFast_PSP) 
+                else if (PowerMode == Ndis802_11PowerModeFast_PSP)
                 {
                     // do NOT turn on PSM bit here, wait until MlmeCheckForPsmChange()
                     // to exclude certain situations.
@@ -1236,6 +1272,8 @@
             Status = -EOPNOTSUPP;
             break;
     }
+    if(StateMachineTouched) // Upper layer sent a MLME-related operations
+        MlmeHandler(pAdapter);
 
     return Status;
 }
@@ -1305,8 +1343,8 @@
             DBGPRINT(RT_DEBUG_TRACE, "Query::OID_802_11_BSSID_LIST (%d BSS returned)\n",pAdapter->PortCfg.BssTab.BssNr);
             // Claculate total buffer size required
             BssBufSize = sizeof(ULONG);
-            
-            for (i = 0; i < pAdapter->PortCfg.BssTab.BssNr; i++) 
+
+            for (i = 0; i < pAdapter->PortCfg.BssTab.BssNr; i++)
             {
                 // Align pointer to 4 bytes boundary.
                 Padding = 4 - (pAdapter->PortCfg.BssTab.BssEntry[i].VarIELen & 0x0003);
@@ -1328,13 +1366,13 @@
             memset(pBuf, 0, BssBufSize);
             pBssidList = (PNDIS_802_11_BSSID_LIST_EX) pBuf;
             pBssidList->NumberOfItems = pAdapter->PortCfg.BssTab.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->PortCfg.BssTab.BssNr; i++) 
+            for (i = 0; i < pAdapter->PortCfg.BssTab.BssNr; i++)
             {
                 pBss = (PNDIS_WLAN_BSSID_EX) pPtr;
                 memcpy(&pBss->MacAddress, &pAdapter->PortCfg.BssTab.BssEntry[i].Bssid, ETH_ALEN);
@@ -1348,7 +1386,7 @@
                     memcpy(pBss->Ssid.Ssid, pAdapter->PortCfg.BssTab.BssEntry[i].Ssid, pAdapter->PortCfg.BssTab.BssEntry[i].SsidLen);
                 }
                 pBss->Privacy = pAdapter->PortCfg.BssTab.BssEntry[i].Privacy;
-                pBss->Rssi = pAdapter->PortCfg.BssTab.BssEntry[i].Rssi - pAdapter->PortCfg.RssiToDbm; 
+                pBss->Rssi = pAdapter->PortCfg.BssTab.BssEntry[i].Rssi - pAdapter->PortCfg.RssiToDbm;
                 pBss->NetworkTypeInUse = Ndis802_11DS;
                 pBss->Configuration.Length = sizeof(NDIS_802_11_CONFIGURATION);
                 pBss->Configuration.BeaconPeriod = pAdapter->PortCfg.BssTab.BssEntry[i].BeaconPeriod;
@@ -1356,7 +1394,7 @@
 
                 MAP_CHANNEL_ID_TO_KHZ(pAdapter->PortCfg.BssTab.BssEntry[i].Channel, pBss->Configuration.DSConfig);
 
-                if (pAdapter->PortCfg.BssTab.BssEntry[i].BssType == BSS_INFRA) 
+                if (pAdapter->PortCfg.BssTab.BssEntry[i].BssType == BSS_INFRA)
                     pBss->InfrastructureMode = Ndis802_11Infrastructure;
                 else
                     pBss->InfrastructureMode = Ndis802_11IBSS;
@@ -1370,12 +1408,12 @@
                 {
                     pBss->IELength = sizeof(NDIS_802_11_FIXED_IEs);
                     memcpy(pBss->IEs, &pAdapter->PortCfg.BssTab.BssEntry[i].FixIEs, sizeof(NDIS_802_11_FIXED_IEs));
-                    pPtr = pPtr + sizeof(NDIS_WLAN_BSSID_EX) - 4 + sizeof(NDIS_802_11_FIXED_IEs);
+                    pPtr = pPtr + sizeof(NDIS_WLAN_BSSID_EX) - 1 + sizeof(NDIS_802_11_FIXED_IEs);
                 }
                 else
                 {
                     pBss->IELength = sizeof(NDIS_802_11_FIXED_IEs) + pAdapter->PortCfg.BssTab.BssEntry[i].VarIELen;
-                    pPtr = pPtr + sizeof(NDIS_WLAN_BSSID_EX) - 4 + sizeof(NDIS_802_11_FIXED_IEs);
+                    pPtr = pPtr + sizeof(NDIS_WLAN_BSSID_EX) - 1 + sizeof(NDIS_802_11_FIXED_IEs);
                     memcpy(pBss->IEs, &pAdapter->PortCfg.BssTab.BssEntry[i].FixIEs, sizeof(NDIS_802_11_FIXED_IEs));
                     memcpy(pPtr, pAdapter->PortCfg.BssTab.BssEntry[i].VarIEs, pAdapter->PortCfg.BssTab.BssEntry[i].VarIELen);
                     pPtr += pAdapter->PortCfg.BssTab.BssEntry[i].VarIELen;
@@ -1385,7 +1423,7 @@
                 if (Padding == 4)
                     Padding = 0;
                 pPtr += Padding;
-                pBss->Length = sizeof(NDIS_WLAN_BSSID_EX) - 4 + sizeof(NDIS_802_11_FIXED_IEs) + pAdapter->PortCfg.BssTab.BssEntry[i].VarIELen + Padding;
+                pBss->Length = sizeof(NDIS_WLAN_BSSID_EX) - 1 + sizeof(NDIS_802_11_FIXED_IEs) + pAdapter->PortCfg.BssTab.BssEntry[i].VarIELen + Padding;
                 BssLen += pBss->Length;
             }
             wrq->u.data.length = BssLen;
@@ -1451,11 +1489,11 @@
             wrq->u.data.length = sizeof(NDIS_802_11_CONFIGURATION);
             if(copy_to_user(wrq->u.data.pointer, &Configuration, wrq->u.data.length))
 	   	 Status = -EFAULT;
-            DBGPRINT(RT_DEBUG_TRACE, "Query::OID_802_11_CONFIGURATION(BeaconPeriod=%d,AtimW=%d,Channel=%d) \n", 
+            DBGPRINT(RT_DEBUG_TRACE, "Query::OID_802_11_CONFIGURATION(BeaconPeriod=%d,AtimW=%d,Channel=%d) \n",
                                     Configuration.BeaconPeriod, Configuration.ATIMWindow, pAdapter->PortCfg.Channel);
             break;
         case OID_802_11_RSSI:
-            ulInfo = pAdapter->PortCfg.LastRssi - pAdapter->PortCfg.RssiToDbm; 
+            ulInfo = pAdapter->PortCfg.LastRssi - pAdapter->PortCfg.RssiToDbm;
             wrq->u.data.length = sizeof(ulInfo);
             if(copy_to_user(wrq->u.data.pointer, &ulInfo, wrq->u.data.length))
 	    	Status = -EFAULT;
@@ -1484,7 +1522,7 @@
             Statistics.FrameDuplicateCount.QuadPart = pAdapter->WlanCounters.FrameDuplicateCount.QuadPart;
             Statistics.ReceivedFragmentCount.QuadPart = pAdapter->WlanCounters.ReceivedFragmentCount.QuadPart;
             Statistics.MulticastReceivedFrameCount.QuadPart = pAdapter->WlanCounters.MulticastReceivedFrameCount.QuadPart;
-#ifdef RT2500_DBG			
+#ifdef RT2500_DBG
             Statistics.FCSErrorCount = pAdapter->RalinkCounters.RealFcsErrCount;
 #else
             Statistics.FCSErrorCount.QuadPart = pAdapter->WlanCounters.FCSErrorCount.QuadPart;
@@ -1611,8 +1649,8 @@
 }
 
 INT RT2500_ioctl(
-    IN  struct net_device   *net_dev, 
-    IN  OUT struct ifreq    *rq, 
+    IN  struct net_device   *net_dev,
+    IN  OUT struct ifreq    *rq,
     IN  INT                 cmd)
 {
     PRTMP_ADAPTER                       pAdapter= net_dev->priv;
@@ -1624,16 +1662,17 @@
     NDIS_802_11_RTS_THRESHOLD           RtsThresh;
     NDIS_802_11_FRAGMENTATION_THRESHOLD FragThresh;
     NDIS_802_11_MAC_ADDRESS             Bssid;
-    INT                                 Status = NDIS_STATUS_SUCCESS;   
+    INT                                 Status = NDIS_STATUS_SUCCESS;
     USHORT                              subcmd;
     BOOLEAN                             StateMachineTouched = FALSE;
     int                                 i, chan = -1, index = 0, len = 0;
+    ULONG				Length;
 
 
     switch(cmd) {
         case SIOCGIWNAME:
             DBGPRINT(RT_DEBUG_TRACE, "IOCTL::SIOCGIWNAME\n");
-            strcpy(wrq->u.name, "RT2500 Wireless");   //Less then 16 bytes. 
+            strcpy(wrq->u.name, "RT2500 Wireless");   //Less then 16 bytes.
             break;
         case SIOCSIWESSID:  //Set ESSID
             erq = &wrq->u.essid;
@@ -1646,30 +1685,36 @@
                     break;
                 }
 
+#if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,19)
+		Length = erq->length - 1; // minux null character.
+#else
+		Length = erq->length;
+#endif
+
 		if(RTMP_TEST_FLAG(pAdapter, fRTMP_ADAPTER_INTERRUPT_IN_USE))
 		{
-                	if (copy_from_user(Ssid.Ssid, erq->pointer, (erq->length - 1)))
+                	if (copy_from_user(Ssid.Ssid, erq->pointer, Length))
                 	{
                    	 Status = -EFAULT;
                    	 break;
                 	}
-                	Ssid.SsidLength = erq->length - 1;  //minus null character.
+                	Ssid.SsidLength = Length;
 		}else{
 			// This SEEMS to be needed to actual work RobinC when iface
 			// is down
-	                if (copy_from_user(pAdapter->PortCfg.Ssid, erq->pointer, (erq->length - 1)))
+	                if (copy_from_user(pAdapter->PortCfg.Ssid, erq->pointer, Length))
 	                {
 	                    Status = -EFAULT;
 	                    break;
 	                }
-	                pAdapter->PortCfg.SsidLen = erq->length - 1;  //minus null character.
+	                pAdapter->PortCfg.SsidLen = Length;
 
-			memcpy(pAdapter->Mlme.CntlAux.Ssid, pAdapter->PortCfg.Ssid, pAdapter->PortCfg.SsidLen);	
-			pAdapter->Mlme.CntlAux.SsidLen = pAdapter->PortCfg.SsidLen; 
+			memcpy(pAdapter->Mlme.CntlAux.Ssid, pAdapter->PortCfg.Ssid, pAdapter->PortCfg.SsidLen);
+			pAdapter->Mlme.CntlAux.SsidLen = pAdapter->PortCfg.SsidLen;
 		}
             }
             else
-                Ssid.SsidLength = 0;  // ANY ssid 
+                Ssid.SsidLength = 0;  // ANY ssid
 
             pSsid = &Ssid;
 
@@ -1686,10 +1731,10 @@
 
              // tell CNTL state machine to call NdisMSetInformationComplete() after completing
             // this request, because this request is initiated by NDIS.
-            pAdapter->Mlme.CntlAux.CurrReqIsFromNdis = FALSE; 
+            pAdapter->Mlme.CntlAux.CurrReqIsFromNdis = FALSE;
 
-            MlmeEnqueue(&pAdapter->Mlme.Queue, 
-                    MLME_CNTL_STATE_MACHINE, 
+            MlmeEnqueue(&pAdapter->Mlme.Queue,
+                    MLME_CNTL_STATE_MACHINE,
                     OID_802_11_SSID,
                     sizeof(NDIS_802_11_SSID),
                     (VOID *)pSsid
@@ -1708,7 +1753,7 @@
 			Status = -EFAULT;
             DBGPRINT(RT_DEBUG_TRACE, "ioctl::SIOCGIWESSID (Len=%d, ssid=%s...)\n", erq->length, pAdapter->PortCfg.Ssid);
             break;
-        case SIOCGIWNWID: // get network id 
+        case SIOCGIWNWID: // get network id
             Status = -EOPNOTSUPP;
             break;
         case SIOCSIWNWID: // set network id (the cell)
@@ -1717,14 +1762,14 @@
         case SIOCSIWFREQ: // set channel/frequency (Hz)
             frq = &wrq->u.freq;
             if((frq->e == 0) && (frq->m <= 1000))
-                chan = frq->m;  // Setting by channel number 
+                chan = frq->m;  // Setting by channel number
             else
-                MAP_KHZ_TO_CHANNEL_ID( (frq->m /100) , chan); // Setting by frequency - search the table , like 2.412G, 2.422G, 
+                MAP_KHZ_TO_CHANNEL_ID( (frq->m /100) , chan); // Setting by frequency - search the table , like 2.412G, 2.422G,
             pAdapter->PortCfg.IbssConfig.Channel = chan;
             DBGPRINT(RT_DEBUG_TRACE, "ioctl::SIOCSIWFREQ[cmd=0x%x] (Channel=%d)\n", SIOCSIWFREQ, pAdapter->PortCfg.IbssConfig.Channel);
             if(RTMP_TEST_FLAG(pAdapter, fRTMP_ADAPTER_INTERRUPT_IN_USE) && (pAdapter->PortCfg.BssType == BSS_MONITOR || pAdapter->PortCfg.BssType == BSS_INDEP))
             {
-               pAdapter->PortCfg.Channel = chan; 
+               pAdapter->PortCfg.Channel = chan;
                AsicSwitchChannel(pAdapter, pAdapter->PortCfg.Channel);
                AsicLockChannel(pAdapter, pAdapter->PortCfg.Channel);
             }
@@ -1822,7 +1867,7 @@
                 if(wrq->u.encoding.pointer)
                 {
                     wrq->u.encoding.length = pAdapter->PortCfg.SharedKey[index].KeyLen;
-                    if(copy_to_user(wrq->u.encoding.pointer, 
+                    if(copy_to_user(wrq->u.encoding.pointer,
                                 pAdapter->PortCfg.SharedKey[index].Key,
                                 pAdapter->PortCfg.SharedKey[index].KeyLen))
 			Status = -EFAULT;
@@ -1843,14 +1888,15 @@
                     len = WEP_LARGE_KEY_LEN;
 
                 memset(pAdapter->PortCfg.SharedKey[index].Key, 0x00, MAX_LEN_OF_KEY);
-                if(copy_from_user(pAdapter->PortCfg.SharedKey[index].Key, 
+                if(copy_from_user(pAdapter->PortCfg.SharedKey[index].Key,
                                 wrq->u.encoding.pointer, len)){
 			Status = -EINVAL;
 			break;
 		}
                 pAdapter->PortCfg.SharedKey[index].KeyLen = len <= WEP_SMALL_KEY_LEN ? WEP_SMALL_KEY_LEN : WEP_LARGE_KEY_LEN;
             }
-            pAdapter->PortCfg.DefaultKeyId = (UCHAR) index;
+	    else
+            	pAdapter->PortCfg.DefaultKeyId = (UCHAR) index;
             if (wrq->u.encoding.flags & IW_ENCODE_DISABLED)
                 pAdapter->PortCfg.WepStatus = Ndis802_11WEPDisabled;
             else
@@ -1858,7 +1904,7 @@
 
             if (wrq->u.encoding.flags & IW_ENCODE_RESTRICTED)
                 pAdapter->PortCfg.AuthMode = Ndis802_11AuthModeShared;
-            if (wrq->u.encoding.flags & IW_ENCODE_OPEN) 
+            if (wrq->u.encoding.flags & IW_ENCODE_OPEN)
                 pAdapter->PortCfg.AuthMode = Ndis802_11AuthModeOpen;
 
             if(pAdapter->PortCfg.WepStatus == Ndis802_11WEPDisabled)
@@ -1905,11 +1951,11 @@
 
             // tell CNTL state machine to call NdisMSetInformationComplete() after completing
             // this request, because this request is initiated by NDIS.
-            pAdapter->Mlme.CntlAux.CurrReqIsFromNdis = FALSE; 
+            pAdapter->Mlme.CntlAux.CurrReqIsFromNdis = FALSE;
 
-            MlmeEnqueue(&pAdapter->Mlme.Queue, 
-                        MLME_CNTL_STATE_MACHINE, 
-                        OID_802_11_BSSID, 
+            MlmeEnqueue(&pAdapter->Mlme.Queue,
+                        MLME_CNTL_STATE_MACHINE,
+                        OID_802_11_BSSID,
                         sizeof(NDIS_802_11_MAC_ADDRESS),
                         (VOID *)&Bssid);
             Status = NDIS_STATUS_SUCCESS;
@@ -1928,13 +1974,13 @@
                 BssType = Ndis802_11Infrastructure;
                 wrq->u.mode = IW_MODE_INFRA;
             }
-#if (LINUX_VERSION_CODE > KERNEL_VERSION(2,4,20)) 
+#if (LINUX_VERSION_CODE > KERNEL_VERSION(2,4,20))
             else if (pAdapter->PortCfg.BssType == BSS_MONITOR)
             {
                 BssType = Ndis802_11Monitor;
                 wrq->u.mode = IW_MODE_MONITOR;
             }
-#endif	    
+#endif
 	    else
             {
                 BssType = Ndis802_11AutoUnknown;
@@ -1963,7 +2009,7 @@
                 pAdapter->PortCfg.BssType = BSS_INFRA;
                 DBGPRINT(RT_DEBUG_TRACE, "ioctl::SIOCSIWMODE (INFRA)\n");
             }
-#if (LINUX_VERSION_CODE > KERNEL_VERSION(2,4,20)) 	    
+#if (LINUX_VERSION_CODE > KERNEL_VERSION(2,4,20))
 	    else if (wrq->u.mode == IW_MODE_MONITOR)
             {
                 if (pAdapter->PortCfg.BssType != BSS_MONITOR)
@@ -1974,7 +2020,7 @@
                 pAdapter->PortCfg.BssType = BSS_MONITOR;
                 DBGPRINT(RT_DEBUG_TRACE, "ioctl::SIOCSIWMODE (MONITOR)\n");
             }
-#endif 
+#endif
   	    else
             {
                 Status  = -ENOSYS;
@@ -1999,7 +2045,7 @@
 	 	}
                 else
                 {
-                    pAdapter->net_dev->type = 1; 
+                    pAdapter->net_dev->type = 1;
                     RTMP_IO_WRITE32(pAdapter, RXCSR0, 0x7e);
                 }
             }
@@ -2013,23 +2059,23 @@
 		Status = -EOPNOTSUPP;
 		break;
         case SIOCGIWTXPOW:  //get transmit power (dBm)
-#if WIRELESS_EXT >= 17	
+#if WIRELESS_EXT >= 17
 	    // Krellan: Get TxPower in dBm now, not percentage
 	    {
 	    	 ULONG R3;
 	    	 UCHAR Channel = pAdapter->PortCfg.Channel;
-	    	 
+
 	    	 // Krellan: This code comes from AsicSwitchChannel(),
 	    	 // as we must know the channel we are currently on,
 	    	 // in order to get the correct EEPROM-recommended
 	    	 // value to establish as 0 dBm.
-			 if (Channel <= 14)    
+			 if (Channel <= 14)
 				  R3 = pAdapter->PortCfg.ChannelTxPower[Channel - 1];
-			 else 
+			 else
 				  R3 = pAdapter->PortCfg.ChannelTxPower[0];
 
 			 if (R3 > 31)  R3 = 31;
-			 
+
 			 wrq->u.txpower.value = pAdapter->PortCfg.TxPowerDriver - R3;
 			 wrq->u.txpower.flags = IW_TXPOW_DBM;
 			 wrq->u.txpower.fixed = !(pAdapter->PortCfg.TxPowerAuto);
@@ -2061,7 +2107,7 @@
 					 else
 					 {
 						 Value = wrq->u.txpower.value;
-						 
+
 						 if (Value < MIN_TXPOWER_DBM || Value > MAX_TXPOWER_DBM)
 						 {
 						    Status = -EINVAL;
@@ -2107,14 +2153,14 @@
             break;
 
         case RTPRIV_IOCTL_SET:
-            {               
+            {
                 char *this_char;
                 char *value;
 
                 if( !access_ok(VERIFY_READ, wrq->u.data.pointer, wrq->u.data.length) )
                     break;
 
-                while ((this_char = strsep((char**)&wrq->u.data.pointer, ",")) != NULL) 
+                while ((this_char = strsep((char**)&wrq->u.data.pointer, ",")) != NULL)
                 {
                     if (!*this_char)
                          continue;
@@ -2127,8 +2173,8 @@
 
                     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 (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;
@@ -2161,8 +2207,12 @@
             break;
 #endif
 
-	case RTPRIV_IOCTL_RFMONTX:
-	    Status = RTMPIoctlRFMONTX(pAdapter, wrq);
+	case RTPRIV_IOCTL_SET_RFMONTX:
+	    Status = RTMPIoctlSetRFMONTX(pAdapter, wrq);
+	    break;
+
+	case RTPRIV_IOCTL_GET_RFMONTX:
+	    Status = RTMPIoctlGetRFMONTX(pAdapter, wrq);
 	    break;
 
         default:
@@ -2181,7 +2231,7 @@
 UCHAR   BCAST[] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff};
 /*
     ========================================================================
-    
+
     Routine Description:
         Add WPA key process
 
@@ -2193,7 +2243,7 @@
         NDIS_SUCCESS                    Add key successfully
 
     Note:
-        
+
     ========================================================================
 */
 NDIS_STATUS RTMPWPAAddKeyProc(
@@ -2228,7 +2278,7 @@
         // 1. KeyIdx must be 0, otherwise, return NDIS_STATUS_INVALID_DATA
         if (KeyIdx != 0)
             return(NDIS_STATUS_FAILURE);
-        
+
         // 2. Check bTx, it must be true, otherwise, return NDIS_STATUS_INVALID_DATA
         if (bTxKey == FALSE)
             return(NDIS_STATUS_FAILURE);
@@ -2236,7 +2286,7 @@
         // 3. If BSSID is not all 0xff, return NDIS_STATUS_INVALID_DATA
         if (NdisEqualMemory(pKey->BSSID, BCAST, 6))
             return(NDIS_STATUS_FAILURE);
-            
+
         // 4. Selct RxMic / TxMic based on Supp / Authenticator
         if (pAdapter->PortCfg.AuthMode == Ndis802_11AuthModeWPANone)
         {
@@ -2277,16 +2327,16 @@
         // 6. Check RxTsc
         if (bKeyRSC == TRUE)
         {
-            memcpy(&pAdapter->PortCfg.PairwiseKey[PairwiseIdx].RxTsc, &pKey->KeyRSC, 6);            
+            memcpy(&pAdapter->PortCfg.PairwiseKey[PairwiseIdx].RxTsc, &pKey->KeyRSC, 6);
         }
         else
         {
-            memset(pAdapter->PortCfg.PairwiseKey[PairwiseIdx].RxTsc, 0, 6);        
+            memset(pAdapter->PortCfg.PairwiseKey[PairwiseIdx].RxTsc, 0, 6);
         }
 
         // 7. Copy information into Pairwise Key structure.
         // pKey->KeyLength will include TxMic and RxMic, therefore, we use 16 bytes hardcoded.
-        pAdapter->PortCfg.PairwiseKey[PairwiseIdx].KeyLen = 16;     
+        pAdapter->PortCfg.PairwiseKey[PairwiseIdx].KeyLen = 16;
         memcpy(pAdapter->PortCfg.PairwiseKey[PairwiseIdx].Key, &pKey->KeyMaterial, 16);
         memcpy(pAdapter->PortCfg.PairwiseKey[PairwiseIdx].RxMic, pRxMic, 8);
         memcpy(pAdapter->PortCfg.PairwiseKey[PairwiseIdx].TxMic, pTxMic, 8);
@@ -2300,36 +2350,43 @@
         pAdapter->PortCfg.PairwiseKey[PairwiseIdx].TxTsc[5] = 0;
         Status = NDIS_STATUS_SUCCESS;
 
-        DBGPRINT(RT_DEBUG_INFO, "TKIP Key = ");
+#ifdef RT2500_DBG
+	printk("Pairwise Key (Index-%d) = ", PairwiseIdx);
         for (i = 0; i < 16; i++)
         {
-            DBGPRINT(RT_DEBUG_INFO, "%02x:", pAdapter->PortCfg.PairwiseKey[PairwiseIdx].Key[i]);
+		printk("%02x:",
+		       pAdapter->PortCfg.PairwiseKey[PairwiseIdx].Key[i]);
         }
-        DBGPRINT(RT_DEBUG_INFO, "\n");
-        DBGPRINT(RT_DEBUG_INFO, "TKIP Rx MIC Key = ");
+        printk("\n");
+        printk("PairwiseKey Rx MIC Key = ");
         for (i = 0; i < 8; i++)
         {
-            DBGPRINT(RT_DEBUG_INFO, "%02x:", pAdapter->PortCfg.PairwiseKey[PairwiseIdx].RxMic[i]);
+		printk("%02x:",
+		       pAdapter->PortCfg.PairwiseKey[PairwiseIdx].RxMic[i]);
         }
-        DBGPRINT(RT_DEBUG_INFO, "\n");
-        DBGPRINT(RT_DEBUG_INFO, "TKIP Tx MIC Key = ");
+        printk("\n");
+        printk("PairwiseKey Tx MIC Key = ");
         for (i = 0; i < 8; i++)
         {
-            DBGPRINT(RT_DEBUG_INFO, "%02x:", pAdapter->PortCfg.PairwiseKey[PairwiseIdx].TxMic[i]);
+		printk("%02x:",
+		       pAdapter->PortCfg.PairwiseKey[PairwiseIdx].TxMic[i]);
         }
-        DBGPRINT(RT_DEBUG_INFO, "\n");
-        DBGPRINT(RT_DEBUG_INFO, "TKIP RxTSC = ");
+        printk("\n");
+        printk("RxTSC = ");
         for (i = 0; i < 6; i++)
         {
-            DBGPRINT(RT_DEBUG_INFO, "%02x:", pAdapter->PortCfg.PairwiseKey[PairwiseIdx].RxTsc[i]);
+		printk("%02x:",
+		       pAdapter->PortCfg.PairwiseKey[PairwiseIdx].RxTsc[i]);
         }
-        DBGPRINT(RT_DEBUG_INFO, "\n");
-        DBGPRINT(RT_DEBUG_INFO, "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]);
-
+        printk("\n");
+        printk("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]);
+#endif
     }
     else    // Group Key
     {
+	DBGPRINT(RT_DEBUG_TRACE, "Ready to set Group key\n");
         // 1. Check BSSID, if not current BSSID or Bcast, return NDIS_STATUS_INVALID_DATA
         if ((!NdisEqualMemory(&pKey->BSSID, &BCAST, 6)) &&
             (!NdisEqualMemory(&pKey->BSSID, &pAdapter->PortCfg.Bssid, 6)))
@@ -2374,7 +2431,7 @@
 
         // 6. Copy information into Group Key structure.
         // pKey->KeyLength will include TxMic and RxMic, therefore, we use 16 bytes hardcoded.
-        pAdapter->PortCfg.GroupKey[KeyIdx].KeyLen = 16;     
+        pAdapter->PortCfg.GroupKey[KeyIdx].KeyLen = 16;
         memcpy(pAdapter->PortCfg.GroupKey[KeyIdx].Key, &pKey->KeyMaterial, 16);
         memcpy(pAdapter->PortCfg.GroupKey[KeyIdx].RxMic, pRxMic, 8);
         memcpy(pAdapter->PortCfg.GroupKey[KeyIdx].TxMic, pTxMic, 8);
@@ -2397,33 +2454,35 @@
             memcpy(pAdapter->PortCfg.SharedKey[KeyIdx].Key, &pKey->KeyMaterial, pKey->KeyLength);
         }
 
-        DBGPRINT(RT_DEBUG_INFO, "TKIP Key = ");
+#ifdef RT2500_DBG
+        printk("GroupKey Key (Index-%d) = ", KeyIdx);
         for (i = 0; i < 16; i++)
         {
-            DBGPRINT(RT_DEBUG_INFO, "%02x:", pAdapter->PortCfg.GroupKey[KeyIdx].Key[i]);
+		printk("%02x:", pAdapter->PortCfg.GroupKey[KeyIdx].Key[i]);
         }
-        DBGPRINT(RT_DEBUG_INFO, "\n");
-        DBGPRINT(RT_DEBUG_INFO, "TKIP Rx MIC Key = ");
+        printk("\n");
+        printk("GroupKey Rx MIC Key = ");
         for (i = 0; i < 8; i++)
         {
-            DBGPRINT(RT_DEBUG_INFO, "%02x:", pAdapter->PortCfg.GroupKey[KeyIdx].RxMic[i]);
+		printk("%02x:", pAdapter->PortCfg.GroupKey[KeyIdx].RxMic[i]);
         }
-        DBGPRINT(RT_DEBUG_INFO, "\n");
-        DBGPRINT(RT_DEBUG_INFO, "TKIP Tx MIC Key = ");
+        printk("\n");
+        printk("GroupKey Tx MIC Key = ");
         for (i = 0; i < 8; i++)
         {
-            DBGPRINT(RT_DEBUG_INFO, "%02x:", pAdapter->PortCfg.GroupKey[KeyIdx].TxMic[i]);
+		printk("%02x:", pAdapter->PortCfg.GroupKey[KeyIdx].TxMic[i]);
         }
-        DBGPRINT(RT_DEBUG_INFO, "\n");
-        DBGPRINT(RT_DEBUG_INFO, "TKIP RxTSC = ");
+        printk("\n");
+        printk("RxTSC = ");
         for (i = 0; i < 6; i++)
         {
-            DBGPRINT(RT_DEBUG_INFO, "%02x:", pAdapter->PortCfg.GroupKey[KeyIdx].RxTsc[i]);
+		printk("%02x:", pAdapter->PortCfg.GroupKey[KeyIdx].RxTsc[i]);
         }
-        DBGPRINT(RT_DEBUG_INFO, "\n");
-        DBGPRINT(RT_DEBUG_INFO, "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]);
-
+        printk("\n");
+        printk("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]);
+#endif
     }
     return (Status);
 }
@@ -2499,7 +2558,7 @@
                     break;
                 }
             }
-            
+
         }
         // c. If no pairwise supported, delete Group Key 0.
         //    The will be false since we do support pairwise keys.
@@ -2545,7 +2604,7 @@
         None
 
     Note:
-        
+
     ========================================================================
 */
 VOID    RTMPWPARemoveAllKeys(
@@ -2562,7 +2621,7 @@
     {
         pAdapter->PortCfg.PairwiseKey[i].KeyLen = 0;
     }
-    
+
     for (i = 0; i < GROUP_KEY_NO; i++)
     {
         pAdapter->PortCfg.GroupKey[i].KeyLen = 0;
@@ -2578,7 +2637,7 @@
     Arguments:
         pAdapter                        Pointer to our adapter
         phmode
-        
+
     ========================================================================
 */
 VOID    RTMPSetPhyMode(
@@ -2586,7 +2645,7 @@
     IN  ULONG phymode)
 {
     INT     i;
-    
+
     DBGPRINT(RT_DEBUG_TRACE,"RTMPSetPhyMode(=%d)\n", phymode);
 
     // the selected phymode must be supported by the RF IC encoded in E2PROM
@@ -2611,7 +2670,7 @@
 	if (i == pAdapter->PortCfg.ChannelListNum)
 		pAdapter->PortCfg.IbssConfig.Channel = FirstChannel(pAdapter);
     pAdapter->PortCfg.Channel = pAdapter->PortCfg.IbssConfig.Channel;
-	
+
     AsicSwitchChannel(pAdapter, pAdapter->PortCfg.Channel);
     AsicLockChannel(pAdapter, pAdapter->PortCfg.Channel);
 
@@ -2859,7 +2918,7 @@
     // Changing DesiredRate may affect the MAX TX rate we used to TX frames out
     MlmeUpdateTxRates(pAdapter, FALSE);
 }
-/* 
+/*
     ==========================================================================
     Description:
         Set Country Region
@@ -2868,7 +2927,7 @@
     ==========================================================================
 */
 INT Set_CountryRegion_Proc(
-    IN  PRTMP_ADAPTER   pAdapter, 
+    IN  PRTMP_ADAPTER   pAdapter,
     IN  PUCHAR          arg)
 {
     ULONG                               region;
@@ -2886,7 +2945,7 @@
 
     return success;
 }
-/* 
+/*
     ==========================================================================
     Description:
         Set SSID
@@ -2895,7 +2954,7 @@
     ==========================================================================
 */
 INT Set_SSID_Proc(
-    IN  PRTMP_ADAPTER   pAdapter, 
+    IN  PRTMP_ADAPTER   pAdapter,
     IN  PUCHAR          arg)
 {
     NDIS_802_11_SSID                    Ssid, *pSsid=NULL;
@@ -2904,8 +2963,8 @@
 
 
     /* Protect against oops if net is down, this will not work with if-preup
-     use iwconfig properly */   
-    printk("'iwpriv <dev> set essid' is deprecated, please use 'iwconfg <dev> essid' instead\n"); 
+     use iwconfig properly */
+    printk("'iwpriv <dev> set essid' is deprecated, please use 'iwconfg <dev> essid' instead\n");
     if(!RTMP_TEST_FLAG(pAdapter, fRTMP_ADAPTER_INTERRUPT_IN_USE))
 	return FALSE;
 
@@ -2916,8 +2975,8 @@
         Ssid.SsidLength = strlen(arg);
         pSsid = &Ssid;
 
-	
-   	
+
+
         if (pAdapter->Mlme.CntlMachine.CurrState != CNTL_IDLE)
         {
             MlmeRestartStateMachine(pAdapter);
@@ -2925,10 +2984,10 @@
         }
          // tell CNTL state machine to call NdisMSetInformationComplete() after completing
         // this request, because this request is initiated by NDIS.
-        pAdapter->Mlme.CntlAux.CurrReqIsFromNdis = FALSE; 
+        pAdapter->Mlme.CntlAux.CurrReqIsFromNdis = FALSE;
 
-        MlmeEnqueue(&pAdapter->Mlme.Queue, 
-                    MLME_CNTL_STATE_MACHINE, 
+        MlmeEnqueue(&pAdapter->Mlme.Queue,
+                    MLME_CNTL_STATE_MACHINE,
                     OID_802_11_SSID,
                     sizeof(NDIS_802_11_SSID),
                     (VOID *)pSsid);
@@ -2944,7 +3003,7 @@
 
     return success;
 }
-/* 
+/*
     ==========================================================================
     Description:
         Set Wireless Mode
@@ -2953,26 +3012,24 @@
     ==========================================================================
 */
 INT Set_WirelessMode_Proc(
-    IN  PRTMP_ADAPTER   pAdapter, 
+    IN  PRTMP_ADAPTER   pAdapter,
     IN  PUCHAR          arg)
 {
     ULONG                               WirelessMode;
     int                                 success = TRUE;
 
     WirelessMode = simple_strtol(arg, 0, 10);
+    DBGPRINT(RT_DEBUG_TRACE, "Set_WirelessMode_Proc::(=%d)\n", WirelessMode);
 
     if ((WirelessMode == PHY_11BG_MIXED) || (WirelessMode == PHY_11B) ||
         (WirelessMode == PHY_11A) || (WirelessMode == PHY_11ABG_MIXED))
-    {
         RTMPSetPhyMode(pAdapter, WirelessMode);
-        DBGPRINT(RT_DEBUG_TRACE, "Set_WirelessMode_Proc::(=%d)\n", WirelessMode);
-    }
     else
         success = FALSE;
 
     return success;
 }
-/* 
+/*
     ==========================================================================
     Description:
         Set TxRate
@@ -2981,7 +3038,7 @@
     ==========================================================================
 */
 INT Set_TxRate_Proc(
-    IN  PRTMP_ADAPTER   pAdapter, 
+    IN  PRTMP_ADAPTER   pAdapter,
     IN  PUCHAR          arg)
 {
     ULONG                               TxRate;
@@ -2996,7 +3053,7 @@
         RTMPSetDesiredRates(pAdapter, (LONG) (rate_mapping[TxRate-1] * 1000000));
     return success;
 }
-/* 
+/*
     ==========================================================================
     Description:
         Set AdhocMode support Rate can or can not exceed 11Mbps against WiFi spec.
@@ -3005,7 +3062,7 @@
     ==========================================================================
 */
 INT Set_AdhocModeRate_Proc(
-    IN  PRTMP_ADAPTER   pAdapter, 
+    IN  PRTMP_ADAPTER   pAdapter,
     IN  PUCHAR          arg)
 {
     ULONG       AdhocMode;
@@ -3017,13 +3074,13 @@
     else if (AdhocMode == 0)
         pAdapter->PortCfg.AdhocMode = 0;
     else
-        return FALSE;  //Invalid argument 
+        return FALSE;  //Invalid argument
 
     DBGPRINT(RT_DEBUG_TRACE, "Set_AdhocModeRate_Proc::(AdhocMode=%d)\n", pAdapter->PortCfg.AdhocMode);
 
     return TRUE;
 }
-/* 
+/*
     ==========================================================================
     Description:
         Set Channel
@@ -3032,7 +3089,7 @@
     ==========================================================================
 */
 INT Set_Channel_Proc(
-    IN  PRTMP_ADAPTER   pAdapter, 
+    IN  PRTMP_ADAPTER   pAdapter,
     IN  PUCHAR          arg)
 {
     int                                 success = TRUE;
@@ -3051,7 +3108,32 @@
 
     return success;
 }
-/* 
+/*
+    ==========================================================================
+    Description:
+        For Debug information
+    Return:
+        TRUE if all parameters are OK, FALSE otherwise
+    ==========================================================================
+*/
+#ifdef RT2500_DBG
+INT Set_Debug_Proc(
+    IN  PRTMP_ADAPTER   pAdapter,
+    IN  PUCHAR          arg)
+
+{
+    DBGPRINT(RT_DEBUG_TRACE, "**************************************************************\n");
+	DBGPRINT(RT_DEBUG_TRACE, "==> Set_Debug_Proc arg=%s\n", arg);
+    //To do here.
+
+    rt2500_setdbg(simple_strtoul(arg, 0, 0));
+
+    DBGPRINT(RT_DEBUG_TRACE, "<== Set_Debug_Proc\n");
+    DBGPRINT(RT_DEBUG_TRACE, "**************************************************************\n");
+    return TRUE;
+}
+#endif
+/*
     ==========================================================================
     Description:
         Set 11B/11G Protection
@@ -3060,7 +3142,7 @@
     ==========================================================================
 */
 INT Set_BGProtection_Proc(
-    IN  PRTMP_ADAPTER   pAdapter, 
+    IN  PRTMP_ADAPTER   pAdapter,
     IN  PUCHAR          arg)
 
 {
@@ -3074,15 +3156,15 @@
             break;
         case 2: //Always OFF
             pAdapter->PortCfg.UseBGProtection = 2;
-            break;      
-        default:  //Invalid argument 
+            break;
+        default:  //Invalid argument
             return FALSE;
     }
     DBGPRINT(RT_DEBUG_TRACE, "Set_BGProtection_Proc::(BGProtection=%d)\n", pAdapter->PortCfg.UseBGProtection);
 
     return TRUE;
 }
-/* 
+/*
     ==========================================================================
     Description:
         Set StaWithEtherBridge function on/off
@@ -3091,7 +3173,7 @@
     ==========================================================================
 */
 INT Set_StaWithEtherBridge_Proc(
-    IN  PRTMP_ADAPTER   pAdapter, 
+    IN  PRTMP_ADAPTER   pAdapter,
     IN  PUCHAR          arg)
 
 {
@@ -3103,14 +3185,14 @@
         case 1: //On
             pAdapter->PortCfg.StaWithEtherBridge.Enable = TRUE;
             break;
-        default:  //Invalid argument 
+        default:  //Invalid argument
             return FALSE;
     }
     DBGPRINT(RT_DEBUG_TRACE, "Set_StaWithEtherBridge_Proc::(StaWithEtherBridge=%d)\n", pAdapter->PortCfg.StaWithEtherBridge.Enable);
 
     return TRUE;
 }
-/* 
+/*
     ==========================================================================
     Description:
         Set TxPreamble
@@ -3119,7 +3201,7 @@
     ==========================================================================
 */
 INT Set_TxPreamble_Proc(
-    IN  PRTMP_ADAPTER   pAdapter, 
+    IN  PRTMP_ADAPTER   pAdapter,
     IN  PUCHAR          arg)
 {
     RT_802_11_PREAMBLE                  Preamble;
@@ -3138,7 +3220,7 @@
             pAdapter->PortCfg.WindowsTxPreamble = Preamble;
             MlmeSetTxPreamble(pAdapter, Rt802_11PreambleLong);
             break;
-        default: //Invalid argument 
+        default: //Invalid argument
             return FALSE;
     }
 
@@ -3146,7 +3228,7 @@
 
     return TRUE;
 }
-/* 
+/*
     ==========================================================================
     Description:
         Set RTS Threshold
@@ -3155,15 +3237,15 @@
     ==========================================================================
 */
 INT Set_RTSThreshold_Proc(
-    IN  PRTMP_ADAPTER   pAdapter, 
+    IN  PRTMP_ADAPTER   pAdapter,
     IN  PUCHAR          arg)
-    
-   
+
+
 {
     NDIS_802_11_RTS_THRESHOLD           RtsThresh;
 
-   printk("'iwpriv <dev> set RTSThreshold' is deprecated, please use 'iwconfg <dev> rts' instead\n"); 
- 
+   printk("'iwpriv <dev> set RTSThreshold' is deprecated, please use 'iwconfg <dev> rts' instead\n");
+
     RtsThresh = simple_strtol(arg, 0, 10);
 
     if((RtsThresh > 0) && (RtsThresh <= MAX_RTS_THRESHOLD))
@@ -3176,7 +3258,7 @@
     DBGPRINT(RT_DEBUG_TRACE, "Set_RTSThreshold_Proc::(RTSThreshold=%d)\n", pAdapter->PortCfg.RtsThreshold);
     return TRUE;
 }
-/* 
+/*
     ==========================================================================
     Description:
         Set Fragment Threshold
@@ -3185,14 +3267,14 @@
     ==========================================================================
 */
 INT Set_FragThreshold_Proc(
-    IN  PRTMP_ADAPTER   pAdapter, 
+    IN  PRTMP_ADAPTER   pAdapter,
     IN  PUCHAR          arg)
 {
     NDIS_802_11_FRAGMENTATION_THRESHOLD     FragThresh;
 
-    printk("'iwpriv <dev> set FragThreshold' is deprecated, please use 'iwconfg <dev> frag' instead\n"); 
- 
-    
+    printk("'iwpriv <dev> set FragThreshold' is deprecated, please use 'iwconfg <dev> frag' instead\n");
+
+
     FragThresh = simple_strtol(arg, 0, 10);
 
     if ( (FragThresh >= MIN_FRAG_THRESHOLD) && (FragThresh <= MAX_FRAG_THRESHOLD))
@@ -3200,7 +3282,7 @@
     else if (FragThresh == 0)
         pAdapter->PortCfg.FragmentThreshold = MAX_FRAG_THRESHOLD;
     else
-        return FALSE; //Invalid argument 
+        return FALSE; //Invalid argument
 
     if (pAdapter->PortCfg.FragmentThreshold == MAX_FRAG_THRESHOLD)
         pAdapter->PortCfg.bFragmentZeroDisable = TRUE;
@@ -3211,7 +3293,7 @@
 
     return TRUE;
 }
-/* 
+/*
     ==========================================================================
     Description:
         Set TxBurst
@@ -3220,7 +3302,7 @@
     ==========================================================================
 */
 INT Set_TxBurst_Proc(
-    IN  PRTMP_ADAPTER   pAdapter, 
+    IN  PRTMP_ADAPTER   pAdapter,
     IN  PUCHAR          arg)
 {
     ULONG                               TxBurst;
@@ -3232,13 +3314,13 @@
     else if (TxBurst == 0)
         pAdapter->PortCfg.EnableTxBurst = FALSE;
     else
-        return FALSE;  //Invalid argument 
-    
+        return FALSE;  //Invalid argument
+
     DBGPRINT(RT_DEBUG_TRACE, "Set_TxBurst_Proc::(TxBurst=%d)\n", pAdapter->PortCfg.EnableTxBurst);
 
     return TRUE;
 }
-/* 
+/*
     ==========================================================================
     Description:
         Set TurboRate Enable or Disable
@@ -3247,7 +3329,7 @@
     ==========================================================================
 */
 INT Set_TurboRate_Proc(
-    IN  PRTMP_ADAPTER   pAdapter, 
+    IN  PRTMP_ADAPTER   pAdapter,
     IN  PUCHAR          arg)
 {
     ULONG                               TurboRate;
@@ -3259,13 +3341,13 @@
     else if (TurboRate == 0)
         pAdapter->PortCfg.EnableTurboRate = FALSE;
     else
-        return FALSE;  //Invalid argument 
-    
+        return FALSE;  //Invalid argument
+
     DBGPRINT(RT_DEBUG_TRACE, "Set_TurboRate_Proc::(TurboRate=%d)\n", pAdapter->PortCfg.EnableTurboRate);
 
     return TRUE;
 }
-/* 
+/*
     ==========================================================================
     Description:
         Set Short Slot Time Enable or Disable
@@ -3274,7 +3356,7 @@
     ==========================================================================
 */
 INT Set_ShortSlot_Proc(
-    IN  PRTMP_ADAPTER   pAdapter, 
+    IN  PRTMP_ADAPTER   pAdapter,
     IN  PUCHAR          arg)
 {
     ULONG                               ShortSlot;
@@ -3286,14 +3368,14 @@
     else if (ShortSlot == 0)
         pAdapter->PortCfg.UseShortSlotTime = FALSE;
     else
-        return FALSE;  //Invalid argument 
+        return FALSE;  //Invalid argument
 
     DBGPRINT(RT_DEBUG_TRACE, "Set_ShortSlot_Proc::(ShortSlot=%d)\n", pAdapter->PortCfg.UseShortSlotTime);
 
     return TRUE;
 }
 
-/* 
+/*
     ==========================================================================
     Description:
         Set Network Type(Infrastructure/Adhoc mode)
@@ -3302,17 +3384,17 @@
     ==========================================================================
 */
 INT Set_NetworkType_Proc(
-    IN  PRTMP_ADAPTER   pAdapter, 
+    IN  PRTMP_ADAPTER   pAdapter,
     IN  PUCHAR          arg)
 {
 
-    printk("'iwpriv <dev> set NetworkType' is deprecated, please use 'iwconfg <dev> mode' instead\n"); 
-    
+    printk("'iwpriv <dev> set NetworkType' is deprecated, please use 'iwconfg <dev> mode' instead\n");
+
     if (strcmp(arg, "Adhoc") == 0)
         pAdapter->PortCfg.BssType = BSS_INDEP;
     else //Default Infrastructure mode
         pAdapter->PortCfg.BssType = BSS_INFRA;
-    
+
     // Reset Ralink supplicant to not use, it will be set to start when UI set PMK key
     pAdapter->PortCfg.WpaState = SS_NOTUSE;
 
@@ -3321,7 +3403,7 @@
     return TRUE;
 }
 
-/* 
+/*
     ==========================================================================
     Description:
         Set Authentication mode
@@ -3330,7 +3412,7 @@
     ==========================================================================
 */
 INT Set_AuthMode_Proc(
-    IN  PRTMP_ADAPTER   pAdapter, 
+    IN  PRTMP_ADAPTER   pAdapter,
     IN  PUCHAR          arg)
 {
     if ((strcmp(arg, "OPEN") == 0) || (strcmp(arg, "open") == 0))
@@ -3344,7 +3426,7 @@
     else if ((strcmp(arg, "WPANONE") == 0) || (strcmp(arg, "wpanone") == 0))
         pAdapter->PortCfg.AuthMode = Ndis802_11AuthModeWPANone;
     else
-        return FALSE;  
+        return FALSE;
 
     pAdapter->PortCfg.PortSecured = WPA_802_1X_PORT_NOT_SECURED;
 
@@ -3353,7 +3435,7 @@
     return TRUE;
 }
 
-/* 
+/*
     ==========================================================================
     Description:
         Set Encryption Type
@@ -3362,7 +3444,7 @@
     ==========================================================================
 */
 INT Set_EncrypType_Proc(
-    IN  PRTMP_ADAPTER   pAdapter, 
+    IN  PRTMP_ADAPTER   pAdapter,
     IN  PUCHAR          arg)
 {
     if ((strcmp(arg, "NONE") == 0) || (strcmp(arg, "none") == 0))
@@ -3380,7 +3462,7 @@
 
     return TRUE;
 }
-/* 
+/*
     ==========================================================================
     Description:
         Set Default Key ID
@@ -3389,24 +3471,24 @@
     ==========================================================================
 */
 INT Set_DefaultKeyID_Proc(
-    IN  PRTMP_ADAPTER   pAdapter, 
+    IN  PRTMP_ADAPTER   pAdapter,
     IN  PUCHAR          arg)
 {
     ULONG                               KeyIdx;
-    
-    printk("'iwpriv <dev> set DefaultKeyID' is deprecated, please use 'iwconfg <dev> key' instead\n"); 
-    
+
+    printk("'iwpriv <dev> set DefaultKeyID' is deprecated, please use 'iwconfg <dev> key' instead\n");
+
     KeyIdx = simple_strtol(arg, 0, 10);
     if((KeyIdx >= 1 ) && (KeyIdx <= 4))
         pAdapter->PortCfg.DefaultKeyId = (UCHAR) (KeyIdx - 1 );
     else
-        return FALSE;  //Invalid argument 
+        return FALSE;  //Invalid argument
 
     DBGPRINT(RT_DEBUG_TRACE, "Set_DefaultKeyID_Proc::(DefaultKeyID=%d)\n", pAdapter->PortCfg.DefaultKeyId);
 
     return TRUE;
 }
-/* 
+/*
     ==========================================================================
     Description:
         Set WEP KEY1
@@ -3415,22 +3497,22 @@
     ==========================================================================
 */
 INT Set_Key1_Proc(
-    IN  PRTMP_ADAPTER   pAdapter, 
+    IN  PRTMP_ADAPTER   pAdapter,
     IN  PUCHAR          arg)
 {
     int                                 KeyLen;
     int                                 i;
 
-    printk("'iwpriv <dev> set Key1' is deprecated, please use 'iwconfg <dev> key [1] ' instead\n"); 
-   
+    printk("'iwpriv <dev> set Key1' is deprecated, please use 'iwconfg <dev> key [1] ' instead\n");
+
     KeyLen = strlen(arg);
 
     switch (KeyLen)
     {
         case 5: //wep 40 Ascii type
             pAdapter->PortCfg.SharedKey[0].KeyLen = KeyLen;
-            memcpy(pAdapter->PortCfg.SharedKey[0].Key, arg, KeyLen);    
-            DBGPRINT(RT_DEBUG_TRACE, "Set_Key1_Proc::(Key1=%s and type=%s)\n", arg, "Ascii");       
+            memcpy(pAdapter->PortCfg.SharedKey[0].Key, arg, KeyLen);
+            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++)
@@ -3440,12 +3522,12 @@
             }
             pAdapter->PortCfg.SharedKey[0].KeyLen = KeyLen / 2 ;
             AtoH(arg, pAdapter->PortCfg.SharedKey[0].Key, KeyLen / 2);
-            DBGPRINT(RT_DEBUG_TRACE, "Set_Key1_Proc::(Key1=%s and type=%s)\n", arg, "Hex");     
+            DBGPRINT(RT_DEBUG_TRACE, "Set_Key1_Proc::(Key1=%s and type=%s)\n", arg, "Hex");
             break;
         case 13: //wep 104 Ascii type
             pAdapter->PortCfg.SharedKey[0].KeyLen = KeyLen;
-            memcpy(pAdapter->PortCfg.SharedKey[0].Key, arg, KeyLen);    
-            DBGPRINT(RT_DEBUG_TRACE, "Set_Key1_Proc::(Key1=%s and type=%s)\n", arg, "Ascii");       
+            memcpy(pAdapter->PortCfg.SharedKey[0].Key, arg, KeyLen);
+            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++)
@@ -3455,16 +3537,16 @@
             }
             pAdapter->PortCfg.SharedKey[0].KeyLen = KeyLen / 2 ;
             AtoH(arg, pAdapter->PortCfg.SharedKey[0].Key, KeyLen / 2);
-            DBGPRINT(RT_DEBUG_TRACE, "Set_Key1_Proc::(Key1=%s and type=%s)\n", arg, "Hex");     
+            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);       
+        default: //Invalid argument
+            DBGPRINT(RT_DEBUG_TRACE, "Set_Key1_Proc::Invalid argument (=%s)\n", arg);
             return FALSE;
     }
 
     return TRUE;
 }
-/* 
+/*
     ==========================================================================
     Description:
         Set WEP KEY2
@@ -3473,15 +3555,15 @@
     ==========================================================================
 */
 INT Set_Key2_Proc(
-    IN  PRTMP_ADAPTER   pAdapter, 
+    IN  PRTMP_ADAPTER   pAdapter,
     IN  PUCHAR          arg)
 {
     int                                 KeyLen;
     int                                 i;
 
-    printk("'iwpriv <dev> set Key2' is deprecated, please use 'iwconfg <dev> key [2] ' instead\n"); 
+    printk("'iwpriv <dev> set Key2' is deprecated, please use 'iwconfg <dev> key [2] ' instead\n");
+
 
-    
     KeyLen = strlen(arg);
 
     switch (KeyLen)
@@ -3503,7 +3585,7 @@
             break;
         case 13: //wep 104 Ascii type
             pAdapter->PortCfg.SharedKey[1].KeyLen = KeyLen;
-            memcpy(pAdapter->PortCfg.SharedKey[1].Key, arg, KeyLen);    
+            memcpy(pAdapter->PortCfg.SharedKey[1].Key, arg, KeyLen);
             DBGPRINT(RT_DEBUG_TRACE, "Set_Key2_Proc::(Key2=%s and type=%s)\n", arg, "Ascii");
             break;
         case 26: //wep 104 Hex type
@@ -3516,14 +3598,14 @@
             AtoH(arg, pAdapter->PortCfg.SharedKey[1].Key, KeyLen / 2);
             DBGPRINT(RT_DEBUG_TRACE, "Set_Key2_Proc::(Key2=%s and type=%s)\n", arg, "Hex");
             break;
-        default: //Invalid argument 
+        default: //Invalid argument
             DBGPRINT(RT_DEBUG_TRACE, "Set_Key2_Proc::Invalid argument (=%s)\n", arg);
             return FALSE;
     }
 
     return TRUE;
 }
-/* 
+/*
     ==========================================================================
     Description:
         Set WEP KEY3
@@ -3532,13 +3614,13 @@
     ==========================================================================
 */
 INT Set_Key3_Proc(
-    IN  PRTMP_ADAPTER   pAdapter, 
+    IN  PRTMP_ADAPTER   pAdapter,
     IN  PUCHAR          arg)
 {
     int                                 KeyLen;
     int                                 i;
 
-     printk("'iwpriv <dev> set Key3' is deprecated, please use 'iwconfg <dev> key [3] ' instead\n"); 
+     printk("'iwpriv <dev> set Key3' is deprecated, please use 'iwconfg <dev> key [3] ' instead\n");
 
     KeyLen = strlen(arg);
 
@@ -3574,14 +3656,14 @@
             AtoH(arg, pAdapter->PortCfg.SharedKey[2].Key, KeyLen / 2);
             DBGPRINT(RT_DEBUG_TRACE, "Set_Key3_Proc::(Key3=%s and type=%s)\n", arg, "Hex");
             break;
-        default: //Invalid argument 
+        default: //Invalid argument
             DBGPRINT(RT_DEBUG_TRACE, "Set_Key3_Proc::Invalid argument (=%s)\n", arg);
             return FALSE;
     }
 
     return TRUE;
 }
-/* 
+/*
     ==========================================================================
     Description:
         Set WEP KEY4
@@ -3590,21 +3672,21 @@
     ==========================================================================
 */
 INT Set_Key4_Proc(
-    IN  PRTMP_ADAPTER   pAdapter, 
+    IN  PRTMP_ADAPTER   pAdapter,
     IN  PUCHAR          arg)
 {
     int                                 KeyLen;
     int                                 i;
 
-    printk("'iwpriv <dev> set Key4' is deprecated, please use 'iwconfg <dev> key [4] ' instead\n"); 
-    
+    printk("'iwpriv <dev> set Key4' is deprecated, please use 'iwconfg <dev> key [4] ' instead\n");
+
     KeyLen = strlen(arg);
 
     switch (KeyLen)
     {
         case 5: //wep 40 Ascii type
             pAdapter->PortCfg.SharedKey[3].KeyLen = KeyLen;
-            memcpy(pAdapter->PortCfg.SharedKey[3].Key, arg, KeyLen);    
+            memcpy(pAdapter->PortCfg.SharedKey[3].Key, arg, KeyLen);
             DBGPRINT(RT_DEBUG_TRACE, "Set_Key4_Proc::(Key4=%s and type=%s)\n", arg, "Ascii");
             break;
         case 10: //wep 40 Hex type
@@ -3632,14 +3714,14 @@
             AtoH(arg, pAdapter->PortCfg.SharedKey[3].Key, KeyLen / 2);
             DBGPRINT(RT_DEBUG_TRACE, "Set_Key4_Proc::(Key4=%s and type=%s)\n", arg, "Hex");
             break;
-        default: //Invalid argument 
+        default: //Invalid argument
             DBGPRINT(RT_DEBUG_TRACE, "Set_Key4_Proc::Invalid argument (=%s)\n", arg);
             return FALSE;
     }
 
     return TRUE;
 }
-/* 
+/*
     ==========================================================================
     Description:
         Set WPA PSK key
@@ -3648,7 +3730,7 @@
     ==========================================================================
 */
 INT Set_WPAPSK_Proc(
-    IN  PRTMP_ADAPTER   pAdapter, 
+    IN  PRTMP_ADAPTER   pAdapter,
     IN  PUCHAR          arg)
 {
     UCHAR                               keyMaterial[40];
@@ -3670,16 +3752,16 @@
 
         memcpy(&pAdapter->PortCfg.PskKey.Key, &keyMaterial, 32);
     }
- 
+
     // Use RaConfig as PSK agent.
     // Start STA supplicant state machine
     pAdapter->PortCfg.WpaState = SS_START;
- 
+
     return TRUE;
 }
 
 
-/* 
+/*
     ==========================================================================
     Description:
         Set WPA NONE key
@@ -3689,7 +3771,7 @@
 */
 
 INT Set_WPANONE_Proc(
-    IN  PRTMP_ADAPTER   pAdapter, 
+    IN  PRTMP_ADAPTER   pAdapter,
     IN  PUCHAR          arg)
 {
     UCHAR               keyMaterial[40];
@@ -3700,17 +3782,17 @@
         DBGPRINT(RT_DEBUG_TRACE, "Set failed!!(WPANONE=%s), WPANONE key-string required 8 ~ 64 characters \n", arg);
         return FALSE;
     }
- 
+
     if (strlen(arg) == 64)
     {
-        AtoH(arg, pAdapter->PortCfg.PskKey.Key, 32);
+        AtoH(arg, keyMaterial, 32);
     }
     else
     {
     	PasswordHash((char *)arg, pAdapter->Mlme.CntlAux.Ssid, pAdapter->Mlme.CntlAux.SsidLen, keyMaterial);
-
-    	memcpy(pAdapter->PortCfg.PskKey.Key, keyMaterial, 32);
     }
+    memcpy(pAdapter->PortCfg.PskKey.Key, keyMaterial, 32);
+
     // Use RaConfig as PSK agent.
     // Start STA supplicant state machine
     pAdapter->PortCfg.WpaState = SS_START;
@@ -3718,7 +3800,7 @@
 //-----------------------------------------------------------------------------
 // pasted from "RTMPWPAAddKeyProc(...)"
 // major on Group Key only.
- 
+
     // Group Key
     {
         // 3. Set as default Tx Key if bTxKey is TRUE
@@ -3733,10 +3815,10 @@
 
         // 6. Copy information into Group Key structure.
         // pKey->KeyLength will include TxMic and RxMic, therefore, we use 16 bytes hardcoded.
-        pAdapter->PortCfg.GroupKey[0].KeyLen = 16;     
-        memcpy(pAdapter->PortCfg.GroupKey[0].Key,   (PUCHAR)(keyMaterial) +  0, 16);
-        memcpy(pAdapter->PortCfg.GroupKey[0].RxMic, (PUCHAR)(keyMaterial) + 16, 8);
-        memcpy(pAdapter->PortCfg.GroupKey[0].TxMic, (PUCHAR)(keyMaterial) + 16, 8);
+        pAdapter->PortCfg.GroupKey[0].KeyLen = 16;
+        memcpy(pAdapter->PortCfg.GroupKey[0].Key,   &keyMaterial[0], 16);
+        memcpy(pAdapter->PortCfg.GroupKey[0].RxMic, &keyMaterial[16], 8);
+        memcpy(pAdapter->PortCfg.GroupKey[0].TxMic, &keyMaterial[16], 8);
         memcpy(pAdapter->PortCfg.GroupKey[0].BssId, &pAdapter->PortCfg.Bssid, 6);
 
         // Init TxTsc to one based on WiFi WPA specs
@@ -3754,7 +3836,7 @@
     return TRUE;
 }
 
-/* 
+/*
     ==========================================================================
     Description:
         Read / Write BBP
@@ -3766,7 +3848,7 @@
         None
 
     Note:
-        Usage: 
+        Usage:
                1.) iwpriv ra0 bbp               ==> read all BBP
                2.) iwpriv ra0 bbp 1,2,10,32     ==> raed BBP where ID=1,2,10,32
                3.) iwpriv ra0 bbp 1=10,17=3E    ==> write BBP R1=0x10, R17=0x3E
@@ -3887,9 +3969,9 @@
     kfree(arg);
 }
 
-int RTMPIoctlRFMONTX(
+int RTMPIoctlSetRFMONTX(
     IN PRTMP_ADAPTER   pAdapter,
-    IN OUT struct iwreq    *wrq)
+    IN struct iwreq    *wrq)
 {
     char		*pvalue;
     char		value;
@@ -3898,7 +3980,7 @@
     {
 	pvalue = wrq->u.data.pointer;
 	value = *pvalue;
-	
+
         if (value == 1)
         {
            pAdapter->PortCfg.MallowRFMONTx = TRUE;
@@ -3912,18 +3994,19 @@
         else return -EINVAL;
     }
 
-    /* Display the state. Use "value" to indicate it. */
-    value = pAdapter->PortCfg.MallowRFMONTx == TRUE ? '1'
-                                                    : '0';
-    wrq->u.data.length = sizeof (char);
-
-    if (copy_to_user (wrq->u.data.pointer, &value, wrq->u.data.length))
-        DBGPRINT (RT_DEBUG_ERROR, "RTMPIoctlRFMONTX - copy to user failure.\n");
+    return 0;
+}
 
+int RTMPIoctlGetRFMONTX(
+    IN PRTMP_ADAPTER   pAdapter,
+    OUT struct iwreq    *wrq)
+{
+    *(int *) wrq->u.name = pAdapter->PortCfg.MallowRFMONTx == TRUE ? 1 : 0;
     return 0;
+
 }
 
-/* 
+/*
     ==========================================================================
     Description:
         Read / Write MAC
@@ -3935,13 +4018,13 @@
         None
 
     Note:
-        Usage: 
+        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  PRTMP_ADAPTER   pAdapter,
     IN  struct iwreq    *wrq)
 {
     char                *this_char;
@@ -3996,7 +4079,7 @@
                 {
                     this_char[4-k+j] = this_char[j];
                 }
-                
+
                 while(k < 4)
                     this_char[3-k++]='0';
                 this_char[4]='\0';
@@ -4061,7 +4144,7 @@
                 {
                     temp2[8-k+j] = temp2[j];
                 }
-                
+
                 while(k < 8)
                     temp2[7-k++]='0';
                 temp2[8]='\0';
@@ -4074,7 +4157,7 @@
                     macValue = *temp*256*256*256 + temp[1]*256*256 + temp[2]*256 + temp[3];
 
                     DBGPRINT(RT_DEBUG_TRACE, "macAddr=%02x, macValue=0x%x\n", macAddr, macValue);
-                    
+
                     RTMP_IO_WRITE32(pAdapter, macAddr, macValue);
                     sprintf(msg+strlen(msg), "[0x%02X]:%02X  ", macAddr, macValue);
                     count++;
@@ -4093,7 +4176,7 @@
     wrq->u.data.length = strlen(msg);
     if(copy_to_user(wrq->u.data.pointer, msg, wrq->u.data.length))
     		DBGPRINT(RT_DEBUG_ERROR, "RTMPIoctlMAC - copy to user failure.\n");
-    
+
     DBGPRINT(RT_DEBUG_TRACE, "<==RTMPIoctlMAC\n");
 
    kfree(msg);
@@ -4102,7 +4185,7 @@
 
 #ifdef RALINK_ATE
 
-/* 
+/*
     ==========================================================================
     Description:
         Read / Write E2PROM
@@ -4114,13 +4197,13 @@
         None
 
     Note:
-        Usage: 
+        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	PRTMP_ADAPTER	pAdapter,
 	IN	struct iwreq	*wrq)
 {
 	char				*this_char;
@@ -4136,7 +4219,7 @@
 
 	msg = kmalloc(1024, GFP_KERNEL);
 	arg = kmalloc(255, GFP_KERNEL);
-	
+
 	DBGPRINT(RT_DEBUG_TRACE, "==>RTMPIoctlE2PROM\n");
 	memset(msg, 0x00, 1024);
 	memset(arg, 0x00, 255);
@@ -4178,7 +4261,7 @@
 				{
 					this_char[4-k+j] = this_char[j];
 				}
-				
+
 				while(k < 4)
 					this_char[3-k++]='0';
 				this_char[4]='\0';
@@ -4186,7 +4269,7 @@
 				if(strlen(this_char) == 4)
 				{
 					AtoH(this_char, temp, 4);
-					eepAddr = *temp*256 + temp[1];					
+					eepAddr = *temp*256 + temp[1];
 					if (eepAddr < 0xFFFF)
 					{
 						eepValue = RTMP_EEPROM_READ16(pAdapter, eepAddr);
@@ -4243,7 +4326,7 @@
 				{
 					temp2[4-k+j] = temp2[j];
 				}
-				
+
 				while(k < 4)
 					temp2[3-k++]='0';
 				temp2[4]='\0';
@@ -4255,7 +4338,7 @@
 				eepValue = *temp*256 + temp[1];
 
 				DBGPRINT(RT_DEBUG_TRACE, "eepAddr=%02x, eepValue=0x%x\n", eepAddr, eepValue);
-				
+
 				RTMP_EEPROM_WRITE16(pAdapter, eepAddr, eepValue);
 				sprintf(msg+strlen(msg), "[0x%02X]:%02X  ", eepAddr, eepValue);
 				count++;
@@ -4269,18 +4352,19 @@
 	if(strlen(msg) == 1)
 		sprintf(msg+strlen(msg), "===>Error command format!");
 
-        // Copy the information into the user buffer	
-        DBGPRINT(RT_DEBUG_TRACE, "copy to user [msg=%s]\n", *msg);	
+        // Copy the information into the user buffer
+        DBGPRINT(RT_DEBUG_TRACE, "copy to user [msg=%s]\n", *msg);
 	wrq->u.data.length = strlen(msg);
-	copy_to_user(wrq->u.data.pointer, msg, wrq->u.data.length);
-	
+	if (copy_to_user(wrq->u.data.pointer, msg, wrq->u.data.length))
+    		DBGPRINT(RT_DEBUG_ERROR, "RTMPIoctlE2PROM - copy to user failure.\n");
+
 	DBGPRINT(RT_DEBUG_TRACE, "<==RTMPIoctlE2PROM\n");
 
 	kfree(msg);
 	kfree(arg);
 }
 
-UCHAR TempletFrame[24] = {0x08,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 
+UCHAR TempletFrame[24] = {0x08,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
 
 /*
     ==========================================================================
@@ -4297,7 +4381,7 @@
     ==========================================================================
 */
 INT	Set_ATE_Proc(
-	IN	PRTMP_ADAPTER	pAdapter, 
+	IN	PRTMP_ADAPTER	pAdapter,
 	IN	PUCHAR			arg)
 {
 	USHORT			BbpData;
@@ -4305,7 +4389,7 @@
 	PTXD_STRUC		pTxD;
 	PUCHAR			pDest;
 	UINT			i, j;
-	
+
 	DBGPRINT(RT_DEBUG_TRACE, "==> Set_ATE_Proc (arg = %s)\n", arg);
 
 	mdelay(5);
@@ -4321,8 +4405,8 @@
 	BbpData = 0;
 	MacData &= 0xFBFFFFFF;
 
-	if (!strcmp(arg, "STASTOP")) 
-	{						
+	if (!strcmp(arg, "STASTOP"))
+	{
 		DBGPRINT(RT_DEBUG_TRACE, "ATE: STASTOP\n");
 
 		RTMP_IO_WRITE32(pAdapter, MACCSR1, MacData);
@@ -4333,11 +4417,11 @@
         LinkDown(pAdapter);
 		AsicEnableBssSync(pAdapter);
 		netif_stop_queue(pAdapter->net_dev);
-   		RTMPStationStop(pAdapter);		
+   		RTMPStationStop(pAdapter);
 		RTMP_IO_WRITE32(pAdapter, RXCSR0, 0xffffffff);	// Stop Rx
 	}
-	else if (!strcmp(arg, "STASTART")) 
-	{						
+	else if (!strcmp(arg, "STASTART"))
+	{
 		DBGPRINT(RT_DEBUG_TRACE, "ATE: STASTART\n");
 
 		RTMP_IO_WRITE32(pAdapter, MACCSR1, MacData);
@@ -4350,9 +4434,9 @@
 		RTMPStationStart(pAdapter);
 	}
 	else if (!strcmp(arg, "TXCONT")) 		// Continuous Tx
-	{						
+	{
 		DBGPRINT(RT_DEBUG_TRACE, "ATE: TXCONT\n");
-		
+
 		pAdapter->ate.Mode = ATE_TXCONT;
 
 		BbpData |= 0x80;
@@ -4427,7 +4511,7 @@
 		RTMP_IO_WRITE32(pAdapter, SECCSR1, 0x1);
 	}
 	else if (!strcmp(arg, "TXFRAME"))			// Tx Frames --------------------------------------
-	{						
+	{
 		DBGPRINT(RT_DEBUG_TRACE, "ATE: TXFRAME(Count=%d)\n", pAdapter->ate.TxCount);
 		pAdapter->ate.Mode = ATE_TXFRAME;
 
@@ -4435,7 +4519,7 @@
 		RTMP_BBP_IO_WRITE32_BY_REG_ID(pAdapter, 63, BbpData);
 
 		pAdapter->ate.TxDoneCount = 0;
-		
+
 		for (i = 0; (i < TX_RING_SIZE) && (i < pAdapter->ate.TxCount); i++)
 		{
 			pTxD = (PTXD_STRUC)pAdapter->TxRing[pAdapter->CurEncryptIndex].va_addr;
@@ -4467,7 +4551,7 @@
 		RTMP_IO_WRITE32(pAdapter, SECCSR1, 0x1);
 	}
 	else if (!strcmp(arg, "RXFRAME")) 			// Rx Frames --------------------------------------
-	{						
+	{
 		DBGPRINT(RT_DEBUG_TRACE, "ATE: RXFRAME\n");
 
 		RTMP_IO_WRITE32(pAdapter, MACCSR1, MacData);
@@ -4475,23 +4559,23 @@
 
 		pAdapter->ate.Mode = ATE_RXFRAME;
 		pAdapter->ate.TxDoneCount = pAdapter->ate.TxCount;
-		
+
 		RTMP_IO_WRITE32(pAdapter, TXCSR0, 0x08);		// Abort Tx
 		RTMP_IO_WRITE32(pAdapter, RXCSR0, 0x56);		// Start Rx
 	}
 	else
-	{	
+	{
 		DBGPRINT(RT_DEBUG_TRACE, "ATE:	Invalid arg!\n");
 		return FALSE;
 	}
 
 	mdelay(5);
-	
+
 	DBGPRINT(RT_DEBUG_TRACE, "<== Set_ATE_Proc\n");
 	return TRUE;
 }
 
-/* 
+/*
     ==========================================================================
     Description:
         Set ATE ADDR1=DA for TxFrames    Return:
@@ -4499,21 +4583,21 @@
     ==========================================================================
 */
 INT	Set_ATE_DA_Proc(
-	IN	PRTMP_ADAPTER	pAdapter, 
+	IN	PRTMP_ADAPTER	pAdapter,
 	IN	PUCHAR			arg)
 {
 	char				*value;
 	int					i;
-	
+
 	DBGPRINT(RT_DEBUG_TRACE, "==> Set_ATE_DA_Proc\n");
 	DBGPRINT(RT_DEBUG_TRACE, "arg=%s\n", arg);
-	
+
 	if(strlen(arg) != 17)  //Mac address acceptable format 01:02:03:04:05:06 length 17
 		return FALSE;
 
-    for (i=0, value = strtok(arg,":"); value; value = strtok(NULL,":")) 
+    for (i=0, value = strtok(arg,":"); value; value = strtok(NULL,":"))
 	{
-		if((strlen(value) != 2) || (!isxdigit(*value)) || (!isxdigit(*(value+1))) ) 
+		if((strlen(value) != 2) || (!isxdigit(*value)) || (!isxdigit(*(value+1))) )
 			return FALSE;  //Invalid
 
 		AtoH(value, &pAdapter->ate.Addr1[i++], 2);
@@ -4521,14 +4605,14 @@
 
 	if(i != 6)
 		return FALSE;  //Invalid
-		
+
 	DBGPRINT(RT_DEBUG_TRACE, "DA=%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]);
 	DBGPRINT(RT_DEBUG_TRACE, "<== Set_ATE_DA_Proc\n");
-	
+
 	return TRUE;
 }
 
-/* 
+/*
     ==========================================================================
     Description:
         Set ATE ADDR2=SA for TxFrames    Return:
@@ -4536,21 +4620,21 @@
     ==========================================================================
 */
 INT	Set_ATE_SA_Proc(
-	IN	PRTMP_ADAPTER	pAdapter, 
+	IN	PRTMP_ADAPTER	pAdapter,
 	IN	PUCHAR			arg)
 {
 	char				*value;
 	int					i;
-	
+
 	DBGPRINT(RT_DEBUG_TRACE, "==> Set_ATE_SA_Proc\n");
 	DBGPRINT(RT_DEBUG_TRACE, "arg=%s\n", arg);
-	
+
 	if(strlen(arg) != 17)  //Mac address acceptable format 01:02:03:04:05:06 length 17
 		return FALSE;
 
-    for (i=0, value = strtok(arg,":"); value; value = strtok(NULL,":")) 
+    for (i=0, value = strtok(arg,":"); value; value = strtok(NULL,":"))
 	{
-		if((strlen(value) != 2) || (!isxdigit(*value)) || (!isxdigit(*(value+1))) ) 
+		if((strlen(value) != 2) || (!isxdigit(*value)) || (!isxdigit(*(value+1))) )
 			return FALSE;  //Invalid
 
 		AtoH(value, &pAdapter->ate.Addr2[i++], 2);
@@ -4561,11 +4645,11 @@
 
 	DBGPRINT(RT_DEBUG_TRACE, "DA=%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]);
 	DBGPRINT(RT_DEBUG_TRACE, "<== Set_ATE_SA_Proc\n");
-	
+
 	return TRUE;
 }
 
-/* 
+/*
     ==========================================================================
     Description:
         Set ATE ADDR3=BSSID for TxFrames    Return:
@@ -4573,21 +4657,21 @@
     ==========================================================================
 */
 INT	Set_ATE_BSSID_Proc(
-	IN	PRTMP_ADAPTER	pAdapter, 
+	IN	PRTMP_ADAPTER	pAdapter,
 	IN	PUCHAR			arg)
 {
 	char				*value;
 	int					i;
-	
+
 	DBGPRINT(RT_DEBUG_TRACE, "==> Set_ATE_BSSID_Proc\n");
 	DBGPRINT(RT_DEBUG_TRACE, "arg=%s\n", arg);
-	
+
 	if(strlen(arg) != 17)  //Mac address acceptable format 01:02:03:04:05:06 length 17
 		return FALSE;
 
-    for (i=0, value = strtok(arg,":"); value; value = strtok(NULL,":")) 
+    for (i=0, value = strtok(arg,":"); value; value = strtok(NULL,":"))
 	{
-		if((strlen(value) != 2) || (!isxdigit(*value)) || (!isxdigit(*(value+1))) ) 
+		if((strlen(value) != 2) || (!isxdigit(*value)) || (!isxdigit(*(value+1))) )
 			return FALSE;  //Invalid
 
 		AtoH(value, &pAdapter->ate.Addr3[i++], 2);
@@ -4598,11 +4682,11 @@
 
 	DBGPRINT(RT_DEBUG_TRACE, "DA=%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]);
 	DBGPRINT(RT_DEBUG_TRACE, "<== Set_ATE_BSSID_Proc\n");
-	
+
 	return TRUE;
 }
 
-/* 
+/*
     ==========================================================================
     Description:
         Set ATE Channel    Return:
@@ -4610,11 +4694,11 @@
     ==========================================================================
 */
 INT	Set_ATE_CHANNEL_Proc(
-	IN	PRTMP_ADAPTER	pAdapter, 
+	IN	PRTMP_ADAPTER	pAdapter,
 	IN	PUCHAR			arg)
 {
 	DBGPRINT(RT_DEBUG_TRACE, "==> Set_ATE_CHANNEL_Proc (arg = %s)\n", arg);
-	
+
 	pAdapter->ate.Channel = simple_strtol(arg, 0, 10);
 	if((pAdapter->ate.Channel < 1) || (pAdapter->ate.Channel > 14))
 	{
@@ -4623,11 +4707,11 @@
 	}
 
 	DBGPRINT(RT_DEBUG_TRACE, "<== Set_ATE_CHANNEL_Proc (ATE Channel = %d)\n", pAdapter->ate.Channel);
-	
+
 	return TRUE;
 }
 
-/* 
+/*
     ==========================================================================
     Description:
         Set ATE Tx Power    Return:
@@ -4635,14 +4719,14 @@
     ==========================================================================
 */
 INT	Set_ATE_TX_POWER_Proc(
-	IN	PRTMP_ADAPTER	pAdapter, 
+	IN	PRTMP_ADAPTER	pAdapter,
 	IN	PUCHAR			arg)
 {
 	ULONG R3;
-	
+
 	DBGPRINT(RT_DEBUG_TRACE, "==> Set_ATE_TX_POWER_Proc\n");
 	DBGPRINT(RT_DEBUG_TRACE, "arg=%s\n", arg);
-	
+
 	pAdapter->ate.TxPower = simple_strtol(arg, 0, 10);
 
 	if(pAdapter->ate.TxPower >= 32)
@@ -4659,11 +4743,11 @@
 
 	DBGPRINT(RT_DEBUG_TRACE, "TxPower = %d\n", pAdapter->ate.TxPower);
 	DBGPRINT(RT_DEBUG_TRACE, "<== Set_ATE_TX_POWER_Proc\n");
-	
+
 	return TRUE;
 }
 
-/* 
+/*
     ==========================================================================
     Description:
         Set ATE Tx Length    Return:
@@ -4671,12 +4755,12 @@
     ==========================================================================
 */
 INT	Set_ATE_TX_LENGTH_Proc(
-	IN	PRTMP_ADAPTER	pAdapter, 
+	IN	PRTMP_ADAPTER	pAdapter,
 	IN	PUCHAR			arg)
 {
 	DBGPRINT(RT_DEBUG_TRACE, "==> Set_ATE_TX_LENGTH_Proc\n");
 	DBGPRINT(RT_DEBUG_TRACE, "arg=%s\n", arg);
-	
+
 	pAdapter->ate.TxLength = simple_strtol(arg, 0, 10);
 
 	if((pAdapter->ate.TxLength < 24) || (pAdapter->ate.TxLength > 1500))
@@ -4687,11 +4771,11 @@
 
 	DBGPRINT(RT_DEBUG_TRACE, "TxLength = %d\n", pAdapter->ate.TxLength);
 	DBGPRINT(RT_DEBUG_TRACE, "<== Set_ATE_TX_LENGTH_Proc\n");
-	
+
 	return TRUE;
 }
 
-/* 
+/*
     ==========================================================================
     Description:
         Set ATE Tx Count    Return:
@@ -4699,21 +4783,21 @@
     ==========================================================================
 */
 INT	Set_ATE_TX_COUNT_Proc(
-	IN	PRTMP_ADAPTER	pAdapter, 
+	IN	PRTMP_ADAPTER	pAdapter,
 	IN	PUCHAR			arg)
 {
 	DBGPRINT(RT_DEBUG_TRACE, "==> Set_ATE_TX_COUNT_Proc\n");
 	DBGPRINT(RT_DEBUG_TRACE, "arg=%s\n", arg);
-	
+
 	pAdapter->ate.TxCount = simple_strtol(arg, 0, 10);
 
 	DBGPRINT(RT_DEBUG_TRACE, "TxCount = %d\n", pAdapter->ate.TxCount);
 	DBGPRINT(RT_DEBUG_TRACE, "<== Set_ATE_TX_COUNT_Proc\n");
-	
+
 	return TRUE;
 }
 
-/* 
+/*
     ==========================================================================
     Description:
         Set ATE Tx Rate
@@ -4722,12 +4806,12 @@
     ==========================================================================
 */
 INT	Set_ATE_TX_RATE_Proc(
-	IN	PRTMP_ADAPTER	pAdapter, 
+	IN	PRTMP_ADAPTER	pAdapter,
 	IN	PUCHAR			arg)
 {
 	DBGPRINT(RT_DEBUG_TRACE, "==> Set_ATE_TX_RATE_Proc\n");
 	DBGPRINT(RT_DEBUG_TRACE, "arg=%s\n", arg);
-	
+
 	pAdapter->ate.TxRate = simple_strtol(arg, 0, 10);
 
 	if(pAdapter->ate.TxRate > RATE_54)
@@ -4738,7 +4822,7 @@
 
 	DBGPRINT(RT_DEBUG_TRACE, "TxRate = %d\n", pAdapter->ate.TxRate);
 	DBGPRINT(RT_DEBUG_TRACE, "<== Set_ATE_TX_RATE_Proc\n");
-	
+
 	return TRUE;
 }
 
@@ -4758,7 +4842,7 @@
     RTMPCancelTimer(&pAd->PortCfg.RfTuningTimer);
     if (pAd->PortCfg.LedMode == LED_MODE_TXRX_ACTIVITY)
         RTMPCancelTimer(&pAd->PortCfg.LedCntl.BlinkTimer);
-    RTMPCancelTimer(&pAd->PortCfg.RxAnt.RxAntDiversityTimer);	
+    RTMPCancelTimer(&pAd->PortCfg.RxAnt.RxAntDiversityTimer);
     DBGPRINT(RT_DEBUG_TRACE, "<== RTMPStationStop\n");
 }
 
diff -Nur rt2500-1.1.0-b4/Module/rtmp_init.c rt2500-cvs-2007061011/Module/rtmp_init.c
--- rt2500-1.1.0-b4/Module/rtmp_init.c	2006-06-17 22:12:58.000000000 +0200
+++ rt2500-cvs-2007061011/Module/rtmp_init.c	2007-05-06 11:13:43.000000000 +0200
@@ -1,40 +1,40 @@
-/*************************************************************************** 
- * RT2400/RT2500 SourceForge Project - http://rt2x00.serialmonkey.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.                          * 
- *                                                                         * 
- *   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.             * 
- *                                                                         * 
- *   Licensed under the GNU GPL                                            * 
- *   Original code supplied under license from RaLink Inc, 2004.           * 
- ***************************************************************************/ 
+/***************************************************************************
+ * RT2400/RT2500 SourceForge Project - http://rt2x00.serialmonkey.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.                          *
+ *                                                                         *
+ *   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.             *
+ *                                                                         *
+ *   Licensed under the GNU GPL                                            *
+ *   Original code supplied under license from RaLink Inc, 2004.           *
+ ***************************************************************************/
 
- /*************************************************************************** 
+ /***************************************************************************
  *      Module Name: rtmp_init.c
- *              
- *      Abstract: 
- *              
- *      Revision History: 
- *      Who             When            What 
- *      --------        -----------     ----------------------------- 
- *      PaulL           1st  Aug 02     Initial code     
- *      MarkW           8th  Dec 04     Baseline code  
+ *
+ *      Abstract:
+ *
+ *      Revision History:
+ *      Who             When            What
+ *      --------        -----------     -----------------------------
+ *      PaulL           1st  Aug 02     Initial code
+ *      MarkW           8th  Dec 04     Baseline code
  *      MarkW (rt2400)  8th  Dec 04     Promisc mode support
  *      MarkW           10th Dec 04     Rolled in Ralink 1.4.5.0
  *      LuisCorreia     15th Feb 05     Added Yann's patch for radio hw
  *      MarkW           12th Jul 05     Disabled all but CAM Power modes
- ***************************************************************************/ 
+ ***************************************************************************/
 
 #include    "rt_config.h"
 
@@ -84,9 +84,9 @@
 //  {PSCSR2,    0x00023f20},            // 0xd0
     {PSCSR2,    0x00020002},        // 0xd0
     {PSCSR3,    0x00000002},            // 0xd4
-    {TIMECSR,   0x00003f21},        // 0xDC, to slower down our 1-us tick 
+    {TIMECSR,   0x00003f21},        // 0xDC, to slower down our 1-us tick
     {CSR9,      0x00000780},        // 0x24
-    {CSR11,     0x07041483},        // 0x2C, lrc=7, src=4, slot=20us, CWmax=2^8, CWmax=2^3  
+    {CSR11,     0x07041483},        // 0x2C, lrc=7, src=4, slot=20us, CWmax=2^8, CWmax=2^3
     {CSR18,     0x00140000},        // SIFS=10us - TR switch time, PIFS=SIFS+20us
     {CSR19,     0x016C0028},        // DIFS=SIFS+2*20us, EIFS=364us
     {CNT3,      0x00000000},        // Backoff_CCA_Th, RX_&_TX_CCA_Th
@@ -105,17 +105,17 @@
     {ARTCSR1,   0x1d21252d},        // 0x150, alexsu : OFDM ACK/CTS payload consumed time for 18/12/9/6 mbps
     {ARTCSR2,   0x1919191d},        // 0x154, alexsu : OFDM ACK/CTS payload consumed time for 54/48/36/24 mbps
 
-    {RXCSR0,    0xffffffff},        // 0x80 
+    {RXCSR0,    0xffffffff},        // 0x80
     {RXCSR3,    0xb3aab3af},        // 0x90. RT2530 BBP 51:RSSI, R42:OFDM rate, R47:CCK SIGNAL
     {PCICSR,    0x000003b8},        // 0x8c, alexsu : PCI control register
     {PWRCSR0,   0x3f3b3100},            // 0xC4
     {GPIOCSR,   0x0000ff00},		// 0x120, GPIO default value
 	{TESTCSR,	0x000000f0},		// 0x138, Test CSR, make sure it's running at normal mode
-    {PWRCSR1,   0x000001ff},            // 0xd8     
+    {PWRCSR1,   0x000001ff},            // 0xd8
     {MACCSR0,   0x00213223},        // 0xE0, Enable Tx dribble mode - 2003/10/22:Gary
     {MACCSR1,   0x00235518},            // 0xE4, Disable Rx Reset, tx dribble count, 2x30x16 = 960n,
     {MACCSR2,   0x00000040},            // 0x0134, 64*33ns = 2us
-    {RALINKCSR, 0x9a009a11},            // 0xE8 
+    {RALINKCSR, 0x9a009a11},            // 0xE8
     {CSR7,      0xffffffff},            // 0x1C, Clear all pending interrupt source
     {LEDCSR,    0x00001E46},        // default both LEDs off
     {BBPCSR1,   0x82188200},        // for 2560+2522
@@ -155,7 +155,7 @@
 
     DBGPRINT(RT_DEBUG_INFO, "--> RTMPAllocDMAMemory\n");
 
-    // 1. Allocate Tx Ring DMA descriptor and buffer memory 
+    // 1. Allocate Tx Ring DMA descriptor and buffer memory
     // Allocate Ring descriptors DMA block
     ring = pci_alloc_consistent(pAd->pPci_Dev, (TX_RING_SIZE * RING_DESCRIPTOR_SIZE), &ring_dma);
     if (!ring) {
@@ -165,14 +165,14 @@
 
     // Zero init ring descriptors
     memset(ring, 0, (TX_RING_SIZE * RING_DESCRIPTOR_SIZE));
-    
+
     // Allocate Ring data DMA blocks
     ring_data = pci_alloc_consistent(pAd->pPci_Dev, (TX_RING_SIZE * TX_BUFFER_SIZE), &ring_data_dma);
-    
+
     // If failed, release ring descriptors DMA block & exit
     if (!ring_data) {
         pci_free_consistent(pAd->pPci_Dev, (TX_RING_SIZE * RING_DESCRIPTOR_SIZE), ring, ring_dma);
-        printk(KERN_ERR DRV_NAME "Could not allocate DMA ring buffer memory.\n");       
+        printk(KERN_ERR DRV_NAME "Could not allocate DMA ring buffer memory.\n");
         goto err_out_allocate_txring;
     }
 
@@ -185,7 +185,7 @@
         pAd->TxRing[index].pa_addr = ring_dma;
         ring     += RING_DESCRIPTOR_SIZE;
         ring_dma += RING_DESCRIPTOR_SIZE;
-        
+
         // Init Tx DMA buffer
         pAd->TxRing[index].data_size = TX_BUFFER_SIZE;
         pAd->TxRing[index].va_data_addr = ring_data;
@@ -207,7 +207,7 @@
             index, (unsigned long)pAd->TxRing[index].va_data_addr, (UINT)pAd->TxRing[index].pa_data_addr, pAd->TxRing[index].data_size);
     }
 
-    // 2. Allocate Prio Ring DMA descriptor and buffer memory 
+    // 2. Allocate Prio Ring DMA descriptor and buffer memory
     // Allocate Ring descriptors DMA block
     ring = pci_alloc_consistent(pAd->pPci_Dev, (PRIO_RING_SIZE * RING_DESCRIPTOR_SIZE), &ring_dma);
     if (!ring) {
@@ -224,7 +224,7 @@
     // If failed, release ring descriptors DMA block & exit
     if (!ring_data) {
         pci_free_consistent(pAd->pPci_Dev, (PRIO_RING_SIZE * RING_DESCRIPTOR_SIZE), ring, ring_dma);
-        DBGPRINT(RT_DEBUG_ERROR, "Could not allocate DMA ring buffer memory.\n");       
+        DBGPRINT(RT_DEBUG_ERROR, "Could not allocate DMA ring buffer memory.\n");
         goto err_out_allocate_prioring;
     }
 
@@ -259,7 +259,7 @@
             index, (unsigned long)pAd->PrioRing[index].va_data_addr, (UINT)pAd->PrioRing[index].pa_data_addr, pAd->PrioRing[index].data_size);
     }
 
-    // 3. Allocate Atim Ring DMA descriptor and buffer memory 
+    // 3. Allocate Atim Ring DMA descriptor and buffer memory
     // Allocate Ring descriptors DMA block
     ring = pci_alloc_consistent(pAd->pPci_Dev, (ATIM_RING_SIZE * RING_DESCRIPTOR_SIZE), &ring_dma);
     if (!ring) {
@@ -276,7 +276,7 @@
     // If failed, release ring descriptors DMA block & exit
     if (!ring_data) {
         pci_free_consistent(pAd->pPci_Dev, (ATIM_RING_SIZE * RING_DESCRIPTOR_SIZE), ring, ring_dma);
-        DBGPRINT(RT_DEBUG_ERROR, "Could not allocate DMA ring buffer memory.\n");       
+        DBGPRINT(RT_DEBUG_ERROR, "Could not allocate DMA ring buffer memory.\n");
         goto err_out_allocate_atimring;
     }
 
@@ -328,7 +328,7 @@
     // If failed, release ring descriptors DMA block & exit
     if (!ring_data) {
         pci_free_consistent(pAd->pPci_Dev, (RX_RING_SIZE * RING_DESCRIPTOR_SIZE), ring, ring_dma);
-        DBGPRINT(RT_DEBUG_ERROR, "Could not allocate DMA ring buffer memory.\n");       
+        DBGPRINT(RT_DEBUG_ERROR, "Could not allocate DMA ring buffer memory.\n");
         goto err_out_allocate_rxring;
     }
 
@@ -386,7 +386,7 @@
     // If failed, release ring descriptors DMA block & exit
     if (!ring_data) {
         pci_free_consistent(pAd->pPci_Dev, RING_DESCRIPTOR_SIZE, ring, ring_dma);
-        DBGPRINT(RT_DEBUG_ERROR, "Could not allocate DMA ring buffer memory.\n");       
+        DBGPRINT(RT_DEBUG_ERROR, "Could not allocate DMA ring buffer memory.\n");
         goto err_out_allocate_beaconring;
     }
 
@@ -418,28 +418,28 @@
 
 err_out_allocate_beaconring:
     // Free data DMA blocks first, the start address is the same as TxRing first DMA data block
-    pci_free_consistent(pAd->pPci_Dev, (RX_RING_SIZE * RX_BUFFER_SIZE), 
+    pci_free_consistent(pAd->pPci_Dev, (RX_RING_SIZE * RX_BUFFER_SIZE),
         pAd->RxRing[0].va_data_addr, pAd->RxRing[0].pa_data_addr);
     // Free ring descriptor second, the start address is the same as TxRing first elment
     pci_free_consistent(pAd->pPci_Dev, (RX_RING_SIZE * RING_DESCRIPTOR_SIZE),
         pAd->RxRing[0].va_addr, pAd->RxRing[0].pa_addr);
 err_out_allocate_rxring:
     // Free data DMA blocks first, the start address is the same as TxRing first DMA data block
-    pci_free_consistent(pAd->pPci_Dev, (ATIM_RING_SIZE * ATIM_BUFFER_SIZE), 
+    pci_free_consistent(pAd->pPci_Dev, (ATIM_RING_SIZE * ATIM_BUFFER_SIZE),
         pAd->AtimRing[0].va_data_addr, pAd->AtimRing[0].pa_data_addr);
     // Free ring descriptor second, the start address is the same as TxRing first elment
     pci_free_consistent(pAd->pPci_Dev, (ATIM_RING_SIZE * RING_DESCRIPTOR_SIZE),
         pAd->AtimRing[0].va_addr, pAd->AtimRing[0].pa_addr);
 err_out_allocate_atimring:
     // Free data DMA blocks first, the start address is the same as TxRing first DMA data block
-    pci_free_consistent(pAd->pPci_Dev, (PRIO_RING_SIZE * PRIO_BUFFER_SIZE), 
+    pci_free_consistent(pAd->pPci_Dev, (PRIO_RING_SIZE * PRIO_BUFFER_SIZE),
         pAd->PrioRing[0].va_data_addr, pAd->PrioRing[0].pa_data_addr);
     // Free ring descriptor second, the start address is the same as TxRing first elment
     pci_free_consistent(pAd->pPci_Dev, (PRIO_RING_SIZE * RING_DESCRIPTOR_SIZE),
         pAd->PrioRing[0].va_addr, pAd->PrioRing[0].pa_addr);
 err_out_allocate_prioring:
     // Free data DMA blocks first, the start address is the same as TxRing first DMA data block
-    pci_free_consistent(pAd->pPci_Dev, (TX_RING_SIZE * TX_BUFFER_SIZE), 
+    pci_free_consistent(pAd->pPci_Dev, (TX_RING_SIZE * TX_BUFFER_SIZE),
         pAd->TxRing[0].va_data_addr, pAd->TxRing[0].pa_data_addr);
     // Free ring descriptor second, the start address is the same as TxRing first elment
     pci_free_consistent(pAd->pPci_Dev, (TX_RING_SIZE * RING_DESCRIPTOR_SIZE),
@@ -472,35 +472,35 @@
     DBGPRINT(RT_DEBUG_INFO, "--> RTMPFreeDMAMemory\n");
 
     // Free data DMA blocks first, the start address is the same as TxRing first DMA data block
-    pci_free_consistent(pAd->pPci_Dev, (TX_RING_SIZE * TX_BUFFER_SIZE), 
+    pci_free_consistent(pAd->pPci_Dev, (TX_RING_SIZE * TX_BUFFER_SIZE),
         pAd->TxRing[0].va_data_addr, pAd->TxRing[0].pa_data_addr);
     // Free ring descriptor second, the start address is the same as TxRing first elment
     pci_free_consistent(pAd->pPci_Dev, (TX_RING_SIZE * RING_DESCRIPTOR_SIZE),
         pAd->TxRing[0].va_addr, pAd->TxRing[0].pa_addr);
 
     // Free data DMA blocks first, the start address is the same as TxRing first DMA data block
-    pci_free_consistent(pAd->pPci_Dev, (PRIO_RING_SIZE * PRIO_BUFFER_SIZE), 
+    pci_free_consistent(pAd->pPci_Dev, (PRIO_RING_SIZE * PRIO_BUFFER_SIZE),
         pAd->PrioRing[0].va_data_addr, pAd->PrioRing[0].pa_data_addr);
     // Free ring descriptor second, the start address is the same as TxRing first elment
     pci_free_consistent(pAd->pPci_Dev, (PRIO_RING_SIZE * RING_DESCRIPTOR_SIZE),
         pAd->PrioRing[0].va_addr, pAd->PrioRing[0].pa_addr);
 
     // Free data DMA blocks first, the start address is the same as TxRing first DMA data block
-    pci_free_consistent(pAd->pPci_Dev, (ATIM_RING_SIZE * ATIM_BUFFER_SIZE), 
+    pci_free_consistent(pAd->pPci_Dev, (ATIM_RING_SIZE * ATIM_BUFFER_SIZE),
         pAd->AtimRing[0].va_data_addr, pAd->AtimRing[0].pa_data_addr);
     // Free ring descriptor second, the start address is the same as TxRing first elment
     pci_free_consistent(pAd->pPci_Dev, (ATIM_RING_SIZE * RING_DESCRIPTOR_SIZE),
         pAd->AtimRing[0].va_addr, pAd->AtimRing[0].pa_addr);
-    
+
     // Free data DMA blocks first, the start address is the same as TxRing first DMA data block
-    pci_free_consistent(pAd->pPci_Dev, (RX_RING_SIZE * RX_BUFFER_SIZE), 
+    pci_free_consistent(pAd->pPci_Dev, (RX_RING_SIZE * RX_BUFFER_SIZE),
         pAd->RxRing[0].va_data_addr, pAd->RxRing[0].pa_data_addr);
     // Free ring descriptor second, the start address is the same as TxRing first elment
     pci_free_consistent(pAd->pPci_Dev, (RX_RING_SIZE * RING_DESCRIPTOR_SIZE),
         pAd->RxRing[0].va_addr, pAd->RxRing[0].pa_addr);
 
     // Free data DMA blocks first, the start address is the same as TxRing first DMA data block
-    pci_free_consistent(pAd->pPci_Dev, (BEACON_RING_SIZE * BEACON_BUFFER_SIZE), 
+    pci_free_consistent(pAd->pPci_Dev, (BEACON_RING_SIZE * BEACON_BUFFER_SIZE),
         pAd->BeaconRing.va_data_addr, pAd->BeaconRing.pa_data_addr);
     // Free ring descriptor second, the start address is the same as TxRing first elment
     pci_free_consistent(pAd->pPci_Dev, (BEACON_RING_SIZE * RING_DESCRIPTOR_SIZE),
@@ -582,7 +582,7 @@
     CSR4_STRUC      StaMacReg1;
     NDIS_STATUS     Status = NDIS_STATUS_SUCCESS;
 
-    // 
+    //
     // Read MAC address from CSR3 & CSR4, these CSRs reflects real value
     // stored with EEPROM.
     //
@@ -618,7 +618,7 @@
         None
 
     Note:
-        
+
     ========================================================================
 */
 VOID    NICReadEEPROMParameters(
@@ -637,7 +637,7 @@
     RTMP_IO_READ32(pAdapter, CSR21, &data);
 
     if(data & 0x20)
-        pAdapter->EEPROMAddressNum = 6;     
+        pAdapter->EEPROMAddressNum = 6;
     else
         pAdapter->EEPROMAddressNum = 8;
 
@@ -655,7 +655,7 @@
     for(i = 0; i < NUM_EEPROM_BBP_PARMS; i++)
     {
         value = RTMP_EEPROM_READ16(pAdapter, EEPROM_BBP_BASE_OFFSET + i*2);
-        
+
         pAdapter->EEPROMDefaultValue[i] = value;
     }
 
@@ -707,13 +707,13 @@
 		// Disable TxAgc if the value is not right
 		if ((pAdapter->PortCfg.ChannelTssiRef[i * 2] == 0xff) ||
 			(pAdapter->PortCfg.ChannelTssiRef[i * 2 + 1] == 0xff))
-			pAdapter->PortCfg.bAutoTxAgc = FALSE;					
+			pAdapter->PortCfg.bAutoTxAgc = FALSE;
 	}
-	
+
 	// Tx Tssi delta offset 0x24
 	Power.word = RTMP_EEPROM_READ16(pAdapter, EEPROM_TSSI_DELTA_OFFSET);
 	pAdapter->PortCfg.ChannelTssiDelta = Power.field.Byte0;
-	
+
 #endif
 
     //CountryRegion byte offset = 0x35
@@ -734,11 +734,11 @@
 	pAdapter->PortCfg.RssiToDbm = 0x79;
     }
     else
-    { 
+    {
 	//pAdapter->PortCfg.R17Dec = 0x79 - Power.field.Byte0;
 	pAdapter->PortCfg.RssiToDbm = Power.field.Byte0;
     }
-	
+
 
     DBGPRINT(RT_DEBUG_TRACE, "<-- NICReadEEPROMParameters\n");
 }
@@ -769,11 +769,11 @@
 	EEPROM_NIC_CONFIG2_STRUC    NicConfig2;
 
 	DBGPRINT(RT_DEBUG_TRACE, "--> NICInitAsicFromEEPROM\n");
-	
+
 	for(i = 3; i < NUM_EEPROM_BBP_PARMS; i++)
 	{
 		value = pAdapter->EEPROMDefaultValue[i];
-		
+
 		if((value != 0xFFFF) && (value != 0))
 		{
 			data = value | 0x18000;
@@ -802,12 +802,12 @@
 	// Tx antenna select
     if(Antenna.field.TxDefaultAntenna == 1)       // Antenna A
     {
-		TxValue = (TxValue & 0xFC) | 0x00; 
+		TxValue = (TxValue & 0xFC) | 0x00;
 		BbpCsr1 = (BbpCsr1 & 0xFFFCFFFC) | 0x00000000;
 	}
 	else if(Antenna.field.TxDefaultAntenna == 2)  // Antenna B
 	{
-		TxValue = (TxValue & 0xFC) | 0x02; 
+		TxValue = (TxValue & 0xFC) | 0x02;
 		BbpCsr1 = (BbpCsr1 & 0xFFFCFFFC) | 0x00020002;
 	}
 	else                                          // diverity - start from Antenna B
@@ -818,12 +818,12 @@
 
 	// Rx antenna select
 	if(Antenna.field.RxDefaultAntenna == 1)       // Antenna A
-		RxValue = (RxValue & 0xFC) | 0x00; 
+		RxValue = (RxValue & 0xFC) | 0x00;
 	else if(Antenna.field.RxDefaultAntenna == 2)  // Antenna B
-		RxValue = (RxValue & 0xFC) | 0x02; 
+		RxValue = (RxValue & 0xFC) | 0x02;
 	else                                          // Antenna Diversity
-		RxValue = (RxValue & 0xFC) | 0x02; 
-			
+		RxValue = (RxValue & 0xFC) | 0x02;
+
     // RT5222 needs special treatment to swap TX I/Q
     if (pAdapter->PortCfg.RfType == RFIC_5222)
     {
@@ -831,13 +831,13 @@
         TxValue |= 0x04;         // TX I/Q flip
     }
     // RT2525E need to flip TX I/Q but not RX I/Q
-    else if (pAdapter->PortCfg.RfType == RFIC_2525E)	
+    else if (pAdapter->PortCfg.RfType == RFIC_2525E)
     {
         BbpCsr1 |= 0x00040004;
         TxValue |= 0x04;         // TX I/Q flip
         RxValue &= 0xfb;         // RX I/Q no flip
     }
-    
+
 	// Change to match microsoft definition, 0xff: diversity, 0: A, 1: B
 	pAdapter->PortCfg.CurrentTxAntenna--;
 	pAdapter->PortCfg.CurrentRxAntenna--;
@@ -845,7 +845,7 @@
 	RTMP_IO_WRITE32(pAdapter, BBPCSR1, BbpCsr1);
 	RTMP_BBP_IO_WRITE32_BY_REG_ID(pAdapter, BBP_Tx_Configure, TxValue);
 	RTMP_BBP_IO_WRITE32_BY_REG_ID(pAdapter, BBP_Rx_Configure, RxValue);
-	
+
     // 2003-12-16 software-based RX antenna diversity
     // pAdapter->PortCfg.CurrentRxAntenna = 0xff;   // Diversity ON
     AsicSetRxAnt(pAdapter);
@@ -869,7 +869,7 @@
     if (0 && Antenna.field.HardwareRadioControl == 1)
 	{
 	    pAdapter->PortCfg.bHardwareRadio = TRUE;
-		
+
 	    // Read GPIO pin0 as Hardware controlled radio state
 	    RTMP_IO_READ32(pAdapter, GPIOCSR, &data);
 	    if ((data & 0x01) == 0)
@@ -886,8 +886,8 @@
 	    }
     }
     else
-	    pAdapter->PortCfg.bHardwareRadio = FALSE;		
-	
+	    pAdapter->PortCfg.bHardwareRadio = FALSE;
+
 	NicConfig2.word = pAdapter->EEPROMDefaultValue[1];
 	if (NicConfig2.word == 0xffff)
 	    NicConfig2.word = 0;    // empty E2PROM, use default
@@ -906,7 +906,7 @@
 	    RTMP_BBP_IO_WRITE32_BY_REG_ID(pAdapter, 17, r17);
 
         // 2004-2-2 per David's request, lower R17 low-bound for very good quality NIC
-	    pAdapter->PortCfg.VgcLowerBound -= 6;  
+	    pAdapter->PortCfg.VgcLowerBound -= 6;
 	    DBGPRINT(RT_DEBUG_TRACE,"R17 tuning enable=%d, R17=0x%02x, range=<0x%02x, 0x%02x>\n",
 	        pAdapter->PortCfg.BbpTuningEnable, r17, pAdapter->PortCfg.VgcLowerBound, pAdapter->PortCfg.BbpTuning.VgcUpperBound);
 	}
@@ -916,7 +916,6 @@
 	DBGPRINT(RT_DEBUG_TRACE, "<-- NICInitAsicFromEEPROM\n");
 }
 
-extern VOID MlmeWork(void *vpAd);
 
 void NICInitializeAdapter(IN    PRTMP_ADAPTER   pAdapter)
 {
@@ -938,7 +937,7 @@
     TxCSR2.field.TxDSize = RING_DESCRIPTOR_SIZE;
     TxCSR2.field.NumTxD  = TX_RING_SIZE;
     TxCSR2.field.NumAtimD  = ATIM_RING_SIZE;
-    TxCSR2.field.NumPrioD  = PRIO_RING_SIZE;    
+    TxCSR2.field.NumPrioD  = PRIO_RING_SIZE;
     RTMP_IO_WRITE32(pAdapter, TXCSR2, TxCSR2.word);
 
     // Write TXCSR3 register
@@ -961,22 +960,19 @@
     RxCSR1.field.RxDSize = RING_DESCRIPTOR_SIZE;
     RxCSR1.field.NumRxD  = RX_RING_SIZE;
     RTMP_IO_WRITE32(pAdapter, RXCSR1, RxCSR1.word);
-    
+
     // Write RXCSR2 register
     Value = pAdapter->RxRing[0].pa_addr;
     RTMP_IO_WRITE32(pAdapter, RX_RING_BASE_REG, Value);
 
     // Write CSR1 for host ready
-    // Move Host reay to end of ASIC initialization 
+    // Move Host reay to end of ASIC initialization
     // to ensure no Rx will perform before ASIC init
     // RTMP_IO_WRITE32(pAdapter, CSR1, 0x4);
 
     // Initialze ASIC for TX & Rx operation
     NICInitializeAsic(pAdapter);
 
-#if (LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,0))
-    INIT_WORK(&pAdapter->mlme_work, MlmeWork, (void*)pAdapter);
-#endif
     DBGPRINT(RT_DEBUG_TRACE, "<-- NICInitializeAdapter\n");
 }
 
@@ -1036,13 +1032,13 @@
     else if (pAdapter->bAcceptPromiscuous == TRUE)
     {
         // Register bits with "drop unicast not to me disabled"
-        RTMP_IO_WRITE32(pAdapter, RXCSR0, 0x6e); 
+        RTMP_IO_WRITE32(pAdapter, RXCSR0, 0x6e);
     }
     else
     {
         // Standard default register bits.
-        RTMP_IO_WRITE32(pAdapter, RXCSR0, 0x7e); 
-    }  
+        RTMP_IO_WRITE32(pAdapter, RXCSR0, 0x7e);
+    }
 
     // Clear old FCS jitter before init ASIC
     RTMP_IO_READ32(pAdapter, CNT0, &Index);
@@ -1172,10 +1168,10 @@
     // Init send data structures and related parameters
     NICInitTransmit(pAdapter);
 
-    NICInitializeAdapter(pAdapter); 
+    NICInitializeAdapter(pAdapter);
     NICInitAsicFromEEPROM(pAdapter);
 
-    // Switch to current channel, since during reset process, the connection should remains on. 
+    // Switch to current channel, since during reset process, the connection should remains on.
     AsicSwitchChannel(pAdapter, pAdapter->PortCfg.Channel);
     AsicLockChannel(pAdapter, pAdapter->PortCfg.Channel);
 }
@@ -1200,7 +1196,7 @@
 {
     if(ptr == buffer)
         return TRUE;
-    else if (ptr > buffer) 
+    else if (ptr > buffer)
     {
         while (ptr > buffer)
         {
@@ -1252,7 +1248,7 @@
     }
     else
         return NULL;
-}   
+}
  /**
   * strstr - Find the first substring in a %NUL terminated string
   * @s1: The string to be searched
@@ -1261,7 +1257,7 @@
 char * rtstrstr(const char * s1,const char * s2)
 {
          int l1, l2;
- 
+
          l2 = strlen(s2);
          if (!l2)
                  return (char *) s1;
@@ -1283,7 +1279,7 @@
     Arguments:
         section                     the key of the secion
         key                         Pointer to key string
-        dest                        Pointer to destination      
+        dest                        Pointer to destination
         destsize                    The datasize of the destination
         buffer                      Pointer to the buffer to start find the key
 
@@ -1298,7 +1294,7 @@
 INT RTMPGetKeyParameter(
     IN  PUCHAR  section,
     IN  PCHAR   key,
-    OUT PCHAR   dest,   
+    OUT PCHAR   dest,
     IN  INT     destsize,
     IN  PCHAR   buffer)
 {
@@ -1354,7 +1350,7 @@
            break;
     }
 
-    len = strlen(ptr);    
+    len = strlen(ptr);
     memset(dest, 0x00, destsize);
     strncpy(dest, ptr, len >= destsize ?  destsize: len);
 
@@ -1409,7 +1405,7 @@
     src = PROFILE_PATH;
 
     // Save uid and gid used for filesystem access.
-    // Set user and group to 0 (root)   
+    // Set user and group to 0 (root)
     orgfsuid = current->fsuid;
     orgfsgid = current->fsgid;
     current->fsuid=current->fsgid = 0;
@@ -1426,7 +1422,7 @@
         else
         {
             /* The object must have a read method */
-            if (srcf->f_op && srcf->f_op->read) 
+            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);
@@ -1502,7 +1498,7 @@
                         if (ChannelSanity(pAd, Channel) == TRUE)
                         {
                             pAd->PortCfg.Channel = Channel;
-                            // If default profile in Registry is an ADHOC network, driver should use the specified channel 
+                            // If default profile in Registry is an ADHOC network, driver should use the specified channel
                             // number when starting IBSS the first time, because RaConfig is passive and will not set this
                             // via OID_802_11_CONFIGURATION upon driver bootup.
                             pAd->PortCfg.IbssConfig.Channel = pAd->PortCfg.Channel;
@@ -1571,7 +1567,7 @@
 
                         if((ulInfo > 0) && (ulInfo <= MAX_RTS_THRESHOLD))
                             pAd->PortCfg.RtsThreshold = (USHORT)ulInfo;
-                        else 
+                        else
                             pAd->PortCfg.RtsThreshold = MAX_RTS_THRESHOLD;
 
                         DBGPRINT(RT_DEBUG_TRACE, "%s::(RTSThreshold=%d)\n", __FUNCTION__, pAd->PortCfg.RtsThreshold);
@@ -1650,7 +1646,7 @@
                             {
 				DBGPRINT(RT_DEBUG_INFO, "MAX_PSP power mode not available - defaulting to CAM\n");
                             }
-                            else if ((strcmp(tmpbuf, "Fast_PSP") == 0) || (strcmp(tmpbuf, "fast_psp") == 0) 
+                            else if ((strcmp(tmpbuf, "Fast_PSP") == 0) || (strcmp(tmpbuf, "fast_psp") == 0)
                                 || (strcmp(tmpbuf, "FAST_PSP") == 0))
                             {
 				DBGPRINT(RT_DEBUG_INFO, "FAST_PSP power mode not available - defaulting to CAM\n");
@@ -1763,7 +1759,7 @@
                                         break;
                                     }
                                 }
-                                
+
                                 if (bIsHex)
                                 {
                                     pAd->PortCfg.SharedKey[0].KeyLen = KeyLen / 2 ;
@@ -1773,7 +1769,7 @@
                                 break;
                             case 13: //wep 104 Ascii type
                                 pAd->PortCfg.SharedKey[0].KeyLen = KeyLen;
-                                memcpy(pAd->PortCfg.SharedKey[0].Key, tmpbuf, KeyLen);  
+                                memcpy(pAd->PortCfg.SharedKey[0].Key, tmpbuf, KeyLen);
                                 DBGPRINT(RT_DEBUG_TRACE, "%s::(Key1=%s and type=%s)\n", __FUNCTION__, tmpbuf, "Ascii");
                                 break;
                             case 26: //wep 104 Hex type
@@ -1821,7 +1817,7 @@
                                         break;
                                     }
                                 }
-                                
+
                                 if (bIsHex)
                                 {
                                     pAd->PortCfg.SharedKey[1].KeyLen = KeyLen / 2 ;
@@ -1831,7 +1827,7 @@
                                 break;
                             case 13: //wep 104 Ascii type
                                 pAd->PortCfg.SharedKey[1].KeyLen = KeyLen;
-                                memcpy(pAd->PortCfg.SharedKey[1].Key, tmpbuf, KeyLen);  
+                                memcpy(pAd->PortCfg.SharedKey[1].Key, tmpbuf, KeyLen);
                                 DBGPRINT(RT_DEBUG_TRACE, "%s::(Key2=%s and type=%s)\n", __FUNCTION__, tmpbuf, "Ascii");
                                 break;
                             case 26: //wep 104 Hex type
@@ -1889,7 +1885,7 @@
                                 break;
                             case 13: //wep 104 Ascii type
                                 pAd->PortCfg.SharedKey[2].KeyLen = KeyLen;
-                                memcpy(pAd->PortCfg.SharedKey[2].Key, tmpbuf, KeyLen);  
+                                memcpy(pAd->PortCfg.SharedKey[2].Key, tmpbuf, KeyLen);
                                 DBGPRINT(RT_DEBUG_TRACE, "%s::(Key3=%s and type=%s)\n", __FUNCTION__, tmpbuf, "Ascii");
                                 break;
                             case 26: //wep 104 Hex type
@@ -1947,7 +1943,7 @@
                                 break;
                             case 13: //wep 104 Ascii type
                                 pAd->PortCfg.SharedKey[3].KeyLen = KeyLen;
-                                memcpy(pAd->PortCfg.SharedKey[3].Key, tmpbuf, KeyLen);  
+                                memcpy(pAd->PortCfg.SharedKey[3].Key, tmpbuf, KeyLen);
                                 DBGPRINT(RT_DEBUG_TRACE, "%s::(Key4=%s and type=%s)\n", __FUNCTION__, tmpbuf, "Ascii");
                                 break;
                             case 26: //wep 104 Hex type
@@ -2023,10 +2019,10 @@
     {
         case TX_RING:
             // We have to clean all descriptos in case some error happened with reset
-            do 
+            do
             {
                 pTxD  = (PTXD_STRUC) pAdapter->TxRing[pAdapter->NextTxDoneIndex].va_addr;
-                        
+
                 pTxD->Owner = DESC_OWN_HOST;
                 pTxD->Valid = FALSE;
 
@@ -2036,7 +2032,7 @@
                 {
                     pAdapter->NextTxDoneIndex = 0;
                 }
-        
+
             }   while (Count < TX_RING_SIZE);   // We have to scan all TX ring
 
             // Check for packet in send tx wait waiting queue
@@ -2047,7 +2043,7 @@
 
         case PRIO_RING:
             // We have to clean all descriptos in case some error happened with reset
-            do 
+            do
             {
                 pTxD  = (PTXD_STRUC) pAdapter->PrioRing[pAdapter->NextPrioDoneIndex].va_addr;
 
@@ -2085,7 +2081,7 @@
 
         case RX_RING:
             // We have to clean all descriptos in case some error happened with reset
-            do 
+            do
             {
                 pRxD  = (PRXD_STRUC) pAdapter->RxRing[pAdapter->CurRxIndex].va_addr;
 
@@ -2101,7 +2097,7 @@
 
             }   while (Count < RX_RING_SIZE);       // We have to scan all Rx Ring
             break;
-            
+
         default:
             break;
 
@@ -2172,10 +2168,10 @@
 {
     UINT i;
 
-    DBGPRINT(RT_DEBUG_TRACE, "--> PortCfgInit\n");    
+    DBGPRINT(RT_DEBUG_TRACE, "--> PortCfgInit\n");
 
     pAdapter->PortCfg.UseBGProtection = 0;    // 0: AUTO
-    
+
     pAdapter->PortCfg.CapabilityInfo = 0x0000;
     pAdapter->PortCfg.Psm = PWR_ACTIVE;
     pAdapter->PortCfg.BeaconPeriod = 100;     // in mSec
@@ -2207,7 +2203,7 @@
     pAdapter->PortCfg.LastMicErrorTime = 0;
     pAdapter->PortCfg.MicErrCnt        = 0;
     pAdapter->PortCfg.bBlockAssoc      = FALSE;
-    pAdapter->PortCfg.WpaState         = SS_NOTUSE; 
+    pAdapter->PortCfg.WpaState         = SS_NOTUSE;
 
     pAdapter->PortCfg.RtsThreshold = 2347;
     pAdapter->PortCfg.FragmentThreshold = 2346;
@@ -2261,7 +2257,7 @@
     pAdapter->PortCfg.PhyMode = 0xff;
 //  RTMPSetPhyMode(pAdapter, PHY_11BG_MIXED);   // default in 11BG mixed mode
 //  pAdapter->PortCfg.Channel = FirstChannel(pAdapter);
-    pAdapter->PortCfg.Dsifs = 10;      // in units of usec 
+    pAdapter->PortCfg.Dsifs = 10;      // in units of usec
     pAdapter->PortCfg.TxPreambleInUsed = Rt802_11PreambleLong; // use Long preamble on TX by defaut
 
     // user desired power mode
@@ -2274,7 +2270,7 @@
     pAdapter->bAcceptMulticast = FALSE;
     pAdapter->bAcceptBroadcast = TRUE;
     pAdapter->bAcceptAllMulticast = TRUE;
-    
+
     // parameters to be used when this STA starts a new ADHOC network
     pAdapter->PortCfg.IbssConfig.BeaconPeriod = 100;
     pAdapter->PortCfg.IbssConfig.AtimWin = 0;
@@ -2363,8 +2359,8 @@
     char *srcptr;
     PUCHAR destTemp;
 
-    srcptr = src;   
-    destTemp = (PUCHAR) dest; 
+    srcptr = src;
+    destTemp = (PUCHAR) dest;
 
     while(destlen--)
     {
@@ -2376,7 +2372,7 @@
 
 /*
 	========================================================================
-	
+
 	Routine Description:
 		Init timer objects
 
@@ -2390,7 +2386,7 @@
 		None
 
 	Note:
-		
+
 	========================================================================
 */
 VOID	RTMPInitTimer(
@@ -2406,7 +2402,7 @@
 
 /*
 	========================================================================
-	
+
 	Routine Description:
 		Init timer objects
 
@@ -2418,7 +2414,7 @@
 		None
 
 	Note:
-		
+
 	========================================================================
 */
 VOID	RTMPSetTimer(
@@ -2434,7 +2430,7 @@
 
 /*
 	========================================================================
-	
+
 	Routine Description:
 		Cancel timer objects
 
@@ -2446,14 +2442,15 @@
 
 	Note:
 		Reset NIC to initial state AS IS system boot up time.
-		
+
 	========================================================================
 */
 VOID	RTMPCancelTimer(
 	IN	PRALINK_TIMER_STRUCT	pTimer)
 {
 #if (LINUX_VERSION_CODE > KERNEL_VERSION(2,4,27))
-	del_timer_sync(&pTimer->TimerObj);
+	if (timer_pending(&pTimer->TimerObj))
+		del_timer_sync(&pTimer->TimerObj);
 #else
 	del_timer(&pTimer->TimerObj);
 #endif
diff -Nur rt2500-1.1.0-b4/Module/rtmp_main.c rt2500-cvs-2007061011/Module/rtmp_main.c
--- rt2500-1.1.0-b4/Module/rtmp_main.c	2006-06-17 22:12:58.000000000 +0200
+++ rt2500-cvs-2007061011/Module/rtmp_main.c	2007-05-29 05:49:17.000000000 +0200
@@ -1,35 +1,35 @@
-/*************************************************************************** 
- * RT2400/RT2500 SourceForge Project - http://rt2x00.serialmonkey.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.                          * 
- *                                                                         * 
- *   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.             * 
- *                                                                         * 
- *   Licensed under the GNU GPL                                            * 
- *   Original code supplied under license from RaLink Inc, 2004.           * 
- ***************************************************************************/ 
+/***************************************************************************
+ * RT2400/RT2500 SourceForge Project - http://rt2x00.serialmonkey.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.                          *
+ *                                                                         *
+ *   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.             *
+ *                                                                         *
+ *   Licensed under the GNU GPL                                            *
+ *   Original code supplied under license from RaLink Inc, 2004.           *
+ ***************************************************************************/
 
- /*************************************************************************** 
+ /***************************************************************************
  *      Module Name: rtmp_main.c
- *              
- *      Abstract: 
- *              
- *      Revision History: 
- *      Who             When            What 
- *      --------        -----------     ----------------------------- 
- *      PaulL           25th Nov 02     Initial code     
- *      MarkW           8th  Dec 04     Baseline code  
+ *
+ *      Abstract:
+ *
+ *      Revision History:
+ *      Who             When            What
+ *      --------        -----------     -----------------------------
+ *      PaulL           25th Nov 02     Initial code
+ *      MarkW           8th  Dec 04     Baseline code
  *      MarkW (rt2400)  8th  Dec 04     Promisc mode support
  *      Flavio (rt2400) 8th  Dec 04     Elegant irqreturn_t handling
  *      Flavio (rt2400) 8th  Dec 04     Remove local alloc_netdev
@@ -45,26 +45,24 @@
  *      Tor Petterson   19th Apr 05     Power management: Suspend and Resume
  *      MarkW           15th Jul 05     Disable File Config under 4KSTACK
  *      IvD             15th Jul 05     Support File Config with 4KSTACK
- ***************************************************************************/ 
+ ***************************************************************************/
 
 #include "rt_config.h"
 
-unsigned long IrqFlags;
-
 //  Global static variable, Debug level flag
 // Don't hide this behind debug define. There should be as little difference between debug and no-debug as possible.
 #if LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 0)
-int debug = 0;	/* Default is off. */
+static int debug = 0;	/* Default is off. */
 MODULE_PARM(debug, "i");
-MODULE_PARM_DESC(debug, "Enable level: accepted values: 1 to switch debug on, 0 to switch debug off.");
+MODULE_PARM_DESC(debug, "Debug mask: n selects filter, 0 for none");
 
 static char *ifname = NULL ;
 MODULE_PARM(ifname, "s");
 MODULE_PARM_DESC(ifname, "Network device name (default ra%d)");
 #else
-int debug = 0;	/* Default is off. */
+static int debug = 0;	/* Default is off. */
 module_param(debug, int, 0);
-MODULE_PARM_DESC(debug, "Enable level: accepted values: 1 to switch debug on, 0 to switch debug off.");
+MODULE_PARM_DESC(debug, "Debug mask: n selects filter, 0 for none");
 
 static char *ifname = NULL ;
 module_param(ifname, charp, 0);
@@ -79,78 +77,130 @@
 
 extern	const struct iw_handler_def rt2500_iw_handler_def;
 
+#ifdef RT2500_DBG
+VOID rt2500_setdbg(long mask)
+{
+	debug = mask;
+}
+INT rt2500_dbgprint(int mask, const char *fmt, ...)
+{
+	if(mask & debug) {
+		va_list args;
+		int i;
+
+		va_start(args, fmt);
+
+		//http://www.kernel.org/pub/linux/kernel/v2.6/ChangeLog-2.6.9
+		#if (LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,9))
+		i = vprintk(fmt, args);
+
+		#else
+		// Stack is safe because data is buffered before control returns
+		char printk_buf[160];	// Longest observed line is 147 chars.
+
+		vsnprintf(printk_buf, sizeof(printk_buf), fmt, args);
+		i = printk(printk_buf);
+		#endif /* (LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,9)) */
+
+		va_end(args);
+		return i;
+	}
+	return 0;
+}
+#endif
+
+#ifdef RT2X00DEBUGFS
 /*
  * Register layout information.
  */
 #define CSR_REG_BASE			0x0000
 #define CSR_REG_SIZE			0x0174
 #define EEPROM_BASE			0x0000
-#define EEPROM_SIZE			0x01ff
+#define EEPROM_SIZE			0x0200
+#define BBP_SIZE			0x0040
 
-#if LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0)
-static void
-rt2x00_get_drvinfo(struct net_device *net_dev,
-	struct ethtool_drvinfo *drvinfo)
+static void rt2500pci_read_csr(void *dev, const unsigned long word,
+		void *data)
 {
-	PRTMP_ADAPTER   pAd = net_dev->priv;
+	RTMP_ADAPTER *pAd = dev;
 
-	strcpy(drvinfo->driver, NIC_DEVICE_NAME);
-	strcpy(drvinfo->version, DRV_VERSION);
-	strcpy(drvinfo->bus_info, pci_name(pAd->pPci_Dev));
+	RTMP_IO_READ32(pAd, CSR_REG_BASE + (word * sizeof(u32)), (u32*)data);
 }
 
-static int
-rt2x00_get_regs_len(struct net_device *net_dev)
+static void rt2500pci_write_csr(void *dev, const unsigned long word,
+	void *data)
 {
-	return CSR_REG_SIZE;
+	RTMP_ADAPTER *pAd = dev;
+
+	RTMP_IO_WRITE32(pAd, word, *((u32*)data));
 }
 
-static void
-rt2x00_get_regs(struct net_device *net_dev,
-	struct ethtool_regs *regs, void *data)
+static void rt2500pci_read_eeprom(void *dev, const unsigned long word,
+		void *data)
 {
-	PRTMP_ADAPTER   pAd = net_dev->priv;
-	unsigned int counter;
+	RTMP_ADAPTER *pAd = dev;
 
-	regs->len = CSR_REG_SIZE;
+	*((u16*)data) = RTMP_EEPROM_READ16(pAd, word * sizeof(u16));
+}
 
-	for (counter = 0; counter < CSR_REG_SIZE; counter += sizeof(u32)) {
-		RTMP_IO_READ32(pAd, CSR_REG_BASE + counter, (u32*)data);
-		data += sizeof(u32);
-	}
+static void rt2500pci_write_eeprom(void *dev, const unsigned long word,
+	void *data)
+{
+	/* DANGEROUS, DON'T DO THIS! */
 }
 
-static int
-rt2x00_get_eeprom_len(struct net_device *net_dev)
+static void rt2500pci_read_bbp(void *dev, const unsigned long word,
+		void *data)
 {
-	return EEPROM_SIZE;
+	RTMP_ADAPTER *pAd = dev;
+
+	RTMP_BBP_IO_READ32_BY_REG_ID(pAd, word, ((u8*)data));
 }
 
-static int
-rt2x00_get_eeprom(struct net_device *net_dev,
-	struct ethtool_eeprom *eeprom, u8 *data)
+static void rt2500pci_write_bbp(void *dev, const unsigned long word,
+	void *data)
 {
-	PRTMP_ADAPTER   pAd = net_dev->priv;
-	unsigned int counter;
+	RTMP_ADAPTER *pAd = dev;
 
-	for (counter = eeprom->offset; counter < eeprom->len; counter += sizeof(u16)) {
-		u16 value = RTMP_EEPROM_READ16(pAd, CSR_REG_BASE + counter);
-		memcpy(data, &value, sizeof(u16));
-		data += sizeof(u16);
-	}
+	RTMP_BBP_IO_WRITE32_BY_REG_ID(pAd, word, *((u8*)data));
+}
 
-	return 0;
+static void rt2500pci_open_debugfs(RTMP_ADAPTER *pAd)
+{
+	struct rt2x00debug *debug = &pAd->debug;
+
+	debug->owner 			= THIS_MODULE;
+	debug->mod_name			= DRV_NAME;
+	debug->mod_version		= DRV_VERSION;
+	debug->reg_csr.read		= rt2500pci_read_csr;
+	debug->reg_csr.write		= rt2500pci_write_csr;
+	debug->reg_csr.word_size	= sizeof(u32);
+	debug->reg_csr.length		= CSR_REG_SIZE;
+	debug->reg_eeprom.read		= rt2500pci_read_eeprom;
+	debug->reg_eeprom.write		= rt2500pci_write_eeprom;
+	debug->reg_eeprom.word_size	= sizeof(u16);
+	debug->reg_eeprom.length	= EEPROM_SIZE;
+	debug->reg_bbp.read		= rt2500pci_read_bbp;
+	debug->reg_bbp.write		= rt2500pci_write_bbp;
+	debug->reg_bbp.word_size	= sizeof(u8);
+	debug->reg_bbp.length		= BBP_SIZE;
+	debug->dev 			= pAd;
+
+	snprintf(debug->intf_name, sizeof(debug->intf_name),
+		"%s", pAd->net_dev->name);
+
+	if (rt2x00debug_register(debug))
+		printk(KERN_ERR "Failed to register debug handler.\n");
 }
 
-static struct ethtool_ops rt2x00_ethtool_ops = {
-	.get_drvinfo	= rt2x00_get_drvinfo,
-	.get_regs_len	= rt2x00_get_regs_len,
-	.get_regs	= rt2x00_get_regs,
-	.get_link	= ethtool_op_get_link,
-	.get_eeprom_len	= rt2x00_get_eeprom_len,
-	.get_eeprom	= rt2x00_get_eeprom,
-};
-#endif
+static void rt2500pci_close_debugfs(RTMP_ADAPTER *pAd)
+{
+	rt2x00debug_deregister(&pAd->debug);
+}
+#else /* RT2X00DEBUGFS */
+static inline void rt2500pci_open_debugfs(RTMP_ADAPTER *pAd){}
+static inline void rt2500pci_close_debugfs(RTMP_ADAPTER *pAd){}
+#endif /* RT2X00DEBUGFS */
 
 static INT __devinit RT2500_init_one (
     IN  struct pci_dev              *pPci_Dev,
@@ -158,6 +208,7 @@
 {
     INT rc;
 
+	if (debug) {}	// shuts up compiler when RT2500_DBG not defined
     // wake up and enable device
     if (pci_enable_device (pPci_Dev))
     {
@@ -176,7 +227,7 @@
 // PCI device probe & initialization function
 //
 INT __devinit   RT2500_probe(
-    IN  struct pci_dev              *pPci_Dev, 
+    IN  struct pci_dev              *pPci_Dev,
     IN  const struct pci_device_id  *ent)
 {
     struct  net_device      *net_dev;
@@ -194,7 +245,7 @@
 
     // alloc_etherdev() will set net_dev->name
     net_dev = alloc_etherdev(sizeof(RTMP_ADAPTER));
-    if (net_dev == NULL) 
+    if (net_dev == NULL)
     {
         DBGPRINT(RT_DEBUG_TRACE, "init_ethernet failed\n");
         goto err_out;
@@ -204,9 +255,8 @@
 
     #if (LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,0))
        SET_NETDEV_DEV(net_dev, &(pPci_Dev->dev));
-       SET_ETHTOOL_OPS(net_dev, &rt2x00_ethtool_ops);
     #endif
-        
+
     if (pci_request_regions(pPci_Dev, print_name))
         goto err_out_free_netdev;
 
@@ -215,10 +265,10 @@
 
     // map physical address to virtual address for accessing register
     csr_addr = (unsigned long) ioremap(pci_resource_start(pPci_Dev, 0), pci_resource_len(pPci_Dev, 0));
-    if (!csr_addr) 
+    if (!csr_addr)
     {
-        DBGPRINT(RT_DEBUG_TRACE, "ioremap failed for device %s, region 0x%X @ 0x%lX\n",
-            print_name, (ULONG)pci_resource_len(pPci_Dev, 0), pci_resource_start(pPci_Dev, 0));
+        DBGPRINT(RT_DEBUG_TRACE, "ioremap failed for device %s, region 0x%X @ 0x%X\n",
+            print_name, (ULONG)pci_resource_len(pPci_Dev, 0), (ULONG)pci_resource_start(pPci_Dev, 0));
         goto err_out_free_res;
     }
 
@@ -233,7 +283,7 @@
 
     // Read MAC address
     NICReadAdapterInfo(pAd);
-    
+
     RTMP_IO_READ32(pAd, CSR3, &StaMacReg0.word);
     RTMP_IO_READ32(pAd, CSR4, &StaMacReg1.word);
     net_dev->dev_addr[0] = StaMacReg0.field.Byte0;
@@ -256,13 +306,13 @@
 #if WIRELESS_EXT < 17
     net_dev->get_wireless_stats = RT2500_get_wireless_stats;
 #endif
-    net_dev->wireless_handlers = (struct iw_handler_def *) &rt2500_iw_handler_def;	
+    net_dev->wireless_handlers = (struct iw_handler_def *) &rt2500_iw_handler_def;
 #endif
 
     net_dev->set_multicast_list = RT2500_set_rx_mode;
     net_dev->do_ioctl = RT2500_ioctl;
     net_dev->set_mac_address = rt2500_set_mac_address;
-    
+
 
     // register_netdev() will call dev_alloc_name() for us
     // TODO: Remove the following line to keep the default eth%d name
@@ -284,8 +334,8 @@
     if (Status != NDIS_STATUS_SUCCESS)
 		goto err_out_unmap;
 
-    DBGPRINT(RT_DEBUG_TRACE, "%s: at 0x%lx, VA 0x%lx, IRQ %d. \n", 
-        net_dev->name, pci_resource_start(pPci_Dev, 0), (unsigned long)csr_addr, pPci_Dev->irq);
+    DBGPRINT(RT_DEBUG_TRACE, "%s: at 0x%x, VA 0x%lx, IRQ %d. \n",
+        net_dev->name, (ULONG)pci_resource_start(pPci_Dev, 0), (unsigned long)csr_addr, pPci_Dev->irq);
 
     // Set driver data
     pci_set_drvdata(pPci_Dev, net_dev);
@@ -295,15 +345,17 @@
     // All this occurs while the net iface is down
     // iwconfig can then be used to configure card BEFORE
     // ifconfig ra0 up is applied.
-    // Note the RT2500STA.dat file will still overwrite settings 
+    // Note the RT2500STA.dat file will still overwrite settings
     // but it is useful for the settings iwconfig doesn't let you at
-    PortCfgInit(pAd); 
+    PortCfgInit(pAd);
 
 	MlmeQueueInit(&pAd->Mlme.Queue);	// (never fails)
 
     // Build channel list for default physical mode
     BuildChannelList(pAd);
 
+	rt2500pci_open_debugfs(pAd);
+
     return 0;
 
 err_out_unmap:
@@ -447,7 +499,7 @@
 
     if (pAdapter->PortCfg.BssType == BSS_MONITOR && pAdapter->PortCfg.MallowRFMONTx != TRUE)
     {
-       dev_kfree_skb_irq(skb); 
+       dev_kfree_skb_irq(skb);
        return 0;
     }
 
@@ -465,7 +517,7 @@
         // This function has to manage NdisSendComplete return call within its routine
         // NdisSendComplete will acknowledge upper layer in two steps.
         // 1. Within Packet Enqueue, set the NDIS_STATUS_PENDING
-        // 2. Within TxRingTxDone / PrioRingTxDone call NdisSendComplete with final status          
+        // 2. Within TxRingTxDone / PrioRingTxDone call NdisSendComplete with final status
         // initial skb->data_len=0, we will use this variable to store data size when fragment(in TKIP)
         // and skb->len is actual data len
         skb->data_len = skb->len;
@@ -482,7 +534,7 @@
     // There are two place calling dequeue for TX ring.
     // 1. Here, right after queueing the frame.
     // 2. At the end of TxRingTxDone service routine.
-    if ((!RTMP_TEST_FLAG(pAdapter, fRTMP_ADAPTER_BSS_SCAN_IN_PROGRESS)) && 
+    if ((!RTMP_TEST_FLAG(pAdapter, fRTMP_ADAPTER_BSS_SCAN_IN_PROGRESS)) &&
         (!RTMP_TEST_FLAG(pAdapter, fRTMP_ADAPTER_RADIO_OFF)) &&
         (!RTMP_TEST_FLAG(pAdapter, fRTMP_ADAPTER_RESET_IN_PROGRESS)))
     {
@@ -504,7 +556,7 @@
     Arguments:
         irq                         interrupt line
         dev_instance                Pointer to net_device
-        rgs                         store process's context before entering ISR, 
+        rgs                         store process's context before entering ISR,
                                     this parameter is just for debug purpose.
 
     Return Value:
@@ -514,10 +566,16 @@
 
     ========================================================================
 */
+#if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,19)
 irqreturn_t RTMPIsr(
-    IN  INT             irq, 
-    IN  VOID            *dev_instance, 
+    IN  INT             irq,
+    IN  VOID            *dev_instance,
     IN  struct pt_regs  *rgs)
+#else
+irqreturn_t RTMPIsr(
+    IN  INT             irq,
+    IN  VOID            *dev_instance)
+#endif
 {
     struct net_device   *net_dev = dev_instance;
     PRTMP_ADAPTER       pAdapter = net_dev->priv;
@@ -643,29 +701,29 @@
 	if(!is_valid_ether_addr(&mac->sa_data[0]))
 		return -EINVAL;
 
-#if (LINUX_VERSION_CODE > KERNEL_VERSION(2,4,20)) 	
+#if (LINUX_VERSION_CODE > KERNEL_VERSION(2,4,20))
 	BUG_ON(net_dev->addr_len != ETH_ALEN);
-#endif	
-	
+#endif
+
 	memcpy(net_dev->dev_addr, mac->sa_data, ETH_ALEN);
 	memcpy(pAd->CurrentAddress, mac->sa_data, ETH_ALEN);
-	
+
 	memset(&set_mac, 0x00, sizeof(INT));
 	set_mac = (net_dev->dev_addr[0]) |
 			(net_dev->dev_addr[1] << 8) |
 			(net_dev->dev_addr[2] << 16) |
 			(net_dev->dev_addr[3] << 24);
-	
+
 	RTMP_IO_WRITE32(pAd, CSR3, set_mac);
-	
+
 	memset(&set_mac, 0x00, sizeof(INT));
 	set_mac = (net_dev->dev_addr[4]) |
 			(net_dev->dev_addr[5] << 8);
-	
+
 	RTMP_IO_WRITE32(pAd, CSR4, set_mac);
-	
+
 	printk(KERN_INFO "***rt2x00***: Info - Mac address changed to: %02x:%02x:%02x:%02x:%02x:%02x.\n", net_dev->dev_addr[0], net_dev->dev_addr[1], net_dev->dev_addr[2], net_dev->dev_addr[3], net_dev->dev_addr[4], net_dev->dev_addr[5]);
-	
+
 	return 0;
 }
 
@@ -697,11 +755,13 @@
 
     pAd->iw_stats.status = 0;           // Status - device dependent for now
 
-    pAd->iw_stats.qual.qual = pAd->Mlme.ChannelQuality;//pAd->Mlme.RoamCqi;            // link quality (%retries, SNR, %missed beacons or better...)
-    pAd->iw_stats.qual.level = pAd->PortCfg.LastRssi - RSSI_TO_DBM_OFFSET;   // signal level (dBm)
-        
+    pAd->iw_stats.qual.qual = pAd->Mlme.ChannelQuality;// link quality (%retries, SNR, %missed beacons or better...)
+    pAd->iw_stats.qual.level = abs(pAd->PortCfg.LastRssi);   // signal level (dBm)
+    pAd->iw_stats.qual.level += 256 - RSSI_TO_DBM_OFFSET;
+
     pAd->iw_stats.qual.noise = (pAd->PortCfg.LastR17Value > BBP_R17_DYNAMIC_UP_BOUND) ? BBP_R17_DYNAMIC_UP_BOUND : ((ULONG) pAd->PortCfg.LastR17Value);           // // noise level (dBm)
-    pAd->iw_stats.qual.updated = 3;     // Flags to know if updated
+    pAd->iw_stats.qual.noise += 256 - 143;
+    pAd->iw_stats.qual.updated = 1;     // Flags to know if updated
 
     pAd->iw_stats.discard.nwid = 0;     // Rx : Wrong nwid/essid
     pAd->iw_stats.miss.beacon = 0;      // Missed beacons/superframe
@@ -791,7 +851,7 @@
     IN  struct net_device *net_dev)
 {
     RTMP_ADAPTER *pAd;
-    pAd = net_dev->priv; 
+    pAd = net_dev->priv;
     if (pAd->PortCfg.BssType == BSS_MONITOR)
     {
         RTMP_IO_WRITE32(pAd, RXCSR0, 0x46);
@@ -808,7 +868,7 @@
         pAd->bAcceptPromiscuous = FALSE;
         RTMP_IO_WRITE32(pAd, RXCSR0, 0x7e);
         DBGPRINT(RT_DEBUG_TRACE, "rt2500 acknowledge MONITOR/PROMISC off\n");
-    }   
+    }
 
 }
 
@@ -867,7 +927,9 @@
     IN  struct pci_dev  *pPci_Dev)
 {
     struct net_device   *net_dev = pci_get_drvdata(pPci_Dev);
-    // RTMP_ADAPTER        *pAd = net_dev->priv;
+	RTMP_ADAPTER	*pAd = netdev_priv(net_dev);
+
+	rt2500pci_close_debugfs(pAd);
 
     // Free Ring buffers
     RTMPFreeDMAMemory(net_dev->priv);
@@ -915,7 +977,7 @@
 
     if(pAdapter->PortCfg.bRadio)
         MlmeRadioOff(pAdapter);
-    
+
 #if (LINUX_VERSION_CODE < KERNEL_VERSION(2,6,14))
 	printk(KERN_NOTICE "%s: got suspend request (state %d)\n",
 		dev->name, state);
@@ -944,7 +1006,11 @@
     PRTMP_ADAPTER pAdapter = (PRTMP_ADAPTER) dev->priv;
     int status;
 
-    pci_enable_device(pdev);
+	// FIXME: code should process error case correctly
+	if (pci_enable_device(pdev)) {
+		printk(KERN_ERR "rt2500: could not resume from suspend");
+		return -EIO;
+	}
 
     printk(KERN_NOTICE "%s: got resume request\n", dev->name);
 
@@ -991,7 +1057,7 @@
     suspend:    rt2500_suspend,
     resume:     rt2500_resume,
 #endif /* CONFIG_PM */
-#if LINUX_VERSION_CODE >= 0x20412 || BIG_ENDIAN == TRUE || RTMP_EMBEDDED == TRUE
+#if LINUX_VERSION_CODE >= 0x20412 || BIG_ENDIAN == TRUE
     remove:     __devexit_p(RT2500_remove_one),
 #else
     remove:     __devexit(RT2500_remove_one),
diff -Nur rt2500-1.1.0-b4/Module/rtmp_tkip.c rt2500-cvs-2007061011/Module/rtmp_tkip.c
--- rt2500-1.1.0-b4/Module/rtmp_tkip.c	2006-06-17 22:12:58.000000000 +0200
+++ rt2500-cvs-2007061011/Module/rtmp_tkip.c	2007-03-21 05:25:35.000000000 +0100
@@ -1,125 +1,125 @@
-/*************************************************************************** 
- * RT2400/RT2500 SourceForge Project - http://rt2x00.serialmonkey.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.                          * 
- *                                                                         * 
- *   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.             * 
- *                                                                         * 
- *   Licensed under the GNU GPL                                            * 
- *   Original code supplied under license from RaLink Inc, 2004.           * 
- ***************************************************************************/ 
+/***************************************************************************
+ * RT2400/RT2500 SourceForge Project - http://rt2x00.serialmonkey.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.                          *
+ *                                                                         *
+ *   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.             *
+ *                                                                         *
+ *   Licensed under the GNU GPL                                            *
+ *   Original code supplied under license from RaLink Inc, 2004.           *
+ ***************************************************************************/
 
- /*************************************************************************** 
+ /***************************************************************************
  *      Module Name: rtmp_tkip.c
- *              
- *      Abstract: 
- *              
- *      Revision History: 
- *      Who             When            What 
- *      --------        -----------     ----------------------------- 
- *      PaulW           25th Feb 02     Initial code     
- *      MarkW           8th  Dec 04     Baseline code  
- ***************************************************************************/ 
+ *
+ *      Abstract:
+ *
+ *      Revision History:
+ *      Who             When            What
+ *      --------        -----------     -----------------------------
+ *      PaulW           25th Feb 02     Initial code
+ *      MarkW           8th  Dec 04     Baseline code
+ ***************************************************************************/
 
 #include	"rt_config.h"
 
-// Rotation functions on 32 bit values 
+// Rotation functions on 32 bit values
 #define ROL32( A, n )   ( ((A) << (n)) | ( ((A)>>(32-(n))) ) )
-#define ROR32( A, n )   ROL32( (A), 32-(n) ) 
+#define ROR32( A, n )   ROL32( (A), 32-(n) )
 
 /*
 	========================================================================
 
 	Routine	Description:
-		Convert from UCHAR[] to ULONG in a portable way 
-		
+		Convert from UCHAR[] to ULONG in a portable way
+
 	Arguments:
       pMICKey		pointer to MIC Key
-		
+
 	Return Value:
 		None
 
 	Note:
-		
+
 	========================================================================
 */
-ULONG	RTMPTkipGetUInt32( 	
+ULONG	RTMPTkipGetUInt32(
 	IN	PUCHAR	pMICKey)
-{  	
-	ULONG	res = 0; 
+{
+	ULONG	res = 0;
 	int		i;
-	
-	for (i = 0; i < 4; i++) 
-	{ 
-		res |= (*pMICKey++) << (8 * i); 
+
+	for (i = 0; i < 4; i++)
+	{
+		res |= (*pMICKey++) << (8 * i);
 	}
 
-	return res; 
-} 
+	return res;
+}
 
 /*
 	========================================================================
 
 	Routine	Description:
-		Convert from ULONG to UCHAR[] in a portable way 
-		
+		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
 
 	Note:
-		
+
 	========================================================================
 */
 VOID	RTMPTkipPutUInt32(
 	IN OUT	PUCHAR		pDst,
-	IN		ULONG		val)					  
-{ 	
+	IN		ULONG		val)
+{
 	int i;
-	
-	for(i = 0; i < 4; i++) 
-	{ 
-		*pDst++ = (UCHAR) val; 
-		val >>= 8; 
-	} 
-} 
+
+	for(i = 0; i < 4; i++)
+	{
+		*pDst++ = (UCHAR) val;
+		val >>= 8;
+	}
+}
 
 /*
 	========================================================================
 
 	Routine	Description:
 		Calculate the MIC Value.
-		
+
 	Arguments:
       pAdapter		Pointer to our adapter
       pSrc			Pointer to source data for Calculate MIC Value
       Len			Indicate the length of the source data
-		
+
 	Return Value:
 		None
 
 	Note:
-		
+
 	========================================================================
 */
-VOID	RTMPTkipAppend( 
-	IN	PTKIP_KEY_INFO	pTkip,	
+VOID	RTMPTkipAppend(
+	IN	PTKIP_KEY_INFO	pTkip,
 	IN	PUCHAR			pSrc,
-	IN	UINT			nBytes)						  
+	IN	UINT			nBytes)
 {
     register ULONG  M, L, R, nBytesInM;
 
@@ -128,7 +128,7 @@
     R = pTkip->R;
     nBytesInM = pTkip->nBytesInM;
     M = pTkip->M;
-    
+
     // Alignment case
     if((nBytesInM == 0) && ((((unsigned long)pSrc) & 0x3) == 0))
     {
@@ -141,7 +141,7 @@
 #endif
             pSrc += 4;
             nBytes -= 4;
-            
+
             L ^= M;
             R ^= ROL32( L, 17 );
             L += R;
@@ -154,7 +154,7 @@
         }
         nBytesInM = 0;
         M = 0;
-        
+
         while(nBytes > 0)
         {
             M |= (*pSrc << (8* nBytesInM));
@@ -162,7 +162,7 @@
             nBytesInM++;
             pSrc++;
             nBytes--;
-            
+
             if( nBytesInM >= 4 )
             {
                 L ^=  M;
@@ -186,10 +186,10 @@
         {
             M |= (*pSrc << (8* nBytesInM));
             nBytesInM++;
-            
+
             pSrc++;
             nBytes--;
-            
+
             if( nBytesInM >= 4 )
             {
                 L ^=  M;
@@ -207,23 +207,23 @@
             }
         }
     }
-    
+
     // load data from register to memory
     pTkip->M = M;
     pTkip->nBytesInM = nBytesInM;
     pTkip->L = L;
     pTkip->R = R;
-} 
+}
 
 /*
 	========================================================================
 
 	Routine	Description:
 		Get the MIC Value.
-		
+
 	Arguments:
       pAdapter		Pointer to our adapter
-		
+
 	Return Value:
 		None
 
@@ -231,7 +231,7 @@
 		the MIC Value is store in pAdapter->PrivateInfo.MIC
 	========================================================================
 */
-VOID	RTMPTkipGetMIC( 
+VOID	RTMPTkipGetMIC(
 	IN	PTKIP_KEY_INFO	pTkip)
 {
     static unsigned char Last[] = {"\x5a\x00\x00\x00\x00\x00\x00\x00"};
@@ -242,14 +242,14 @@
     // The appendByte function has already computed the result.
     RTMPTkipPutUInt32(pTkip->MIC, pTkip->L);
     RTMPTkipPutUInt32(pTkip->MIC + 4, pTkip->R);
-} 
+}
 
 /*
 	========================================================================
 
 	Routine	Description:
 		Compare MIC value of received MSDU
-		
+
 	Arguments:
 		pAdapter	Pointer to our adapter
 		pSrc        Pointer to the received Plain text data
@@ -257,13 +257,13 @@
 		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
-		
+
 	Note:
-	
+
 	========================================================================
 */
 BOOLEAN	RTMPTkipCompareMICValue(
@@ -288,19 +288,19 @@
 	RTMPTkipAppend(&pAdapter->PrivateInfo.Rx, pSA, 6);
 	// Priority + 3 bytes of 0
 	RTMPTkipAppend(&pAdapter->PrivateInfo.Rx, Priority, 4);
-	
+
 	// Calculate MIC value from plain text data
 	RTMPTkipAppend(&pAdapter->PrivateInfo.Rx, pSrc, Len);
 
 	// Get MIC value from decrypted plain data
 	RTMPTkipGetMIC(&pAdapter->PrivateInfo.Rx);
-		
+
 	// Move MIC value from MSDU, this steps should move to data path.
 	// Since the MIC value might cross MPDUs.
 	if(!NdisEqualMemory(pAdapter->PrivateInfo.Rx.MIC, pSrc + Len, 8))
 	{
 	    INT		i;
-	    
+
 		DBGPRINT(RT_DEBUG_ERROR, "! TKIP MIC Error !\n");  //MIC error.
 		DBGPRINT(RT_DEBUG_INFO, "Orig MIC value =");  //MIC error.
 		for (i = 0; i < 8; i++)
@@ -324,7 +324,7 @@
 
 	Routine	Description:
 		Compare MIC value of received MSDU
-		
+
 	Arguments:
 		pAdapter	Pointer to our adapter
 		pLLC		LLC header
@@ -333,13 +333,13 @@
 		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
-		
+
 	Note:
-	
+
 	========================================================================
 */
 BOOLEAN	RTMPTkipCompareMICValueWithLLC(
@@ -352,13 +352,13 @@
 	IN	UINT			Len)
 {
     static UCHAR    Priority[4] = {"\x00\x00\x00\x00"};
-    
+
     // Init MIC value calculation and reset the message
     pAdapter->PrivateInfo.Rx.L = RTMPTkipGetUInt32(pMICKey);
     pAdapter->PrivateInfo.Rx.R = RTMPTkipGetUInt32(pMICKey + 4);
     pAdapter->PrivateInfo.Rx.nBytesInM = 0;
     pAdapter->PrivateInfo.Rx.M = 0;
-	
+
     // DA
     RTMPTkipAppend(&pAdapter->PrivateInfo.Rx, pDA, 6);
     // SA
@@ -405,20 +405,20 @@
 	========================================================================
 
 	Routine	Description:
-		Copy frame from waiting queue into relative ring buffer and set 
+		Copy frame from waiting queue into relative ring buffer and set
 	appropriate ASIC register to kick hardware transmit function
-		
+
 	Arguments:
 		pAdapter		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
 
 	Note:
-	
+
 	========================================================================
 */
 VOID RTMPCalculateMICValue(
@@ -430,21 +430,21 @@
 {
     PUCHAR          pSrc;
     static UCHAR    Priority[4] = {"\x00\x00\x00\x00"};
-    
+
     pSrc = (PUCHAR) skb->data;
-    
+
     // Init MIC value calculation and reset the message
     pAdapter->PrivateInfo.Tx.L = RTMPTkipGetUInt32(pWpaKey->TxMic);
     pAdapter->PrivateInfo.Tx.R = RTMPTkipGetUInt32(pWpaKey->TxMic + 4);
     pAdapter->PrivateInfo.Tx.nBytesInM = 0;
     pAdapter->PrivateInfo.Tx.M = 0;
-	
+
     // DA & SA field
     RTMPTkipAppend(&pAdapter->PrivateInfo.Tx, pSrc, 12);
-    
+
     // Priority + 3 bytes of 0
     RTMPTkipAppend(&pAdapter->PrivateInfo.Tx, Priority, 4);
-    
+
     if (LenEncap > 0)
     {
         // LLC encapsulation
@@ -454,7 +454,7 @@
     }
     else
         RTMPTkipAppend(&pAdapter->PrivateInfo.Tx, pSrc + 14, skb->len - 14);
-    
+
     // Compute the final MIC Value
     RTMPTkipGetMIC(&pAdapter->PrivateInfo.Tx);
 }
diff -Nur rt2500-1.1.0-b4/Module/rtmp_type.h rt2500-cvs-2007061011/Module/rtmp_type.h
--- rt2500-1.1.0-b4/Module/rtmp_type.h	2006-06-17 22:12:58.000000000 +0200
+++ rt2500-cvs-2007061011/Module/rtmp_type.h	2007-03-21 05:25:35.000000000 +0100
@@ -1,36 +1,36 @@
-/*************************************************************************** 
- * RT2400/RT2500 SourceForge Project - http://rt2x00.serialmonkey.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.                          * 
- *                                                                         * 
- *   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.             * 
- *                                                                         * 
- *   Licensed under the GNU GPL                                            * 
- *   Original code supplied under license from RaLink Inc, 2004.           * 
- ***************************************************************************/ 
+/***************************************************************************
+ * RT2400/RT2500 SourceForge Project - http://rt2x00.serialmonkey.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.                          *
+ *                                                                         *
+ *   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.             *
+ *                                                                         *
+ *   Licensed under the GNU GPL                                            *
+ *   Original code supplied under license from RaLink Inc, 2004.           *
+ ***************************************************************************/
 
- /*************************************************************************** 
+ /***************************************************************************
  *      Module Name: rtmp_type.h
- *              
- *      Abstract: 
- *              
- *      Revision History: 
- *      Who             When            What 
- *      --------        -----------     ----------------------------- 
- *      PaulL           2md  Jan 03     Initial code     
- *      MarkW           8th  Dec 04     Baseline code  
- ***************************************************************************/ 
+ *
+ *      Abstract:
+ *
+ *      Revision History:
+ *      Who             When            What
+ *      --------        -----------     -----------------------------
+ *      PaulL           2md  Jan 03     Initial code
+ *      MarkW           8th  Dec 04     Baseline code
+ ***************************************************************************/
 
 #ifndef	__RTMP_TYPE_H__
 #define	__RTMP_TYPE_H__
diff -Nur rt2500-1.1.0-b4/Module/rtmp_wep.c rt2500-cvs-2007061011/Module/rtmp_wep.c
--- rt2500-1.1.0-b4/Module/rtmp_wep.c	2006-06-17 22:12:58.000000000 +0200
+++ rt2500-cvs-2007061011/Module/rtmp_wep.c	2007-03-21 05:25:35.000000000 +0100
@@ -1,40 +1,40 @@
-/*************************************************************************** 
- * RT2400/RT2500 SourceForge Project - http://rt2x00.serialmonkey.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.                          * 
- *                                                                         * 
- *   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.             * 
- *                                                                         * 
- *   Licensed under the GNU GPL                                            * 
- *   Original code supplied under license from RaLink Inc, 2004.           * 
- ***************************************************************************/ 
-
- /*************************************************************************** 
- *      Module Name: rtmp_wep.c 
- *              
- *      Abstract: 
- *              
- *      Revision History: 
- *      Who             When            What 
- *      --------        -----------     ----------------------------- 
- *      PaulW           28th Sep 02     Initial code     
- *      MarkW           8th  Dec 04     Baseline code  
- ***************************************************************************/ 
+/***************************************************************************
+ * RT2400/RT2500 SourceForge Project - http://rt2x00.serialmonkey.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.                          *
+ *                                                                         *
+ *   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.             *
+ *                                                                         *
+ *   Licensed under the GNU GPL                                            *
+ *   Original code supplied under license from RaLink Inc, 2004.           *
+ ***************************************************************************/
+
+ /***************************************************************************
+ *      Module Name: rtmp_wep.c
+ *
+ *      Abstract:
+ *
+ *      Revision History:
+ *      Who             When            What
+ *      --------        -----------     -----------------------------
+ *      PaulW           28th Sep 02     Initial code
+ *      MarkW           8th  Dec 04     Baseline code
+ ***************************************************************************/
 
 #include    "rt_config.h"
 
-ULONG FCSTAB_32[256] = 
+ULONG FCSTAB_32[256] =
 {
     0x00000000, 0x77073096, 0xee0e612c, 0x990951ba,
     0x076dc419, 0x706af48f, 0xe963a535, 0x9e6495a3,
@@ -56,57 +56,57 @@
     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 
-}; 
+    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, 
+        0x00, 0x11, 0x22,
         //WEP KEY
-        0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA, 0xBB, 0xCC 
+        0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA, 0xBB, 0xCC
     };
 
 
@@ -114,27 +114,27 @@
     ========================================================================
 
     Routine Description:
-        Init WEP function.  
-        
+        Init WEP function.
+
     Arguments:
       pAdapter      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
 
     Note:
-    
+
     ========================================================================
 */
 VOID    RTMPInitWepEngine(
-    IN  PRTMP_ADAPTER   pAdapter,   
+    IN  PRTMP_ADAPTER   pAdapter,
     IN  PUCHAR          pKey,
     IN  UCHAR           KeyId,
-    IN  UCHAR           KeyLen, 
+    IN  UCHAR           KeyLen,
     IN OUT  PUCHAR      pDest)
 {
     UINT i;
@@ -146,32 +146,32 @@
         WEPKEY[i] = RandomByte(pAdapter);   //Call mlme RandomByte() function.
     ARCFOUR_INIT(&pAdapter->PrivateInfo.WEPCONTEXT, WEPKEY, KeyLen + 3);  //INIT SBOX, KEYLEN+3(IV)
 
-    memcpy(pDest, WEPKEY, 3);  //Append Init Vector 
-    *(pDest+3) = (KeyId << 6);       //Append KEYID 
-    
+    memcpy(pDest, WEPKEY, 3);  //Append Init Vector
+    *(pDest+3) = (KeyId << 6);       //Append KEYID
+
 }
 
 /*
     ========================================================================
 
     Routine Description:
-        Encrypt transimitted data       
-        
+        Encrypt transimitted data
+
     Arguments:
       pAdapter      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
-        
+
     Note:
-    
+
     ========================================================================
 */
 VOID    RTMPEncryptData(
-    IN  PRTMP_ADAPTER   pAdapter,   
+    IN  PRTMP_ADAPTER   pAdapter,
     IN  PUCHAR          pSrc,
     IN  PUCHAR          pDest,
     IN  UINT            Len)
@@ -184,19 +184,19 @@
     ========================================================================
 
     Routine Description:
-        Decrypt received data   
-        
+        Decrypt received 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 RTMPDecryptData(
@@ -209,12 +209,12 @@
     UCHAR   KeyIdx;
 
     memcpy(WEPKEY, pSrc, 3);    //Get WEP IV
-    
+
     KeyIdx = (*(pSrc + 3) & 0xc0) >> 6;
     if (pAdapter->PortCfg.SharedKey[KeyIdx].KeyLen == 0)
         return (FALSE);
-        
-    memcpy(WEPKEY + 3, pAdapter->PortCfg.SharedKey[KeyIdx].Key, pAdapter->PortCfg.SharedKey[KeyIdx].KeyLen);    
+
+    memcpy(WEPKEY + 3, pAdapter->PortCfg.SharedKey[KeyIdx].Key, pAdapter->PortCfg.SharedKey[KeyIdx].KeyLen);
     ARCFOUR_INIT(&pAdapter->PrivateInfo.WEPCONTEXT, WEPKEY, pAdapter->PortCfg.SharedKey[KeyIdx].KeyLen + 3);
     ARCFOUR_DECRYPT(&pAdapter->PrivateInfo.WEPCONTEXT, pSrc, pSrc + 4, Len - 4);
     memcpy(&trailfcs, pSrc + Len - 8, 4);
@@ -236,18 +236,18 @@
     ========================================================================
 
     Routine Description:
-        The Stream Cipher Encryption Algorithm "ARCFOUR" initialize     
-        
+        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
-        
+
     Note:
-    
+
     ========================================================================
 */
 VOID    ARCFOUR_INIT(
@@ -260,7 +260,7 @@
     UINT    stateindex;
     PUCHAR  state;
     UINT    counter;
-    
+
     state = Ctx->STATE;
     Ctx->X = 0;
     Ctx->Y = 0;
@@ -284,16 +284,16 @@
     ========================================================================
 
     Routine Description:
-        Get bytes from ARCFOUR CONTEXT (S-BOX)              
-        
+        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)        
-        
+       UCHAR  - the value of the ARCFOUR CONTEXT (S-BOX)
+
     Note:
-    
+
     ========================================================================
 */
 UCHAR   ARCFOUR_BYTE(
@@ -303,7 +303,7 @@
   UINT y;
   UCHAR sx, sy;
   PUCHAR state;
-  
+
   state = Ctx->STATE;
   x = (Ctx->X + 1) & 0xff;
   sx = state[x];
@@ -315,31 +315,31 @@
   state[x] = sy;
 
   return(state[(sx + sy) & 0xff]);
-  
+
 }
 
 /*
     ========================================================================
 
     Routine Description:
-        The Stream Cipher Decryption Algorithm      
-        
+        The Stream Cipher Decryption Algorithm
+
     Arguments:
         Ctx         Pointer to ARCFOUR CONTEXT (SBOX)
-        pDest           Pointer to the Destination 
+        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          pDest,
     IN  PUCHAR          pSrc,
     IN  UINT            Len)
 {
@@ -353,19 +353,19 @@
     ========================================================================
 
     Routine Description:
-        The Stream Cipher Encryption Algorithm      
-        
+        The Stream Cipher Encryption Algorithm
+
     Arguments:
         Ctx         Pointer to ARCFOUR CONTEXT (SBOX)
-        pDest           Pointer to the Destination 
+        pDest           Pointer to the Destination
         pSrc        Pointer to the Source data
         Len         Indicate the length of the Source dta
-        
+
     Return Value:
         None
-        
+
     Note:
-    
+
     ========================================================================
 */
 VOID    ARCFOUR_ENCRYPT(
@@ -385,17 +385,17 @@
 
     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:
         ULONG - FCS 32 bits
-        
+
     Note:
-    
+
     ========================================================================
 */
 ULONG   RTMP_CALC_FCS32(
@@ -406,24 +406,24 @@
     while (Len--)
        Fcs = (((Fcs) >> 8) ^ FCSTAB_32[((Fcs) ^ (*Cp++)) & 0xff]);
 
-    return (Fcs); 
-} 
+    return (Fcs);
+}
 
 
 /*
     ========================================================================
 
     Routine Description:
-        Get last FCS and encrypt it to the destination              
-        
+        Get last FCS and encrypt it to the destination
+
     Arguments:
-        pDest           Pointer to the Destination 
-        
+        pDest           Pointer to the Destination
+
     Return Value:
         None
-        
+
     Note:
-    
+
     ========================================================================
 */
 VOID    RTMPSetICV(
@@ -431,11 +431,11 @@
     IN  PUCHAR  pDest)
 {
     pAdapter->PrivateInfo.FCSCRC32 ^= 0xffffffff;             /* complement */
-    
+
 #ifdef BIG_ENDIAN
     pAdapter->PrivateInfo.FCSCRC32 = SWAP32(pAdapter->PrivateInfo.FCSCRC32);
 #endif
-    
+
     ARCFOUR_ENCRYPT(&pAdapter->PrivateInfo.WEPCONTEXT, pDest, (PUCHAR) &pAdapter->PrivateInfo.FCSCRC32, 4);
 }
 
diff -Nur rt2500-1.1.0-b4/Module/sanity.c rt2500-cvs-2007061011/Module/sanity.c
--- rt2500-1.1.0-b4/Module/sanity.c	2006-06-17 22:12:58.000000000 +0200
+++ rt2500-cvs-2007061011/Module/sanity.c	2007-03-21 05:25:35.000000000 +0100
@@ -1,41 +1,42 @@
-/*************************************************************************** 
- * RT2400/RT2500 SourceForge Project - http://rt2x00.serialmonkey.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.                          * 
- *                                                                         * 
- *   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.             * 
- *                                                                         * 
- *   Licensed under the GNU GPL                                            * 
- *   Original code supplied under license from RaLink Inc, 2004.           * 
- ***************************************************************************/ 
-
- /*************************************************************************** 
- *      Module Name: sanity.c 
- *              
- *      Abstract: 
- *              
- *      Revision History: 
- *      Who             When            What 
- *      --------        -----------     ----------------------------- 
- *      MarkW           8th  Dec 04     Baseline code  
- ***************************************************************************/ 
+/***************************************************************************
+ * RT2400/RT2500 SourceForge Project - http://rt2x00.serialmonkey.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.                          *
+ *                                                                         *
+ *   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.             *
+ *                                                                         *
+ *   Licensed under the GNU GPL                                            *
+ *   Original code supplied under license from RaLink Inc, 2004.           *
+ ***************************************************************************/
+
+ /***************************************************************************
+ *      Module Name: sanity.c
+ *
+ *      Abstract:
+ *
+ *      Revision History:
+ *      Who             When            What
+ *      --------        -----------     -----------------------------
+ *      MarkW           8th  Dec 04     Baseline code
+ ***************************************************************************/
 
 #include "rt_config.h"
 
-UCHAR   WPA_OUI[] = {0x00, 0x50, 0xf2, 0x01};
+static const UCHAR		WPA_OUI[] = {0x00, 0x50, 0xf2, 0x01};
+static const ie_oui_t	wpa2_oui = {0x00, 0x0f, 0xac};	// 802.11i pp. 28, 30
 
-/* 
+/*
     ==========================================================================
     Description:
         MLME message sanity check
@@ -44,13 +45,13 @@
     ==========================================================================
  */
 BOOLEAN MlmeScanReqSanity(
-    IN PRTMP_ADAPTER pAd, 
-    IN VOID *Msg, 
-    IN ULONG MsgLen, 
-    OUT UCHAR *BssType, 
-    OUT CHAR Ssid[], 
-    OUT UCHAR *SsidLen, 
-    OUT UCHAR *ScanType) 
+    IN PRTMP_ADAPTER pAd,
+    IN VOID *Msg,
+    IN ULONG MsgLen,
+    OUT UCHAR *BssType,
+    OUT CHAR Ssid[],
+    OUT UCHAR *SsidLen,
+    OUT UCHAR *ScanType)
 {
     MLME_SCAN_REQ_STRUCT *Info;
 
@@ -61,16 +62,16 @@
     *ScanType = Info->ScanType;
 
     if ((*BssType == BSS_INFRA || *BssType == BSS_INDEP || *BssType == BSS_ANY) &&
-       (*ScanType == SCAN_ACTIVE || *ScanType == SCAN_PASSIVE)) 
+       (*ScanType == SCAN_ACTIVE || *ScanType == SCAN_PASSIVE))
         return TRUE;
-    else 
+    else
     {
         DBGPRINT(RT_DEBUG_TRACE, "MlmeScanReqSanity fail - wrong BssType or ScanType\n");
         return FALSE;
     }
 }
 
-/* 
+/*
     ==========================================================================
     Description:
         MLME message sanity check
@@ -79,16 +80,16 @@
     ==========================================================================
  */
 BOOLEAN MlmeStartReqSanity(
-    IN PRTMP_ADAPTER pAd, 
-    IN VOID *Msg, 
-    IN ULONG MsgLen, 
-    OUT CHAR Ssid[], 
-    OUT UCHAR *SsidLen) 
+    IN PRTMP_ADAPTER pAd,
+    IN VOID *Msg,
+    IN ULONG MsgLen,
+    OUT CHAR Ssid[],
+    OUT UCHAR *SsidLen)
 {
     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");
@@ -101,7 +102,7 @@
     return TRUE;
 }
 
-/* 
+/*
     ==========================================================================
     Description:
         MLME message sanity check
@@ -110,13 +111,13 @@
     ==========================================================================
  */
 BOOLEAN MlmeAssocReqSanity(
-    IN PRTMP_ADAPTER pAd, 
-    IN VOID *Msg, 
-    IN ULONG MsgLen, 
-    OUT MACADDR *ApAddr, 
-    OUT USHORT *CapabilityInfo, 
-    OUT ULONG *Timeout, 
-    OUT USHORT *ListenIntv) 
+    IN PRTMP_ADAPTER pAd,
+    IN VOID *Msg,
+    IN ULONG MsgLen,
+    OUT MACADDR *ApAddr,
+    OUT USHORT *CapabilityInfo,
+    OUT ULONG *Timeout,
+    OUT USHORT *ListenIntv)
 {
     MLME_ASSOC_REQ_STRUCT *Info;
 
@@ -129,7 +130,7 @@
     return TRUE;
 }
 
-/* 
+/*
     ==========================================================================
     Description:
         MLME message sanity check
@@ -138,12 +139,12 @@
     ==========================================================================
  */
 BOOLEAN MlmeAuthReqSanity(
-    IN PRTMP_ADAPTER pAd, 
-    IN VOID *Msg, 
-    IN ULONG MsgLen, 
-    OUT MACADDR *Addr, 
-    OUT ULONG *Timeout, 
-    OUT USHORT *Alg) 
+    IN PRTMP_ADAPTER pAd,
+    IN VOID *Msg,
+    IN ULONG MsgLen,
+    OUT MACADDR *Addr,
+    OUT ULONG *Timeout,
+    OUT USHORT *Alg)
 {
     MLME_AUTH_REQ_STRUCT *Info;
 
@@ -152,18 +153,18 @@
     *Timeout = Info->Timeout;
     *Alg = Info->Alg;
 
-    if ((*Alg == Ndis802_11AuthModeShared || *Alg == Ndis802_11AuthModeOpen) && !MAC_ADDR_IS_GROUP(*Addr)) 
+    if ((*Alg == Ndis802_11AuthModeShared || *Alg == Ndis802_11AuthModeOpen) && !MAC_ADDR_IS_GROUP(*Addr))
     {
         return TRUE;
-    } 
-    else 
+    }
+    else
     {
         DBGPRINT(RT_DEBUG_TRACE, "MlmeAuthReqSanity fail - wrong algorithm\n");
         return FALSE;
     }
 }
 
-/* 
+/*
     ==========================================================================
     Description:
         MLME message sanity check
@@ -172,16 +173,16 @@
     ==========================================================================
  */
 BOOLEAN PeerAssocRspSanity(
-    IN PRTMP_ADAPTER pAd, 
-    IN VOID *Msg, 
-    IN ULONG MsgLen, 
-    OUT MACADDR *Addr2, 
-    OUT USHORT *CapabilityInfo, 
-    OUT USHORT *Status, 
-    OUT USHORT *Aid, 
-    OUT UCHAR Rates[], 
+    IN PRTMP_ADAPTER pAd,
+    IN VOID *Msg,
+    IN ULONG MsgLen,
+    OUT MACADDR *Addr2,
+    OUT USHORT *CapabilityInfo,
+    OUT USHORT *Status,
+    OUT USHORT *Aid,
+    OUT UCHAR Rates[],
     OUT UCHAR *RatesLen,
-    OUT BOOLEAN *ExtendedRateIeExist) 
+    OUT BOOLEAN *ExtendedRateIeExist)
 {
     CHAR          IeType, *Ptr;
     MACFRAME     *Fr = (MACFRAME *)Msg;
@@ -195,7 +196,7 @@
     // Mask out unnecessary capability information
     *CapabilityInfo &= SUPPORTED_CAPABILITY_INFO;
 
-    if (*Status == MLME_SUCCESS) 
+    if (*Status == MLME_SUCCESS)
     {
         memcpy(Aid, &Fr->Octet[4], 2);
         *Aid = (*Aid) & 0x3fff; // AID is low 14-bit
@@ -207,8 +208,8 @@
         {
             DBGPRINT(RT_DEBUG_TRACE, "PeerAssocRspSanity fail - wrong SupportedRates IE\n");
             return FALSE;
-        } 
-        else 
+        }
+        else
             memcpy(Rates, &Fr->Octet[8], *RatesLen);
 
         // many AP implement proprietary IEs in non-standard order, we'd better
@@ -235,7 +236,7 @@
                     }
                     break;
                 default:
-                    DBGPRINT(RT_DEBUG_TRACE, "PeerAssocRspSanity - ignore unrecognized EID = %d\n", eid_ptr->Eid);
+                    DBGPRINT(RT_DEBUG_TRACE, "PeerAssocRspSanity - ignore unrecognized EID=%d (Len=%d)\n", eid_ptr->Eid, eid_ptr->Len);
                     break;
             }
 
@@ -247,7 +248,7 @@
     return TRUE;
 }
 
-/* 
+/*
     ==========================================================================
     Description:
         MLME message sanity check
@@ -256,11 +257,11 @@
     ==========================================================================
  */
 BOOLEAN PeerDisassocSanity(
-    IN PRTMP_ADAPTER pAd, 
-    IN VOID *Msg, 
-    IN ULONG MsgLen, 
-    OUT MACADDR *Addr2, 
-    OUT USHORT *Reason) 
+    IN PRTMP_ADAPTER pAd,
+    IN VOID *Msg,
+    IN ULONG MsgLen,
+    OUT MACADDR *Addr2,
+    OUT USHORT *Reason)
 {
     MACFRAME *Fr = (MACFRAME *)Msg;
 
@@ -270,7 +271,7 @@
     return TRUE;
 }
 
-/* 
+/*
     ==========================================================================
     Description:
         MLME message sanity check
@@ -279,11 +280,11 @@
     ==========================================================================
  */
 BOOLEAN PeerDeauthSanity(
-    IN PRTMP_ADAPTER pAd, 
-    IN VOID *Msg, 
-    IN ULONG MsgLen, 
-    OUT MACADDR *Addr2, 
-    OUT USHORT *Reason) 
+    IN PRTMP_ADAPTER pAd,
+    IN VOID *Msg,
+    IN ULONG MsgLen,
+    OUT MACADDR *Addr2,
+    OUT USHORT *Reason)
 {
     MACFRAME *Fr = (MACFRAME *)Msg;
 
@@ -293,7 +294,7 @@
     return TRUE;
 }
 
-/* 
+/*
     ==========================================================================
     Description:
         MLME message sanity check
@@ -302,14 +303,14 @@
     ==========================================================================
  */
 BOOLEAN PeerAuthSanity(
-    IN PRTMP_ADAPTER pAd, 
-    IN VOID *Msg, 
-    IN ULONG MsgLen, 
-    OUT MACADDR *Addr, 
-    OUT USHORT *Alg, 
-    OUT USHORT *Seq, 
-    OUT USHORT *Status, 
-    CHAR *ChlgText) 
+    IN PRTMP_ADAPTER pAd,
+    IN VOID *Msg,
+    IN ULONG MsgLen,
+    OUT MACADDR *Addr,
+    OUT USHORT *Alg,
+    OUT USHORT *Seq,
+    OUT USHORT *Status,
+    CHAR *ChlgText)
 {
     MACFRAME     *Fr = (MACFRAME *)Msg;
 
@@ -318,43 +319,43 @@
     memcpy(Seq,    &Fr->Octet[2], 2);
     memcpy(Status, &Fr->Octet[4], 2);
 
-    if (*Alg == Ndis802_11AuthModeOpen) 
+    if (*Alg == Ndis802_11AuthModeOpen)
     {
-        if (*Seq == 1 || *Seq == 2) 
+        if (*Seq == 1 || *Seq == 2)
         {
             return TRUE;
-        } 
-        else 
+        }
+        else
         {
             DBGPRINT(RT_DEBUG_TRACE, "PeerAuthSanity fail - wrong Seg#\n");
             return FALSE;
         }
-    } 
-    else if (*Alg == Ndis802_11AuthModeShared) 
+    }
+    else if (*Alg == Ndis802_11AuthModeShared)
     {
-        if (*Seq == 1 || *Seq == 4) 
+        if (*Seq == 1 || *Seq == 4)
         {
             return TRUE;
-        } 
-        else if (*Seq == 2 || *Seq == 3) 
+        }
+        else if (*Seq == 2 || *Seq == 3)
         {
             memcpy(ChlgText, &Fr->Octet[8], CIPHER_TEXT_LEN);
             return TRUE;
-        } 
-        else 
+        }
+        else
         {
             DBGPRINT(RT_DEBUG_TRACE, "PeerAuthSanity fail - wrong Seg#\n");
             return FALSE;
         }
-    } 
-    else 
+    }
+    else
     {
         DBGPRINT(RT_DEBUG_TRACE, "PeerAuthSanity fail - wrong algorithm\n");
         return FALSE;
     }
 }
 
-/* 
+/*
     ==========================================================================
     Description:
         MLME message sanity check
@@ -363,14 +364,14 @@
     ==========================================================================
  */
 BOOLEAN PeerProbeReqSanity(
-    IN PRTMP_ADAPTER pAd, 
-    IN VOID *Msg, 
-    IN ULONG MsgLen, 
+    IN PRTMP_ADAPTER pAd,
+    IN VOID *Msg,
+    IN ULONG MsgLen,
     OUT MACADDR *Addr2,
-    OUT CHAR Ssid[], 
-    OUT UCHAR *SsidLen) 
-//    OUT UCHAR Rates[], 
-//    OUT UCHAR *RatesLen) 
+    OUT CHAR Ssid[],
+    OUT UCHAR *SsidLen)
+//    OUT UCHAR Rates[],
+//    OUT UCHAR *RatesLen)
 {
     UCHAR Idx;
     UCHAR	RateLen;
@@ -379,27 +380,27 @@
 
     COPY_MAC_ADDR(Addr2, &Fr->Hdr.Addr2);
 
-    if ((Fr->Octet[0] != IE_SSID) || (Fr->Octet[1] > MAX_LEN_OF_SSID)) 
+    if ((Fr->Octet[0] != IE_SSID) || (Fr->Octet[1] > MAX_LEN_OF_SSID))
     {
         DBGPRINT(RT_DEBUG_TRACE, "PeerProbeReqSanity fail - wrong SSID IE(Type=%d,Len=%d)\n",Fr->Octet[0],Fr->Octet[1]);
         return FALSE;
-    } 
-    
+    }
+
     *SsidLen = Fr->Octet[1];
     memcpy(Ssid, &Fr->Octet[2], *SsidLen);
 
-#if 1    
+#if 1
     Idx = *SsidLen + 2;
 
     // -- get supported rates from payload and advance the pointer
     IeType = Fr->Octet[Idx];
     RateLen = Fr->Octet[Idx + 1];
-    if (IeType != IE_SUPP_RATES) 
+    if (IeType != IE_SUPP_RATES)
     {
         DBGPRINT(RT_DEBUG_TRACE, "PeerProbeReqSanity fail - wrong SupportRates IE(Type=%d,Len=%d)\n",Fr->Octet[Idx],Fr->Octet[Idx+1]);
         return FALSE;
     }
-    else 
+    else
     {
         if ((pAd->PortCfg.AdhocMode == 2) && (RateLen < 8))
             return (FALSE);
@@ -408,7 +409,95 @@
     return TRUE;
 }
 
-/* 
+static inline void handle_country_ie(
+		country_ie_p p)
+{
+	int i;
+
+	DBGPRINT(RT_DEBUG_INFO,
+			" -  IE_COUNTRY (ID=%d) (Len=%d) "
+			"(string=\"%c%c:%c\")\n",
+			p->eid, p->length, p->cs.co[0], p->cs.co[1], p->cs.env);
+
+	// drop malformed elements
+	if (p->length & 1 || p->length < 6) {
+		DBGPRINT(RT_DEBUG_ERROR,
+				" -  IE_COUNTRY invalid length\n");
+		return;
+	}
+	for (i = 0; i < offsetof(country_string_t, env); i++) {
+		if (p->cs.co[i] < 'A' || p->cs.co[i] > 'z') {
+			DBGPRINT(RT_DEBUG_ERROR,
+					" -  IE_COUNTRY invalid co fld\n");
+			return;
+		}
+	}
+	if (p->cs.env != ' ' && p->cs.env != 'O' && p->cs.env != 'I') {
+		DBGPRINT(RT_DEBUG_ERROR,
+				" -  IE_COUNTRY invalid env field\n");
+		return;
+	}
+	if (p->length % 3 && *(char *)((char *)p + p->length + 1) != 0) {
+		DBGPRINT(RT_DEBUG_ERROR,
+				" -  IE_COUNTRY pad non-null\n");
+		return;
+	}
+#ifdef RT2500_DBG
+	{
+	int num_subelements = p->length/3 - 1;
+	country_subelement_p sep = p->chans;
+	for (i = 0; i < num_subelements; i++, sep++)
+	{
+		DBGPRINT(RT_DEBUG_INFO,
+				" -  Band %d First chan=%d, Num chans=%d, Max Tx Pwr=%d\n",
+				i, sep->first_chan, sep->num_chans, sep->max_tx_pwr);
+	}
+	}
+#endif /* RT2500_DBG */
+	/* TODO */
+
+} /* End handle_country_ie () */
+
+static inline int handle_rsn_ie(
+		rsn_ie_p p,
+		PNDIS_802_11_VARIABLE_IEs pVIE)
+{
+	DBGPRINT(RT_DEBUG_INFO,
+			" -  IE_RSN (ID=%d, Len=%d)\n",
+			p->eid, p->length);
+
+	// drop malformed elements
+	if (p->length < 2 || p->length & 1) {
+		DBGPRINT(RT_DEBUG_ERROR,
+				" -  IE_RSN invalid length\n");
+		return 0;
+	}
+	if (wtohs(p->version) != 1) {
+		DBGPRINT(RT_DEBUG_ERROR,
+				" -  IE_RSN invalid version %d\n",
+				p->version);
+		return 0;
+	}
+	if (p->length >= 6) { // group cipher suite
+		if (!RTMPEqualMemory(&p->gcsuite.oui, wpa2_oui, sizeof(wpa2_oui)))
+		{
+			DBGPRINT(RT_DEBUG_ERROR,
+					" -  IE_RSN invalid oui "
+					"%02x %02x %02x\n",
+					p->gcsuite.oui[0], p->gcsuite.oui[1], p->gcsuite.oui[2]);
+			return 0;
+		}
+	}
+	// Copy to pVIE which will report to microsoft bssid list.
+	pVIE->ElementID = p->eid;
+	pVIE->Length = p->length;
+	memcpy(pVIE->data, &p->version, p->length);
+
+	return (p->length + 2);
+
+} /* End handle_rsn_ie () */
+
+/*
     ==========================================================================
     Description:
         MLME message sanity check
@@ -417,47 +506,56 @@
     ==========================================================================
  */
 BOOLEAN PeerBeaconAndProbeRspSanity(
-    IN PRTMP_ADAPTER pAd, 
-    IN VOID *Msg, 
-    IN ULONG MsgLen, 
-    OUT MACADDR *Addr2, 
-    OUT MACADDR *Bssid, 
-    OUT CHAR Ssid[], 
-    OUT UCHAR *SsidLen, 
-    OUT UCHAR *BssType, 
-    OUT USHORT *BeaconPeriod, 
-    OUT UCHAR *Channel, 
-    OUT LARGE_INTEGER *Timestamp, 
-    OUT BOOLEAN *CfExist, 
-    OUT CF_PARM *CfParm, 
-    OUT USHORT *AtimWin, 
-    OUT USHORT *CapabilityInfo, 
-    OUT UCHAR Rate[], 
+    IN PRTMP_ADAPTER pAd,
+    IN VOID *Msg,
+    IN ULONG MsgLen,
+    OUT MACADDR *Addr2,
+    OUT MACADDR *Bssid,
+    OUT CHAR Ssid[],
+    OUT UCHAR *SsidLen,
+    OUT UCHAR *BssType,
+    OUT USHORT *BeaconPeriod,
+    OUT UCHAR *Channel,
+    OUT LARGE_INTEGER *Timestamp,
+    OUT BOOLEAN *CfExist,
+    OUT CF_PARM *CfParm,
+    OUT USHORT *AtimWin,
+    OUT USHORT *CapabilityInfo,
+    OUT UCHAR Rate[],
     OUT UCHAR *RateLen,
     OUT BOOLEAN *ExtendedRateIeExist,
     OUT UCHAR *Erp,
-    OUT UCHAR *DtimCount, 
-    OUT UCHAR *DtimPeriod, 
-    OUT UCHAR *BcastFlag, 
-    OUT UCHAR *MessageToMe, 
+    OUT UCHAR *DtimCount,
+    OUT UCHAR *DtimPeriod,
+    OUT UCHAR *BcastFlag,
+    OUT UCHAR *MessageToMe,
     OUT UCHAR *Legacy,
     OUT UCHAR SupRate[],
 	OUT UCHAR *SupRateLen,
 	OUT UCHAR ExtRate[],
 	OUT UCHAR *ExtRateLen,
-    OUT	PNDIS_802_11_VARIABLE_IEs pVIE) 
+    OUT USHORT *VarIELen,	// Length of all saved IEs.
+    OUT	PNDIS_802_11_VARIABLE_IEs pVIE)
 {
     CHAR                *Ptr, TimLen;
     MACFRAME            *Fr;
     PBEACON_EID_STRUCT  eid_ptr;
     UCHAR               SubType;
     UCHAR               Sanity;
+    UCHAR               VarIE[MAX_VIE_LEN];
+
+	// armor against buffer overflow
+	UCHAR						*vielim = &VarIE[MAX_VIE_LEN];
+    NDIS_802_11_VARIABLE_IEs    *ptVIE = (PNDIS_802_11_VARIABLE_IEs)VarIE;
+
+	DBGPRINT(RT_DEBUG_TRACE,"===> %s\n", __FUNCTION__);
 
     // Add for 3 necessary EID field check
     Sanity = 0;
 
     *ExtendedRateIeExist = FALSE;
     *Erp = 0;
+	*VarIELen = 0;
 
     Fr = (MACFRAME *)Msg;
 
@@ -481,40 +579,48 @@
     // get capability info from payload and advance the pointer
     memcpy(CapabilityInfo, Ptr, 2);
     Ptr += 2;
-    if (CAP_IS_ESS_ON(*CapabilityInfo)) 
+    DBGPRINT(RT_DEBUG_INFO, " - CapabilityInfo=0x%.2x\n", *CapabilityInfo);
+    if (CAP_IS_ESS_ON(*CapabilityInfo))
     {
         *BssType = BSS_INFRA;
-    } 
-    else 
+    }
+    else
     {
         *BssType = BSS_INDEP;
     }
 
     // Mask out unnecessary capability information
     *CapabilityInfo &= SUPPORTED_CAPABILITY_INFO;
-    
+
     eid_ptr = (PBEACON_EID_STRUCT) Ptr;
 
     // get variable fields from payload and advance the pointer
     while(((UCHAR*)eid_ptr + eid_ptr->Len + 1) < ((UCHAR*)Fr + MsgLen))
     {
+		DBGPRINT(RT_DEBUG_INFO, " - IE #%d len=%d\n",
+							eid_ptr->Eid, eid_ptr->Len);
         switch(eid_ptr->Eid)
         {
             case IE_SSID:
-                // Already has one SSID EID in this beacon, ignore the second one
+                // Already have one SSID EID in this beacon, ignore second one
 				if (Sanity & 0x1)
 					break;
                 if(eid_ptr->Len <= MAX_LEN_OF_SSID)
                 {
                     memcpy(Ssid, eid_ptr->Octet, eid_ptr->Len);
-		    memset(Ssid + eid_ptr->Len,0,1);
+					if (eid_ptr->Len < MAX_LEN_OF_SSID)
+                    	memset(Ssid + eid_ptr->Len,0,1);
                     *SsidLen = eid_ptr->Len;
                     Sanity |= 0x1;
-                    //DBGPRINT(RT_DEBUG_TRACE, "PeerBeaconAndProbeRspSanity - ESSID=%s Len=%d\n",Ssid,eid_ptr->Len);
+                    DBGPRINT(RT_DEBUG_INFO, " -  SSID=%s Len=%d\n",
+							Ssid, eid_ptr->Len);
+                    DBGHEXSTR(RT_DEBUG_INFO, " -  SSID(hex)=",
+							Ssid, eid_ptr->Len);
                 }
                 else
                 {
-                    DBGPRINT(RT_DEBUG_TRACE, "PeerBeaconAndProbeRspSanity - wrong IE_SSID (len=%d)\n",eid_ptr->Len);
+                    DBGPRINT(RT_DEBUG_TRACE, "<=== %s - bad IE_SSID len=%d\n",
+							__FUNCTION__, eid_ptr->Len);
                     return FALSE;
                 }
                 break;
@@ -546,13 +652,15 @@
                 }
                 else
                 {
-                    DBGPRINT(RT_DEBUG_TRACE, "PeerBeaconAndProbeRspSanity - wrong IE_SUPP_RATES (len=%d)\n",eid_ptr->Len);
+                    DBGPRINT(RT_DEBUG_TRACE,
+							"<=== %s - wrong IE_SUPP_RATES (len=%d)\n",
+							__FUNCTION__, eid_ptr->Len);
                     return FALSE;
                 }
                 break;
 
             case IE_FH_PARM:
-                DBGPRINT(RT_DEBUG_TRACE, "PeerBeaconAndProbeRspSanity(IE_FH_PARM) \n");
+                DBGPRINT(RT_DEBUG_INFO, " - (IE_FH_PARM) \n");
                 break;
 
             case IE_DS_PARM:
@@ -561,14 +669,18 @@
                     *Channel = *eid_ptr->Octet;
                     if (ChannelSanity(pAd, *Channel) == 0)
                     {
-                        DBGPRINT(RT_DEBUG_TRACE, "PeerBeaconAndProbeRspSanity - wrong IE_DS_PARM (ch=%d)\n",*Channel);
+                        DBGPRINT(RT_DEBUG_TRACE,
+								"<=== %s - wrong IE_DS_PARM (ch=%d)\n",
+								__FUNCTION__, *Channel);
                         return FALSE;
                     }
                     Sanity |= 0x4;
                 }
                 else
                 {
-                    DBGPRINT(RT_DEBUG_TRACE, "PeerBeaconAndProbeRspSanity - wrong IE_DS_PARM (len=%d)\n",eid_ptr->Len);
+                    DBGPRINT(RT_DEBUG_TRACE,
+							"<=== %s - wrong IE_DS_PARM (len=%d)\n",
+							__FUNCTION__, eid_ptr->Len);
                     return FALSE;
                 }
                 break;
@@ -581,7 +693,8 @@
                 }
                 else
                 {
-                    DBGPRINT(RT_DEBUG_TRACE, "PeerBeaconAndProbeRspSanity - wrong IE_CF_PARM\n");
+                    DBGPRINT(RT_DEBUG_TRACE, "<=== %s - wrong IE_CF_PARM\n",
+							__FUNCTION__);
                     return FALSE;
                 }
                 break;
@@ -593,7 +706,8 @@
                 }
                 else
                 {
-                    DBGPRINT(RT_DEBUG_TRACE, "PeerBeaconAndProbeRspSanity - wrong IE_IBSS_PARM\n");
+                    DBGPRINT(RT_DEBUG_TRACE, "<=== %s - wrong IE_IBSS_PARM\n",
+							__FUNCTION__);
                     return FALSE;
                 }
                 break;
@@ -605,18 +719,45 @@
                 }
                 break;
 
+			case IE_COUNTRY:
+				handle_country_ie((country_ie_p)eid_ptr);
+				break;
+
             // New for WPA
             case IE_WPA:
-                // Check the OUI version, filter out non-standard usage
-                if (RTMPEqualMemory(eid_ptr->Octet, WPA_OUI, 4))
-                {
-                    // Copy to pVIE which will report to microsoft bssid list.
-                    pVIE->ElementID = eid_ptr->Eid;
-                    pVIE->Length = eid_ptr->Len;
-                    memcpy(pVIE->data, eid_ptr->Octet, eid_ptr->Len);
-                }
-                DBGPRINT(RT_DEBUG_INFO, "PeerBeaconAndProbeRspSanity - Receive IE_WPA\n");
-                break;
+				if (vielim >= (UCHAR *)ptVIE + eid_ptr->Len + 2)
+				{
+                    // ptVIE will report to microsoft bssid list.
+                   	ptVIE->ElementID = eid_ptr->Eid;
+                   	ptVIE->Length = eid_ptr->Len;
+                   	memcpy(ptVIE->data, eid_ptr->Octet, eid_ptr->Len);
+					ptVIE = (PNDIS_802_11_VARIABLE_IEs)((UCHAR *)ptVIE +
+							ptVIE->Length + 2);
+					DBGPRINT(RT_DEBUG_INFO, " -  OUI (%02x:%02x:%02x:%02x)\n",
+							eid_ptr->Octet[0], eid_ptr->Octet[1],
+							eid_ptr->Octet[2], eid_ptr->Octet[3]);
+                }
+				else
+				{
+					DBGPRINT(RT_DEBUG_ERROR,
+							" -  IE_WPA rcv area needs %d bytes: has %d left\n",
+							eid_ptr->Len + 2, vielim - (UCHAR *)ptVIE);
+				}
+                break;
+
+			case IE_RSN:
+				if (vielim >= (UCHAR *)ptVIE + eid_ptr->Len + 2)
+				{
+					ptVIE = (PNDIS_802_11_VARIABLE_IEs)((UCHAR *)ptVIE +
+							handle_rsn_ie((rsn_ie_p)eid_ptr, ptVIE));
+				}
+				else
+				{
+					DBGPRINT(RT_DEBUG_ERROR,
+							" -  IE_RSN rcv area needs %d bytes: has %d left\n",
+							eid_ptr->Len + 2, vielim - (UCHAR *)ptVIE);
+				}
+				break;
 
             case IE_EXT_SUPP_RATES:
                 // concatenate all extended rates to Rates[] and RateLen
@@ -654,15 +795,20 @@
                     *Erp = (UCHAR)eid_ptr->Octet[0];
                 }
                 break;
-                
+
             default:
-                DBGPRINT(RT_DEBUG_INFO, "PeerBeaconAndProbeRspSanity - unrecognized EID = %d\n", eid_ptr->Eid);
+                DBGPRINT(RT_DEBUG_ERROR, " -  EID=%d (Len=%d) unrecognized\n",
+						eid_ptr->Eid, eid_ptr->Len);
                 break;
         }
-        
+
         eid_ptr = (PBEACON_EID_STRUCT)((UCHAR*)eid_ptr + 2 + eid_ptr->Len);
     }
-
+	if ((UCHAR *)ptVIE > VarIE) {
+		int vielen = (UCHAR *)ptVIE - VarIE;
+		*VarIELen = vielen;
+		memcpy(pVIE, VarIE, vielen);
+	}
 
     // in 802.11a band, AP may skip this DS IE in their BEACON
     if ((pAd->PortCfg.Channel > 14) && ((Sanity & 0x04)==0))
@@ -670,7 +816,8 @@
         *Channel = pAd->PortCfg.Channel;
         Sanity |= 0x04;
     }
-    
+
+	DBGPRINT(RT_DEBUG_TRACE, "<=== %s: Sanity=0x%02x\n", __FUNCTION__, Sanity);
     if (Sanity != 0x7)
     {
         DBGPRINT(RT_DEBUG_WARN, "PeerBeaconAndProbeRspSanity - missing field, Sanity=0x%02x\n", Sanity);
@@ -683,19 +830,19 @@
 
 }
 
-/* 
+/*
     ==========================================================================
     Description:
     ==========================================================================
  */
 BOOLEAN GetTimBit(
-    IN CHAR *Ptr, 
-    IN USHORT Aid, 
-    OUT UCHAR *TimLen, 
-    OUT UCHAR *BcastFlag, 
-    OUT UCHAR *DtimCount, 
+    IN CHAR *Ptr,
+    IN USHORT Aid,
+    OUT UCHAR *TimLen,
+    OUT UCHAR *BcastFlag,
+    OUT UCHAR *DtimCount,
     OUT UCHAR *DtimPeriod,
-    OUT UCHAR *MessageToMe) 
+    OUT UCHAR *MessageToMe)
 {
     UCHAR          BitCntl, N1, N2, MyByte, MyBit;
     CHAR          *IdxPtr;
@@ -717,11 +864,11 @@
     IdxPtr++;
     BitCntl = *IdxPtr;
 
-    if ((*DtimCount == 0) && (BitCntl & 0x01)) 
+    if ((*DtimCount == 0) && (BitCntl & 0x01))
         *BcastFlag = TRUE;
-    else 
+    else
         *BcastFlag = FALSE;
-    
+
 #if 1
     // Parse Partial Virtual Bitmap from TIM element
     N1 = BitCntl & 0xfe;    // N1 is the first bitmap byte#
@@ -738,10 +885,10 @@
 
         //if (*IdxPtr)
         //    DBGPRINT(RT_DEBUG_WARN, ("TIM bitmap = 0x%02x\n", *IdxPtr));
-            
+
         if (*IdxPtr & (0x01 << MyBit))
             *MessageToMe = TRUE;
-        else 
+        else
             *MessageToMe = FALSE;
     }
 #else
@@ -760,15 +907,15 @@
  *  \post
  */
 BOOLEAN GetLegacy(
-    IN CHAR *Ptr, 
-    OUT UCHAR *Legacy) 
+    IN CHAR *Ptr,
+    OUT UCHAR *Legacy)
 {
     *Legacy = 0;
     return TRUE;
 }
 
 UCHAR ChannelSanity(
-    IN PRTMP_ADAPTER pAd, 
+    IN PRTMP_ADAPTER pAd,
     IN UCHAR channel)
 {
     UCHAR index;
@@ -780,52 +927,52 @@
     }
     return 0;
 
-#if 0    
+#if 0
     switch (pAd->PortCfg.CountryRegion)
     {
         case REGION_FCC:    // 1 - 11
             if ((channel > 0) && (channel < 12))
                 return 1;
             break;
-            
+
         case REGION_IC:     // 1 -11
             if ((channel > 0) && (channel < 12))
                 return 1;
             break;
-            
+
         case REGION_ETSI:   // 1 - 13
             if ((channel > 0) && (channel < 14))
                 return 1;
             break;
-            
+
         case REGION_SPAIN:  // 10 - 11
             if ((channel > 9) && (channel < 12))
                 return 1;
             break;
-            
+
         case REGION_FRANCE: // 10 -13
             if ((channel > 9) && (channel < 14))
                 return 1;
             break;
-            
+
         case REGION_MKK:    // 14
-            if (channel == 14)              
+            if (channel == 14)
                 return 1;
             break;
-            
+
         case REGION_MKK1:   // 1 - 14
             if ((channel > 0) && (channel < 15))
                 return 1;
             break;
-            
+
         case REGION_ISRAEL: // 3 - 9
             if ((channel > 2) && (channel < 10))
                 return 1;
             break;
-            
+
         default:            // Error
-            return 0;           
-    }   
+            return 0;
+    }
     return (0);
-#endif    
+#endif
 }
diff -Nur rt2500-1.1.0-b4/Module/sync.c rt2500-cvs-2007061011/Module/sync.c
--- rt2500-1.1.0-b4/Module/sync.c	2006-06-17 22:12:58.000000000 +0200
+++ rt2500-cvs-2007061011/Module/sync.c	2007-05-15 21:41:35.000000000 +0200
@@ -1,37 +1,37 @@
-/*************************************************************************** 
- * RT2400/RT2500 SourceForge Project - http://rt2x00.serialmonkey.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.                          * 
- *                                                                         * 
- *   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.             * 
- *                                                                         * 
- *   Licensed under the GNU GPL                                            * 
- *   Original code supplied under license from RaLink Inc, 2004.           * 
- ***************************************************************************/ 
-
- /*************************************************************************** 
- *      Module Name: sync.c 
- *              
- *      Abstract: 
- *              
- *      Revision History: 
- *      Who             When            What 
- *      --------        -----------     ----------------------------- 
- *      MarkW           8th  Dec 04     Baseline code  
+/***************************************************************************
+ * RT2400/RT2500 SourceForge Project - http://rt2x00.serialmonkey.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.                          *
+ *                                                                         *
+ *   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.             *
+ *                                                                         *
+ *   Licensed under the GNU GPL                                            *
+ *   Original code supplied under license from RaLink Inc, 2004.           *
+ ***************************************************************************/
+
+ /***************************************************************************
+ *      Module Name: sync.c
+ *
+ *      Abstract:
+ *
+ *      Revision History:
+ *      Who             When            What
+ *      --------        -----------     -----------------------------
+ *      MarkW           8th  Dec 04     Baseline code
  *      MarkW           10th Dec 04     Rolled in Ralink 1.4.5.0
 * 		MarkW			5th  Jun 05		Fix no-SSID broadcasting assoc.
- ***************************************************************************/ 
+ ***************************************************************************/
 
 #include "rt_config.h"
 
@@ -59,7 +59,7 @@
 /*
     ==========================================================================
     Description:
-        The sync state machine, 
+        The sync state machine,
     Parameters:
         Sm - pointer to the state machine
     Note:
@@ -93,9 +93,9 @@
     ==========================================================================
  */
 VOID SyncStateMachineInit(
-    IN PRTMP_ADAPTER pAd, 
-    IN STATE_MACHINE *Sm, 
-    OUT STATE_MACHINE_FUNC Trans[]) 
+    IN PRTMP_ADAPTER pAd,
+    IN STATE_MACHINE *Sm,
+    OUT STATE_MACHINE_FUNC Trans[])
 {
     StateMachineInit(Sm, (STATE_MACHINE_FUNC*)Trans, MAX_SYNC_STATE, MAX_SYNC_MSG, (STATE_MACHINE_FUNC)Drop, SYNC_IDLE, SYNC_MACHINE_BASE);
 
@@ -105,7 +105,7 @@
     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_RSP, (STATE_MACHINE_FUNC)PeerBeacon);
-    StateMachineSetAction(Sm, SYNC_IDLE, MT2_PEER_PROBE_REQ, (STATE_MACHINE_FUNC)PeerProbeReqAction); 
+    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);
@@ -127,14 +127,14 @@
     RTMPInitTimer(pAd, &pAd->Mlme.SyncAux.ScanTimer, ScanTimeout);
 }
 
-/* 
+/*
     ==========================================================================
     Description:
         Becaon timeout handler, executed in timer thread
     ==========================================================================
  */
 VOID BeaconTimeout(
-    IN  unsigned long data) 
+    IN  unsigned long data)
 {
     RTMP_ADAPTER *pAd = (RTMP_ADAPTER *)data;
 
@@ -143,30 +143,30 @@
     MlmeHandler(pAd);
 }
 
-/* 
+/*
     ==========================================================================
     Description:
         ATIM timeout handler, executed in timer thread
     ==========================================================================
  */
 VOID AtimTimeout(
-    IN  unsigned long data) 
+    IN  unsigned long data)
 {
     RTMP_ADAPTER *pAd = (RTMP_ADAPTER *)data;
-    
+
     DBGPRINT(RT_DEBUG_TRACE,"SYNC - AtimTimeout \n");
     MlmeEnqueue(&pAd->Mlme.Queue, SYNC_STATE_MACHINE, MT2_ATIM_TIMEOUT, 0, NULL);
     MlmeHandler(pAd);
 }
 
-/* 
+/*
     ==========================================================================
     Description:
         Scan timeout handler, executed in timer thread
     ==========================================================================
  */
 VOID ScanTimeout(
-    IN  unsigned long data) 
+    IN  unsigned long data)
 {
     RTMP_ADAPTER *pAd = (RTMP_ADAPTER *)data;
 
@@ -175,15 +175,15 @@
     MlmeHandler(pAd);
 }
 
-/* 
+/*
     ==========================================================================
     Description:
         MLME SCAN req state machine procedure
     ==========================================================================
  */
 VOID MlmeScanReqAction(
-    IN PRTMP_ADAPTER pAd, 
-    IN MLME_QUEUE_ELEM *Elem) 
+    IN PRTMP_ADAPTER pAd,
+    IN MLME_QUEUE_ELEM *Elem)
 {
     UCHAR          Ssid[MAX_LEN_OF_SSID], SsidLen, ScanType, BssType;
     ULONG          Now;
@@ -192,13 +192,13 @@
     RTMPSuspendMsduTransmission(pAd);
 
     // first check the parameter sanity
-    if (MlmeScanReqSanity(pAd, 
-                          Elem->Msg, 
-                          Elem->MsgLen, 
-                          &BssType, 
-                          Ssid, 
-                          &SsidLen, 
-                          &ScanType)) 
+    if (MlmeScanReqSanity(pAd,
+                          Elem->Msg,
+                          Elem->MsgLen,
+                          &BssType,
+                          Ssid,
+                          &SsidLen,
+                          &ScanType))
     {
         DBGPRINT(RT_DEBUG_TRACE, "SYNC - MlmeScanReqAction\n");
         Now = jiffies;
@@ -212,12 +212,12 @@
         pAd->Mlme.SyncAux.ScanType = ScanType;
         pAd->Mlme.SyncAux.SsidLen = SsidLen;
         memcpy(pAd->Mlme.SyncAux.Ssid, Ssid, SsidLen);
-        
+
         // start from the first channel
         pAd->Mlme.SyncAux.Channel = FirstChannel(pAd);
         ScanNextChannel(pAd);
-    } 
-    else 
+    }
+    else
     {
         printk(KERN_ERR DRV_NAME "SYNC - MlmeScanReqAction() sanity check fail. BUG!!!\n");
         pAd->Mlme.SyncMachine.CurrState = SYNC_IDLE;
@@ -225,15 +225,15 @@
     }
 }
 
-/* 
+/*
     ==========================================================================
     Description:
         MLME JOIN req state machine procedure
     ==========================================================================
  */
 VOID MlmeJoinReqAction(
-    IN PRTMP_ADAPTER pAd, 
-    IN MLME_QUEUE_ELEM *Elem) 
+    IN PRTMP_ADAPTER pAd,
+    IN MLME_QUEUE_ELEM *Elem)
 {
     BSS_ENTRY    *pBss;
     MLME_JOIN_REQ_STRUCT *Info = (MLME_JOIN_REQ_STRUCT *)(Elem->Msg);
@@ -255,7 +255,7 @@
     AsicSwitchChannel(pAd, pBss->Channel);
     AsicLockChannel(pAd, pBss->Channel);
     DBGPRINT(RT_DEBUG_TRACE, "SYNC - Switch to channel %d, SSID %s \n", pBss->Channel, pAd->Mlme.SyncAux.Ssid);
-    DBGPRINT(RT_DEBUG_TRACE, "SYNC - Wait BEACON from %02x:%02x:%02x:%02x:%02x:%02x ...\n", 
+    DBGPRINT(RT_DEBUG_TRACE, "SYNC - Wait BEACON from %02x:%02x:%02x:%02x:%02x:%02x ...\n",
         pAd->Mlme.SyncAux.Bssid.Octet[0], pAd->Mlme.SyncAux.Bssid.Octet[1],
         pAd->Mlme.SyncAux.Bssid.Octet[2], pAd->Mlme.SyncAux.Bssid.Octet[3],
         pAd->Mlme.SyncAux.Bssid.Octet[4], pAd->Mlme.SyncAux.Bssid.Octet[5]);
@@ -264,17 +264,17 @@
     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) 
+    IN PRTMP_ADAPTER pAd,
+    IN MLME_QUEUE_ELEM *Elem)
 {
-    UCHAR         Ssid[MAX_LEN_OF_SSID], SsidLen; 
+    UCHAR         Ssid[MAX_LEN_OF_SSID], SsidLen;
 
     // New for WPA security suites
     UCHAR                       VarIE[MAX_VIE_LEN];     // Total VIE length = MAX_VIE_LEN - -5
@@ -293,20 +293,20 @@
     TimeStamp.vv.LowPart  = 0;
     TimeStamp.vv.HighPart = 0;
 
-    if (MlmeStartReqSanity(pAd, Elem->Msg, Elem->MsgLen, Ssid, &SsidLen)) 
+    if (MlmeStartReqSanity(pAd, Elem->Msg, Elem->MsgLen, Ssid, &SsidLen))
     {
         // reset all the timers
         RTMPCancelTimer(&pAd->Mlme.SyncAux.ScanTimer);
         RTMPCancelTimer(&pAd->Mlme.SyncAux.BeaconTimer);
 
-        // PortCfg.PrivacyInvoked should have been set via OID_802_11_WEP_STATUS. 
+        // PortCfg.PrivacyInvoked should have been set via OID_802_11_WEP_STATUS.
         // pAd->PortCfg.PrivacyInvoked = FALSE;
 
-        memcpy(pAd->PortCfg.Ssid, Ssid, SsidLen); 
+        memcpy(pAd->PortCfg.Ssid, Ssid, SsidLen);
         pAd->PortCfg.SsidLen           = SsidLen;
         pAd->PortCfg.BssType           = BSS_INDEP;
-        Privacy = (pAd->PortCfg.WepStatus == Ndis802_11Encryption1Enabled) || 
-                  (pAd->PortCfg.WepStatus == Ndis802_11Encryption2Enabled) || 
+        Privacy = (pAd->PortCfg.WepStatus == Ndis802_11Encryption1Enabled) ||
+                  (pAd->PortCfg.WepStatus == Ndis802_11Encryption2Enabled) ||
                   (pAd->PortCfg.WepStatus == Ndis802_11Encryption3Enabled);
         pAd->PortCfg.CapabilityInfo    = CAP_GENERATE(0,1,0,0,Privacy, (pAd->PortCfg.WindowsTxPreamble == Rt802_11PreambleShort));
         pAd->PortCfg.BeaconPeriod      = pAd->PortCfg.IbssConfig.BeaconPeriod;
@@ -328,7 +328,7 @@
 
         // generate a radom number as BSSID
         MacAddrRandomBssid(pAd, &pAd->PortCfg.Bssid);
-        AsicSetBssid(pAd, &pAd->PortCfg.Bssid); 
+        AsicSetBssid(pAd, &pAd->PortCfg.Bssid);
         AsicSwitchChannel(pAd, pAd->PortCfg.Channel);
         AsicLockChannel(pAd, pAd->PortCfg.Channel);
 
@@ -341,17 +341,17 @@
         if (Bssidx == BSS_NOT_FOUND)
         {
             Bssidx = BssTableSetEntry(pAd, &pAd->PortCfg.BssTab, &pAd->PortCfg.Bssid,
-                Ssid, SsidLen, pAd->PortCfg.BssType, pAd->PortCfg.BeaconPeriod, 
-                CfExist, &CfParm, pAd->PortCfg.AtimWin, pAd->PortCfg.CapabilityInfo, 
+                Ssid, SsidLen, pAd->PortCfg.BssType, pAd->PortCfg.BeaconPeriod,
+                CfExist, &CfParm, pAd->PortCfg.AtimWin, pAd->PortCfg.CapabilityInfo,
                 pAd->PortCfg.SupportedRates, pAd->PortCfg.SupportedRatesLen, TRUE,
-                pAd->PortCfg.Channel, Elem->Rssi, TimeStamp, pVIE);
+                pAd->PortCfg.Channel, Elem->Rssi, TimeStamp, 0, pVIE);
         }
 #endif
 
         pAd->Mlme.SyncMachine.CurrState = SYNC_IDLE;
         MlmeCntlConfirm(pAd, MT2_START_CONF, (USHORT)MLME_SUCCESS);
-    } 
-    else 
+    }
+    else
     {
         printk(KERN_ERR DRV_NAME "SYNC - MlmeStartReqAction() sanity check fail. BUG!!!\n");
         pAd->Mlme.SyncMachine.CurrState = SYNC_IDLE;
@@ -359,18 +359,18 @@
     }
 }
 
-/* 
+/*
     ==========================================================================
     Description:
         peer sends beacon back when scanning
     ==========================================================================
  */
 VOID PeerBeaconAtScanAction(
-    IN PRTMP_ADAPTER pAd, 
-    IN MLME_QUEUE_ELEM *Elem) 
+    IN PRTMP_ADAPTER pAd,
+    IN MLME_QUEUE_ELEM *Elem)
 {
     MACADDR         Bssid, Addr2;
-    UCHAR           Ssid[MAX_LEN_OF_SSID], BssType, Channel, Rates[MAX_LEN_OF_SUPPORTED_RATES], RatesLen, 
+    UCHAR           Ssid[MAX_LEN_OF_SSID], BssType, Channel, Rates[MAX_LEN_OF_SUPPORTED_RATES], RatesLen,
                     SsidLen, DtimCount, DtimPeriod, BcastFlag, MessageToMe, Legacy;
     CF_PARM         CfParm;
     USHORT          BeaconPeriod, AtimWin, CapabilityInfo;
@@ -383,54 +383,55 @@
 	UCHAR           SupRateLen, ExtRateLen;
 
     // New for WPA security suites
-    UCHAR                       VarIE[MAX_VIE_LEN];     // Total VIE length = MAX_VIE_LEN - -5
+    USHORT           VarIELen;	// Length of all saved IEs.
+    UCHAR            VarIE[MAX_VIE_LEN];     // Total VIE length = MAX_VIE_LEN - -5
     NDIS_802_11_VARIABLE_IEs    *pVIE = NULL;
 
     // NdisFillMemory(Ssid, MAX_LEN_OF_SSID, 0x00);
     Fr = (MACFRAME *) Elem->Msg;
     // Init Variable IE structure
     pVIE = (PNDIS_802_11_VARIABLE_IEs) VarIE;
-    pVIE->Length = 0;
-    if (PeerBeaconAndProbeRspSanity(pAd, 
-                                Elem->Msg, 
-                                Elem->MsgLen, 
-                                &Addr2, 
-                                &Bssid, Ssid, 
-                                &SsidLen, 
-                                &BssType, 
-                                &BeaconPeriod, 
-                                &Channel, 
-                                &TimeStamp, 
-                                &CfExist, 
-                                &CfParm, 
-                                &AtimWin, 
-                                &CapabilityInfo, 
-                                Rates, 
+    if (PeerBeaconAndProbeRspSanity(pAd,
+                                Elem->Msg,
+                                Elem->MsgLen,
+                                &Addr2,
+                                &Bssid, Ssid,
+                                &SsidLen,
+                                &BssType,
+                                &BeaconPeriod,
+                                &Channel,
+                                &TimeStamp,
+                                &CfExist,
+                                &CfParm,
+                                &AtimWin,
+                                &CapabilityInfo,
+                                Rates,
                                 &RatesLen,
                                 &ExtendedRateIeExist,
                                 &Erp,
-                                &DtimCount, 
-                                &DtimPeriod, 
-                                &BcastFlag, 
-                                &MessageToMe, 
+                                &DtimCount,
+                                &DtimPeriod,
+                                &BcastFlag,
+                                &MessageToMe,
                                 &Legacy,
                                 SupRate,
                                 &SupRateLen,
                                 ExtRate,
                                 &ExtRateLen,
-                                pVIE)) 
+                                &VarIELen,
+                                pVIE))
     {
         ULONG Idx;
         UCHAR Rssi = 0;
 	UCHAR Noise = 0;
 
         // This correct im-proper RSSI indication during SITE SURVEY issue.
-        // Always report bigger RSSI during SCANNING when receiving multiple BEACONs from the same AP. 
-        // This case happens because BEACONs come from adjacent channels, so RSSI become weaker as we 
+        // Always report bigger RSSI during SCANNING when receiving multiple BEACONs from the same AP.
+        // This case happens because BEACONs come from adjacent channels, so RSSI become weaker as we
         // switch to more far away channels.
         Idx = BssTableSearch(&pAd->PortCfg.BssTab, &Bssid);
         if (Idx != BSS_NOT_FOUND)
-	{ 
+	{
             Rssi = pAd->PortCfg.BssTab.BssEntry[Idx].Rssi;
 	    Noise = pAd->PortCfg.BssTab.BssEntry[Idx].Noise;
 	}
@@ -445,25 +446,25 @@
 
         // Mask out unnecessary capability information
         CapabilityInfo &= SUPPORTED_CAPABILITY_INFO;
-        BssTableSetEntry(pAd, &pAd->PortCfg.BssTab, &Bssid, Ssid, SsidLen, BssType, 
-                         BeaconPeriod, CfExist, &CfParm, AtimWin, CapabilityInfo, Rates, 
-                         RatesLen, ExtendedRateIeExist, Channel, Rssi, Noise, TimeStamp, pVIE);
+        BssTableSetEntry(pAd, &pAd->PortCfg.BssTab, &Bssid, Ssid, SsidLen, BssType,
+                         BeaconPeriod, CfExist, &CfParm, AtimWin, CapabilityInfo, Rates,
+                         RatesLen, ExtendedRateIeExist, Channel, Rssi, Noise, TimeStamp, VarIELen, pVIE);
     }
     // 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) 
+    IN PRTMP_ADAPTER pAd,
+    IN MLME_QUEUE_ELEM *Elem)
 {
     MACADDR       Bssid, Addr2;
-    UCHAR         Ssid[MAX_LEN_OF_SSID], SsidLen, BssType, Channel, RatesLen, MessageToMe, 
+    UCHAR         Ssid[MAX_LEN_OF_SSID], SsidLen, BssType, Channel, RatesLen, MessageToMe,
                   Rates[MAX_LEN_OF_SUPPORTED_RATES], DtimCount, DtimPeriod, BcastFlag, Legacy;
     LARGE_INTEGER TimeStamp;
     USHORT        BeaconPeriod, AtimWin, CapabilityInfo;
@@ -474,46 +475,48 @@
 	UCHAR		  SupRateLen, ExtRateLen;
 
 	// New for WPA security suites
-	UCHAR						VarIE[MAX_VIE_LEN];		// Total VIE length = MAX_VIE_LEN - -5
+    USHORT        VarIELen;				// Length of all saved IEs.
+	UCHAR         VarIE[MAX_VIE_LEN];	// Total VIE length = MAX_VIE_LEN - -5
 	NDIS_802_11_VARIABLE_IEs	*pVIE = NULL;
 
 	// Init Variable IE structure
 	pVIE = (PNDIS_802_11_VARIABLE_IEs) VarIE;
 	pVIE->Length = 0;
-    if (PeerBeaconAndProbeRspSanity(pAd, 
-                                Elem->Msg, 
-                                Elem->MsgLen, 
-                                &Addr2, 
-                                &Bssid, 
-                                Ssid, 
-                                &SsidLen, 
-                                &BssType, 
-                                &BeaconPeriod, 
-                                &Channel, 
-                                &TimeStamp, 
-                                &CfExist, 
-                                &Cf, 
-                                &AtimWin, 
-                                &CapabilityInfo, 
-                                Rates, 
+    if (PeerBeaconAndProbeRspSanity(pAd,
+                                Elem->Msg,
+                                Elem->MsgLen,
+                                &Addr2,
+                                &Bssid,
+                                Ssid,
+                                &SsidLen,
+                                &BssType,
+                                &BeaconPeriod,
+                                &Channel,
+                                &TimeStamp,
+                                &CfExist,
+                                &Cf,
+                                &AtimWin,
+                                &CapabilityInfo,
+                                Rates,
                                 &RatesLen,
                                 &ExtendedRateIeExist,
                                 &Erp,
-                                &DtimCount, 
-                                &DtimPeriod, 
-                                &BcastFlag, 
-                                &MessageToMe, 
+                                &DtimCount,
+                                &DtimPeriod,
+                                &BcastFlag,
+                                &MessageToMe,
                                 &Legacy,
 								SupRate,
 								&SupRateLen,
 								ExtRate,
 								&ExtRateLen,
-                                pVIE)) 
+                                &VarIELen,
+                                pVIE))
     {
 		// Disqualify 11b only adhoc when we are in 11g only adhoc mode
 		if ((BssType == BSS_INDEP) && (pAd->PortCfg.AdhocMode == 2) && (RatesLen < 12))
 			return;
-		
+
 		if (MAC_ADDR_EQUAL(&pAd->Mlme.SyncAux.Bssid, &Bssid))
         {
             DBGPRINT(RT_DEBUG_TRACE, "SYNC - receive desired BEACON at JoinWaitBeacon...\n");
@@ -522,7 +525,7 @@
 			// Update RSSI to prevent No signal display when cards first initialized
             pAd->PortCfg.LastRssi = Elem->Rssi;
 			pAd->PortCfg.AvgRssi  = Elem->Rssi;
-			
+
             if (pAd->Mlme.SyncAux.SsidLen > 0)
             {
             	memcpy(pAd->PortCfg.Ssid, pAd->Mlme.SyncAux.Ssid, pAd->Mlme.SyncAux.SsidLen);
@@ -533,7 +536,7 @@
             	memcpy(pAd->PortCfg.Ssid, Ssid, SsidLen);
             	pAd->PortCfg.SsidLen = SsidLen;
 			}
-        
+
             COPY_MAC_ADDR(&pAd->PortCfg.Bssid, &Bssid);
             AsicSetBssid(pAd, &pAd->PortCfg.Bssid);
 
@@ -620,22 +623,22 @@
 			{
                 pAd->PortCfg.ExtRateLen = 0;
 			}
-			
-            DBGPRINT(RT_DEBUG_TRACE, "SYNC - AP's SupportedRatesLen=%d, set STA's SupportedRateLen=%d\n", 
+
+            DBGPRINT(RT_DEBUG_TRACE, "SYNC - AP's SupportedRatesLen=%d, set STA's SupportedRateLen=%d\n",
                 RatesLen, pAd->PortCfg.SupportedRatesLen);
-            
+
 			// Mask out unnecessary capability information
 			CapabilityInfo &= SUPPORTED_CAPABILITY_INFO;
-			
+
             // Check for 802.11g information, if 802.11 b/g mixed mode.
             // We can't support its short preamble for now.
            	pAd->PortCfg.CapabilityInfo = CapabilityInfo;
 
-            if ((BssType == BSS_INDEP) && (CAP_IS_IBSS_ON(CapabilityInfo))) 
+            if ((BssType == BSS_INDEP) && (CAP_IS_IBSS_ON(CapabilityInfo)))
             {
                 pAd->PortCfg.AtimWin = AtimWin;
-            } 
-            else if (BssType == BSS_INFRA) 
+            }
+            else if (BssType == BSS_INFRA)
             {
                 pAd->PortCfg.CfpPeriod = Cf.CfpPeriod;
                 pAd->PortCfg.CfpMaxDuration = Cf.CfpMaxDuration;
@@ -650,19 +653,19 @@
             MlmeCntlConfirm(pAd, MT2_JOIN_CONF, MLME_SUCCESS);
         }
         // not to me BEACON, ignored
-    } 
+    }
     // sanity check fail, ignore this frame
 }
 
-/* 
+/*
     ==========================================================================
     Description:
         receive BEACON from peer
     ==========================================================================
  */
 VOID PeerBeacon(
-    IN PRTMP_ADAPTER pAd, 
-    IN MLME_QUEUE_ELEM *Elem) 
+    IN PRTMP_ADAPTER pAd,
+    IN MLME_QUEUE_ELEM *Elem)
 {
     MACADDR       Bssid, Addr2;
     CHAR          Ssid[MAX_LEN_OF_SSID];
@@ -679,7 +682,8 @@
 	UCHAR		  SupRateLen, ExtRateLen;
 
     // New for WPA security suites
-    UCHAR                       VarIE[MAX_VIE_LEN];     // Total VIE length = MAX_VIE_LEN - -5
+    USHORT        VarIELen;				// Length of all saved IEs.
+    UCHAR         VarIE[MAX_VIE_LEN];	// Total VIE length = MAX_VIE_LEN - -5
     NDIS_802_11_VARIABLE_IEs    *pVIE = NULL;
 
     if (!INFRA_ON(pAd) && !ADHOC_ON(pAd))
@@ -688,35 +692,36 @@
     // Init Variable IE structure
     pVIE = (PNDIS_802_11_VARIABLE_IEs) VarIE;
     pVIE->Length = 0;
-    if (PeerBeaconAndProbeRspSanity(pAd, 
-                                Elem->Msg, 
-                                Elem->MsgLen, 
-                                &Addr2, 
-                                &Bssid, 
-                                Ssid, 
-                                &SsidLen, 
-                                &BssType, 
-                                &BeaconPeriod, 
-                                &Channel, 
-                                &TimeStamp, 
-                                &CfExist, 
-                                &CfParm, 
-                                &AtimWin, 
-                                &CapabilityInfo, 
-                                Rates, 
+    if (PeerBeaconAndProbeRspSanity(pAd,
+                                Elem->Msg,
+                                Elem->MsgLen,
+                                &Addr2,
+                                &Bssid,
+                                Ssid,
+                                &SsidLen,
+                                &BssType,
+                                &BeaconPeriod,
+                                &Channel,
+                                &TimeStamp,
+                                &CfExist,
+                                &CfParm,
+                                &AtimWin,
+                                &CapabilityInfo,
+                                Rates,
                                 &RatesLen,
                                 &ExtendedRateIeExist,
                                 &Erp,
-                                &DtimCount, 
-                                &DtimPeriod, 
-                                &BcastFlag, 
-                                &MessageToMe, 
+                                &DtimCount,
+                                &DtimPeriod,
+                                &BcastFlag,
+                                &MessageToMe,
                                 &Legacy,
                                 SupRate,
                                 &SupRateLen,
                                 ExtRate,
                                 &ExtRateLen,
-                                pVIE)) 
+                                &VarIELen,
+                                pVIE))
     {
         BOOLEAN is_my_bssid, is_my_ssid;
         ULONG   Bssidx, Now;
@@ -732,7 +737,7 @@
             return;
 
 		//
-        // Housekeeping "SsidBssTab" table for later-on ROAMing usage. 
+        // Housekeeping "SsidBssTab" table for later-on ROAMing usage.
         //
         Bssidx = BssTableSearch(&pAd->Mlme.CntlAux.SsidBssTab, &Bssid);
         if (Bssidx == BSS_NOT_FOUND)
@@ -743,24 +748,24 @@
 				return;
 			if (!RTMPEqualMemory(pAd->PortCfg.Ssid, pAd->Mlme.CntlAux.Ssid, pAd->PortCfg.SsidLen))
 				return;
-			
+
             // discover new AP of this network, create BSS entry
-            Bssidx = BssTableSetEntry(pAd, &pAd->Mlme.CntlAux.SsidBssTab, &Bssid, Ssid, SsidLen, 
-                        BssType, BeaconPeriod, CfExist, &CfParm, AtimWin, CapabilityInfo, 
-                        Rates, RatesLen, ExtendedRateIeExist, Channel, Elem->Rssi, Elem->Noise, TimeStamp, pVIE);
+            Bssidx = BssTableSetEntry(pAd, &pAd->Mlme.CntlAux.SsidBssTab, &Bssid, Ssid, SsidLen,
+                        BssType, BeaconPeriod, CfExist, &CfParm, AtimWin, CapabilityInfo,
+                        Rates, RatesLen, ExtendedRateIeExist, Channel, Elem->Rssi, Elem->Noise, TimeStamp, VarIELen, pVIE);
 
             if (Bssidx == BSS_NOT_FOUND) // return if BSS table full
-                return;  
+                return;
 
-            DBGPRINT(RT_DEBUG_TRACE, "SYNC - New AP added to SsidBssTab[%d], RSSI=%d, MAC=%02x:%02x:%02x:%02x:%02x:%02x\n", 
-                Bssidx, Elem->Rssi, Bssid.Octet[0], Bssid.Octet[1], Bssid.Octet[2], 
+            DBGPRINT(RT_DEBUG_TRACE, "SYNC - New AP added to SsidBssTab[%d], RSSI=%d, MAC=%02x:%02x:%02x:%02x:%02x:%02x\n",
+                Bssidx, Elem->Rssi, Bssid.Octet[0], Bssid.Octet[1], Bssid.Octet[2],
                 Bssid.Octet[3], Bssid.Octet[4], Bssid.Octet[5]);
         }
 
         // 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_ssid && (! is_my_bssid) && ADHOC_ON(pAd))
-        {
+        if (is_my_ssid && (! is_my_bssid) && ADHOC_ON(pAd)
+	    && (BssType == BSS_INDEP)) {
             INT i;
 			// Add to safe guard adhoc wep status mismatch
 			if (pAd->PortCfg.WepStatus != pAd->Mlme.CntlAux.SsidBssTab.BssEntry[Bssidx].WepStatus)
@@ -773,7 +778,7 @@
                 {
                     AsicDisableSync(pAd);
                     memcpy(&pAd->PortCfg.Bssid, &Bssid, 6);
-                    AsicSetBssid(pAd, &pAd->PortCfg.Bssid); 
+                    AsicSetBssid(pAd, &pAd->PortCfg.Bssid);
                     MakeIbssBeacon(pAd);
                     AsicEnableIbssSync(pAd);
                     break;
@@ -781,9 +786,9 @@
             }
         }
 
-        DBGPRINT(RT_DEBUG_INFO, "SYNC - PeerBeacon from %02x:%02x:%02x:%02x:%02x:%02x - Dtim=%d/%d, Rssi=%02x\n", 
-            Bssid.Octet[0], Bssid.Octet[1], Bssid.Octet[2], 
-            Bssid.Octet[3], Bssid.Octet[4], Bssid.Octet[5], 
+        DBGPRINT(RT_DEBUG_INFO, "SYNC - PeerBeacon from %02x:%02x:%02x:%02x:%02x:%02x - Dtim=%d/%d, Rssi=%02x\n",
+            Bssid.Octet[0], Bssid.Octet[1], Bssid.Octet[2],
+            Bssid.Octet[3], Bssid.Octet[4], Bssid.Octet[5],
             DtimCount, DtimPeriod, Elem->Rssi);
 
         Now = jiffies;
@@ -793,24 +798,24 @@
 
         //
         // BEACON from my BSSID - either IBSS or INFRA network
-        // 
+        //
         if (is_my_bssid)
         {
-            // 2002/12/06 - patch Abocom AP bug, which forgets to set "Privacy" bit in 
-            // AssocRsp even though this bit is ON in Beacon. So we update according 
+            // 2002/12/06 - patch Abocom AP bug, which forgets to set "Privacy" bit in
+            // AssocRsp even though this bit is ON in Beacon. So we update according
             // to following Beacon frame.
             // pAd->PortCfg.PrivacyInvoked = CAP_IS_PRIVACY_ON(CapabilityInfo);
-            
+
             pAd->PortCfg.LastBeaconRxTime = Now;
 #if 1
             // 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()
-            if (ADHOC_ON(pAd) && (RatesLen <= 4))   
+            if (ADHOC_ON(pAd) && (RatesLen <= 4))
             {
                 // this timestamp is for MlmePeriodicExec() to check if all 11B peers have left
                 pAd->PortCfg.Last11bBeaconRxTime = Now;
-                
+
                 if (pAd->PortCfg.MaxTxRate > RATE_11)
                 {
                     DBGPRINT(RT_DEBUG_TRACE, "SYNC - 11b peer joined. down-grade to 11b TX rates \n");
@@ -828,22 +833,22 @@
                 (pAd->PortCfg.LastRssi < pAd->PortCfg.RssiTrigger))
             {
                 // NDIS_802_11_RSSI Dbm = pAd->PortCfg.LastRssi - RSSI_TO_DBM_OFFSET;
-                // DBGPRINT(RT_DEBUG_TRACE, "SYNC - NdisMIndicateStatus *** RSSI %d dBm, less than threshold %d dBm\n", 
+                // DBGPRINT(RT_DEBUG_TRACE, "SYNC - NdisMIndicateStatus *** RSSI %d dBm, less than threshold %d dBm\n",
                 //     Dbm, pAd->PortCfg.RssiTrigger - RSSI_TO_DBM_OFFSET);
             }
             else if ((pAd->PortCfg.RssiTriggerMode == RSSI_TRIGGERED_UPON_EXCCEED_THRESHOLD) &&
                 (pAd->PortCfg.LastRssi > pAd->PortCfg.RssiTrigger))
             {
                 // NDIS_802_11_RSSI Dbm = pAd->PortCfg.LastRssi - RSSI_TO_DBM_OFFSET;
-                // DBGPRINT(RT_DEBUG_TRACE, "SYNC - NdisMIndicateStatus *** RSSI %d dBm, greater than threshold %d dBm\n", 
+                // DBGPRINT(RT_DEBUG_TRACE, "SYNC - NdisMIndicateStatus *** RSSI %d dBm, greater than threshold %d dBm\n",
                 //     Dbm, pAd->PortCfg.RssiTrigger - RSSI_TO_DBM_OFFSET);
             }
 
             if (INFRA_ON(pAd)) // && (pAd->PortCfg.PhyMode == PHY_11BG_MIXED))
             {
                 BOOLEAN bUseShortSlot, bUseBGProtection;
-                
-                // decide to use/change to - 
+
+                // 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
@@ -867,7 +872,7 @@
             }
 
             // only INFRASTRUCTURE mode support power-saving feature
-            if (INFRA_ON(pAd) && (pAd->PortCfg.Psm == PWR_SAVE)) 
+            if (INFRA_ON(pAd) && (pAd->PortCfg.Psm == PWR_SAVE))
             {
                 //  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
@@ -882,17 +887,17 @@
                 else if (BcastFlag && (DtimCount == 0) && pAd->PortCfg.RecvDtim)
                 {
                     DBGPRINT(RT_DEBUG_TRACE, "SYNC - AP backlog broadcast/multicast, stay AWAKE\n");
-                } 
+                }
                 else if ((RTMPFreeDescriptorRequest(pAd, TX_RING, TX_RING_SIZE) != NDIS_STATUS_SUCCESS) ||
                     (RTMPFreeDescriptorRequest(pAd, PRIO_RING, PRIO_RING_SIZE) != NDIS_STATUS_SUCCESS))
                 {
                     DBGPRINT(RT_DEBUG_TRACE, "SYNC - outgoing frame in TxRing/PrioRing, stay AWAKE\n");
                 }
-                else 
+                else
                 {
                     USHORT NextDtim = DtimCount;
 
-                    if (NextDtim == 0) 
+                    if (NextDtim == 0)
                         NextDtim = DtimPeriod;
 
                     TbttNumToNextWakeUp = pAd->PortCfg.DefaultListenCount;
@@ -906,20 +911,21 @@
 
 #ifndef SINGLE_ADHOC_LINKUP
             // At least another peer in this IBSS, declare MediaState as CONNECTED
-            if (ADHOC_ON(pAd) && (pAd->MediaState == NdisMediaStateDisconnected))
-            {
+            if (ADHOC_ON(pAd)
+		&& (pAd->MediaState == NdisMediaStateDisconnected)
+		&& (BssType == BSS_INDEP)) {
                 pAd->MediaState = NdisMediaStateConnected;
 
                 // 2003/03/12 - john
                 // Make sure this entry in "PortCfg.BssTab" table, thus complies to Microsoft's policy that
-                // "site survey" result should always include the current connected network. 
+                // "site survey" result should always include the current connected network.
                 //
                 Bssidx = BssTableSearch(&pAd->PortCfg.BssTab, &Bssid);
                 if (Bssidx == BSS_NOT_FOUND)
                 {
-                    Bssidx = BssTableSetEntry(pAd, &pAd->PortCfg.BssTab, &Bssid, Ssid, SsidLen, 
-                                BssType, BeaconPeriod, CfExist, &CfParm, AtimWin, CapabilityInfo, 
-                                Rates, RatesLen, ExtendedRateIeExist, Channel, Elem->Rssi, Elem->Noise, TimeStamp, pVIE);
+                    Bssidx = BssTableSetEntry(pAd, &pAd->PortCfg.BssTab, &Bssid, Ssid, SsidLen,
+                                BssType, BeaconPeriod, CfExist, &CfParm, AtimWin, CapabilityInfo,
+                                Rates, RatesLen, ExtendedRateIeExist, Channel, Elem->Rssi, Elem->Noise, TimeStamp, VarIELen, pVIE);
                 }
             }
 #endif
@@ -929,15 +935,15 @@
     // 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) 
+    IN PRTMP_ADAPTER pAd,
+    IN MLME_QUEUE_ELEM *Elem)
 {
     MACADDR       Addr2;
     CHAR          Ssid[MAX_LEN_OF_SSID];
@@ -947,13 +953,13 @@
     UCHAR         *OutBuffer = NULL;
     ULONG         FrameLen = 0;
     LARGE_INTEGER FakeTimestamp;
-    UCHAR         SsidIe = IE_SSID, DsIe = IE_DS_PARM, IbssIe = IE_IBSS_PARM, SuppIe = IE_SUPP_RATES, 
+    UCHAR         SsidIe = IE_SSID, DsIe = IE_DS_PARM, IbssIe = IE_IBSS_PARM, SuppIe = IE_SUPP_RATES,
                   DsLen = 1, IbssLen = 2;
     UCHAR         SupportedRatesLen;
     UCHAR         SupportedRates[MAX_LEN_OF_SUPPORTED_RATES];
     UCHAR         ExtRateIe = IE_EXT_SUPP_RATES, ExtRatesLen;
     UCHAR         ErpIe[3] = {IE_ERP, 1, 0};
-    
+
     if (! ADHOC_ON(pAd))
         return;
 
@@ -962,8 +968,8 @@
         if ((SsidLen == 0) || RTMPEqualMemory(Ssid, pAd->PortCfg.Ssid, (ULONG) SsidLen))
         {
             CSR15_STRUC Csr15;
-            
-            // we should respond a ProbeRsp only when we're the last BEACON transmitter 
+
+            // we should respond a ProbeRsp only when we're the last BEACON transmitter
             // in this ADHOC network.
             RTMP_IO_READ32(pAd, CSR15, &Csr15.word);
             if (Csr15.field.BeaconSent == 0)
@@ -1016,28 +1022,28 @@
                 return;
 
             pAd->PortCfg.AtimWin = 0;  // ??????
-            DBGPRINT(RT_DEBUG_TRACE, "SYNC - Send PROBE_RSP to %02x:%02x:%02x:%02x:%02x:%02x...\n", 
+            DBGPRINT(RT_DEBUG_TRACE, "SYNC - Send PROBE_RSP to %02x:%02x:%02x:%02x:%02x:%02x...\n",
                 Addr2.Octet[0],Addr2.Octet[1],Addr2.Octet[2],Addr2.Octet[3],Addr2.Octet[4],Addr2.Octet[5] );
             MgtMacHeaderInit(pAd, &ProbeRspHdr, SUBTYPE_PROBE_RSP, 0, &Addr2, &pAd->PortCfg.Bssid);
 
             if (SupportedRatesLen <= 8)
             {
-                MakeOutgoingFrame(OutBuffer,                        &FrameLen, 
-                              MAC_HDR_LEN,                      &ProbeRspHdr, 
+                MakeOutgoingFrame(OutBuffer,                        &FrameLen,
+                              MAC_HDR_LEN,                      &ProbeRspHdr,
                               TIMESTAMP_LEN,                    &FakeTimestamp,
                               2,                                &pAd->PortCfg.BeaconPeriod,
                               2,                                &pAd->PortCfg.CapabilityInfo,
-                              1,                                &SsidIe, 
-                              1,                                &pAd->PortCfg.SsidLen, 
+                              1,                                &SsidIe,
+                              1,                                &pAd->PortCfg.SsidLen,
                               pAd->PortCfg.SsidLen,             pAd->PortCfg.Ssid,
-                              1,                                &SuppIe, 
+                              1,                                &SuppIe,
                               1,                                &SupportedRatesLen,
-                              SupportedRatesLen,                SupportedRates, 
-                              1,                                &DsIe, 
-                              1,                                &DsLen, 
+                              SupportedRatesLen,                SupportedRates,
+                              1,                                &DsIe,
+                              1,                                &DsLen,
                               1,                                &pAd->PortCfg.Channel,
-                              1,                                &IbssIe, 
-                              1,                                &IbssLen, 
+                              1,                                &IbssIe,
+                              1,                                &IbssLen,
                               2,                                &pAd->PortCfg.AtimWin,
                               END_OF_ARGS);
             }
@@ -1045,22 +1051,22 @@
             {
                 ExtRatesLen = SupportedRatesLen - 8;
                 SupportedRatesLen = 8;
-                MakeOutgoingFrame(OutBuffer,                        &FrameLen, 
-                              MAC_HDR_LEN,                      &ProbeRspHdr, 
+                MakeOutgoingFrame(OutBuffer,                        &FrameLen,
+                              MAC_HDR_LEN,                      &ProbeRspHdr,
                               TIMESTAMP_LEN,                    &FakeTimestamp,
                               2,                                &pAd->PortCfg.BeaconPeriod,
                               2,                                &pAd->PortCfg.CapabilityInfo,
-                              1,                                &SsidIe, 
-                              1,                                &pAd->PortCfg.SsidLen, 
+                              1,                                &SsidIe,
+                              1,                                &pAd->PortCfg.SsidLen,
                               pAd->PortCfg.SsidLen,             pAd->PortCfg.Ssid,
-                              1,                                &SuppIe, 
+                              1,                                &SuppIe,
                               1,                                &SupportedRatesLen,
-                              SupportedRatesLen,                SupportedRates, 
-                              1,                                &DsIe, 
-                              1,                                &DsLen, 
+                              SupportedRatesLen,                SupportedRates,
+                              1,                                &DsIe,
+                              1,                                &DsLen,
                               1,                                &pAd->PortCfg.Channel,
-                              1,                                &IbssIe, 
-                              1,                                &IbssLen, 
+                              1,                                &IbssIe,
+                              1,                                &IbssLen,
                               2,                                &pAd->PortCfg.AtimWin,
                               3,                                ErpIe,
                               1,                                &ExtRateIe,
@@ -1073,7 +1079,7 @@
 			{
 				ULONG	tmp;
 				UCHAR	WpaIe = IE_WPA;
-				
+
 				if (pAd->PortCfg.WepStatus == Ndis802_11Encryption2Enabled) 	// Tkip
 				{
 				MakeOutgoingFrame(OutBuffer + FrameLen,			&tmp,
@@ -1092,43 +1098,43 @@
 							END_OF_ARGS);
 					FrameLen += tmp;
 				}
-			}                
+			}
             MiniportMMRequest(pAd, OutBuffer, FrameLen);
         }
     }
 }
 
 VOID BeaconTimeoutAtJoinAction(
-    IN PRTMP_ADAPTER pAd, 
-    IN MLME_QUEUE_ELEM *Elem) 
+    IN PRTMP_ADAPTER pAd,
+    IN MLME_QUEUE_ELEM *Elem)
 {
     DBGPRINT(RT_DEBUG_TRACE, "SYNC - BeaconTimeoutAtJoinAction\n");
     pAd->Mlme.SyncMachine.CurrState = SYNC_IDLE;
     MlmeCntlConfirm(pAd, MT2_JOIN_CONF, MLME_REJ_TIMEOUT);
 }
 
-/* 
+/*
     ==========================================================================
     Description:
         Scan timeout procedure. basically add channel index by 1 and rescan
     ==========================================================================
  */
 VOID ScanTimeoutAction(
-    IN PRTMP_ADAPTER pAd, 
-    IN MLME_QUEUE_ELEM *Elem) 
+    IN PRTMP_ADAPTER pAd,
+    IN MLME_QUEUE_ELEM *Elem)
 {
     pAd->Mlme.SyncAux.Channel = NextChannel(pAd, pAd->Mlme.SyncAux.Channel);
     ScanNextChannel(pAd);
 }
 
-/* 
+/*
     ==========================================================================
     Description:
         Scan next channel
     ==========================================================================
  */
 VOID ScanNextChannel(
-    IN PRTMP_ADAPTER pAd) 
+    IN PRTMP_ADAPTER pAd)
 {
     MACHDR          Hdr;
     UCHAR           SsidIe = IE_SSID, SuppRateIe = IE_SUPP_RATES;
@@ -1138,36 +1144,36 @@
     ULONG           FrameLen = 0;
     UCHAR           SsidLen = 0;
 
-    if (pAd->Mlme.SyncAux.Channel == 0) 
+    if (pAd->Mlme.SyncAux.Channel == 0)
     {
         DBGPRINT(RT_DEBUG_INFO, "SYNC - End of SCAN, restore to channel %d\n",pAd->PortCfg.Channel);
         AsicSwitchChannel(pAd, pAd->PortCfg.Channel);
         AsicLockChannel(pAd, pAd->PortCfg.Channel);
-        
+
         pAd->Mlme.SyncMachine.CurrState = SYNC_IDLE;
         MlmeCntlConfirm(pAd, MT2_SCAN_CONF, MLME_SUCCESS);
-    } 
-    else 
+    }
+    else
     {
         AsicSwitchChannel(pAd, pAd->Mlme.SyncAux.Channel);
 
-        // Total SCAN time still limits within 3 sec (DDK constraint). 
+        // Total SCAN time still limits within 3 sec (DDK constraint).
         // TODO: We need more intelligent rules here to further improve out-of-service issue.
         // e.g. temporary stop copying NDIS packet to TxRing until SCAN complete
 //      if (INFRA_ON(pAd) || ADHOC_ON(pAd))
 
 		// We need to shorten active scan time in order for WZC connect issue
-        if (pAd->Mlme.SyncAux.ScanType == SCAN_ACTIVE) 
-            RTMPSetTimer(pAd, &pAd->Mlme.SyncAux.ScanTimer, ACTIVE_SCAN_TIME); 
+        if (pAd->Mlme.SyncAux.ScanType == SCAN_ACTIVE)
+            RTMPSetTimer(pAd, &pAd->Mlme.SyncAux.ScanTimer, ACTIVE_SCAN_TIME);
         else if (pAd->PortCfg.PhyMode == PHY_11ABG_MIXED)
-            RTMPSetTimer(pAd, &pAd->Mlme.SyncAux.ScanTimer, MIN_CHANNEL_TIME); 
+            RTMPSetTimer(pAd, &pAd->Mlme.SyncAux.ScanTimer, MIN_CHANNEL_TIME);
         else
             RTMPSetTimer(pAd, &pAd->Mlme.SyncAux.ScanTimer, MAX_CHANNEL_TIME);
 
 		MgtMacHeaderInit(pAd, &Hdr, SUBTYPE_PROBE_REQ, 0, &pAd->PortCfg.Broadcast, &pAd->PortCfg.Broadcast);
 		// There is no need to send broadcast probe request if active scan is in effect.
 		// The same rulr should apply to passive scan also.
-        if (pAd->Mlme.SyncAux.ScanType == SCAN_PASSIVE) 
+        if (pAd->Mlme.SyncAux.ScanType == SCAN_PASSIVE)
         {
 			// Send the first probe request with empty SSID
             NStatus = MlmeAllocateMemory(pAd, (PVOID)&OutBuffer);  //Get an unused nonpaged memory
@@ -1184,15 +1190,15 @@
             MakeOutgoingFrame(OutBuffer,        &FrameLen,
                           sizeof(MACHDR),   (UCHAR*)&Hdr,
                               1,                &SsidIe,
-                              1,                &SsidLen,  
+                              1,                &SsidLen,
                               1,                &SuppRateIe,
                               1,                &pAd->PortCfg.SupportedRatesLen,
-                              pAd->PortCfg.SupportedRatesLen, pAd->PortCfg.SupportedRates, 
+                              pAd->PortCfg.SupportedRatesLen, pAd->PortCfg.SupportedRates,
                               END_OF_ARGS);
-                              
+
             MiniportMMRequest(pAd, OutBuffer, FrameLen);
         }
-        else if (pAd->Mlme.SyncAux.ScanType == SCAN_ACTIVE) 
+        else if (pAd->Mlme.SyncAux.ScanType == SCAN_ACTIVE)
         {
             // Allocate another for probe scan with SSID
             NStatus = MlmeAllocateMemory(pAd, (PVOID)&OutBuffer2);  //Get an unused nonpaged memory
@@ -1212,9 +1218,9 @@
                               SsidLen,			pAd->PortCfg.Ssid,
                               1,                &SuppRateIe,
                               1,                &pAd->PortCfg.SupportedRatesLen,
-                              pAd->PortCfg.SupportedRatesLen, pAd->PortCfg.SupportedRates, 
+                              pAd->PortCfg.SupportedRatesLen, pAd->PortCfg.SupportedRates,
                               END_OF_ARGS);
-                              
+
             MiniportMMRequest(pAd, OutBuffer2, FrameLen);
 
  			DBGPRINT(RT_DEBUG_INFO, "SYNC - send active ProbeReq @ channel=%d with essid=%s\n", pAd->Mlme.SyncAux.Channel, pAd->PortCfg.Ssid);
@@ -1224,55 +1230,55 @@
     }
 }
 
-/* 
+/*
     ==========================================================================
     Description:
     ==========================================================================
  */
 VOID InvalidStateWhenScan(
-    IN PRTMP_ADAPTER pAd, 
-    IN MLME_QUEUE_ELEM *Elem) 
+    IN PRTMP_ADAPTER pAd,
+    IN MLME_QUEUE_ELEM *Elem)
 {
     DBGPRINT(RT_DEBUG_TRACE, "AYNC - InvalidStateWhenScan(state=%d). Reset SYNC machine\n", pAd->Mlme.SyncMachine.CurrState);
     pAd->Mlme.SyncMachine.CurrState = SYNC_IDLE;
     MlmeCntlConfirm(pAd, MT2_SCAN_CONF, MLME_STATE_MACHINE_REJECT);
 }
 
-/* 
+/*
     ==========================================================================
     Description:
     ==========================================================================
  */
 VOID InvalidStateWhenJoin(
-    IN PRTMP_ADAPTER pAd, 
-    IN MLME_QUEUE_ELEM *Elem) 
+    IN PRTMP_ADAPTER pAd,
+    IN MLME_QUEUE_ELEM *Elem)
 {
     DBGPRINT(RT_DEBUG_TRACE, "InvalidStateWhenJoin(state=%d). Reset SYNC machine\n", pAd->Mlme.SyncMachine.CurrState);
     pAd->Mlme.SyncMachine.CurrState = SYNC_IDLE;
     MlmeCntlConfirm(pAd, MT2_JOIN_CONF, MLME_STATE_MACHINE_REJECT);
 }
 
-/* 
+/*
     ==========================================================================
     Description:
     ==========================================================================
  */
 VOID InvalidStateWhenStart(
-    IN PRTMP_ADAPTER pAd, 
-    IN MLME_QUEUE_ELEM *Elem) 
+    IN PRTMP_ADAPTER pAd,
+    IN MLME_QUEUE_ELEM *Elem)
 {
     DBGPRINT(RT_DEBUG_TRACE, "InvalidStateWhenStart(state=%d). Reset SYNC machine\n", pAd->Mlme.SyncMachine.CurrState);
     pAd->Mlme.SyncMachine.CurrState = SYNC_IDLE;
     MlmeCntlConfirm(pAd, MT2_START_CONF, MLME_STATE_MACHINE_REJECT);
 }
 
-/* 
+/*
     ==========================================================================
     Description:
     ==========================================================================
  */
 VOID EnqueuePsPoll(
-    IN PRTMP_ADAPTER pAd) 
+    IN PRTMP_ADAPTER pAd)
 {
     NDIS_STATUS    NState;
     PSPOLL_FRAME   *PsFr;
@@ -1291,10 +1297,10 @@
 // driver force send out a BEACON frame to cover ADHOC mode BEACON starving issue
 // that is, in ADHOC mode, driver guarantee itself can send out at least a BEACON
 // per a specified duration, even the peer's clock is faster than us and win all the
-// hardware-based BEACON TX oppertunity. 
+// hardware-based BEACON TX oppertunity.
 // we may remove this software feature once 2560 IC fix this problem in ASIC.
 VOID EnqueueBeaconFrame(
-    IN PRTMP_ADAPTER pAd) 
+    IN PRTMP_ADAPTER pAd)
 {
     NDIS_STATUS    NState;
     PTXD_STRUC     pTxD = (PTXD_STRUC)pAd->BeaconRing.va_addr;
@@ -1313,10 +1319,10 @@
     }
 }
 
-/* 
+/*
     ==========================================================================
     Description:
-        Send out a NULL frame to AP. The prpose is to inform AP this client 
+        Send out a NULL frame to AP. The prpose is to inform AP this client
         current PSM bit.
     NOTE:
         This routine should only be used in infrastructure mode.
@@ -1324,7 +1330,7 @@
  */
 VOID EnqueueNullFrame(
     IN PRTMP_ADAPTER pAd,
-    IN UCHAR         TxRate) 
+    IN UCHAR         TxRate)
 {
     NDIS_STATUS    NState;
     MACHDR         *NullFr;
@@ -1339,7 +1345,7 @@
     }
 }
 
-/* 
+/*
     ==========================================================================
     Description:
     ==========================================================================
@@ -1359,7 +1365,7 @@
     if (NState == NDIS_STATUS_SUCCESS)
     {
         MgtMacHeaderInit(pAd, &Hdr, SUBTYPE_PROBE_REQ, 0, &pAd->PortCfg.Broadcast, &pAd->PortCfg.Broadcast);
-            
+
         // this ProbeRequest explicitly specify SSID to reduce unwanted ProbeResponse
         MakeOutgoingFrame(OutBuffer,                      &FrameLen,
                           sizeof(MACHDR),                 &Hdr,
@@ -1368,13 +1374,13 @@
                           pAd->PortCfg.SsidLen,           pAd->PortCfg.Ssid,
                           1,                              &SuppRateIe,
                           1,                              &pAd->PortCfg.SupportedRatesLen,
-                          pAd->PortCfg.SupportedRatesLen, pAd->PortCfg.SupportedRates, 
+                          pAd->PortCfg.SupportedRatesLen, pAd->PortCfg.SupportedRates,
                           END_OF_ARGS);
         MiniportMMRequest(pAd, OutBuffer, FrameLen);
     }
 }
 
-/* 
+/*
     ==========================================================================
     Description:
         Update PortCfg->ChannelList[] according to 1) Country Region 2) RF IC type,
@@ -1464,7 +1470,7 @@
     }
 
     pAd->PortCfg.ChannelListNum = index;
-    DBGPRINT(RT_DEBUG_TRACE,"country code=%d, RFIC=%d, PHY mode=%d, support %d channels\n", 
+    DBGPRINT(RT_DEBUG_TRACE,"country code=%d, RFIC=%d, PHY mode=%d, support %d channels\n",
         pAd->PortCfg.CountryRegion, pAd->PortCfg.RfType, pAd->PortCfg.PhyMode, pAd->PortCfg.ChannelListNum);
     for (i=0;i<index;i++)
     {
@@ -1472,10 +1478,10 @@
     }
 }
 
-/* 
+/*
     ==========================================================================
     Description:
-        This routine return the first channel number according to the country 
+        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:
@@ -1488,7 +1494,7 @@
     return pAd->PortCfg.ChannelList[0];
 }
 
-/* 
+/*
     ==========================================================================
     Description:
         This routine returns the next channel number. This routine is called
@@ -1500,12 +1506,12 @@
     ==========================================================================
  */
 UCHAR NextChannel(
-    IN PRTMP_ADAPTER pAd, 
+    IN PRTMP_ADAPTER pAd,
     IN UCHAR channel)
 {
     int i;
     UCHAR next_channel = 0;
-            
+
     for (i = 0; i < (pAd->PortCfg.ChannelListNum - 1); i++)
         if (channel == pAd->PortCfg.ChannelList[i])
         {
diff -Nur rt2500-1.1.0-b4/Module/unload rt2500-cvs-2007061011/Module/unload
--- rt2500-1.1.0-b4/Module/unload	2006-06-17 22:12:58.000000000 +0200
+++ rt2500-cvs-2007061011/Module/unload	1970-01-01 01:00:00.000000000 +0100
@@ -1,2 +0,0 @@
-/sbin/ifconfig ra0 down
-/sbin/rmmod rt2500
\ Kein Zeilenumbruch am Dateiende.
diff -Nur rt2500-1.1.0-b4/Module/wpa.c rt2500-cvs-2007061011/Module/wpa.c
--- rt2500-1.1.0-b4/Module/wpa.c	2006-06-17 22:12:58.000000000 +0200
+++ rt2500-cvs-2007061011/Module/wpa.c	2007-05-15 21:41:35.000000000 +0200
@@ -1,37 +1,37 @@
-/*************************************************************************** 
- * RT2400/RT2500 SourceForge Project - http://rt2x00.serialmonkey.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.                          * 
- *                                                                         * 
- *   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.             * 
- *                                                                         * 
- *   Licensed under the GNU GPL                                            * 
- *   Original code supplied under license from RaLink Inc, 2004.           * 
- ***************************************************************************/ 
-
- /*************************************************************************** 
- *      Module Name: wpa.c 
- *              
- *      Abstract: 
- *              
- *      Revision History: 
- *      Who             When            What 
- *      --------        -----------     ----------------------------- 
- *      JanL            22nd Jul 03     Initial code     
+/***************************************************************************
+ * RT2400/RT2500 SourceForge Project - http://rt2x00.serialmonkey.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.                          *
+ *                                                                         *
+ *   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.             *
+ *                                                                         *
+ *   Licensed under the GNU GPL                                            *
+ *   Original code supplied under license from RaLink Inc, 2004.           *
+ ***************************************************************************/
+
+ /***************************************************************************
+ *      Module Name: wpa.c
+ *
+ *      Abstract:
+ *
+ *      Revision History:
+ *      Who             When            What
+ *      --------        -----------     -----------------------------
+ *      JanL            22nd Jul 03     Initial code
  *      PaulL           28th Nov 03     Modify for supplicant
  *      MarkW           8th  Dec 04     Baseline code
- ***************************************************************************/ 
+ ***************************************************************************/
 
 #include "rt_config.h"
 
@@ -47,6 +47,7 @@
         };
 UCHAR   CipherWpaPskTkipLen = (sizeof(CipherWpaPskTkip) / sizeof(UCHAR));
 
+// Needed for APs using WPA1 IEs (#221) to indicate CCMP encryption
 UCHAR   CipherWpaPskAes[] = {
         0xDD, 0x16,             // RSN IE
         0x00, 0x50, 0xf2, 0x01, // oui
@@ -59,16 +60,19 @@
         };
 UCHAR   CipherWpaPskAesLen = (sizeof(CipherWpaPskAes) / sizeof(UCHAR));
 
+static UCHAR MSOUI[] = {0x00, 0x50, 0xf2, 0x01};	// Microsoft OUI
+static UCHAR WGOUI[] = {0x00, 0x0f, 0xac};	// 802.11i Working Group OUI
+
 /*
     ========================================================================
-    
+
     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
@@ -76,12 +80,12 @@
     Note:
         All these constants are defined in wpa.h
         For supplicant, there is only EAPOL Key message avaliable
-        
+
     ========================================================================
 */
 BOOLEAN WpaMsgTypeSubst(
     IN  UCHAR   EAPType,
-    OUT ULONG   *MsgType)   
+    OUT ULONG   *MsgType)
 {
     switch (EAPType)
     {
@@ -102,23 +106,23 @@
             break;
         default:
             DBGPRINT(RT_DEBUG_INFO, "WpaMsgTypeSubst : return FALSE; \n");
-            return FALSE;       
-    }   
+            return FALSE;
+    }
     return TRUE;
 }
 
-/*  
+/*
     ==========================================================================
-    Description: 
+    Description:
         association state machine init, including state transition and timer init
-    Parameters: 
+    Parameters:
         S - pointer to the association state machine
     ==========================================================================
  */
 VOID WpaPskStateMachineInit(
-    IN  PRTMP_ADAPTER   pAd, 
-    IN  STATE_MACHINE *S, 
-    OUT STATE_MACHINE_FUNC Trans[]) 
+    IN  PRTMP_ADAPTER   pAd,
+    IN  STATE_MACHINE *S,
+    OUT STATE_MACHINE_FUNC Trans[])
 {
     StateMachineInit(S, (STATE_MACHINE_FUNC*)Trans, MAX_WPA_PSK_STATE, MAX_WPA_PSK_MSG, (STATE_MACHINE_FUNC)Drop, WPA_PSK_IDLE, WPA_MACHINE_BASE);
     StateMachineSetAction(S, WPA_PSK_IDLE, EAP_MSG_TYPE_EAPOLKey, (STATE_MACHINE_FUNC)WpaEAPOLKeyAction);
@@ -127,10 +131,10 @@
 /*
     ==========================================================================
     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 : 
+        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
@@ -138,13 +142,13 @@
     ==========================================================================
 */
 VOID WpaEAPOLKeyAction(
-    IN  PRTMP_ADAPTER   pAdapter, 
-    IN  MLME_QUEUE_ELEM *Elem) 
+    IN  PRTMP_ADAPTER   pAdapter,
+    IN  MLME_QUEUE_ELEM *Elem)
 {
     INT             MsgType;
     UCHAR           ZeroReplay[LEN_KEY_DESC_REPLAY];
     PKEY_DESCRIPTER pKeyDesc;
-    
+
     DBGPRINT(RT_DEBUG_TRACE, "-----> WpaEAPOLKeyAction\n");
     // Get 802.11 header first
     pKeyDesc = (PKEY_DESCRIPTER) &Elem->Msg[(LENGTH_802_11 + LENGTH_802_1_H + LENGTH_EAPOL_H)];
@@ -153,9 +157,12 @@
 	*(USHORT *)((UCHAR *)pKeyDesc+1) = SWAP16(*(USHORT *)((UCHAR *)pKeyDesc+1));
 #endif
     // Sanity check, this should only happen in WPA-PSK mode
-    if (pAdapter->PortCfg.AuthMode != Ndis802_11AuthModeWPAPSK)
+    if (pAdapter->PortCfg.AuthMode != Ndis802_11AuthModeWPAPSK) {
+    	DBGPRINT(RT_DEBUG_TRACE,
+				"<----- WpaEAPOLKeyAction - AuthMode (%d) != WPPSK\n",
+				pAdapter->PortCfg.AuthMode);
         return;
-
+	}
     // 0. Debug print all bit information
     DBGPRINT(RT_DEBUG_INFO, "KeyInfo Key Description Version %d\n", pKeyDesc->KeyInfo.KeyDescVer);
     DBGPRINT(RT_DEBUG_INFO, "KeyInfo Key Type %d\n", pKeyDesc->KeyInfo.KeyType);
@@ -167,7 +174,7 @@
     DBGPRINT(RT_DEBUG_INFO, "KeyInfo Error %d\n", pKeyDesc->KeyInfo.Error);
     DBGPRINT(RT_DEBUG_INFO, "KeyInfo Request %d\n", pKeyDesc->KeyInfo.Request);
     DBGPRINT(RT_DEBUG_INFO, "KeyInfo DL %d\n", pKeyDesc->KeyInfo.DL);
-    
+
     // 1. Check EAPOL frame version and type
     if ((Elem->Msg[LENGTH_802_11+LENGTH_802_1_H] != EAPOL_VER) || (pKeyDesc->Type != RSN_KEY_DESC))
     {
@@ -190,9 +197,18 @@
     // First validate replay counter, only accept message with larger replay counter
     // Let equal pass, some AP start with all zero replay counter
     memset(ZeroReplay, 0, LEN_KEY_DESC_REPLAY);
-    if ((RTMPCompareMemory(pKeyDesc->ReplayCounter, pAdapter->PortCfg.ReplayCounter, LEN_KEY_DESC_REPLAY) != 1) &&
-        (RTMPCompareMemory(pKeyDesc->ReplayCounter, ZeroReplay, LEN_KEY_DESC_REPLAY) != 0))
+    if ((RTMPCompareMemory(pKeyDesc->ReplayCounter,
+			pAdapter->PortCfg.ReplayCounter, LEN_KEY_DESC_REPLAY) != 1) &&
+        (RTMPCompareMemory(pKeyDesc->ReplayCounter,
+						 ZeroReplay, LEN_KEY_DESC_REPLAY) != 0)) {
+        DBGPRINT(RT_DEBUG_TRACE, "<----- %s:  Replay count error\n",
+				__FUNCTION__);
+		DBGHEXSTR(RT_DEBUG_TRACE, "  AP replay = ",
+				pKeyDesc->ReplayCounter, LEN_KEY_DESC_REPLAY);
+		DBGHEXSTR(RT_DEBUG_TRACE, "  our replay = ",
+			pAdapter->PortCfg.ReplayCounter, LEN_KEY_DESC_REPLAY);
         return;
+	}
 
     // Classify message Type, either pairwise message 1, 3, or group message 1 for supplicant
     MsgType = EAPOL_MSG_INVALID;
@@ -228,12 +244,13 @@
     {
         MsgType = EAPOL_GROUP_MSG_1;
         DBGPRINT(RT_DEBUG_TRACE, "Receive EAPOL Key Group Message 1\n");
-    }
-    
+    } else
+	DBGPRINT(RT_DEBUG_TRACE, "Receive INVALID EAPOL Key Message\n");
+
 #ifdef BIG_ENDIAN
 	*(USHORT *)((UCHAR *)pKeyDesc+1) = SWAP16(*(USHORT *)((UCHAR *)pKeyDesc+1));
 #endif
-    
+
     // 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 (pAdapter->PortCfg.WpaState)
@@ -245,7 +262,7 @@
                 pAdapter->PortCfg.WpaState = SS_WAIT_MSG_3;
             }
             break;
-                
+
         case SS_WAIT_MSG_3:
             if (MsgType == EAPOL_PAIR_MSG_1)
             {
@@ -258,7 +275,7 @@
                 pAdapter->PortCfg.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)
@@ -281,34 +298,34 @@
                 pAdapter->PortCfg.WpaState = SS_FINISH;
             }
             break;
-                
+
         default:
-            break;              
+            break;
     }
-    
+
     DBGPRINT(RT_DEBUG_TRACE, "<----- WpaEAPOLKeyAction\n");
 }
 
 /*
     ========================================================================
-    
+
     Routine Description:
         Process Pairwise key 4-way handshaking
 
     Arguments:
         pAdapter    Pointer to our adapter
         Elem        Message body
-        
+
     Return Value:
         None
-        
+
     Note:
-        
+
     ========================================================================
 */
 VOID    WpaPairMsg1Action(
-    IN  PRTMP_ADAPTER   pAdapter, 
-    IN  MLME_QUEUE_ELEM *Elem) 
+    IN  PRTMP_ADAPTER   pAdapter,
+    IN  MLME_QUEUE_ELEM *Elem)
 {
     PHEADER_802_11      pHeader;
     UCHAR               PTK[80];
@@ -321,39 +338,39 @@
     UCHAR               EAPHEAD[8] = {0xaa, 0xaa, 0x03, 0x00, 0x00, 0x00,0x88,0x8e};
     PEAPOL_PACKET       pMsg1;
     EAPOL_PACKET        Packet;
-    UCHAR               Mic[16];    
-       
+    UCHAR               Mic[16];
+
     DBGPRINT(RT_DEBUG_TRACE, "WpaPairMsg1Action ----->\n");
-    
+
     pHeader = (PHEADER_802_11) Elem->Msg;
-    
+
     // Save Data Length to pDesc for receiving packet, then put in outgoing frame   Data Len fields.
     pMsg1 = (PEAPOL_PACKET) &Elem->Msg[LENGTH_802_11 + LENGTH_802_1_H];
-    
+
     // Process message 1 from authenticator
     // Key must be Pairwise key, already verified at callee.
     // 1. Save Replay counter, it will use to verify message 3 and construct message 2
-    memcpy(pAdapter->PortCfg.ReplayCounter, pMsg1->KeyDesc.ReplayCounter, LEN_KEY_DESC_REPLAY);     
+    memcpy(pAdapter->PortCfg.ReplayCounter, pMsg1->KeyDesc.ReplayCounter, LEN_KEY_DESC_REPLAY);
 
     // 2. Save ANonce
     memcpy(pAdapter->PortCfg.ANonce, pMsg1->KeyDesc.KeyNonce, LEN_KEY_DESC_NONCE);
-        
+
     // TSNonce <--- SNonce
     // Generate random SNonce
-    GenRandom(pAdapter, pAdapter->PortCfg.SNonce);  
+    GenRandom(pAdapter, pAdapter->PortCfg.SNonce);
 
     // TPTK <--- Calc PTK(ANonce, TSNonce)
-    WpaCountPTK(pAdapter->PortCfg.PskKey.Key,   
+    WpaCountPTK(pAdapter->PortCfg.PskKey.Key,
         pAdapter->PortCfg.ANonce,
-        pAdapter->PortCfg.Bssid.Octet, 
-        pAdapter->PortCfg.SNonce, 
-        pAdapter->CurrentAddress,    
-        PTK, 
-        LEN_PTK);   
+        pAdapter->PortCfg.Bssid.Octet,
+        pAdapter->PortCfg.SNonce,
+        pAdapter->CurrentAddress,
+        PTK,
+        LEN_PTK);
 
     // Save key to PTK entry
     memcpy(pAdapter->PortCfg.PTK, PTK, LEN_PTK);
-    
+
     // =====================================
     // Use Priority Ring & MiniportMMRequest
     // =====================================
@@ -364,7 +381,7 @@
     AckRate = pAdapter->PortCfg.ExpectedACKRate[pAdapter->PortCfg.TxRate];
     AckDuration = RTMPCalcDuration(pAdapter, AckRate, 14);
     Header_802_11.Controlhead.Duration = pAdapter->PortCfg.Dsifs + AckDuration;
-    
+
     // Zero message 2 body
     memset(&Packet, 0, sizeof(Packet));
     Packet.Version = EAPOL_VER;
@@ -399,17 +416,17 @@
     memcpy(Packet.KeyDesc.KeyNonce, pAdapter->PortCfg.SNonce, LEN_KEY_DESC_NONCE);
 
     // 5. Key Replay Count
-    memcpy(Packet.KeyDesc.ReplayCounter, pAdapter->PortCfg.ReplayCounter, LEN_KEY_DESC_REPLAY);     
-    
+    memcpy(Packet.KeyDesc.ReplayCounter, pAdapter->PortCfg.ReplayCounter, LEN_KEY_DESC_REPLAY);
+
 #ifdef BIG_ENDIAN
 	*(USHORT *)(&(Packet.KeyDesc.KeyInfo)) = SWAP16(*(USHORT *)(&(Packet.KeyDesc.KeyInfo)));
 #endif
-    
+
     // Send EAPOL(0, 1, 0, 0, 0, K, 0, TSNonce, 0, MIC(TPTK), 0)
-    // Out buffer for transmitting message 2        
+    // Out buffer for transmitting message 2
     NStatus = MlmeAllocateMemory(pAdapter, (PVOID)&OutBuffer);  //Get an unused nonpaged memory
-    if (NStatus != NDIS_STATUS_SUCCESS) 
-        return;                 
+    if (NStatus != NDIS_STATUS_SUCCESS)
+        return;
 
     // Prepare EAPOL frame for MIC calculation
     // Be careful, only EAPOL frame is counted for MIC calculation
@@ -423,7 +440,7 @@
     {
         // AES
         UCHAR digest[80];
-            
+
         HMAC_SHA1(OutBuffer, FrameLen, PTK, LEN_EAP_MICK, digest);
         memcpy(Mic, digest, LEN_KEY_DESC_MIC);
     }
@@ -433,12 +450,12 @@
         DBGPRINT(RT_DEBUG_INFO, " PMK = ");
         for (i = 0; i < 16; i++)
             DBGPRINT(RT_DEBUG_INFO, "%2x-", pAdapter->PortCfg.PskKey.Key[i]);
-        
+
         DBGPRINT(RT_DEBUG_INFO, "\n PTK = ");
         for (i = 0; i < 64; i++)
             DBGPRINT(RT_DEBUG_INFO, "%2x-", pAdapter->PortCfg.PTK[i]);
         DBGPRINT(RT_DEBUG_INFO, "\n FrameLen = %d\n", FrameLen);
-        
+
         hmac_md5(PTK,  LEN_EAP_MICK, OutBuffer, FrameLen, Mic);
     }
     memcpy(Packet.KeyDesc.KeyMic, Mic, LEN_KEY_DESC_MIC);
@@ -446,36 +463,202 @@
     FrameLen = 0;
     // Make  Transmitting frame
     MakeOutgoingFrame(OutBuffer, &FrameLen, sizeof(MACHDR), &Header_802_11,
-        sizeof(EAPHEAD), EAPHEAD, 
+        sizeof(EAPHEAD), EAPHEAD,
         Packet.Len[1] + 4, &Packet,
         END_OF_ARGS);
 
     // Send using priority queue
     MiniportMMRequest(pAdapter, OutBuffer, FrameLen);
-        
+
     DBGPRINT(RT_DEBUG_TRACE, "WpaPairMsg1Action <-----\n");
 }
 
 /*
+	========================================================================
+
+	Description:
+		Check the information element packaged in the KeyData field of the
+		EAPOL packet. At least one of the AP's offerings in each of
+
+		1) the group cipher suite
+		2) the pairwise master key cipher(s), and
+		3) the authentication and key management suite
+
+		need to match the configuration for the corresponding attribute
+		in the driver.
+
+	Arguments:
+		pAd			Pointer to our adapter
+		pie			Pointer to the "logical" IE
+		pie_len		Value of the real IE length field.
+		poui		Pointer to the WPA1/WPA2 OUI
+
+	Return Value:
+		0 -> OK:	At least one of the offerings in each category
+					matches what is configured in the driver.
+
+	Note:
+		On entry, it is known that the length of the RSN IE is consistent
+		with the length specification of the EAPOL KeyData field, and that
+		the IE is at least long enough to contain one group cipher suite
+		selection, one PMK cipher suite selection,
+		and one AKM suite selection.
+	========================================================================
+*/
+static int checkEAPIE(
+	IN RTMP_ADAPTER *pAd,
+	IN rsn_ie_t		*pie,		// (not really, if we're WPA 1)
+	IN u8			pie_len,	// ... so we provide the length separately.
+	IN ie_oui_t		*poui)
+{
+	suite_list_t	*suite_list_p;
+	suite_sel_t		*suite_sel_p;
+	int				i, j;
+	int				needs = 7;
+	suite_sel_t		*limit = (suite_sel_t *)((void *)pie + pie_len + 2);
+
+	if (wtohs(pie->version) != 1) {
+		DBGPRINT(RT_DEBUG_ERROR, "Invalid ver %d (sb 1)\n",
+				wtohs(pie->version));
+		return needs;
+	}
+	if (memcmp(pie->gcsuite.oui, poui, sizeof(ie_oui_t)) != 0) {
+		DBGPRINT(RT_DEBUG_ERROR, "Invalid Grp Cipher OUI %02x:%02x:%02x\n",
+				pie->gcsuite.oui[0], pie->gcsuite.oui[1], pie->gcsuite.oui[2]);
+		return needs;
+	}
+	switch (pie->gcsuite.type) {
+		case CIPHER_TYPE_WEP40:
+		case CIPHER_TYPE_WEP104:
+    		if (pAd->PortCfg.WepStatus == Ndis802_11Encryption1Enabled)
+				needs &= 6;
+			break;
+		case CIPHER_TYPE_TKIP:
+    		if (pAd->PortCfg.WepStatus == Ndis802_11Encryption2Enabled)
+				needs &= 6;
+			break;
+		case CIPHER_TYPE_CCMP:
+    		if (pAd->PortCfg.WepStatus == Ndis802_11Encryption3Enabled)
+				needs &= 6;
+			break;
+		default:
+			DBGPRINT(RT_DEBUG_ERROR, "Invalid Grp Cipher Type %d\n",
+					pie->gcsuite.type);
+			return needs;
+	} /* End switch (group cipher suite type) */
+
+	suite_list_p = (suite_list_t *)((void *)&pie->gcsuite+sizeof(suite_sel_t));
+
+	// Search the PMK list
+	for (suite_sel_p = suite_list_p->suite,
+		i = 0, j = wtohs(suite_list_p->count);
+		suite_sel_p + 1 <= limit && i < j;
+		suite_sel_p++, i++) {
+		if (memcmp(suite_sel_p->oui, poui, sizeof(ie_oui_t)) != 0) {
+			DBGPRINT(RT_DEBUG_ERROR, "Invalid PMK Cipher OUI "
+									"%02x:%02x:%02x\n",
+					suite_sel_p->oui[0], suite_sel_p->oui[1],
+					suite_sel_p->oui[2]);
+			break;			// Keep going. We may also have a valid one.
+		}
+		switch (suite_sel_p->type) {
+			case CIPHER_TYPE_WEP40:
+			case CIPHER_TYPE_WEP104:
+    			if (pAd->PortCfg.WepStatus == Ndis802_11Encryption1Enabled)
+					needs &= 5;
+				break;
+			case CIPHER_TYPE_TKIP:
+    			if (pAd->PortCfg.WepStatus == Ndis802_11Encryption2Enabled)
+					needs &= 5;
+				break;
+			case CIPHER_TYPE_CCMP:
+    			if (pAd->PortCfg.WepStatus == Ndis802_11Encryption3Enabled)
+					needs &= 5;
+				break;
+			default:
+				DBGPRINT(RT_DEBUG_ERROR, "Invalid PMK Cipher Type %d\n",
+						suite_sel_p->type);
+				break;			// Keep going. We may also have a valid one.
+		} /* End switch (PMK type) */
+	} /* End search PMK list */
+
+	if (suite_sel_p >= limit && i < j) {
+		DBGPRINT(RT_DEBUG_ERROR, "Too many PMK suites in EAPOL pkt "
+								"(have %d, room for %d) (need=%d)\n",
+								j, i, needs);
+		return needs;
+	}
+	if (j == 0) {
+		DBGPRINT(RT_DEBUG_ERROR, "Zero count PMK list in EAPOL pkt "
+								"(need=%d)\n", needs);
+		return needs;
+	}
+
+	suite_list_p = (suite_list_t *)suite_sel_p;
+
+	//Search the Authentication and Key Management (AKM) list
+	for (suite_sel_p = suite_list_p->suite,
+		i = 0, j = wtohs(suite_list_p->count);
+		suite_sel_p + 1 <= limit && i < j;
+		suite_sel_p++, i++) {
+		if (memcmp(suite_sel_p->oui, poui, sizeof(ie_oui_t)) != 0) {
+			DBGPRINT(RT_DEBUG_ERROR, "Invalid AKM OUI %02x:%02x:%02x\n",
+					suite_sel_p->oui[0], suite_sel_p->oui[1],
+					suite_sel_p->oui[2]);
+			break;			// Keep going. We may also have a valid one.
+		}
+		switch (suite_sel_p->type) {
+			case AKM_TYPE_802_1X:
+				if (pAd->PortCfg.AuthMode == Ndis802_11AuthModeWPA)
+					needs &= 3;
+				break;
+			case AKM_TYPE_PSK:
+				if (pAd->PortCfg.AuthMode >= Ndis802_11AuthModeWPAPSK)
+					needs &= 3;
+				break;
+			default:
+				DBGPRINT(RT_DEBUG_ERROR, "Invalid PMK Cipher Type %d\n",
+						suite_sel_p->type);
+				break;			// Keep going. We may also have a valid one.
+		} /* End switch (AKM type) */
+	} /* End search AKM list */
+
+	if (suite_sel_p >= limit && i < j) {
+		DBGPRINT(RT_DEBUG_ERROR, "Too many AKM suites in EAPOL pkt "
+								"(have %d, room for %d) (need=%d)\n",
+								j, i, needs);
+		return needs;			// NB. May still have met all needs.
+	}
+	if (j == 0) {
+		DBGPRINT(RT_DEBUG_ERROR, "Zero count AKM list in EAPOL pkt "
+								"(need=%d)\n", needs);
+		return needs;
+	}
+
+	return needs;
+
+} /* End checkEAPIE () */
+
+/*
     ========================================================================
-    
+
     Routine Description:
         Process Pairwise key 4-way handshaking
 
     Arguments:
         pAdapter    Pointer to our adapter
         Elem        Message body
-        
+
     Return Value:
         None
-        
+
     Note:
-        
+
     ========================================================================
 */
 VOID    WpaPairMsg3Action(
-    IN  PRTMP_ADAPTER   pAdapter, 
-    IN  MLME_QUEUE_ELEM *Elem) 
+    IN  PRTMP_ADAPTER   pAdapter,
+    IN  MLME_QUEUE_ELEM *Elem)
 {
     PHEADER_802_11      pHeader;
     UCHAR               *OutBuffer = NULL;
@@ -487,46 +670,74 @@
     UCHAR               EAPHEAD[8] = {0xaa, 0xaa, 0x03, 0x00, 0x00, 0x00,0x88,0x8e};
     EAPOL_PACKET        Packet;
     PEAPOL_PACKET       pMsg3;
-    PUCHAR              pTmp;
-    UCHAR               Mic[16], OldMic[16];    
+    UCHAR               Mic[16], OldMic[16];
     NDIS_802_11_KEY     PeerKey;
-    
-       
+
+
     DBGPRINT(RT_DEBUG_TRACE, "WpaPairMsg3Action ----->\n");
-    
+
     pHeader = (PHEADER_802_11) Elem->Msg;
-    
+
     // Process message 3 frame.
     pMsg3 = (PEAPOL_PACKET) &Elem->Msg[LENGTH_802_11 + LENGTH_802_1_H];
 
 #ifdef BIG_ENDIAN
 	*(USHORT *)(&(pMsg3->KeyDesc.KeyInfo)) = SWAP16(*(USHORT *)(&(pMsg3->KeyDesc.KeyInfo)));
 #endif
+	#define pie ((rsn_ie_t *)(void *)pMsg3->KeyDesc.KeyData)
+	if (wtohs(pie->length) + 2 != pMsg3->KeyDesc.KeyDataLen[1]) {
+        DBGPRINT(RT_DEBUG_ERROR, "RSN IE len %d != KeyDataLen %d)\n",
+				pie->length + 2, pMsg3->KeyDesc.KeyDataLen[1]);
+		return;
+	}
+	else {
+		switch (pie->eid) {
+			case IE_RSN:
+				if (wtohs(pie->length) < MIN_RSN_KEYDATA_LEN) {
+        			DBGPRINT(RT_DEBUG_ERROR,
+							"RSN IE msg 3 too short (sb >= %d, is %d)\n",
+							MIN_RSN_KEYDATA_LEN, wtohs(pie->length));
+					DBGHEXSTR(RT_DEBUG_ERROR, "KeyData ",
+							pMsg3->KeyDesc.KeyData,
+							pMsg3->KeyDesc.KeyDataLen[1]);
+					return;
+				}
+				if (checkEAPIE(pAdapter, pie, pie->length,
+								(ie_oui_t *)WGOUI) != 0) return;
+				break;
+			case IE_WPA:
+				#undef pie
+				#define pie ((RSN_EID_STRUCT *)(void *)pMsg3->KeyDesc.KeyData)
+				if (wtohs(pie->Length) < MIN_WPA_KEYDATA_LEN) {
+        			DBGPRINT(RT_DEBUG_ERROR,
+							"WPA IE msg 3 too short (sb >= %d, is %d)\n",
+							MIN_WPA_KEYDATA_LEN, wtohs(pie->Length));
+					DBGHEXSTR(RT_DEBUG_ERROR, "KeyData ",
+							pMsg3->KeyDesc.KeyData,
+							pMsg3->KeyDesc.KeyDataLen[1]);
+					return;
+				}
+				if (memcmp(pie->Oui, MSOUI, sizeof(pie->Oui)) != 0) {
+					DBGPRINT(RT_DEBUG_ERROR,
+							"Invalid WPA 1 OUI %02x:%02x:%02x:%02x\n",
+							pie->Oui[0], pie->Oui[1], pie->Oui[2], pie->Oui[3]);
+					return;
+				}
+				if (checkEAPIE(pAdapter, (rsn_ie_t *)&pie->Oui[2], pie->Length,
+								(ie_oui_t *)MSOUI) != 0) return;
+				break;
+			default:
+        		DBGPRINT(RT_DEBUG_ERROR, "RSN IE type %d invalid)\n",
+						pie->Eid);
+				return;
+		} /* End switch (element ID) */
+	} /* End if (packet length sane) */
+	#undef pie
+
+	DBGPRINT(RT_DEBUG_TRACE, "RSN IE matched msg 3 of 4-way handshake "
+				"KeyDataLen=%d)\n",
+				 pMsg3->KeyDesc.KeyDataLen[1]);
 
-    // 1. Verify RSN IE & cipher type match
-    if (pAdapter->PortCfg.WepStatus == Ndis802_11Encryption3Enabled)
-    {
-        if (pMsg3->KeyDesc.KeyInfo.KeyDescVer != 2)
-            return;
-        pTmp = (PUCHAR) &CipherWpaPskAes;
-    }
-    else    // TKIP
-    {
-        if (pMsg3->KeyDesc.KeyInfo.KeyDescVer != 1)
-            return;
-        pTmp = (PUCHAR) &CipherWpaPskTkip;
-    }
-
-    // Fix compatibility issue, when AP append nonsense data after auth mode with different size.
-    // We should qualify this kind of RSN as acceptable
-    if (!NdisEqualMemory((PUCHAR) &pMsg3->KeyDesc.KeyData[2], pTmp + 2, CipherWpaPskTkipLen - 2))
-    {
-        DBGPRINT(RT_DEBUG_ERROR, " RSN IE mismatched msg 3 of 4-way handshake!!!!!!!!!! \n");
-        return;
-    }
-    else
-        DBGPRINT(RT_DEBUG_TRACE, " RSN IE matched in msg 3 of 4-way handshake!!!!!!!!!! \n");
-    
 #ifdef BIG_ENDIAN
 	*(USHORT *)(&(pMsg3->KeyDesc.KeyInfo)) = SWAP16(*(USHORT *)(&(pMsg3->KeyDesc.KeyInfo)));
 #endif
@@ -539,7 +750,7 @@
     {
         // AES
         UCHAR digest[80];
-            
+
         HMAC_SHA1((PUCHAR) pMsg3, pMsg3->Len[1] + 4, pAdapter->PortCfg.PTK, LEN_EAP_MICK, digest);
         memcpy(Mic, digest, LEN_KEY_DESC_MIC);
     }
@@ -547,7 +758,7 @@
     {
         hmac_md5(pAdapter->PortCfg.PTK, LEN_EAP_MICK, (PUCHAR) pMsg3, pMsg3->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");
@@ -556,17 +767,32 @@
     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, pAdapter->PortCfg.ReplayCounter, LEN_KEY_DESC_REPLAY) != 1)
+    // 3. Check Replay Counter, it has to be larger than last one.
+	//    No need to be exact one larger
+    if (RTMPCompareMemory(pMsg3->KeyDesc.ReplayCounter,
+				pAdapter->PortCfg.ReplayCounter, LEN_KEY_DESC_REPLAY) != 1) {
+        DBGPRINT(RT_DEBUG_TRACE, " Replay count error\n");
+		DBGHEXSTR(RT_DEBUG_TRACE, " AP replay = ",
+				pMsg3->KeyDesc.ReplayCounter, LEN_KEY_DESC_REPLAY);
+		DBGHEXSTR(RT_DEBUG_TRACE, " our replay = ",
+				pAdapter->PortCfg.ReplayCounter, LEN_KEY_DESC_REPLAY);
         return;
-
+	}
     // Update new replay counter
-    memcpy(pAdapter->PortCfg.ReplayCounter, pMsg3->KeyDesc.ReplayCounter, LEN_KEY_DESC_REPLAY);     
+    memcpy(pAdapter->PortCfg.ReplayCounter, pMsg3->KeyDesc.ReplayCounter,
+			LEN_KEY_DESC_REPLAY);
 
     // 4. Double check ANonce
-    if (!NdisEqualMemory(pAdapter->PortCfg.ANonce, pMsg3->KeyDesc.KeyNonce, LEN_KEY_DESC_NONCE))
+    if (!NdisEqualMemory(pAdapter->PortCfg.ANonce, pMsg3->KeyDesc.KeyNonce,
+				LEN_KEY_DESC_NONCE)) {
+        DBGPRINT(RT_DEBUG_TRACE, " Nonce error\n");
+		DBGHEXSTR(RT_DEBUG_TRACE, " AP Nonce = ",
+				pMsg3->KeyDesc.KeyNonce, LEN_KEY_DESC_NONCE);
+		DBGHEXSTR(RT_DEBUG_TRACE, " our Nonce = ",
+				pAdapter->PortCfg.ANonce, LEN_KEY_DESC_NONCE);
         return;
-    
+	}
+
     // 5. Construct Message 4
     // =====================================
     // Use Priority Ring & MiniportMMRequest
@@ -578,22 +804,22 @@
     AckRate = pAdapter->PortCfg.ExpectedACKRate[pAdapter->PortCfg.TxRate];
     AckDuration = RTMPCalcDuration(pAdapter, AckRate, 14);
     Header_802_11.Controlhead.Duration = pAdapter->PortCfg.Dsifs + AckDuration;
-    
+
     // Zero message 4 body
     memset(&Packet, 0, sizeof(Packet));
     Packet.Version = EAPOL_VER;
     Packet.Type    = EAPOLKey;
     Packet.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 = RSN_KEY_DESC;
-    
+
 #ifdef BIG_ENDIAN
 	*(USHORT *)(&(pMsg3->KeyDesc.KeyInfo)) = SWAP16(*(USHORT *)(&(pMsg3->KeyDesc.KeyInfo)));
 #endif
-    
+
     // Key descriptor version and appropriate RSN IE
     Packet.KeyDesc.KeyInfo.KeyDescVer = pMsg3->KeyDesc.KeyInfo.KeyDescVer;
 
@@ -603,16 +829,16 @@
     // KeyMic field presented
     Packet.KeyDesc.KeyInfo.KeyMic  = 1;
 
-    // Key Replay count 
-    memcpy(Packet.KeyDesc.ReplayCounter, pMsg3->KeyDesc.ReplayCounter, LEN_KEY_DESC_REPLAY);        
+    // Key Replay count
+    memcpy(Packet.KeyDesc.ReplayCounter, pMsg3->KeyDesc.ReplayCounter, LEN_KEY_DESC_REPLAY);
 #ifdef BIG_ENDIAN
         *(USHORT *)&Packet.KeyDesc.KeyInfo = SWAP16(*(USHORT *)&Packet.KeyDesc.KeyInfo);
 #endif
 
-    // Out buffer for transmitting message 4        
+    // Out buffer for transmitting message 4
     NStatus = MlmeAllocateMemory(pAdapter, (PVOID)&OutBuffer);  //Get an unused nonpaged memory
     if (NStatus != NDIS_STATUS_SUCCESS)
-        return;                 
+        return;
 
     // Prepare EAPOL frame for MIC calculation
     // Be careful, only EAPOL frame is counted for MIC calculation
@@ -626,7 +852,7 @@
     {
         // AES
         UCHAR digest[80];
-            
+
         HMAC_SHA1(OutBuffer, FrameLen, pAdapter->PortCfg.PTK, LEN_EAP_MICK, digest);
         memcpy(Mic, digest, LEN_KEY_DESC_MIC);
     }
@@ -637,10 +863,10 @@
     memcpy(Packet.KeyDesc.KeyMic, Mic, LEN_KEY_DESC_MIC);
 
     FrameLen = 0;
-    
+
     // Make  Transmitting frame
     MakeOutgoingFrame(OutBuffer, &FrameLen, sizeof(MACHDR), &Header_802_11,
-        sizeof(EAPHEAD), EAPHEAD, 
+        sizeof(EAPHEAD), EAPHEAD,
         Packet.Len[1] + 4, &Packet,
         END_OF_ARGS);
 
@@ -651,38 +877,38 @@
     // 7. Update PTK
     memset(&PeerKey, 0, sizeof(PeerKey));
     PeerKey.Length    = sizeof(PeerKey);
-    PeerKey.KeyIndex  = 0xe0000000;           
+    PeerKey.KeyIndex  = 0xe0000000;
     PeerKey.KeyLength = 16;
     memcpy(PeerKey.BSSID, pAdapter->PortCfg.Bssid.Octet, 6);
     memcpy(&PeerKey.KeyRSC, pMsg3->KeyDesc.KeyRsc, LEN_KEY_DESC_RSC);
     memcpy(PeerKey.KeyMaterial, &pAdapter->PortCfg.PTK[32], 32);
     // Call Add peer key function
     RTMPWPAAddKeyProc(pAdapter, &PeerKey);
-    
+
     DBGPRINT(RT_DEBUG_TRACE, "WpaPairMsg3Action <-----\n");
 }
 
 
 /*
     ========================================================================
-    
+
     Routine Description:
         Process Group key 2-way handshaking
 
     Arguments:
         pAdapter    Pointer to our adapter
         Elem        Message body
-        
+
     Return Value:
         None
-        
+
     Note:
-        
+
     ========================================================================
 */
 VOID    WpaGroupMsg1Action(
-    IN  PRTMP_ADAPTER   pAdapter, 
-    IN  MLME_QUEUE_ELEM *Elem) 
+    IN  PRTMP_ADAPTER   pAdapter,
+    IN  MLME_QUEUE_ELEM *Elem)
 {
     PHEADER_802_11      pHeader;
     UCHAR               *OutBuffer = NULL;
@@ -697,12 +923,12 @@
     UCHAR               Mic[16], OldMic[16];
     UCHAR               GTK[32], Key[32];
     NDIS_802_11_KEY     GroupKey;
-    
-       
+
+
     DBGPRINT(RT_DEBUG_TRACE, "WpaGroupMsg1Action ----->\n");
-    
+
     pHeader = (PHEADER_802_11) Elem->Msg;
-    
+
     // Process Group message 1 frame.
     pGroup = (PEAPOL_PACKET) &Elem->Msg[LENGTH_802_11 + LENGTH_802_1_H];
 
@@ -712,7 +938,7 @@
         return;
 
     // Update new replay counter
-    memcpy(pAdapter->PortCfg.ReplayCounter, pGroup->KeyDesc.ReplayCounter, LEN_KEY_DESC_REPLAY);        
+    memcpy(pAdapter->PortCfg.ReplayCounter, pGroup->KeyDesc.ReplayCounter, LEN_KEY_DESC_REPLAY);
 
     // 2. Verify MIC is valid
     // Save the MIC and replace with zero
@@ -722,7 +948,7 @@
     {
         // AES
         UCHAR digest[80];
-            
+
         HMAC_SHA1((PUCHAR) pGroup, pGroup->Len[1] + 4, pAdapter->PortCfg.PTK, LEN_EAP_MICK, digest);
         memcpy(Mic, digest, LEN_KEY_DESC_MIC);
     }
@@ -730,7 +956,7 @@
     {
         hmac_md5(pAdapter->PortCfg.PTK, LEN_EAP_MICK, (PUCHAR) pGroup, pGroup->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");
@@ -749,12 +975,12 @@
         if (pGroup->KeyDesc.KeyInfo.KeyDescVer != 2)
             return;
         // Decrypt AES GTK
-        AES_GTK_KEY_UNWRAP(&pAdapter->PortCfg.PTK[16], GTK, pGroup->KeyDesc.KeyData);       
+        AES_GTK_KEY_UNWRAP(&pAdapter->PortCfg.PTK[16], GTK, pGroup->KeyDesc.KeyData);
     }
     else    // TKIP
     {
         INT i;
-        
+
         if (pGroup->KeyDesc.KeyInfo.KeyDescVer != 1)
             return;
         // Decrypt TKIP GTK
@@ -766,9 +992,9 @@
         for (i = 0; i < 256; i++)
             ARCFOUR_BYTE(&pAdapter->PrivateInfo.WEPCONTEXT);
         // Decrypt GTK. Becareful, there is no ICV to check the result is correct or not
-        ARCFOUR_DECRYPT(&pAdapter->PrivateInfo.WEPCONTEXT, GTK, pGroup->KeyDesc.KeyData, 32);       
+        ARCFOUR_DECRYPT(&pAdapter->PrivateInfo.WEPCONTEXT, GTK, pGroup->KeyDesc.KeyData, 32);
     }
-    
+
     // 4. Construct Group Message 2
     pAdapter->Sequence = ((pAdapter->Sequence) + 1) & (MAX_SEQ_NUMBER);
     WpaMacHeaderInit(pAdapter, &Header_802_11, 1, &pAdapter->PortCfg.Bssid);
@@ -777,18 +1003,18 @@
     AckRate = pAdapter->PortCfg.ExpectedACKRate[pAdapter->PortCfg.TxRate];
     AckDuration = RTMPCalcDuration(pAdapter, AckRate, 14);
     Header_802_11.Controlhead.Duration = pAdapter->PortCfg.Dsifs + AckDuration;
-    
+
     // Zero Group message 1 body
     memset(&Packet, 0, sizeof(Packet));
     Packet.Version = EAPOL_VER;
     Packet.Type    = EAPOLKey;
     Packet.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)
     //
     Packet.KeyDesc.Type = RSN_KEY_DESC;
-    
+
     // Key descriptor version and appropriate RSN IE
     Packet.KeyDesc.KeyInfo.KeyDescVer = pGroup->KeyDesc.KeyInfo.KeyDescVer;
 
@@ -800,18 +1026,18 @@
 
     // Secure bit is 1
     Packet.KeyDesc.KeyInfo.Secure  = 1;
-    
-    // Key Replay count 
-    memcpy(Packet.KeyDesc.ReplayCounter, pGroup->KeyDesc.ReplayCounter, LEN_KEY_DESC_REPLAY);       
+
+    // Key Replay count
+    memcpy(Packet.KeyDesc.ReplayCounter, pGroup->KeyDesc.ReplayCounter, LEN_KEY_DESC_REPLAY);
 
 #ifdef BIG_ENDIAN
 	*(USHORT *)(&(Packet.KeyDesc.KeyInfo)) = SWAP16(*(USHORT *)(&(Packet.KeyDesc.KeyInfo)));
 #endif
 
-    // Out buffer for transmitting group message 2      
+    // Out buffer for transmitting group message 2
     NStatus = MlmeAllocateMemory(pAdapter, (PVOID)&OutBuffer);  //Get an unused nonpaged memory
     if (NStatus != NDIS_STATUS_SUCCESS)
-        return;                 
+        return;
 
     // Prepare EAPOL frame for MIC calculation
     // Be careful, only EAPOL frame is counted for MIC calculation
@@ -825,7 +1051,7 @@
     {
         // AES
         UCHAR digest[80];
-            
+
         HMAC_SHA1(OutBuffer, FrameLen, pAdapter->PortCfg.PTK, LEN_EAP_MICK, digest);
         memcpy(Mic, digest, LEN_KEY_DESC_MIC);
     }
@@ -836,15 +1062,15 @@
         for (i = 0; i < 64; i++)
             DBGPRINT(RT_DEBUG_INFO, "%2x-", pAdapter->PortCfg.PTK[i]);
         DBGPRINT(RT_DEBUG_INFO, "\n FrameLen = %d\n", FrameLen);
-            
+
         hmac_md5(pAdapter->PortCfg.PTK, LEN_EAP_MICK, OutBuffer, FrameLen, Mic);
     }
     memcpy(Packet.KeyDesc.KeyMic, Mic, LEN_KEY_DESC_MIC);
 
-    FrameLen = 0;   
+    FrameLen = 0;
     // Make Transmitting frame
     MakeOutgoingFrame(OutBuffer, &FrameLen, sizeof(MACHDR), &Header_802_11,
-        sizeof(EAPHEAD), EAPHEAD, 
+        sizeof(EAPHEAD), EAPHEAD,
         Packet.Len[1] + 4, &Packet,
         END_OF_ARGS);
 
@@ -853,72 +1079,72 @@
 
     // 6 Free allocated memory
     MlmeFreeMemory(pAdapter, OutBuffer);
-    
+
     // 6. Update GTK
     memset(&GroupKey, 0, sizeof(GroupKey));
     GroupKey.Length    = sizeof(GroupKey);
-    GroupKey.KeyIndex  = 0x20000000 | pGroup->KeyDesc.KeyInfo.KeyIndex;           
+    GroupKey.KeyIndex  = 0x20000000 | pGroup->KeyDesc.KeyInfo.KeyIndex;
     GroupKey.KeyLength = 16;
     memcpy(GroupKey.BSSID, pAdapter->PortCfg.Bssid.Octet, 6);
     memcpy(GroupKey.KeyMaterial, GTK, 32);
     // Call Add peer key function
     RTMPWPAAddKeyProc(pAdapter, &GroupKey);
-    
+
     DBGPRINT(RT_DEBUG_TRACE, "WpaGroupMsg1Action <-----\n");
 }
 /*
     ========================================================================
-    
+
     Routine Description:
         Init WPA MAC header
 
     Arguments:
         pAdapter    Pointer to our adapter
-        
+
     Return Value:
         None
-        
+
     Note:
-        
+
     ========================================================================
 */
 VOID    WpaMacHeaderInit(
-    IN      PRTMP_ADAPTER   pAd, 
-    IN OUT  PHEADER_802_11  Hdr, 
-    IN      UCHAR           wep, 
-    IN      PMACADDR        pAddr1) 
+    IN      PRTMP_ADAPTER   pAd,
+    IN OUT  PHEADER_802_11  Hdr,
+    IN      UCHAR           wep,
+    IN      PMACADDR        pAddr1)
 {
     memset(Hdr, 0, sizeof(HEADER_802_11));
-    Hdr->Controlhead.Frame.Type = BTYPE_DATA;   
+    Hdr->Controlhead.Frame.Type = BTYPE_DATA;
     Hdr->Controlhead.Frame.ToDs = 1;
     if (wep == 1)
         Hdr->Controlhead.Frame.Wep = 1;
-    
+
      // Addr1: DA, Addr2: BSSID, Addr3: SA
     COPY_MAC_ADDR(&Hdr->Controlhead.Addr1, pAddr1);
     COPY_MAC_ADDR(&Hdr->Controlhead.Addr2, &pAd->CurrentAddress);
     COPY_MAC_ADDR(&Hdr->Addr3, &pAd->PortCfg.Bssid);
-    Hdr->Sequence = pAd->Sequence;      
+    Hdr->Sequence = pAd->Sequence;
 }
 
 /*
     ========================================================================
 
     Routine Description:
-        Copy frame from waiting queue into relative ring buffer and set 
+        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:
         pAdapter        Pointer to our adapter
         PNDIS_PACKET    Pointer to outgoing Ndis frame
         NumberOfFrag    Number of fragment required
-        
+
     Return Value:
         None
 
     Note:
-    
+
     ========================================================================
 */
 VOID    WpaHardEncrypt(
@@ -938,38 +1164,58 @@
 #endif
     ULONG           Iv16;
     ULONG           Iv32;
-    PWPA_KEY        pWpaKey;
+    PWPA_KEY        pWpaKey = NULL;
     UCHAR           RetryMode = SHORT_RETRY;
     static UCHAR    Priority[4] = {"\x00\x00\x00\x00"};
+    INT idx;
+    PHEADER_802_11 pHeader;
+    unsigned long  flags;
 
     // Make sure Tx ring resource won't be used by other threads
-    spin_lock_irq(&pAdapter->TxRingLock);
+    spin_lock_irqsave(&pAdapter->TxRingLock, flags);
 
     FrameGap = IFS_BACKOFF;     // Default frame gap mode
-    
-    // outgoing frame always wakeup PHY to prevent frame lost and 
+
+    // outgoing frame always wakeup PHY to prevent frame lost and
     // turn off PSM bit to improve performance
     if (pAdapter->PortCfg.Psm == PWR_SAVE)
     {
         MlmeSetPsmBit(pAdapter, PWR_ACTIVE);
     }
     AsicForceWakeup(pAdapter);
-    
+
     pAdapter->TxRing[pAdapter->CurEncryptIndex].FrameType = BTYPE_DATA;
 
     pSrc = pPacket; // Point to start of MSDU
-    
+
+#if 0
     pWpaKey = (PWPA_KEY) &pAdapter->PortCfg.PairwiseKey[0];
     pWpaKey->Type = PAIRWISE_KEY;
+#else
+    pHeader = (PHEADER_802_11) pSrc;
+
+    for (idx = 0; idx < PAIRWISE_KEY_NO; idx++) {
+	if ((memcmp(&pHeader->Controlhead.Addr1,
+		    pAdapter->PortCfg.PairwiseKey[idx].BssId, 6) == 0)
+	    && (pAdapter->PortCfg.PairwiseKey[idx].KeyLen != 0)) {
+		pWpaKey = (PWPA_KEY) &pAdapter->PortCfg.PairwiseKey[idx];
+		pWpaKey->Type = PAIRWISE_KEY;
+		DBGPRINT(RT_DEBUG_TRACE,
+			 "WpaHardEncrypt:(U) Tx Use Pairwise Key(%d)\n", idx);
+		break;
+	}
+    }
+#endif
     if (pWpaKey == NULL)
     {
         // No pairwise key, this should not happen
-        spin_unlock_irq(&pAdapter->TxRingLock);
+	DBGPRINT(RT_DEBUG_ERROR, "WpaHardEncrypt: No pairwise key!!!!!\n");
+        spin_unlock_irqrestore(&pAdapter->TxRingLock, flags);
         return;
     }
-    
+
     // Get the Tx Ring descriptor & Dma Buffer address
-    pDest = (PUCHAR) pAdapter->TxRing[pAdapter->CurEncryptIndex].va_data_addr;              
+    pDest = (PUCHAR) pAdapter->TxRing[pAdapter->CurEncryptIndex].va_data_addr;
 #ifndef BIG_ENDIAN
     pTxD  = (PTXD_STRUC) pAdapter->TxRing[pAdapter->CurEncryptIndex].va_addr;
 #else
@@ -979,14 +1225,16 @@
 	pTxD = &TxD;
 	RTMPDescriptorEndianChange((PUCHAR)pTxD, TYPE_TXD);
 #endif
-        
+
     if ((pTxD->Owner == DESC_OWN_NIC) || (pTxD->CipherOwn == DESC_OWN_NIC))
     {
         // Descriptor owned by NIC. No descriptor avaliable
         // This should not happen since caller guaranteed.
         // Make sure to release Tx ring resource
+	DBGPRINT(RT_DEBUG_ERROR,
+		 "WpaHardEncrypt: Descriptor ownedby NIC. No descriptor available!!!!!!\n");
         pAdapter->RalinkCounters.TxRingErrCount++;
-        spin_unlock_irq(&pAdapter->TxRingLock);
+        spin_unlock_irqrestore(&pAdapter->TxRingLock, flags);
         return;
     }
     if (pTxD->Valid == TRUE)
@@ -995,17 +1243,19 @@
         // This should not happen since caller guaranteed.
         // Make sure to release Tx ring resource
         pTxD->Valid = FALSE;
-                
+
 #ifdef BIG_ENDIAN
 		RTMPDescriptorEndianChange((PUCHAR)pTxD, TYPE_TXD);
 		*pDestTxD = TxD;
 #endif
 
+	DBGPRINT(RT_DEBUG_ERROR,
+		 "WpaHardEncrypt: Ndis packet of last round did not cleared!!!!!\n");
         pAdapter->RalinkCounters.TxRingErrCount++;
-        spin_unlock_irq(&pAdapter->TxRingLock);
+        spin_unlock_irqrestore(&pAdapter->TxRingLock, flags);
         return;
     }
-        
+
     // Copy whole frame to Tx ring buffer
     memcpy(pDest, pPacket, Len);
     pDest += Len;
@@ -1026,16 +1276,21 @@
             tkipIv.IV16.field.Rsvd = 0;
             tkipIv.IV16.field.ExtIV = 1;// 0: non-extended IV, 1: extended IV
             tkipIv.IV16.field.KeyID = 0;
-            tkipIv.IV32 = *(PULONG)(pWpaKey->TxTsc + 2);
+            //tkipIv.IV32 = *(PULONG)(pWpaKey->TxTsc + 2);
+	    memcpy(&tkipIv.IV32, &pWpaKey->TxTsc[2], 4);
 
+#ifdef BIG_ENDIAN
+	    pTxD-Iv = SWAP32(tipIv.IV16.word);
+#else
             pTxD->Iv = tkipIv.IV16.word;
+#endif
 
             *((PUCHAR) &pTxD->Eiv) = *((PUCHAR) &tkipIv.IV32 + 3);
             *((PUCHAR) &pTxD->Eiv + 1) = *((PUCHAR) &tkipIv.IV32 + 2);
             *((PUCHAR) &pTxD->Eiv + 2) = *((PUCHAR) &tkipIv.IV32 + 1);
             *((PUCHAR) &pTxD->Eiv + 3) = *((PUCHAR) &tkipIv.IV32);
         }
-            
+
         // Increase TxTsc value for next transmission
         while (++pWpaKey->TxTsc[i] == 0x0)
         {
@@ -1043,13 +1298,13 @@
             if (i == 6)
                 break;
         }
-            
+
         // Set IV offset
         pTxD->IvOffset = LENGTH_802_11;
 
         // Copy TKey
         memcpy(pTxD->Key, pWpaKey->Key, 16);
-            
+
         // Set Cipher suite
         CipherAlg = CIPHER_TKIP;
 
@@ -1059,10 +1314,10 @@
         pAdapter->PrivateInfo.Tx.R = RTMPTkipGetUInt32(pWpaKey->TxMic + 4);
         pAdapter->PrivateInfo.Tx.nBytesInM = 0;
         pAdapter->PrivateInfo.Tx.M = 0;
-    	
+
         // DA & SA field
         RTMPTkipAppend(&pAdapter->PrivateInfo.Tx, pSrc + 4, 12);
-        
+
         // Priority + 3 bytes of 0
         RTMPTkipAppend(&pAdapter->PrivateInfo.Tx, Priority, 4);
 
@@ -1086,9 +1341,9 @@
         *(pTmp + 1) = pWpaKey->TxTsc[1];
         *(pTmp + 2) = 0;
         *(pTmp + 3) = 0x20;
-            
+
         Iv32 = *(PULONG)(&pWpaKey->TxTsc[2]);
-            
+
         // Increase TxTsc value for next transmission
         while (++pWpaKey->TxTsc[i] == 0x0)
         {
@@ -1096,13 +1351,13 @@
             if (i == 6)
                 break;
         }
-            
+
         // Copy IV
         memcpy(&pTxD->Iv, &Iv16, 4);
-            
+
         // Copy EIV
         memcpy(&pTxD->Eiv, &Iv32, 4);
-            
+
         // Set IV offset
         pTxD->IvOffset = LENGTH_802_11;
 
@@ -1111,11 +1366,11 @@
 
         // Set Cipher suite
         CipherAlg = CIPHER_AES;
-            
+
         // IV + EIV + HW MIC
         Len += 16;
-    }               
-                
+    }
+
 #ifdef BIG_ENDIAN
 	RTMPFrameEndianChange(pAdapter, pOriginDest, DIR_WRITE, FALSE);
  	RTMPDescriptorEndianChange((PUCHAR)pTxD, TYPE_TXD);
@@ -1123,7 +1378,7 @@
 	pTxD = pDestTxD;
 #endif
 
-    RTMPWriteTxDescriptor(pTxD, TRUE, CipherAlg, TRUE, FALSE, FALSE, RetryMode, FrameGap, 
+    RTMPWriteTxDescriptor(pTxD, TRUE, CipherAlg, TRUE, FALSE, FALSE, RetryMode, FrameGap,
            pAdapter->PortCfg.TxRate, 4, Len, pAdapter->PortCfg.TxPreambleInUsed, 0);
 
     // Increase & maintain Tx Ring Index
@@ -1131,28 +1386,28 @@
     if (pAdapter->CurEncryptIndex >= TX_RING_SIZE)
     {
         pAdapter->CurEncryptIndex = 0;
-    }       
-    pAdapter->RalinkCounters.EncryptCount++;        
-    
+    }
+    pAdapter->RalinkCounters.EncryptCount++;
+
     // Kick Encrypt Control Register at the end of all ring buffer preparation
     RTMP_IO_WRITE32(pAdapter, SECCSR1, 0x1);
-        
+
     // Make sure to release Tx ring resource
-    spin_unlock_irq(&pAdapter->TxRingLock);
+    spin_unlock_irqrestore(&pAdapter->TxRingLock, flags);
 }
 
 /*
     ========================================================================
-    
+
     Routine Description:
-        SHA1 function 
+        SHA1 function
 
     Arguments:
-        
+
     Return Value:
 
     Note:
-        
+
     ========================================================================
 */
 VOID    HMAC_SHA1(
@@ -1167,8 +1422,8 @@
     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) 
+    // if key is longer than 64 bytes reset it to key=SHA1(key)
+    if (key_len > 64)
     {
         SHA_CTX      tctx;
         SHAInit(&tctx);
@@ -1181,20 +1436,20 @@
     memcpy(k_ipad, key, key_len);
     memcpy(k_opad, key, key_len);
 
-    // XOR key with ipad and opad values  
-    for (i = 0; i < 64; i++) 
-    {   
+    // XOR key with ipad and opad values
+    for (i = 0; i < 64; i++)
+    {
         k_ipad[i] ^= 0x36;
         k_opad[i] ^= 0x5c;
     }
 
-    // perform inner SHA1 
+    // 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  
+    //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 */
@@ -1203,17 +1458,17 @@
 
 /*
     ========================================================================
-    
+
     Routine Description:
-        PRF function 
+        PRF function
 
     Arguments:
-        
+
     Return Value:
 
     Note:
         802.1i  Annex F.9
-        
+
     ========================================================================
 */
 VOID    PRF(
@@ -1230,7 +1485,7 @@
     UCHAR   input[1024];
     INT     currentindex = 0;
     INT     total_len;
-    
+
     memcpy(input, prefix, prefix_len);
     input[prefix_len] = 0;
     memcpy(&input[prefix_len + 1], data, data_len);
@@ -1242,22 +1497,22 @@
         HMAC_SHA1(input, total_len, key, key_len, &output[currentindex]);
         currentindex += 20;
         input[total_len - 1]++;
-    }   
+    }
 }
 
 /*
     ========================================================================
-    
+
     Routine Description:
         Count TPTK from PMK
 
     Arguments:
-        
+
     Return Value:
         Output      Store the TPTK
 
     Note:
-        
+
     ========================================================================
 */
 VOID WpaCountPTK(
@@ -1268,11 +1523,11 @@
     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', ' ', 
+    UCHAR   Prefix[] = {'P', 'a', 'i', 'r', 'w', 'i', 's', 'e', ' ', 'k', 'e', 'y', ' ',
                         'e', 'x', 'p', 'a', 'n', 's', 'i', 'o', 'n'};
 
     memset(temp, 0, sizeof(temp));
@@ -1281,52 +1536,52 @@
     if (RTMPCompareMemory(SA, AA, 6) == 1)
         memcpy(concatenation, AA, 6);
     else
-        memcpy(concatenation, SA, 6);       
+        memcpy(concatenation, SA, 6);
     CurrPos += 6;
 
     // Get larger address
     if (RTMPCompareMemory(SA, AA, 6) == 1)
         memcpy(&concatenation[CurrPos], SA, 6);
     else
-        memcpy(&concatenation[CurrPos], AA, 6);     
+        memcpy(&concatenation[CurrPos], AA, 6);
     CurrPos += 6;
 
     // Get smaller address
-    if (RTMPCompareMemory(ANonce, SNonce, 32) == 1) 
+    if (RTMPCompareMemory(ANonce, SNonce, 32) == 1)
         memcpy(&concatenation[CurrPos], SNonce, 32);
-    else        
+    else
         memcpy(&concatenation[CurrPos], ANonce, 32);
     CurrPos += 32;
 
     // Get larger address
-    if (RTMPCompareMemory(ANonce, SNonce, 32) == 1) 
+    if (RTMPCompareMemory(ANonce, SNonce, 32) == 1)
         memcpy(&concatenation[CurrPos], ANonce, 32);
-    else        
+    else
         memcpy(&concatenation[CurrPos], SNonce, 32);
     CurrPos += 32;
-        
+
     PRF(PMK, LEN_MASTER_KEY, Prefix,  22, concatenation, 76 , output, len);
 }
 
 /*
     ========================================================================
-    
+
     Routine Description:
         Misc function to Generate random number
 
     Arguments:
-        
+
     Return Value:
 
     Note:
         802.1i  Annex F.9
-        
+
     ========================================================================
 */
 VOID    GenRandom(
-    IN  PRTMP_ADAPTER   pAd, 
+    IN  PRTMP_ADAPTER   pAd,
     OUT UCHAR           *random)
-{   
+{
     INT     i, curr;
     UCHAR   local[80], KeyCounter[32];
     UCHAR   result[80];
@@ -1337,9 +1592,9 @@
     memset(local, 0, 80);
     memset(KeyCounter, 0, 32);
     memcpy(local, pAd->CurrentAddress, ETH_ALEN);
-    
+
     for (i = 0; i < 32; i++)
-    {       
+    {
         curr =  ETH_ALEN;
         CurrentTime = jiffies;
         memcpy(local,  pAd->CurrentAddress, ETH_ALEN);
@@ -1348,29 +1603,29 @@
         curr += sizeof(CurrentTime);
         memcpy(&local[curr],  result, 32);
         curr += 32;
-        memcpy(&local[curr],  &i,  2);      
+        memcpy(&local[curr],  &i,  2);
         curr += 2;
-        PRF(KeyCounter, 32, prefix,12, local,   curr, result, 32); 
+        PRF(KeyCounter, 32, prefix,12, local,   curr, result, 32);
     }
-    memcpy(random, result,  32);    
+    memcpy(random, result,  32);
 }
 
 /*
     ========================================================================
-    
+
     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( 
+VOID    AES_GTK_KEY_UNWRAP(
     IN  UCHAR   *key,
     OUT UCHAR   *plaintext,
     IN  UCHAR   *ciphertext)
@@ -1381,7 +1636,7 @@
     INT         num_blocks = 2;
     INT         j;
     aes_context aesctx;
-    
+
     // Initialize
     // A = C[0]
     memcpy(A, ciphertext, 8);
@@ -1391,7 +1646,7 @@
     memcpy(R2, &ciphertext[16], 8);
 
     aes_set_key(&aesctx, key, 128);
-    
+
     for (j = 5; j >= 0; j--)
     {
         xor = num_blocks * j + 2;
@@ -1401,7 +1656,7 @@
         aes_decrypt(&aesctx, BIN, BOUT);
         memcpy(A, &BOUT[0], 8);
         memcpy(R2, &BOUT[8], 8);
-        
+
         xor = num_blocks * j + 1;
         memcpy(BIN, A, 8);
         BIN[7] = A[7] ^ xor;
diff -Nur rt2500-1.1.0-b4/Module/wpa.h rt2500-cvs-2007061011/Module/wpa.h
--- rt2500-1.1.0-b4/Module/wpa.h	2006-06-17 22:12:58.000000000 +0200
+++ rt2500-cvs-2007061011/Module/wpa.h	2007-03-21 05:25:35.000000000 +0100
@@ -1,35 +1,35 @@
-/*************************************************************************** 
- * RT2400/RT2500 SourceForge Project - http://rt2x00.serialmonkey.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.                          * 
- *                                                                         * 
- *   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.             * 
- *                                                                         * 
- *   Licensed under the GNU GPL                                            * 
- *   Original code supplied under license from RaLink Inc, 2004.           * 
- ***************************************************************************/ 
-
- /*************************************************************************** 
- *      Module Name: wpa.h 
- *              
- *      Abstract: 
- *              
- *      Revision History: 
- *      Who             When            What 
- *      --------        -----------     ----------------------------- 
- *      MarkW           8th  Dec 04     Baseline code  
- ***************************************************************************/ 
+/***************************************************************************
+ * RT2400/RT2500 SourceForge Project - http://rt2x00.serialmonkey.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.                          *
+ *                                                                         *
+ *   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.             *
+ *                                                                         *
+ *   Licensed under the GNU GPL                                            *
+ *   Original code supplied under license from RaLink Inc, 2004.           *
+ ***************************************************************************/
+
+ /***************************************************************************
+ *      Module Name: wpa.h
+ *
+ *      Abstract:
+ *
+ *      Revision History:
+ *      Who             When            What
+ *      --------        -----------     -----------------------------
+ *      MarkW           8th  Dec 04     Baseline code
+ ***************************************************************************/
 
 #ifndef __WPA_H__
 #define __WPA_H__
@@ -57,7 +57,7 @@
 #define DESC_TYPE_AES               2
 #define RSN_KEY_DESC                0xfe
 
-#define LEN_MASTER_KEY              32  
+#define LEN_MASTER_KEY              32
 
 // EAPOL EK, MK
 #define LEN_EAP_EK                  16
@@ -131,7 +131,7 @@
     UCHAR       KeyRsc[LEN_KEY_DESC_RSC];
     UCHAR       KeyId[LEN_KEY_DESC_ID];
     UCHAR       KeyMic[LEN_KEY_DESC_MIC];
-    UCHAR       KeyDataLen[2];     
+    UCHAR       KeyDataLen[2];
     UCHAR       KeyData[MAX_LEN_OF_RSNIE];
 }   KEY_DESCRIPTER, *PKEY_DESCRIPTER;
 
diff -Nur rt2500-1.1.0-b4/THANKS rt2500-cvs-2007061011/THANKS
--- rt2500-1.1.0-b4/THANKS	2006-06-17 22:12:58.000000000 +0200
+++ rt2500-cvs-2007061011/THANKS	2007-05-05 19:48:18.000000000 +0200
@@ -8,6 +8,7 @@
 * Mark Wallis - mwallis@serialmonkey.com
 * Robin Cornelius - robin@cornelius.demon.co.uk
 * Gertjan van Wingerde - gwingerde@users.sourceforge.net
+* Olivier Cornu - o.cornu@gmail.com
 
 And Special thanks to those that have contributed to the project