Staging: comedi: remove C99 comments in APCI1710_82x54.c
[linux-2.6] / drivers / staging / rt2860 / sta / connect.c
1 /*
2  *************************************************************************
3  * Ralink Tech Inc.
4  * 5F., No.36, Taiyuan St., Jhubei City,
5  * Hsinchu County 302,
6  * Taiwan, R.O.C.
7  *
8  * (c) Copyright 2002-2007, Ralink Technology, Inc.
9  *
10  * This program is free software; you can redistribute it and/or modify  *
11  * it under the terms of the GNU General Public License as published by  *
12  * the Free Software Foundation; either version 2 of the License, or     *
13  * (at your option) any later version.                                   *
14  *                                                                       *
15  * This program is distributed in the hope that it will be useful,       *
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
18  * GNU General Public License for more details.                          *
19  *                                                                       *
20  * You should have received a copy of the GNU General Public License     *
21  * along with this program; if not, write to the                         *
22  * Free Software Foundation, Inc.,                                       *
23  * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
24  *                                                                       *
25  *************************************************************************
26
27         Module Name:
28         connect.c
29
30         Abstract:
31
32         Revision History:
33         Who                     When                    What
34         --------        ----------              ----------------------------------------------
35         John                    2004-08-08                      Major modification from RT2560
36 */
37 #include "../rt_config.h"
38
39 UCHAR   CipherSuiteWpaNoneTkip[] = {
40                 0x00, 0x50, 0xf2, 0x01, // oui
41                 0x01, 0x00,                             // Version
42                 0x00, 0x50, 0xf2, 0x02, // Multicast
43                 0x01, 0x00,                             // Number of unicast
44                 0x00, 0x50, 0xf2, 0x02, // unicast
45                 0x01, 0x00,                             // number of authentication method
46                 0x00, 0x50, 0xf2, 0x00  // authentication
47                 };
48 UCHAR   CipherSuiteWpaNoneTkipLen = (sizeof(CipherSuiteWpaNoneTkip) / sizeof(UCHAR));
49
50 UCHAR   CipherSuiteWpaNoneAes[] = {
51                 0x00, 0x50, 0xf2, 0x01, // oui
52                 0x01, 0x00,                             // Version
53                 0x00, 0x50, 0xf2, 0x04, // Multicast
54                 0x01, 0x00,                             // Number of unicast
55                 0x00, 0x50, 0xf2, 0x04, // unicast
56                 0x01, 0x00,                             // number of authentication method
57                 0x00, 0x50, 0xf2, 0x00  // authentication
58                 };
59 UCHAR   CipherSuiteWpaNoneAesLen = (sizeof(CipherSuiteWpaNoneAes) / sizeof(UCHAR));
60
61 // The following MACRO is called after 1. starting an new IBSS, 2. succesfully JOIN an IBSS,
62 // or 3. succesfully ASSOCIATE to a BSS, 4. successfully RE_ASSOCIATE to a BSS
63 // All settings successfuly negotiated furing MLME state machines become final settings
64 // and are copied to pAd->StaActive
65 #define COPY_SETTINGS_FROM_MLME_AUX_TO_ACTIVE_CFG(_pAd)                                 \
66 {                                                                                       \
67         (_pAd)->CommonCfg.SsidLen = (_pAd)->MlmeAux.SsidLen;                                \
68         NdisMoveMemory((_pAd)->CommonCfg.Ssid, (_pAd)->MlmeAux.Ssid, (_pAd)->MlmeAux.SsidLen); \
69         COPY_MAC_ADDR((_pAd)->CommonCfg.Bssid, (_pAd)->MlmeAux.Bssid);                      \
70         (_pAd)->CommonCfg.Channel = (_pAd)->MlmeAux.Channel;                                \
71         (_pAd)->CommonCfg.CentralChannel = (_pAd)->MlmeAux.CentralChannel;                  \
72         (_pAd)->StaActive.Aid = (_pAd)->MlmeAux.Aid;                                        \
73         (_pAd)->StaActive.AtimWin = (_pAd)->MlmeAux.AtimWin;                                \
74         (_pAd)->StaActive.CapabilityInfo = (_pAd)->MlmeAux.CapabilityInfo;                  \
75         (_pAd)->CommonCfg.BeaconPeriod = (_pAd)->MlmeAux.BeaconPeriod;                      \
76         (_pAd)->StaActive.CfpMaxDuration = (_pAd)->MlmeAux.CfpMaxDuration;                  \
77         (_pAd)->StaActive.CfpPeriod = (_pAd)->MlmeAux.CfpPeriod;                            \
78         (_pAd)->StaActive.SupRateLen = (_pAd)->MlmeAux.SupRateLen;                          \
79         NdisMoveMemory((_pAd)->StaActive.SupRate, (_pAd)->MlmeAux.SupRate, (_pAd)->MlmeAux.SupRateLen);\
80         (_pAd)->StaActive.ExtRateLen = (_pAd)->MlmeAux.ExtRateLen;                          \
81         NdisMoveMemory((_pAd)->StaActive.ExtRate, (_pAd)->MlmeAux.ExtRate, (_pAd)->MlmeAux.ExtRateLen);\
82         NdisMoveMemory(&(_pAd)->CommonCfg.APEdcaParm, &(_pAd)->MlmeAux.APEdcaParm, sizeof(EDCA_PARM));\
83         NdisMoveMemory(&(_pAd)->CommonCfg.APQosCapability, &(_pAd)->MlmeAux.APQosCapability, sizeof(QOS_CAPABILITY_PARM));\
84         NdisMoveMemory(&(_pAd)->CommonCfg.APQbssLoad, &(_pAd)->MlmeAux.APQbssLoad, sizeof(QBSS_LOAD_PARM));\
85         COPY_MAC_ADDR((_pAd)->MacTab.Content[BSSID_WCID].Addr, (_pAd)->MlmeAux.Bssid);      \
86         (_pAd)->MacTab.Content[BSSID_WCID].Aid = (_pAd)->MlmeAux.Aid;                       \
87         (_pAd)->MacTab.Content[BSSID_WCID].PairwiseKey.CipherAlg = (_pAd)->StaCfg.PairCipher;\
88         COPY_MAC_ADDR((_pAd)->MacTab.Content[BSSID_WCID].PairwiseKey.BssId, (_pAd)->MlmeAux.Bssid);\
89         (_pAd)->MacTab.Content[BSSID_WCID].RateLen = (_pAd)->StaActive.SupRateLen + (_pAd)->StaActive.ExtRateLen;\
90 }
91
92 /*
93         ==========================================================================
94         Description:
95
96         IRQL = PASSIVE_LEVEL
97
98         ==========================================================================
99 */
100 VOID MlmeCntlInit(
101         IN PRTMP_ADAPTER pAd,
102         IN STATE_MACHINE *S,
103         OUT STATE_MACHINE_FUNC Trans[])
104 {
105         // Control state machine differs from other state machines, the interface
106         // follows the standard interface
107         pAd->Mlme.CntlMachine.CurrState = CNTL_IDLE;
108 }
109
110 /*
111         ==========================================================================
112         Description:
113
114         IRQL = DISPATCH_LEVEL
115
116         ==========================================================================
117 */
118 VOID MlmeCntlMachinePerformAction(
119         IN PRTMP_ADAPTER pAd,
120         IN STATE_MACHINE *S,
121         IN MLME_QUEUE_ELEM *Elem)
122 {
123         switch(pAd->Mlme.CntlMachine.CurrState)
124         {
125                 case CNTL_IDLE:
126                         {
127                                 CntlIdleProc(pAd, Elem);
128                         }
129                         break;
130                 case CNTL_WAIT_DISASSOC:
131                         CntlWaitDisassocProc(pAd, Elem);
132                         break;
133                 case CNTL_WAIT_JOIN:
134                         CntlWaitJoinProc(pAd, Elem);
135                         break;
136
137                 // CNTL_WAIT_REASSOC is the only state in CNTL machine that does
138                 // not triggered directly or indirectly by "RTMPSetInformation(OID_xxx)".
139                 // Therefore not protected by NDIS's "only one outstanding OID request"
140                 // rule. Which means NDIS may SET OID in the middle of ROAMing attempts.
141                 // Current approach is to block new SET request at RTMPSetInformation()
142                 // when CntlMachine.CurrState is not CNTL_IDLE
143                 case CNTL_WAIT_REASSOC:
144                         CntlWaitReassocProc(pAd, Elem);
145                         break;
146
147                 case CNTL_WAIT_START:
148                         CntlWaitStartProc(pAd, Elem);
149                         break;
150                 case CNTL_WAIT_AUTH:
151                         CntlWaitAuthProc(pAd, Elem);
152                         break;
153                 case CNTL_WAIT_AUTH2:
154                         CntlWaitAuthProc2(pAd, Elem);
155                         break;
156                 case CNTL_WAIT_ASSOC:
157                         CntlWaitAssocProc(pAd, Elem);
158                         break;
159
160                 case CNTL_WAIT_OID_LIST_SCAN:
161                         if(Elem->MsgType == MT2_SCAN_CONF)
162                         {
163                                 // Resume TxRing after SCANING complete. We hope the out-of-service time
164                                 // won't be too long to let upper layer time-out the waiting frames
165                                 RTMPResumeMsduTransmission(pAd);
166                                 if (pAd->StaCfg.CCXReqType != MSRN_TYPE_UNUSED)
167                                 {
168                                         // Cisco scan request is finished, prepare beacon report
169                                         MlmeEnqueue(pAd, AIRONET_STATE_MACHINE, MT2_AIRONET_SCAN_DONE, 0, NULL);
170                                 }
171                                 pAd->Mlme.CntlMachine.CurrState = CNTL_IDLE;
172
173                 //
174                                 // Set LED status to previous status.
175                                 //
176                                 if (pAd->bLedOnScanning)
177                                 {
178                                         pAd->bLedOnScanning = FALSE;
179                                         RTMPSetLED(pAd, pAd->LedStatus);
180                                 }
181 #ifdef DOT11N_DRAFT3
182                                 // AP sent a 2040Coexistence mgmt frame, then station perform a scan, and then send back the respone.
183                                 if (pAd->CommonCfg.BSSCoexist2040.field.InfoReq == 1)
184                                 {
185                                         Update2040CoexistFrameAndNotify(pAd, BSSID_WCID, TRUE);
186                                 }
187 #endif // DOT11N_DRAFT3 //
188                         }
189                         break;
190
191                 case CNTL_WAIT_OID_DISASSOC:
192                         if (Elem->MsgType == MT2_DISASSOC_CONF)
193                         {
194                                 LinkDown(pAd, FALSE);
195                                 pAd->Mlme.CntlMachine.CurrState = CNTL_IDLE;
196                         }
197                         break;
198                 default:
199                         DBGPRINT_ERR(("!ERROR! CNTL - Illegal message type(=%ld)", Elem->MsgType));
200                         break;
201         }
202 }
203
204
205 /*
206         ==========================================================================
207         Description:
208
209         IRQL = DISPATCH_LEVEL
210
211         ==========================================================================
212 */
213 VOID CntlIdleProc(
214         IN PRTMP_ADAPTER pAd,
215         IN MLME_QUEUE_ELEM *Elem)
216 {
217         MLME_DISASSOC_REQ_STRUCT   DisassocReq;
218
219         if (RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_RADIO_OFF))
220                 return;
221
222         switch(Elem->MsgType)
223         {
224                 case OID_802_11_SSID:
225                         CntlOidSsidProc(pAd, Elem);
226                         break;
227
228                 case OID_802_11_BSSID:
229                         CntlOidRTBssidProc(pAd,Elem);
230                         break;
231
232                 case OID_802_11_BSSID_LIST_SCAN:
233                         CntlOidScanProc(pAd,Elem);
234                         break;
235
236                 case OID_802_11_DISASSOCIATE:
237 #ifdef RALINK_ATE
238                         if(ATE_ON(pAd))
239                         {
240                                 DBGPRINT(RT_DEBUG_TRACE, ("The driver is in ATE mode now\n"));
241                                 break;
242                         }
243 #endif // RALINK_ATE //
244                         DisassocParmFill(pAd, &DisassocReq, pAd->CommonCfg.Bssid, REASON_DISASSOC_STA_LEAVING);
245                         MlmeEnqueue(pAd, ASSOC_STATE_MACHINE, MT2_MLME_DISASSOC_REQ, sizeof(MLME_DISASSOC_REQ_STRUCT), &DisassocReq);
246                         pAd->Mlme.CntlMachine.CurrState = CNTL_WAIT_OID_DISASSOC;
247 #ifdef WPA_SUPPLICANT_SUPPORT
248             if (pAd->StaCfg.WpaSupplicantUP != WPA_SUPPLICANT_ENABLE_WITH_WEB_UI)
249 #endif // WPA_SUPPLICANT_SUPPORT //
250             {
251                         // Set the AutoReconnectSsid to prevent it reconnect to old SSID
252                         // Since calling this indicate user don't want to connect to that SSID anymore.
253                         pAd->MlmeAux.AutoReconnectSsidLen= 32;
254                         NdisZeroMemory(pAd->MlmeAux.AutoReconnectSsid, pAd->MlmeAux.AutoReconnectSsidLen);
255             }
256                         break;
257
258                 case MT2_MLME_ROAMING_REQ:
259                         CntlMlmeRoamingProc(pAd, Elem);
260                         break;
261
262         case OID_802_11_MIC_FAILURE_REPORT_FRAME:
263             WpaMicFailureReportFrame(pAd, Elem);
264             break;
265
266 #ifdef QOS_DLS_SUPPORT
267                 case RT_OID_802_11_SET_DLS_PARAM:
268                         CntlOidDLSSetupProc(pAd, Elem);
269                         break;
270 #endif // QOS_DLS_SUPPORT //
271
272                 default:
273                         DBGPRINT(RT_DEBUG_TRACE, ("CNTL - Illegal message in CntlIdleProc(MsgType=%ld)\n",Elem->MsgType));
274                         break;
275         }
276 }
277
278 VOID CntlOidScanProc(
279         IN PRTMP_ADAPTER pAd,
280         IN MLME_QUEUE_ELEM *Elem)
281 {
282         MLME_SCAN_REQ_STRUCT       ScanReq;
283         ULONG                      BssIdx = BSS_NOT_FOUND;
284         BSS_ENTRY                  CurrBss;
285
286 #ifdef RALINK_ATE
287 /* Disable scanning when ATE is running. */
288         if (ATE_ON(pAd))
289                 return;
290 #endif // RALINK_ATE //
291
292
293         // record current BSS if network is connected.
294         // 2003-2-13 do not include current IBSS if this is the only STA in this IBSS.
295         if (OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_MEDIA_STATE_CONNECTED))
296         {
297                 BssIdx = BssSsidTableSearch(&pAd->ScanTab, pAd->CommonCfg.Bssid, pAd->CommonCfg.Ssid, pAd->CommonCfg.SsidLen, pAd->CommonCfg.Channel);
298                 if (BssIdx != BSS_NOT_FOUND)
299                 {
300                         NdisMoveMemory(&CurrBss, &pAd->ScanTab.BssEntry[BssIdx], sizeof(BSS_ENTRY));
301                 }
302         }
303
304         // clean up previous SCAN result, add current BSS back to table if any
305         BssTableInit(&pAd->ScanTab);
306         if (BssIdx != BSS_NOT_FOUND)
307         {
308                 // DDK Note: If the NIC is associated with a particular BSSID and SSID
309                 //    that are not contained in the list of BSSIDs generated by this scan, the
310                 //    BSSID description of the currently associated BSSID and SSID should be
311                 //    appended to the list of BSSIDs in the NIC's database.
312                 // To ensure this, we append this BSS as the first entry in SCAN result
313                 NdisMoveMemory(&pAd->ScanTab.BssEntry[0], &CurrBss, sizeof(BSS_ENTRY));
314                 pAd->ScanTab.BssNr = 1;
315         }
316
317         ScanParmFill(pAd, &ScanReq, "", 0, BSS_ANY, SCAN_ACTIVE);
318         MlmeEnqueue(pAd, SYNC_STATE_MACHINE, MT2_MLME_SCAN_REQ,
319                 sizeof(MLME_SCAN_REQ_STRUCT), &ScanReq);
320         pAd->Mlme.CntlMachine.CurrState = CNTL_WAIT_OID_LIST_SCAN;
321 }
322
323 /*
324         ==========================================================================
325         Description:
326                 Before calling this routine, user desired SSID should already been
327                 recorded in CommonCfg.Ssid[]
328         IRQL = DISPATCH_LEVEL
329
330         ==========================================================================
331 */
332 VOID CntlOidSsidProc(
333         IN PRTMP_ADAPTER pAd,
334         IN MLME_QUEUE_ELEM * Elem)
335 {
336         PNDIS_802_11_SSID          pOidSsid = (NDIS_802_11_SSID *)Elem->Msg;
337         MLME_DISASSOC_REQ_STRUCT   DisassocReq;
338         ULONG                                      Now;
339
340         // BBP and RF are not accessible in PS mode, we has to wake them up first
341         if (OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_DOZE))
342                 AsicForceWakeup(pAd, RTMP_HALT);
343
344         // Step 1. record the desired user settings to MlmeAux
345         NdisZeroMemory(pAd->MlmeAux.Ssid, MAX_LEN_OF_SSID);
346         NdisMoveMemory(pAd->MlmeAux.Ssid, pOidSsid->Ssid, pOidSsid->SsidLength);
347         pAd->MlmeAux.SsidLen = (UCHAR)pOidSsid->SsidLength;
348         NdisZeroMemory(pAd->MlmeAux.Bssid, MAC_ADDR_LEN);
349         pAd->MlmeAux.BssType = pAd->StaCfg.BssType;
350
351
352         //
353         // Update Reconnect Ssid, that user desired to connect.
354         //
355         NdisZeroMemory(pAd->MlmeAux.AutoReconnectSsid, MAX_LEN_OF_SSID);
356         NdisMoveMemory(pAd->MlmeAux.AutoReconnectSsid, pAd->MlmeAux.Ssid, pAd->MlmeAux.SsidLen);
357         pAd->MlmeAux.AutoReconnectSsidLen = pAd->MlmeAux.SsidLen;
358
359         // step 2. find all matching BSS in the lastest SCAN result (inBssTab)
360         //    & log them into MlmeAux.SsidBssTab for later-on iteration. Sort by RSSI order
361         BssTableSsidSort(pAd, &pAd->MlmeAux.SsidBssTab, pAd->MlmeAux.Ssid, pAd->MlmeAux.SsidLen);
362
363         DBGPRINT(RT_DEBUG_TRACE, ("CntlOidSsidProc():CNTL - %d BSS of %d BSS match the desire (%d)SSID - %s\n",
364                         pAd->MlmeAux.SsidBssTab.BssNr, pAd->ScanTab.BssNr, pAd->MlmeAux.SsidLen, pAd->MlmeAux.Ssid));
365         NdisGetSystemUpTime(&Now);
366
367         if (OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_MEDIA_STATE_CONNECTED) &&
368                 (pAd->CommonCfg.SsidLen == pAd->MlmeAux.SsidBssTab.BssEntry[0].SsidLen) &&
369                 NdisEqualMemory(pAd->CommonCfg.Ssid, pAd->MlmeAux.SsidBssTab.BssEntry[0].Ssid, pAd->CommonCfg.SsidLen) &&
370                 MAC_ADDR_EQUAL(pAd->CommonCfg.Bssid, pAd->MlmeAux.SsidBssTab.BssEntry[0].Bssid))
371         {
372                 // Case 1. already connected with an AP who has the desired SSID
373                 //         with highest RSSI
374
375                 // Add checking Mode "LEAP" for CCX 1.0
376                 if (((pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPA) ||
377                          (pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPAPSK) ||
378                          (pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPA2) ||
379                          (pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPA2PSK)
380 #ifdef LEAP_SUPPORT
381                          || (pAd->StaCfg.LeapAuthMode == CISCO_AuthModeLEAP)
382 #endif // LEAP_SUPPORT //
383                          ) &&
384                         (pAd->StaCfg.PortSecured == WPA_802_1X_PORT_NOT_SECURED))
385                 {
386                         // case 1.1 For WPA, WPA-PSK, if the 1x port is not secured, we have to redo
387                         //          connection process
388                         DBGPRINT(RT_DEBUG_TRACE, ("CntlOidSsidProc():CNTL - disassociate with current AP...\n"));
389                         DisassocParmFill(pAd, &DisassocReq, pAd->CommonCfg.Bssid, REASON_DISASSOC_STA_LEAVING);
390                         MlmeEnqueue(pAd, ASSOC_STATE_MACHINE, MT2_MLME_DISASSOC_REQ,
391                                                 sizeof(MLME_DISASSOC_REQ_STRUCT), &DisassocReq);
392                         pAd->Mlme.CntlMachine.CurrState = CNTL_WAIT_DISASSOC;
393                 }
394                 else if (pAd->bConfigChanged == TRUE)
395                 {
396                         // case 1.2 Important Config has changed, we have to reconnect to the same AP
397                         DBGPRINT(RT_DEBUG_TRACE, ("CntlOidSsidProc():CNTL - disassociate with current AP Because config changed...\n"));
398                         DisassocParmFill(pAd, &DisassocReq, pAd->CommonCfg.Bssid, REASON_DISASSOC_STA_LEAVING);
399                         MlmeEnqueue(pAd, ASSOC_STATE_MACHINE, MT2_MLME_DISASSOC_REQ,
400                                                 sizeof(MLME_DISASSOC_REQ_STRUCT), &DisassocReq);
401                         pAd->Mlme.CntlMachine.CurrState = CNTL_WAIT_DISASSOC;
402                 }
403                 else
404                 {
405                         // case 1.3. already connected to the SSID with highest RSSI.
406                         DBGPRINT(RT_DEBUG_TRACE, ("CntlOidSsidProc():CNTL - already with this BSSID. ignore this SET_SSID request\n"));
407                         //
408                         // (HCT 12.1) 1c_wlan_mediaevents required
409                         // media connect events are indicated when associating with the same AP
410                         //
411                         if (INFRA_ON(pAd))
412                         {
413                                 //
414                                 // Since MediaState already is NdisMediaStateConnected
415                                 // We just indicate the connect event again to meet the WHQL required.
416                                 //
417                                 pAd->IndicateMediaState = NdisMediaStateConnected;
418                                 RTMP_IndicateMediaState(pAd);
419                 pAd->ExtraInfo = GENERAL_LINK_UP;   // Update extra information to link is up
420                         }
421
422                         pAd->Mlme.CntlMachine.CurrState = CNTL_IDLE;
423 #ifdef NATIVE_WPA_SUPPLICANT_SUPPORT
424             {
425                 union iwreq_data    wrqu;
426
427                 memset(wrqu.ap_addr.sa_data, 0, MAC_ADDR_LEN);
428                 memcpy(wrqu.ap_addr.sa_data, pAd->MlmeAux.Bssid, MAC_ADDR_LEN);
429                 wireless_send_event(pAd->net_dev, SIOCGIWAP, &wrqu, NULL);
430
431             }
432 #endif // NATIVE_WPA_SUPPLICANT_SUPPORT //
433                 }
434         }
435         else if (INFRA_ON(pAd))
436         {
437                 //
438                 // For RT61
439                 // [88888] OID_802_11_SSID should have returned NDTEST_WEP_AP2(Returned: )
440                 // RT61 may lost SSID, and not connect to NDTEST_WEP_AP2 and will connect to NDTEST_WEP_AP2 by Autoreconnect
441                 // But media status is connected, so the SSID not report correctly.
442                 //
443                 if (!SSID_EQUAL(pAd->CommonCfg.Ssid, pAd->CommonCfg.SsidLen, pAd->MlmeAux.Ssid, pAd->MlmeAux.SsidLen))
444                 {
445                         //
446                         // Different SSID means not Roaming case, so we let LinkDown() to Indicate a disconnect event.
447                         //
448                         pAd->MlmeAux.CurrReqIsFromNdis = TRUE;
449                 }
450                 // case 2. active INFRA association existent
451                 //    roaming is done within miniport driver, nothing to do with configuration
452                 //    utility. so upon a new SET(OID_802_11_SSID) is received, we just
453                 //    disassociate with the current associated AP,
454                 //    then perform a new association with this new SSID, no matter the
455                 //    new/old SSID are the same or not.
456                 DBGPRINT(RT_DEBUG_TRACE, ("CntlOidSsidProc():CNTL - disassociate with current AP...\n"));
457                 DisassocParmFill(pAd, &DisassocReq, pAd->CommonCfg.Bssid, REASON_DISASSOC_STA_LEAVING);
458                 MlmeEnqueue(pAd, ASSOC_STATE_MACHINE, MT2_MLME_DISASSOC_REQ,
459                                         sizeof(MLME_DISASSOC_REQ_STRUCT), &DisassocReq);
460                 pAd->Mlme.CntlMachine.CurrState = CNTL_WAIT_DISASSOC;
461         }
462         else
463         {
464                 if (ADHOC_ON(pAd))
465                 {
466                         DBGPRINT(RT_DEBUG_TRACE, ("CntlOidSsidProc():CNTL - drop current ADHOC\n"));
467                         LinkDown(pAd, FALSE);
468                         OPSTATUS_CLEAR_FLAG(pAd, fOP_STATUS_MEDIA_STATE_CONNECTED);
469                         pAd->IndicateMediaState = NdisMediaStateDisconnected;
470                         RTMP_IndicateMediaState(pAd);
471             pAd->ExtraInfo = GENERAL_LINK_DOWN;
472                         DBGPRINT(RT_DEBUG_TRACE, ("CntlOidSsidProc():NDIS_STATUS_MEDIA_DISCONNECT Event C!\n"));
473                 }
474
475                 if ((pAd->MlmeAux.SsidBssTab.BssNr == 0) &&
476                         (pAd->StaCfg.bAutoReconnect == TRUE) &&
477                         (pAd->MlmeAux.BssType == BSS_INFRA) &&
478                         (MlmeValidateSSID(pAd->MlmeAux.Ssid, pAd->MlmeAux.SsidLen) == TRUE)
479                         )
480                 {
481                         MLME_SCAN_REQ_STRUCT       ScanReq;
482
483                         DBGPRINT(RT_DEBUG_TRACE, ("CntlOidSsidProc():CNTL - No matching BSS, start a new scan\n"));
484                         ScanParmFill(pAd, &ScanReq, pAd->MlmeAux.Ssid, pAd->MlmeAux.SsidLen, BSS_ANY, SCAN_ACTIVE);
485                         MlmeEnqueue(pAd, SYNC_STATE_MACHINE, MT2_MLME_SCAN_REQ, sizeof(MLME_SCAN_REQ_STRUCT), &ScanReq);
486                         pAd->Mlme.CntlMachine.CurrState = CNTL_WAIT_OID_LIST_SCAN;
487                         // Reset Missed scan number
488                         pAd->StaCfg.LastScanTime = Now;
489                 }
490                 else
491                 {
492                         pAd->MlmeAux.BssIdx = 0;
493                         IterateOnBssTab(pAd);
494                 }
495         }
496 }
497
498
499 /*
500         ==========================================================================
501         Description:
502
503         IRQL = DISPATCH_LEVEL
504
505         ==========================================================================
506 */
507 VOID CntlOidRTBssidProc(
508         IN PRTMP_ADAPTER pAd,
509         IN MLME_QUEUE_ELEM * Elem)
510 {
511         ULONG       BssIdx;
512         PUCHAR      pOidBssid = (PUCHAR)Elem->Msg;
513         MLME_DISASSOC_REQ_STRUCT    DisassocReq;
514         MLME_JOIN_REQ_STRUCT        JoinReq;
515
516 #ifdef RALINK_ATE
517 /* No need to perform this routine when ATE is running. */
518         if (ATE_ON(pAd))
519                 return;
520 #endif // RALINK_ATE //
521
522         // record user desired settings
523         COPY_MAC_ADDR(pAd->MlmeAux.Bssid, pOidBssid);
524         pAd->MlmeAux.BssType = pAd->StaCfg.BssType;
525
526         //
527         // Update Reconnect Ssid, that user desired to connect.
528         //
529         NdisZeroMemory(pAd->MlmeAux.AutoReconnectSsid, MAX_LEN_OF_SSID);
530         pAd->MlmeAux.AutoReconnectSsidLen = pAd->MlmeAux.SsidLen;
531         NdisMoveMemory(pAd->MlmeAux.AutoReconnectSsid, pAd->MlmeAux.Ssid, pAd->MlmeAux.SsidLen);
532
533         // find the desired BSS in the latest SCAN result table
534         BssIdx = BssTableSearch(&pAd->ScanTab, pOidBssid, pAd->MlmeAux.Channel);
535         if (BssIdx == BSS_NOT_FOUND)
536         {
537                 DBGPRINT(RT_DEBUG_TRACE, ("CNTL - BSSID not found. reply NDIS_STATUS_NOT_ACCEPTED\n"));
538                 pAd->Mlme.CntlMachine.CurrState = CNTL_IDLE;
539                 return;
540         }
541
542         // copy the matched BSS entry from ScanTab to MlmeAux.SsidBssTab. Why?
543         // Because we need this entry to become the JOIN target in later on SYNC state machine
544         pAd->MlmeAux.BssIdx = 0;
545         pAd->MlmeAux.SsidBssTab.BssNr = 1;
546         NdisMoveMemory(&pAd->MlmeAux.SsidBssTab.BssEntry[0], &pAd->ScanTab.BssEntry[BssIdx], sizeof(BSS_ENTRY));
547
548         // 2002-11-26 skip the following checking. i.e. if user wants to re-connect to same AP
549         //   we just follow normal procedure. The reason of user doing this may because he/she changed
550         //   AP to another channel, but we still received BEACON from it thus don't claim Link Down.
551         //   Since user knows he's changed AP channel, he'll re-connect again. By skipping the following
552         //   checking, we'll disassociate then re-do normal association with this AP at the new channel.
553         // 2003-1-6 Re-enable this feature based on microsoft requirement which prefer not to re-do
554         //   connection when setting the same BSSID.
555         if (OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_MEDIA_STATE_CONNECTED) &&
556                 MAC_ADDR_EQUAL(pAd->CommonCfg.Bssid, pOidBssid))
557         {
558                 // already connected to the same BSSID, go back to idle state directly
559                 DBGPRINT(RT_DEBUG_TRACE, ("CNTL - already in this BSSID. ignore this SET_BSSID request\n"));
560                 pAd->Mlme.CntlMachine.CurrState = CNTL_IDLE;
561 #ifdef NATIVE_WPA_SUPPLICANT_SUPPORT
562             {
563                 union iwreq_data    wrqu;
564
565                 memset(wrqu.ap_addr.sa_data, 0, MAC_ADDR_LEN);
566                 memcpy(wrqu.ap_addr.sa_data, pAd->MlmeAux.Bssid, MAC_ADDR_LEN);
567                 wireless_send_event(pAd->net_dev, SIOCGIWAP, &wrqu, NULL);
568
569             }
570 #endif // NATIVE_WPA_SUPPLICANT_SUPPORT //
571         }
572         else
573         {
574                 if (INFRA_ON(pAd))
575                 {
576                         // disassoc from current AP first
577                         DBGPRINT(RT_DEBUG_TRACE, ("CNTL - disassociate with current AP ...\n"));
578                         DisassocParmFill(pAd, &DisassocReq, pAd->CommonCfg.Bssid, REASON_DISASSOC_STA_LEAVING);
579                         MlmeEnqueue(pAd, ASSOC_STATE_MACHINE, MT2_MLME_DISASSOC_REQ,
580                                                 sizeof(MLME_DISASSOC_REQ_STRUCT), &DisassocReq);
581
582                         pAd->Mlme.CntlMachine.CurrState = CNTL_WAIT_DISASSOC;
583                 }
584                 else
585                 {
586                         if (ADHOC_ON(pAd))
587                         {
588                                 DBGPRINT(RT_DEBUG_TRACE, ("CNTL - drop current ADHOC\n"));
589                                 LinkDown(pAd, FALSE);
590                                 OPSTATUS_CLEAR_FLAG(pAd, fOP_STATUS_MEDIA_STATE_CONNECTED);
591                                 pAd->IndicateMediaState = NdisMediaStateDisconnected;
592                                 RTMP_IndicateMediaState(pAd);
593                 pAd->ExtraInfo = GENERAL_LINK_DOWN;
594                                 DBGPRINT(RT_DEBUG_TRACE, ("NDIS_STATUS_MEDIA_DISCONNECT Event C!\n"));
595                         }
596
597                         // Change the wepstatus to original wepstatus
598                         pAd->StaCfg.WepStatus   = pAd->StaCfg.OrigWepStatus;
599                         pAd->StaCfg.PairCipher  = pAd->StaCfg.OrigWepStatus;
600                         pAd->StaCfg.GroupCipher = pAd->StaCfg.OrigWepStatus;
601
602                         // Check cipher suite, AP must have more secured cipher than station setting
603                         // Set the Pairwise and Group cipher to match the intended AP setting
604                         // We can only connect to AP with less secured cipher setting
605                         if ((pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPA) || (pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPAPSK))
606                         {
607                                 pAd->StaCfg.GroupCipher = pAd->ScanTab.BssEntry[BssIdx].WPA.GroupCipher;
608
609                                 if (pAd->StaCfg.WepStatus == pAd->ScanTab.BssEntry[BssIdx].WPA.PairCipher)
610                                         pAd->StaCfg.PairCipher = pAd->ScanTab.BssEntry[BssIdx].WPA.PairCipher;
611                                 else if (pAd->ScanTab.BssEntry[BssIdx].WPA.PairCipherAux != Ndis802_11WEPDisabled)
612                                         pAd->StaCfg.PairCipher = pAd->ScanTab.BssEntry[BssIdx].WPA.PairCipherAux;
613                                 else    // There is no PairCipher Aux, downgrade our capability to TKIP
614                                         pAd->StaCfg.PairCipher = Ndis802_11Encryption2Enabled;
615                         }
616                         else if ((pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPA2) || (pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPA2PSK))
617                         {
618                                 pAd->StaCfg.GroupCipher = pAd->ScanTab.BssEntry[BssIdx].WPA2.GroupCipher;
619
620                                 if (pAd->StaCfg.WepStatus == pAd->ScanTab.BssEntry[BssIdx].WPA2.PairCipher)
621                                         pAd->StaCfg.PairCipher = pAd->ScanTab.BssEntry[BssIdx].WPA2.PairCipher;
622                                 else if (pAd->ScanTab.BssEntry[BssIdx].WPA2.PairCipherAux != Ndis802_11WEPDisabled)
623                                         pAd->StaCfg.PairCipher = pAd->ScanTab.BssEntry[BssIdx].WPA2.PairCipherAux;
624                                 else    // There is no PairCipher Aux, downgrade our capability to TKIP
625                                         pAd->StaCfg.PairCipher = Ndis802_11Encryption2Enabled;
626
627                                 // RSN capability
628                                 pAd->StaCfg.RsnCapability = pAd->ScanTab.BssEntry[BssIdx].WPA2.RsnCapability;
629                         }
630
631                         // Set Mix cipher flag
632                         pAd->StaCfg.bMixCipher = (pAd->StaCfg.PairCipher == pAd->StaCfg.GroupCipher) ? FALSE : TRUE;
633                         if (pAd->StaCfg.bMixCipher == TRUE)
634                         {
635                                 // If mix cipher, re-build RSNIE
636                                 RTMPMakeRSNIE(pAd, pAd->StaCfg.AuthMode, pAd->StaCfg.WepStatus, 0);
637                         }
638                         // No active association, join the BSS immediately
639                         DBGPRINT(RT_DEBUG_TRACE, ("CNTL - joining %02x:%02x:%02x:%02x:%02x:%02x ...\n",
640                                 pOidBssid[0],pOidBssid[1],pOidBssid[2],pOidBssid[3],pOidBssid[4],pOidBssid[5]));
641
642                         JoinParmFill(pAd, &JoinReq, pAd->MlmeAux.BssIdx);
643                         MlmeEnqueue(pAd, SYNC_STATE_MACHINE, MT2_MLME_JOIN_REQ, sizeof(MLME_JOIN_REQ_STRUCT), &JoinReq);
644
645                         pAd->Mlme.CntlMachine.CurrState = CNTL_WAIT_JOIN;
646                 }
647         }
648 }
649
650 // Roaming is the only external request triggering CNTL state machine
651 // despite of other "SET OID" operation. All "SET OID" related oerations
652 // happen in sequence, because no other SET OID will be sent to this device
653 // until the the previous SET operation is complete (successful o failed).
654 // So, how do we quarantee this ROAMING request won't corrupt other "SET OID"?
655 // or been corrupted by other "SET OID"?
656 //
657 // IRQL = DISPATCH_LEVEL
658 VOID CntlMlmeRoamingProc(
659         IN PRTMP_ADAPTER pAd,
660         IN MLME_QUEUE_ELEM *Elem)
661 {
662         // TODO:
663         // AP in different channel may show lower RSSI than actual value??
664         // should we add a weighting factor to compensate it?
665         DBGPRINT(RT_DEBUG_TRACE,("CNTL - Roaming in MlmeAux.RoamTab...\n"));
666
667         NdisMoveMemory(&pAd->MlmeAux.SsidBssTab, &pAd->MlmeAux.RoamTab, sizeof(pAd->MlmeAux.RoamTab));
668         pAd->MlmeAux.SsidBssTab.BssNr = pAd->MlmeAux.RoamTab.BssNr;
669
670         BssTableSortByRssi(&pAd->MlmeAux.SsidBssTab);
671         pAd->MlmeAux.BssIdx = 0;
672         IterateOnBssTab(pAd);
673 }
674
675 #ifdef QOS_DLS_SUPPORT
676 /*
677         ==========================================================================
678         Description:
679
680         IRQL = DISPATCH_LEVEL
681
682         ==========================================================================
683 */
684 VOID CntlOidDLSSetupProc(
685         IN PRTMP_ADAPTER pAd,
686         IN MLME_QUEUE_ELEM *Elem)
687 {
688         PRT_802_11_DLS          pDLS = (PRT_802_11_DLS)Elem->Msg;
689         MLME_DLS_REQ_STRUCT     MlmeDlsReq;
690         INT                                     i;
691         USHORT                          reason = REASON_UNSPECIFY;
692
693         DBGPRINT(RT_DEBUG_TRACE,("CNTL - (OID set %02x:%02x:%02x:%02x:%02x:%02x with Valid=%d, Status=%d, TimeOut=%d, CountDownTimer=%d)\n",
694                 pDLS->MacAddr[0], pDLS->MacAddr[1], pDLS->MacAddr[2], pDLS->MacAddr[3], pDLS->MacAddr[4], pDLS->MacAddr[5],
695                 pDLS->Valid, pDLS->Status, pDLS->TimeOut, pDLS->CountDownTimer));
696
697         if (!pAd->CommonCfg.bDLSCapable)
698                 return;
699
700         // DLS will not be supported when Adhoc mode
701         if (INFRA_ON(pAd))
702         {
703                 for (i = 0; i < MAX_NUM_OF_DLS_ENTRY; i++)
704                 {
705                         if (pDLS->Valid && pAd->StaCfg.DLSEntry[i].Valid && (pAd->StaCfg.DLSEntry[i].Status == DLS_FINISH) &&
706                                 (pDLS->TimeOut == pAd->StaCfg.DLSEntry[i].TimeOut) && MAC_ADDR_EQUAL(pDLS->MacAddr, pAd->StaCfg.DLSEntry[i].MacAddr))
707                         {
708                                 // 1. Same setting, just drop it
709                                 DBGPRINT(RT_DEBUG_TRACE,("CNTL - setting unchanged\n"));
710                                 break;
711                         }
712                         else if (!pDLS->Valid && pAd->StaCfg.DLSEntry[i].Valid && (pAd->StaCfg.DLSEntry[i].Status == DLS_FINISH) &&
713                                 MAC_ADDR_EQUAL(pDLS->MacAddr, pAd->StaCfg.DLSEntry[i].MacAddr))
714                         {
715                                 // 2. Disable DLS link case, just tear down DLS link
716                                 reason = REASON_QOS_UNWANTED_MECHANISM;
717                                 pAd->StaCfg.DLSEntry[i].Valid   = FALSE;
718                                 pAd->StaCfg.DLSEntry[i].Status  = DLS_NONE;
719                                 DlsParmFill(pAd, &MlmeDlsReq, &pAd->StaCfg.DLSEntry[i], reason);
720                                 MlmeEnqueue(pAd, DLS_STATE_MACHINE, MT2_MLME_DLS_TEAR_DOWN, sizeof(MLME_DLS_REQ_STRUCT), &MlmeDlsReq);
721                                 DBGPRINT(RT_DEBUG_TRACE,("CNTL - start tear down procedure\n"));
722                                 break;
723                         }
724                         else if ((i < MAX_NUM_OF_DLS_ENTRY) && pDLS->Valid && !pAd->StaCfg.DLSEntry[i].Valid)
725                         {
726                                 // 3. Enable case, start DLS setup procedure
727                                 NdisMoveMemory(&pAd->StaCfg.DLSEntry[i], pDLS, sizeof(RT_802_11_DLS_UI));
728
729                                 //Update countdown timer
730                                 pAd->StaCfg.DLSEntry[i].CountDownTimer = pAd->StaCfg.DLSEntry[i].TimeOut;
731                                 DlsParmFill(pAd, &MlmeDlsReq, &pAd->StaCfg.DLSEntry[i], reason);
732                                 MlmeEnqueue(pAd, DLS_STATE_MACHINE, MT2_MLME_DLS_REQ, sizeof(MLME_DLS_REQ_STRUCT), &MlmeDlsReq);
733                                 DBGPRINT(RT_DEBUG_TRACE,("CNTL - DLS setup case\n"));
734                                 break;
735                         }
736                         else if ((i < MAX_NUM_OF_DLS_ENTRY) && pDLS->Valid && pAd->StaCfg.DLSEntry[i].Valid &&
737                                 (pAd->StaCfg.DLSEntry[i].Status == DLS_FINISH) && !MAC_ADDR_EQUAL(pDLS->MacAddr, pAd->StaCfg.DLSEntry[i].MacAddr))
738                         {
739                                 // 4. update mac case, tear down old DLS and setup new DLS
740                                 reason = REASON_QOS_UNWANTED_MECHANISM;
741                                 pAd->StaCfg.DLSEntry[i].Valid   = FALSE;
742                                 pAd->StaCfg.DLSEntry[i].Status  = DLS_NONE;
743                                 DlsParmFill(pAd, &MlmeDlsReq, &pAd->StaCfg.DLSEntry[i], reason);
744                                 MlmeEnqueue(pAd, DLS_STATE_MACHINE, MT2_MLME_DLS_TEAR_DOWN, sizeof(MLME_DLS_REQ_STRUCT), &MlmeDlsReq);
745                                 NdisMoveMemory(&pAd->StaCfg.DLSEntry[i], pDLS, sizeof(RT_802_11_DLS_UI));
746                                 DlsParmFill(pAd, &MlmeDlsReq, &pAd->StaCfg.DLSEntry[i], reason);
747                                 MlmeEnqueue(pAd, DLS_STATE_MACHINE, MT2_MLME_DLS_REQ, sizeof(MLME_DLS_REQ_STRUCT), &MlmeDlsReq);
748                                 DBGPRINT(RT_DEBUG_TRACE,("CNTL - DLS tear down and restart case\n"));
749                                 break;
750                         }
751                         else if (pDLS->Valid && pAd->StaCfg.DLSEntry[i].Valid &&
752                                 MAC_ADDR_EQUAL(pDLS->MacAddr, pAd->StaCfg.DLSEntry[i].MacAddr) && (pAd->StaCfg.DLSEntry[i].TimeOut != pDLS->TimeOut))
753                         {
754                                 // 5. update timeout case, start DLS setup procedure (no tear down)
755                                 pAd->StaCfg.DLSEntry[i].TimeOut = pDLS->TimeOut;
756                                 //Update countdown timer
757                                 pAd->StaCfg.DLSEntry[i].CountDownTimer = pAd->StaCfg.DLSEntry[i].TimeOut;
758                                 DlsParmFill(pAd, &MlmeDlsReq, &pAd->StaCfg.DLSEntry[i], reason);
759                                 MlmeEnqueue(pAd, DLS_STATE_MACHINE, MT2_MLME_DLS_REQ, sizeof(MLME_DLS_REQ_STRUCT), &MlmeDlsReq);
760                                 DBGPRINT(RT_DEBUG_TRACE,("CNTL - DLS update timeout case\n"));
761                                 break;
762                         }
763                         else if (pDLS->Valid && pAd->StaCfg.DLSEntry[i].Valid &&
764                                 (pAd->StaCfg.DLSEntry[i].Status != DLS_FINISH) && MAC_ADDR_EQUAL(pDLS->MacAddr, pAd->StaCfg.DLSEntry[i].MacAddr))
765                         {
766                                 // 6. re-setup case, start DLS setup procedure (no tear down)
767                                 DlsParmFill(pAd, &MlmeDlsReq, &pAd->StaCfg.DLSEntry[i], reason);
768                                 MlmeEnqueue(pAd, DLS_STATE_MACHINE, MT2_MLME_DLS_REQ, sizeof(MLME_DLS_REQ_STRUCT), &MlmeDlsReq);
769                                 DBGPRINT(RT_DEBUG_TRACE,("CNTL - DLS retry setup procedure\n"));
770                                 break;
771                         }
772                         else
773                         {
774                                 DBGPRINT(RT_DEBUG_WARN,("CNTL - DLS not changed in entry - %d - Valid=%d, Status=%d, TimeOut=%d\n",
775                                         i, pAd->StaCfg.DLSEntry[i].Valid, pAd->StaCfg.DLSEntry[i].Status, pAd->StaCfg.DLSEntry[i].TimeOut));
776                         }
777                 }
778         }
779 }
780 #endif // QOS_DLS_SUPPORT //
781
782 /*
783         ==========================================================================
784         Description:
785
786         IRQL = DISPATCH_LEVEL
787
788         ==========================================================================
789 */
790 VOID CntlWaitDisassocProc(
791         IN PRTMP_ADAPTER pAd,
792         IN MLME_QUEUE_ELEM *Elem)
793 {
794         MLME_START_REQ_STRUCT     StartReq;
795
796         if (Elem->MsgType == MT2_DISASSOC_CONF)
797         {
798                 DBGPRINT(RT_DEBUG_TRACE, ("CNTL - Dis-associate successful\n"));
799
800             if (pAd->CommonCfg.bWirelessEvent)
801                 {
802                         RTMPSendWirelessEvent(pAd, IW_DISASSOC_EVENT_FLAG, pAd->MacTab.Content[BSSID_WCID].Addr, BSS0, 0);
803                 }
804
805                 LinkDown(pAd, FALSE);
806
807                 // case 1. no matching BSS, and user wants ADHOC, so we just start a new one
808                 if ((pAd->MlmeAux.SsidBssTab.BssNr==0) && (pAd->StaCfg.BssType == BSS_ADHOC))
809                 {
810                         DBGPRINT(RT_DEBUG_TRACE, ("CNTL - No matching BSS, start a new ADHOC (Ssid=%s)...\n",pAd->MlmeAux.Ssid));
811                         StartParmFill(pAd, &StartReq, pAd->MlmeAux.Ssid, pAd->MlmeAux.SsidLen);
812                         MlmeEnqueue(pAd, SYNC_STATE_MACHINE, MT2_MLME_START_REQ, sizeof(MLME_START_REQ_STRUCT), &StartReq);
813                         pAd->Mlme.CntlMachine.CurrState = CNTL_WAIT_START;
814                 }
815                 // case 2. try each matched BSS
816                 else
817                 {
818                         pAd->MlmeAux.BssIdx = 0;
819
820                         IterateOnBssTab(pAd);
821                 }
822         }
823 }
824
825 /*
826         ==========================================================================
827         Description:
828
829         IRQL = DISPATCH_LEVEL
830
831         ==========================================================================
832 */
833 VOID CntlWaitJoinProc(
834         IN PRTMP_ADAPTER pAd,
835         IN MLME_QUEUE_ELEM *Elem)
836 {
837         USHORT                      Reason;
838         MLME_AUTH_REQ_STRUCT        AuthReq;
839
840         if (Elem->MsgType == MT2_JOIN_CONF)
841         {
842                 NdisMoveMemory(&Reason, Elem->Msg, sizeof(USHORT));
843                 if (Reason == MLME_SUCCESS)
844                 {
845                         // 1. joined an IBSS, we are pretty much done here
846                         if (pAd->MlmeAux.BssType == BSS_ADHOC)
847                         {
848                             //
849                                 // 5G bands rules of Japan:
850                                 // Ad hoc must be disabled in W53(ch52,56,60,64) channels.
851                                 //
852                                 if ( (pAd->CommonCfg.bIEEE80211H == 1) &&
853                       RadarChannelCheck(pAd, pAd->CommonCfg.Channel)
854                                    )
855                                 {
856                                         pAd->Mlme.CntlMachine.CurrState = CNTL_IDLE;
857                                         DBGPRINT(RT_DEBUG_TRACE, ("CNTL - Channel=%d, Join adhoc on W53(52,56,60,64) Channels are not accepted\n", pAd->CommonCfg.Channel));
858                                         return;
859                                 }
860
861                                 LinkUp(pAd, BSS_ADHOC);
862                                 pAd->Mlme.CntlMachine.CurrState = CNTL_IDLE;
863                                 DBGPRINT(RT_DEBUG_TRACE, ("CNTL - join the IBSS = %02x:%02x:%02x:%02x:%02x:%02x ...\n",
864                                 pAd->CommonCfg.Bssid[0],pAd->CommonCfg.Bssid[1],pAd->CommonCfg.Bssid[2],
865                                 pAd->CommonCfg.Bssid[3],pAd->CommonCfg.Bssid[4],pAd->CommonCfg.Bssid[5]));
866
867                 pAd->IndicateMediaState = NdisMediaStateConnected;
868                 pAd->ExtraInfo = GENERAL_LINK_UP;
869                         }
870                         // 2. joined a new INFRA network, start from authentication
871                         else
872                         {
873 #ifdef LEAP_SUPPORT
874                                 // Add AuthMode "LEAP" for CCX 1.X
875                                 if (pAd->StaCfg.LeapAuthMode == CISCO_AuthModeLEAP)
876                                 {
877                                         AuthParmFill(pAd, &AuthReq, pAd->MlmeAux.Bssid, CISCO_AuthModeLEAP);
878                                 }
879                                 else
880 #endif // LEAP_SUPPORT //
881                                 {
882                                         // either Ndis802_11AuthModeShared or Ndis802_11AuthModeAutoSwitch, try shared key first
883                                         if ((pAd->StaCfg.AuthMode == Ndis802_11AuthModeShared) ||
884                                                 (pAd->StaCfg.AuthMode == Ndis802_11AuthModeAutoSwitch))
885                                         {
886                                                 AuthParmFill(pAd, &AuthReq, pAd->MlmeAux.Bssid, Ndis802_11AuthModeShared);
887                                         }
888                                         else
889                                         {
890                                                 AuthParmFill(pAd, &AuthReq, pAd->MlmeAux.Bssid, Ndis802_11AuthModeOpen);
891                                         }
892                                 }
893                                 MlmeEnqueue(pAd, AUTH_STATE_MACHINE, MT2_MLME_AUTH_REQ,
894                                                         sizeof(MLME_AUTH_REQ_STRUCT), &AuthReq);
895
896                                 pAd->Mlme.CntlMachine.CurrState = CNTL_WAIT_AUTH;
897                         }
898                 }
899                 else
900                 {
901                         // 3. failed, try next BSS
902                         pAd->MlmeAux.BssIdx++;
903                         IterateOnBssTab(pAd);
904                 }
905         }
906 }
907
908
909 /*
910         ==========================================================================
911         Description:
912
913         IRQL = DISPATCH_LEVEL
914
915         ==========================================================================
916 */
917 VOID CntlWaitStartProc(
918         IN PRTMP_ADAPTER pAd,
919         IN MLME_QUEUE_ELEM *Elem)
920 {
921         USHORT      Result;
922
923         if (Elem->MsgType == MT2_START_CONF)
924         {
925                 NdisMoveMemory(&Result, Elem->Msg, sizeof(USHORT));
926                 if (Result == MLME_SUCCESS)
927                 {
928                     //
929                         // 5G bands rules of Japan:
930                         // Ad hoc must be disabled in W53(ch52,56,60,64) channels.
931                         //
932                         if ( (pAd->CommonCfg.bIEEE80211H == 1) &&
933                   RadarChannelCheck(pAd, pAd->CommonCfg.Channel)
934                            )
935                         {
936                                 pAd->Mlme.CntlMachine.CurrState = CNTL_IDLE;
937                                 DBGPRINT(RT_DEBUG_TRACE, ("CNTL - Channel=%d, Start adhoc on W53(52,56,60,64) Channels are not accepted\n", pAd->CommonCfg.Channel));
938                                 return;
939                         }
940 #ifdef DOT11_N_SUPPORT
941                         if (pAd->CommonCfg.PhyMode >= PHY_11ABGN_MIXED)
942                         {
943                                 N_ChannelCheck(pAd);
944                                 SetCommonHT(pAd);
945                                 NdisMoveMemory(&pAd->MlmeAux.AddHtInfo, &pAd->CommonCfg.AddHTInfo, sizeof(ADD_HT_INFO_IE));
946                                 RTMPCheckHt(pAd, BSSID_WCID, &pAd->CommonCfg.HtCapability, &pAd->CommonCfg.AddHTInfo);
947                                 pAd->StaActive.SupportedPhyInfo.bHtEnable = TRUE;
948                                 NdisZeroMemory(&pAd->StaActive.SupportedPhyInfo.MCSSet[0], 16);
949                                 NdisMoveMemory(&pAd->StaActive.SupportedPhyInfo.MCSSet[0], &pAd->CommonCfg.HtCapability.MCSSet[0], 16);
950                                 COPY_HTSETTINGS_FROM_MLME_AUX_TO_ACTIVE_CFG(pAd);
951
952                                 if ((pAd->CommonCfg.HtCapability.HtCapInfo.ChannelWidth  == BW_40) &&
953                                         (pAd->CommonCfg.AddHTInfo.AddHtInfo.ExtChanOffset == EXTCHA_ABOVE))
954                                 {
955                                         pAd->MlmeAux.CentralChannel = pAd->CommonCfg.Channel + 2;
956                                 }
957                                 else if ((pAd->CommonCfg.HtCapability.HtCapInfo.ChannelWidth  == BW_40) &&
958                                                  (pAd->CommonCfg.AddHTInfo.AddHtInfo.ExtChanOffset == EXTCHA_BELOW))
959                                 {
960                                         pAd->MlmeAux.CentralChannel = pAd->CommonCfg.Channel - 2;
961                                 }
962                         }
963                         else
964 #endif // DOT11_N_SUPPORT //
965                         {
966                                 pAd->StaActive.SupportedPhyInfo.bHtEnable = FALSE;
967                         }
968                         LinkUp(pAd, BSS_ADHOC);
969                         pAd->Mlme.CntlMachine.CurrState = CNTL_IDLE;
970                         // Before send beacon, driver need do radar detection
971                         if ((pAd->CommonCfg.Channel > 14 )
972                                 && (pAd->CommonCfg.bIEEE80211H == 1)
973                                 && RadarChannelCheck(pAd, pAd->CommonCfg.Channel))
974                         {
975                                 pAd->CommonCfg.RadarDetect.RDMode = RD_SILENCE_MODE;
976                                 pAd->CommonCfg.RadarDetect.RDCount = 0;
977 #ifdef DFS_SUPPORT
978                                 BbpRadarDetectionStart(pAd);
979 #endif // DFS_SUPPORT //
980                         }
981
982                         DBGPRINT(RT_DEBUG_TRACE, ("CNTL - start a new IBSS = %02x:%02x:%02x:%02x:%02x:%02x ...\n",
983                                 pAd->CommonCfg.Bssid[0],pAd->CommonCfg.Bssid[1],pAd->CommonCfg.Bssid[2],
984                                 pAd->CommonCfg.Bssid[3],pAd->CommonCfg.Bssid[4],pAd->CommonCfg.Bssid[5]));
985                 }
986                 else
987                 {
988                         DBGPRINT(RT_DEBUG_TRACE, ("CNTL - Start IBSS fail. BUG!!!!!\n"));
989                         pAd->Mlme.CntlMachine.CurrState = CNTL_IDLE;
990                 }
991         }
992 }
993
994 /*
995         ==========================================================================
996         Description:
997
998         IRQL = DISPATCH_LEVEL
999
1000         ==========================================================================
1001 */
1002 VOID CntlWaitAuthProc(
1003         IN PRTMP_ADAPTER pAd,
1004         IN MLME_QUEUE_ELEM *Elem)
1005 {
1006         USHORT                       Reason;
1007         MLME_ASSOC_REQ_STRUCT        AssocReq;
1008         MLME_AUTH_REQ_STRUCT         AuthReq;
1009
1010         if (Elem->MsgType == MT2_AUTH_CONF)
1011         {
1012                 NdisMoveMemory(&Reason, Elem->Msg, sizeof(USHORT));
1013                 if (Reason == MLME_SUCCESS)
1014                 {
1015                         DBGPRINT(RT_DEBUG_TRACE, ("CNTL - AUTH OK\n"));
1016                         AssocParmFill(pAd, &AssocReq, pAd->MlmeAux.Bssid, pAd->MlmeAux.CapabilityInfo,
1017                                                   ASSOC_TIMEOUT, pAd->StaCfg.DefaultListenCount);
1018
1019 #ifdef LEAP_SUPPORT
1020                         //
1021                         // Cisco Leap CCKM supported Re-association.
1022                         //
1023                         if (LEAP_CCKM_ON(pAd) && (pAd->StaCfg.CCKMLinkUpFlag == TRUE))
1024                         {
1025                                 //if CCKM is turn on , that's mean Fast Reauthentication
1026                                 //Use CCKM Reassociation instead of normal association for Fast Roaming.
1027                                 MlmeEnqueue(pAd, ASSOC_STATE_MACHINE, MT2_MLME_REASSOC_REQ,
1028                                                         sizeof(MLME_ASSOC_REQ_STRUCT), &AssocReq);
1029
1030                                 pAd->Mlme.CntlMachine.CurrState = CNTL_WAIT_REASSOC;
1031                         }
1032                         else
1033 #endif // LEAP_SUPPORT //
1034                         {
1035                                 MlmeEnqueue(pAd, ASSOC_STATE_MACHINE, MT2_MLME_ASSOC_REQ,
1036                                                         sizeof(MLME_ASSOC_REQ_STRUCT), &AssocReq);
1037
1038                                 pAd->Mlme.CntlMachine.CurrState = CNTL_WAIT_ASSOC;
1039                         }
1040                 }
1041                 else
1042                 {
1043                         // This fail may because of the AP already keep us in its MAC table without
1044                         // ageing-out. The previous authentication attempt must have let it remove us.
1045                         // so try Authentication again may help. For D-Link DWL-900AP+ compatibility.
1046                         DBGPRINT(RT_DEBUG_TRACE, ("CNTL - AUTH FAIL, try again...\n"));
1047 #ifdef LEAP_SUPPORT
1048                         //Add AuthMode "LEAP" for CCX 1.X
1049                         if (pAd->StaCfg.LeapAuthMode == CISCO_AuthModeLEAP)
1050                         {
1051                                 AuthParmFill(pAd, &AuthReq, pAd->MlmeAux.Bssid, CISCO_AuthModeLEAP);
1052                         }
1053                         else
1054 #endif // LEAP_SUPPORT //
1055                         {
1056                                 if ((pAd->StaCfg.AuthMode == Ndis802_11AuthModeShared) ||
1057                                         (pAd->StaCfg.AuthMode == Ndis802_11AuthModeAutoSwitch))
1058                                 {
1059                                         // either Ndis802_11AuthModeShared or Ndis802_11AuthModeAutoSwitch, try shared key first
1060                                         AuthParmFill(pAd, &AuthReq, pAd->MlmeAux.Bssid, Ndis802_11AuthModeShared);
1061                                 }
1062                                 else
1063                                 {
1064                                         AuthParmFill(pAd, &AuthReq, pAd->MlmeAux.Bssid, Ndis802_11AuthModeOpen);
1065                                 }
1066                         }
1067                         MlmeEnqueue(pAd, AUTH_STATE_MACHINE, MT2_MLME_AUTH_REQ,
1068                                                 sizeof(MLME_AUTH_REQ_STRUCT), &AuthReq);
1069
1070                         pAd->Mlme.CntlMachine.CurrState = CNTL_WAIT_AUTH2;
1071                 }
1072         }
1073 }
1074
1075 /*
1076         ==========================================================================
1077         Description:
1078
1079         IRQL = DISPATCH_LEVEL
1080
1081         ==========================================================================
1082 */
1083 VOID CntlWaitAuthProc2(
1084         IN PRTMP_ADAPTER pAd,
1085         IN MLME_QUEUE_ELEM *Elem)
1086 {
1087         USHORT                       Reason;
1088         MLME_ASSOC_REQ_STRUCT        AssocReq;
1089         MLME_AUTH_REQ_STRUCT         AuthReq;
1090
1091         if (Elem->MsgType == MT2_AUTH_CONF)
1092         {
1093                 NdisMoveMemory(&Reason, Elem->Msg, sizeof(USHORT));
1094                 if (Reason == MLME_SUCCESS)
1095                 {
1096                         DBGPRINT(RT_DEBUG_TRACE, ("CNTL - AUTH OK\n"));
1097                         AssocParmFill(pAd, &AssocReq, pAd->MlmeAux.Bssid, pAd->MlmeAux.CapabilityInfo,
1098                                                   ASSOC_TIMEOUT, pAd->StaCfg.DefaultListenCount);
1099                         MlmeEnqueue(pAd, ASSOC_STATE_MACHINE, MT2_MLME_ASSOC_REQ,
1100                                                 sizeof(MLME_ASSOC_REQ_STRUCT), &AssocReq);
1101
1102                         pAd->Mlme.CntlMachine.CurrState = CNTL_WAIT_ASSOC;
1103                 }
1104                 else
1105                 {
1106 #ifdef LEAP_SUPPORT
1107                         // Process LEAP first, since it use different control variable
1108                         // We don't want to affect other poven operation
1109                         if (pAd->StaCfg.LeapAuthMode == CISCO_AuthModeLEAP)
1110                         {
1111                                 // LEAP Auth not success, try next BSS
1112                                 DBGPRINT(RT_DEBUG_TRACE, ("CNTL - *LEAP* AUTH FAIL, give up; try next BSS\n"));
1113                                 DBGPRINT(RT_DEBUG_TRACE, ("Total match BSSID [=%d]\n", pAd->MlmeAux.SsidBssTab.BssNr));
1114                                 pAd->Mlme.CntlMachine.CurrState = CNTL_IDLE;
1115                                 pAd->MlmeAux.BssIdx++;
1116                                 IterateOnBssTab(pAd);
1117                         }
1118                         else
1119 #endif // LEAP_SUPPORT //
1120                         if ((pAd->StaCfg.AuthMode == Ndis802_11AuthModeAutoSwitch) &&
1121                                  (pAd->MlmeAux.Alg == Ndis802_11AuthModeShared))
1122                         {
1123                                 DBGPRINT(RT_DEBUG_TRACE, ("CNTL - AUTH FAIL, try OPEN system...\n"));
1124                                 AuthParmFill(pAd, &AuthReq, pAd->MlmeAux.Bssid, Ndis802_11AuthModeOpen);
1125                                 MlmeEnqueue(pAd, AUTH_STATE_MACHINE, MT2_MLME_AUTH_REQ,
1126                                                         sizeof(MLME_AUTH_REQ_STRUCT), &AuthReq);
1127
1128                                 pAd->Mlme.CntlMachine.CurrState = CNTL_WAIT_AUTH2;
1129                         }
1130                         else
1131                         {
1132                                 // not success, try next BSS
1133                                 DBGPRINT(RT_DEBUG_TRACE, ("CNTL - AUTH FAIL, give up; try next BSS\n"));
1134                                 pAd->Mlme.CntlMachine.CurrState = CNTL_IDLE; //???????
1135                                 pAd->MlmeAux.BssIdx++;
1136                                 IterateOnBssTab(pAd);
1137                         }
1138                 }
1139         }
1140 }
1141
1142 /*
1143         ==========================================================================
1144         Description:
1145
1146         IRQL = DISPATCH_LEVEL
1147
1148         ==========================================================================
1149 */
1150 VOID CntlWaitAssocProc(
1151         IN PRTMP_ADAPTER pAd,
1152         IN MLME_QUEUE_ELEM *Elem)
1153 {
1154         USHORT      Reason;
1155
1156         if (Elem->MsgType == MT2_ASSOC_CONF)
1157         {
1158                 NdisMoveMemory(&Reason, Elem->Msg, sizeof(USHORT));
1159                 if (Reason == MLME_SUCCESS)
1160                 {
1161                         LinkUp(pAd, BSS_INFRA);
1162                         pAd->Mlme.CntlMachine.CurrState = CNTL_IDLE;
1163                         DBGPRINT(RT_DEBUG_TRACE, ("CNTL - Association successful on BSS #%ld\n",pAd->MlmeAux.BssIdx));
1164
1165                         if (pAd->CommonCfg.bWirelessEvent)
1166                         {
1167                                 RTMPSendWirelessEvent(pAd, IW_ASSOC_EVENT_FLAG, pAd->MacTab.Content[BSSID_WCID].Addr, BSS0, 0);
1168                         }
1169                 }
1170                 else
1171                 {
1172                         // not success, try next BSS
1173                         DBGPRINT(RT_DEBUG_TRACE, ("CNTL - Association fails on BSS #%ld\n",pAd->MlmeAux.BssIdx));
1174                         pAd->MlmeAux.BssIdx++;
1175                         IterateOnBssTab(pAd);
1176                 }
1177         }
1178 }
1179
1180 /*
1181         ==========================================================================
1182         Description:
1183
1184         IRQL = DISPATCH_LEVEL
1185
1186         ==========================================================================
1187 */
1188 VOID CntlWaitReassocProc(
1189         IN PRTMP_ADAPTER pAd,
1190         IN MLME_QUEUE_ELEM *Elem)
1191 {
1192         USHORT      Result;
1193
1194         if (Elem->MsgType == MT2_REASSOC_CONF)
1195         {
1196                 NdisMoveMemory(&Result, Elem->Msg, sizeof(USHORT));
1197                 if (Result == MLME_SUCCESS)
1198                 {
1199                         //
1200                         // NDIS requires a new Link UP indication but no Link Down for RE-ASSOC
1201                         //
1202                         LinkUp(pAd, BSS_INFRA);
1203
1204                         // send wireless event - for association
1205                         if (pAd->CommonCfg.bWirelessEvent)
1206                                 RTMPSendWirelessEvent(pAd, IW_ASSOC_EVENT_FLAG, pAd->MacTab.Content[BSSID_WCID].Addr, BSS0, 0);
1207
1208
1209 #ifdef LEAP_SUPPORT
1210                         if (LEAP_CCKM_ON(pAd))
1211                         {
1212                                 STA_PORT_SECURED(pAd);
1213                                 pAd->StaCfg.WpaState = SS_FINISH;
1214                         }
1215 #endif // LEAP_SUPPORT //
1216                         pAd->Mlme.CntlMachine.CurrState = CNTL_IDLE;
1217                         DBGPRINT(RT_DEBUG_TRACE, ("CNTL - Re-assocition successful on BSS #%ld\n", pAd->MlmeAux.RoamIdx));
1218                 }
1219                 else
1220                 {
1221                         // reassoc failed, try to pick next BSS in the BSS Table
1222                         DBGPRINT(RT_DEBUG_TRACE, ("CNTL - Re-assocition fails on BSS #%ld\n", pAd->MlmeAux.RoamIdx));
1223                         pAd->MlmeAux.RoamIdx++;
1224                         IterateOnBssTab2(pAd);
1225                 }
1226         }
1227 }
1228
1229 /*
1230         ==========================================================================
1231         Description:
1232
1233         IRQL = DISPATCH_LEVEL
1234
1235         ==========================================================================
1236 */
1237 VOID LinkUp(
1238         IN PRTMP_ADAPTER pAd,
1239         IN UCHAR BssType)
1240 {
1241         ULONG   Now;
1242         UINT32  Data;
1243         BOOLEAN Cancelled;
1244         UCHAR   Value = 0, idx;
1245         MAC_TABLE_ENTRY *pEntry = NULL, *pCurrEntry;
1246
1247         if (RTMP_TEST_PSFLAG(pAd, fRTMP_PS_SET_PCI_CLK_OFF_COMMAND))
1248         {
1249                 RTMPPCIeLinkCtrlValueRestore(pAd, RESTORE_HALT);
1250                 RTMPusecDelay(6000);
1251                 pAd->bPCIclkOff = FALSE;
1252         }
1253
1254         pEntry = &pAd->MacTab.Content[BSSID_WCID];
1255
1256         //
1257         // ASSOC - DisassocTimeoutAction
1258         // CNTL - Dis-associate successful
1259         // !!! LINK DOWN !!!
1260         // [88888] OID_802_11_SSID should have returned NDTEST_WEP_AP2(Returned: )
1261         //
1262         // To prevent DisassocTimeoutAction to call Link down after we link up,
1263         // cancel the DisassocTimer no matter what it start or not.
1264         //
1265         RTMPCancelTimer(&pAd->MlmeAux.DisassocTimer,  &Cancelled);
1266
1267         COPY_SETTINGS_FROM_MLME_AUX_TO_ACTIVE_CFG(pAd);
1268
1269 #ifdef DOT11_N_SUPPORT
1270         COPY_HTSETTINGS_FROM_MLME_AUX_TO_ACTIVE_CFG(pAd);
1271 #endif // DOT11_N_SUPPORT //
1272         // It's quite difficult to tell if a newly added KEY is WEP or CKIP until a new BSS
1273         // is formed (either ASSOC/RE-ASSOC done or IBSS started. LinkUP should be a safe place
1274         // to examine if cipher algorithm switching is required.
1275         //rt2860b. Don't know why need this
1276         SwitchBetweenWepAndCkip(pAd);
1277
1278         // Before power save before link up function, We will force use 1R.
1279         // So after link up, check Rx antenna # again.
1280         RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R3, &Value);
1281         if(pAd->Antenna.field.RxPath == 3)
1282         {
1283                 Value |= (0x10);
1284         }
1285         else if(pAd->Antenna.field.RxPath == 2)
1286         {
1287                 Value |= (0x8);
1288         }
1289         else if(pAd->Antenna.field.RxPath == 1)
1290         {
1291                 Value |= (0x0);
1292         }
1293         RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R3, Value);
1294         pAd->StaCfg.BBPR3 = Value;
1295
1296         if (BssType == BSS_ADHOC)
1297         {
1298                 OPSTATUS_SET_FLAG(pAd, fOP_STATUS_ADHOC_ON);
1299                 OPSTATUS_CLEAR_FLAG(pAd, fOP_STATUS_INFRA_ON);
1300
1301 #ifdef CARRIER_DETECTION_SUPPORT // Roger sync Carrier
1302                 // No carrier detection when adhoc
1303                 // CarrierDetectionStop(pAd);
1304                 pAd->CommonCfg.CarrierDetect.CD_State = CD_NORMAL;
1305 #endif // CARRIER_DETECTION_SUPPORT //
1306
1307                 DBGPRINT(RT_DEBUG_TRACE, ("!!!Adhoc LINK UP !!! \n" ));
1308         }
1309         else
1310         {
1311                 OPSTATUS_SET_FLAG(pAd, fOP_STATUS_INFRA_ON);
1312                 OPSTATUS_CLEAR_FLAG(pAd, fOP_STATUS_ADHOC_ON);
1313
1314                 DBGPRINT(RT_DEBUG_TRACE, ("!!!Infra LINK UP !!! \n" ));
1315         }
1316
1317         // 3*3
1318         // reset Tx beamforming bit
1319         RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R4, &Value);
1320         Value &= (~0x01);
1321         Value |= pAd->CommonCfg.RegTransmitSetting.field.TxBF;
1322         RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R4, Value);
1323
1324 #ifdef DOT11_N_SUPPORT
1325         // Change to AP channel
1326     if ((pAd->CommonCfg.CentralChannel > pAd->CommonCfg.Channel) && (pAd->MlmeAux.HtCapability.HtCapInfo.ChannelWidth == BW_40))
1327         {
1328                 // Must using 40MHz.
1329                 pAd->CommonCfg.BBPCurrentBW = BW_40;
1330                 AsicSwitchChannel(pAd, pAd->CommonCfg.CentralChannel, FALSE);
1331                 AsicLockChannel(pAd, pAd->CommonCfg.CentralChannel);
1332
1333                 RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R4, &Value);
1334                 Value &= (~0x18);
1335                 Value |= 0x10;
1336                 RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R4, Value);
1337
1338                 //  RX : control channel at lower
1339                 RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R3, &Value);
1340                 Value &= (~0x20);
1341                 RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R3, Value);
1342         pAd->StaCfg.BBPR3 = Value;
1343
1344                 RTMP_IO_READ32(pAd, TX_BAND_CFG, &Data);
1345                 Data &= 0xfffffffe;
1346                 RTMP_IO_WRITE32(pAd, TX_BAND_CFG, Data);
1347
1348                 if (pAd->MACVersion == 0x28600100)
1349                 {
1350                         RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R69, 0x1A);
1351                         RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R70, 0x0A);
1352                         RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R73, 0x16);
1353             DBGPRINT(RT_DEBUG_TRACE, ("!!!rt2860C !!! \n" ));
1354                 }
1355
1356                 DBGPRINT(RT_DEBUG_TRACE, ("!!!40MHz Lower LINK UP !!! Control Channel at Below. Central = %d \n", pAd->CommonCfg.CentralChannel ));
1357         }
1358         else if ((pAd->CommonCfg.CentralChannel < pAd->CommonCfg.Channel) && (pAd->MlmeAux.HtCapability.HtCapInfo.ChannelWidth == BW_40))
1359     {
1360             // Must using 40MHz.
1361                 pAd->CommonCfg.BBPCurrentBW = BW_40;
1362                 AsicSwitchChannel(pAd, pAd->CommonCfg.CentralChannel, FALSE);
1363             AsicLockChannel(pAd, pAd->CommonCfg.CentralChannel);
1364
1365                 RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R4, &Value);
1366                 Value &= (~0x18);
1367                 Value |= 0x10;
1368                 RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R4, Value);
1369
1370                 RTMP_IO_READ32(pAd, TX_BAND_CFG, &Data);
1371                 Data |= 0x1;
1372                 RTMP_IO_WRITE32(pAd, TX_BAND_CFG, Data);
1373
1374                 RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R3, &Value);
1375             Value |= (0x20);
1376                 RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R3, Value);
1377         pAd->StaCfg.BBPR3 = Value;
1378
1379                 if (pAd->MACVersion == 0x28600100)
1380                 {
1381                         RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R69, 0x1A);
1382                         RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R70, 0x0A);
1383                         RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R73, 0x16);
1384                             DBGPRINT(RT_DEBUG_TRACE, ("!!!rt2860C !!! \n" ));
1385                 }
1386
1387             DBGPRINT(RT_DEBUG_TRACE, ("!!! 40MHz Upper LINK UP !!! Control Channel at UpperCentral = %d \n", pAd->CommonCfg.CentralChannel ));
1388     }
1389     else
1390 #endif // DOT11_N_SUPPORT //
1391     {
1392             pAd->CommonCfg.BBPCurrentBW = BW_20;
1393                 pAd->CommonCfg.CentralChannel = pAd->CommonCfg.Channel;
1394                 AsicSwitchChannel(pAd, pAd->CommonCfg.Channel, FALSE);
1395                 AsicLockChannel(pAd, pAd->CommonCfg.Channel);
1396
1397                 RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R4, &Value);
1398                 Value &= (~0x18);
1399                 RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R4, Value);
1400
1401                 RTMP_IO_READ32(pAd, TX_BAND_CFG, &Data);
1402                 Data &= 0xfffffffe;
1403                 RTMP_IO_WRITE32(pAd, TX_BAND_CFG, Data);
1404
1405                 RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R3, &Value);
1406                 Value &= (~0x20);
1407                 RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R3, Value);
1408         pAd->StaCfg.BBPR3 = Value;
1409
1410                 if (pAd->MACVersion == 0x28600100)
1411                 {
1412                         RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R69, 0x16);
1413                         RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R70, 0x08);
1414                         RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R73, 0x11);
1415             DBGPRINT(RT_DEBUG_TRACE, ("!!!rt2860C !!! \n" ));
1416                 }
1417
1418             DBGPRINT(RT_DEBUG_TRACE, ("!!! 20MHz LINK UP !!! \n" ));
1419     }
1420
1421         RTMPSetAGCInitValue(pAd, pAd->CommonCfg.BBPCurrentBW);
1422         //
1423         // Save BBP_R66 value, it will be used in RTUSBResumeMsduTransmission
1424         //
1425         RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R66, &pAd->BbpTuning.R66CurrentValue);
1426
1427         DBGPRINT(RT_DEBUG_TRACE, ("!!! LINK UP !!! (BssType=%d, AID=%d, ssid=%s, Channel=%d, CentralChannel = %d)\n",
1428                 BssType, pAd->StaActive.Aid, pAd->CommonCfg.Ssid, pAd->CommonCfg.Channel, pAd->CommonCfg.CentralChannel));
1429
1430 #ifdef DOT11_N_SUPPORT
1431         DBGPRINT(RT_DEBUG_TRACE, ("!!! LINK UP !!! (Density =%d, )\n", pAd->MacTab.Content[BSSID_WCID].MpduDensity));
1432 #endif // DOT11_N_SUPPORT //
1433
1434                 AsicSetBssid(pAd, pAd->CommonCfg.Bssid);
1435
1436         AsicSetSlotTime(pAd, TRUE);
1437         AsicSetEdcaParm(pAd, &pAd->CommonCfg.APEdcaParm);
1438
1439         // Call this for RTS protectionfor legacy rate, we will always enable RTS threshold, but normally it will not hit
1440         AsicUpdateProtect(pAd, 0, (OFDMSETPROTECT | CCKSETPROTECT), TRUE, FALSE);
1441
1442 #ifdef DOT11_N_SUPPORT
1443         if ((pAd->StaActive.SupportedPhyInfo.bHtEnable == TRUE))
1444         {
1445                 // Update HT protectionfor based on AP's operating mode.
1446         if (pAd->MlmeAux.AddHtInfo.AddHtInfo2.NonGfPresent == 1)
1447         {
1448                 AsicUpdateProtect(pAd, pAd->MlmeAux.AddHtInfo.AddHtInfo2.OperaionMode,  ALLN_SETPROTECT, FALSE, TRUE);
1449         }
1450         else
1451                         AsicUpdateProtect(pAd, pAd->MlmeAux.AddHtInfo.AddHtInfo2.OperaionMode,  ALLN_SETPROTECT, FALSE, FALSE);
1452         }
1453 #endif // DOT11_N_SUPPORT //
1454
1455         NdisZeroMemory(&pAd->DrsCounters, sizeof(COUNTER_DRS));
1456
1457         NdisGetSystemUpTime(&Now);
1458         pAd->StaCfg.LastBeaconRxTime = Now;   // last RX timestamp
1459
1460         if ((pAd->CommonCfg.TxPreamble != Rt802_11PreambleLong) &&
1461                 CAP_IS_SHORT_PREAMBLE_ON(pAd->StaActive.CapabilityInfo))
1462         {
1463                 MlmeSetTxPreamble(pAd, Rt802_11PreambleShort);
1464         }
1465
1466         OPSTATUS_CLEAR_FLAG(pAd, fOP_STATUS_AGGREGATION_INUSED);
1467
1468         if (pAd->CommonCfg.RadarDetect.RDMode == RD_SILENCE_MODE)
1469         {
1470 #ifdef DFS_SUPPORT
1471                 RadarDetectionStop(pAd);
1472 #endif // DFS_SUPPORT //
1473         }
1474         pAd->CommonCfg.RadarDetect.RDMode = RD_NORMAL_MODE;
1475
1476         if (BssType == BSS_ADHOC)
1477         {
1478                 MakeIbssBeacon(pAd);
1479                 if ((pAd->CommonCfg.Channel > 14)
1480                         && (pAd->CommonCfg.bIEEE80211H == 1)
1481                         && RadarChannelCheck(pAd, pAd->CommonCfg.Channel))
1482                 {
1483                         ; //Do nothing
1484                 }
1485                 else
1486                 {
1487                         AsicEnableIbssSync(pAd);
1488                 }
1489
1490                 // In ad hoc mode, use MAC table from index 1.
1491                 // p.s ASIC use all 0xff as termination of WCID table search.To prevent it's 0xff-ff-ff-ff-ff-ff, Write 0 here.
1492                 RTMP_IO_WRITE32(pAd, MAC_WCID_BASE, 0x00);
1493                 RTMP_IO_WRITE32(pAd, 0x1808, 0x00);
1494
1495                 // If WEP is enabled, add key material and cipherAlg into Asic
1496                 // Fill in Shared Key Table(offset: 0x6c00) and Shared Key Mode(offset: 0x7000)
1497
1498                 if (pAd->StaCfg.WepStatus == Ndis802_11WEPEnabled)
1499                 {
1500                         PUCHAR  Key;
1501                         UCHAR   CipherAlg;
1502
1503                         for (idx=0; idx < SHARE_KEY_NUM; idx++)
1504                 {
1505                                 CipherAlg = pAd->SharedKey[BSS0][idx].CipherAlg;
1506                         Key = pAd->SharedKey[BSS0][idx].Key;
1507
1508                                 if (pAd->SharedKey[BSS0][idx].KeyLen > 0)
1509                                 {
1510                                         // Set key material and cipherAlg to Asic
1511                                 AsicAddSharedKeyEntry(pAd, BSS0, idx, CipherAlg, Key, NULL, NULL);
1512
1513                     if (idx == pAd->StaCfg.DefaultKeyId)
1514                                         {
1515                                                 // Update WCID attribute table and IVEIV table for this group key table
1516                                                 RTMPAddWcidAttributeEntry(pAd, BSS0, idx, CipherAlg, NULL);
1517                                         }
1518                                 }
1519
1520
1521                         }
1522                 }
1523                 // If WPANone is enabled, add key material and cipherAlg into Asic
1524                 // Fill in Shared Key Table(offset: 0x6c00) and Shared Key Mode(offset: 0x7000)
1525                 else if (pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPANone)
1526                 {
1527                         pAd->StaCfg.DefaultKeyId = 0;   // always be zero
1528
1529             NdisZeroMemory(&pAd->SharedKey[BSS0][0], sizeof(CIPHER_KEY));
1530                                                         pAd->SharedKey[BSS0][0].KeyLen = LEN_TKIP_EK;
1531                         NdisMoveMemory(pAd->SharedKey[BSS0][0].Key, pAd->StaCfg.PMK, LEN_TKIP_EK);
1532
1533             if (pAd->StaCfg.PairCipher == Ndis802_11Encryption2Enabled)
1534             {
1535                         NdisMoveMemory(pAd->SharedKey[BSS0][0].RxMic, &pAd->StaCfg.PMK[16], LEN_TKIP_RXMICK);
1536                         NdisMoveMemory(pAd->SharedKey[BSS0][0].TxMic, &pAd->StaCfg.PMK[16], LEN_TKIP_TXMICK);
1537             }
1538
1539                         // Decide its ChiperAlg
1540                         if (pAd->StaCfg.PairCipher == Ndis802_11Encryption2Enabled)
1541                                 pAd->SharedKey[BSS0][0].CipherAlg = CIPHER_TKIP;
1542                         else if (pAd->StaCfg.PairCipher == Ndis802_11Encryption3Enabled)
1543                                 pAd->SharedKey[BSS0][0].CipherAlg = CIPHER_AES;
1544                         else
1545             {
1546                 DBGPRINT(RT_DEBUG_TRACE, ("Unknow Cipher (=%d), set Cipher to AES\n", pAd->StaCfg.PairCipher));
1547                                 pAd->SharedKey[BSS0][0].CipherAlg = CIPHER_AES;
1548             }
1549
1550                         // Set key material and cipherAlg to Asic
1551                         AsicAddSharedKeyEntry(pAd,
1552                                                                   BSS0,
1553                                                                   0,
1554                                                                   pAd->SharedKey[BSS0][0].CipherAlg,
1555                                                                   pAd->SharedKey[BSS0][0].Key,
1556                                                                   pAd->SharedKey[BSS0][0].TxMic,
1557                                                                   pAd->SharedKey[BSS0][0].RxMic);
1558
1559             // Update WCID attribute table and IVEIV table for this group key table
1560                         RTMPAddWcidAttributeEntry(pAd, BSS0, 0, pAd->SharedKey[BSS0][0].CipherAlg, NULL);
1561
1562                 }
1563
1564         }
1565         else // BSS_INFRA
1566         {
1567                 // Check the new SSID with last SSID
1568                 while (Cancelled == TRUE)
1569                 {
1570                         if (pAd->CommonCfg.LastSsidLen == pAd->CommonCfg.SsidLen)
1571                         {
1572                                 if (RTMPCompareMemory(pAd->CommonCfg.LastSsid, pAd->CommonCfg.Ssid, pAd->CommonCfg.LastSsidLen) == 0)
1573                                 {
1574                                         // Link to the old one no linkdown is required.
1575                                         break;
1576                                 }
1577                         }
1578                         // Send link down event before set to link up
1579                         pAd->IndicateMediaState = NdisMediaStateDisconnected;
1580                         RTMP_IndicateMediaState(pAd);
1581             pAd->ExtraInfo = GENERAL_LINK_DOWN;
1582                         DBGPRINT(RT_DEBUG_TRACE, ("NDIS_STATUS_MEDIA_DISCONNECT Event AA!\n"));
1583                         break;
1584                 }
1585
1586                 //
1587                 // On WPA mode, Remove All Keys if not connect to the last BSSID
1588                 // Key will be set after 4-way handshake.
1589                 //
1590                 if ((pAd->StaCfg.AuthMode >= Ndis802_11AuthModeWPA))
1591                 {
1592                         ULONG           IV;
1593
1594                         // Remove all WPA keys
1595                         RTMPWPARemoveAllKeys(pAd);
1596                         pAd->StaCfg.PortSecured = WPA_802_1X_PORT_NOT_SECURED;
1597                         pAd->StaCfg.PrivacyFilter = Ndis802_11PrivFilter8021xWEP;
1598
1599                         // Fixed connection failed with Range Maximizer - 515 AP (Marvell Chip) when security is WPAPSK/TKIP
1600                         // If IV related values are too large in GroupMsg2, AP would ignore this message.
1601                         IV = 0;
1602                         IV |= (pAd->StaCfg.DefaultKeyId << 30);
1603                         AsicUpdateWCIDIVEIV(pAd, BSSID_WCID, IV, 0);
1604
1605                         RTMP_CLEAR_PSFLAG(pAd, fRTMP_PS_CAN_GO_SLEEP);
1606                 }
1607                 // NOTE:
1608                 // the decision of using "short slot time" or not may change dynamically due to
1609                 // new STA association to the AP. so we have to decide that upon parsing BEACON, not here
1610
1611                 // NOTE:
1612                 // the decision to use "RTC/CTS" or "CTS-to-self" protection or not may change dynamically
1613                 // due to new STA association to the AP. so we have to decide that upon parsing BEACON, not here
1614
1615                 ComposePsPoll(pAd);
1616                 ComposeNullFrame(pAd);
1617
1618                         AsicEnableBssSync(pAd);
1619
1620                 // Add BSSID to WCID search table
1621                 AsicUpdateRxWCIDTable(pAd, BSSID_WCID, pAd->CommonCfg.Bssid);
1622
1623                 NdisAcquireSpinLock(&pAd->MacTabLock);
1624                 // add this BSSID entry into HASH table
1625                 {
1626                         UCHAR HashIdx;
1627
1628                         //pEntry = &pAd->MacTab.Content[BSSID_WCID];
1629                         HashIdx = MAC_ADDR_HASH_INDEX(pAd->CommonCfg.Bssid);
1630                         if (pAd->MacTab.Hash[HashIdx] == NULL)
1631                         {
1632                                 pAd->MacTab.Hash[HashIdx] = pEntry;
1633                         }
1634                         else
1635                         {
1636                                 pCurrEntry = pAd->MacTab.Hash[HashIdx];
1637                                 while (pCurrEntry->pNext != NULL)
1638                                         pCurrEntry = pCurrEntry->pNext;
1639                                 pCurrEntry->pNext = pEntry;
1640                         }
1641                 }
1642                 NdisReleaseSpinLock(&pAd->MacTabLock);
1643
1644
1645                 // If WEP is enabled, add paiewise and shared key
1646 #ifdef WPA_SUPPLICANT_SUPPORT
1647         if (((pAd->StaCfg.WpaSupplicantUP)&&
1648              (pAd->StaCfg.WepStatus == Ndis802_11WEPEnabled)&&
1649              (pAd->StaCfg.PortSecured == WPA_802_1X_PORT_SECURED)) ||
1650             ((pAd->StaCfg.WpaSupplicantUP == WPA_SUPPLICANT_DISABLE)&&
1651               (pAd->StaCfg.WepStatus == Ndis802_11WEPEnabled)))
1652 #else
1653                 if (pAd->StaCfg.WepStatus == Ndis802_11WEPEnabled)
1654 #endif // WPA_SUPPLICANT_SUPPORT //
1655                 {
1656                         PUCHAR  Key;
1657                         UCHAR   CipherAlg;
1658
1659                         for (idx=0; idx < SHARE_KEY_NUM; idx++)
1660                 {
1661                                 CipherAlg = pAd->SharedKey[BSS0][idx].CipherAlg;
1662                         Key = pAd->SharedKey[BSS0][idx].Key;
1663
1664                                 if (pAd->SharedKey[BSS0][idx].KeyLen > 0)
1665                                 {
1666                                         // Set key material and cipherAlg to Asic
1667                                 AsicAddSharedKeyEntry(pAd, BSS0, idx, CipherAlg, Key, NULL, NULL);
1668
1669                                         if (idx == pAd->StaCfg.DefaultKeyId)
1670                                         {
1671                                                 // Assign group key info
1672                                                 RTMPAddWcidAttributeEntry(pAd, BSS0, idx, CipherAlg, NULL);
1673
1674                                                 // Assign pairwise key info
1675                                                 RTMPAddWcidAttributeEntry(pAd, BSS0, idx, CipherAlg, pEntry);
1676                                         }
1677                                 }
1678                         }
1679                 }
1680
1681                 // only INFRASTRUCTURE mode need to indicate connectivity immediately; ADHOC mode
1682                 // should wait until at least 2 active nodes in this BSSID.
1683                 OPSTATUS_SET_FLAG(pAd, fOP_STATUS_MEDIA_STATE_CONNECTED);
1684
1685         // For GUI ++
1686                 if (pAd->StaCfg.AuthMode < Ndis802_11AuthModeWPA)
1687                 {
1688                         pAd->IndicateMediaState = NdisMediaStateConnected;
1689                         pAd->ExtraInfo = GENERAL_LINK_UP;
1690                 }
1691         // --
1692                 RTMP_IndicateMediaState(pAd);
1693
1694                 // Add BSSID in my MAC Table.
1695         NdisAcquireSpinLock(&pAd->MacTabLock);
1696                 RTMPMoveMemory(pAd->MacTab.Content[BSSID_WCID].Addr, pAd->CommonCfg.Bssid, MAC_ADDR_LEN);
1697                 pAd->MacTab.Content[BSSID_WCID].Aid = BSSID_WCID;
1698                 pAd->MacTab.Content[BSSID_WCID].pAd = pAd;
1699                 pAd->MacTab.Content[BSSID_WCID].ValidAsCLI = TRUE;      //Although this is bssid..still set ValidAsCl
1700                 pAd->MacTab.Size = 1;   // infra mode always set MACtab size =1.
1701                 pAd->MacTab.Content[BSSID_WCID].Sst = SST_ASSOC;
1702                 pAd->MacTab.Content[BSSID_WCID].AuthState = SST_ASSOC;
1703                 pAd->MacTab.Content[BSSID_WCID].WepStatus = pAd->StaCfg.WepStatus;
1704         NdisReleaseSpinLock(&pAd->MacTabLock);
1705
1706                 DBGPRINT(RT_DEBUG_TRACE, ("!!! LINK UP !!!  ClientStatusFlags=%lx)\n",
1707                         pAd->MacTab.Content[BSSID_WCID].ClientStatusFlags));
1708
1709                 MlmeUpdateTxRates(pAd, TRUE, BSS0);
1710 #ifdef DOT11_N_SUPPORT
1711                 MlmeUpdateHtTxRates(pAd, BSS0);
1712                 DBGPRINT(RT_DEBUG_TRACE, ("!!! LINK UP !! (StaActive.bHtEnable =%d, )\n", pAd->StaActive.SupportedPhyInfo.bHtEnable));
1713 #endif // DOT11_N_SUPPORT //
1714
1715                 //
1716                 // Report Adjacent AP report.
1717                 //
1718 #ifdef LEAP_SUPPORT
1719                 CCXAdjacentAPReport(pAd);
1720 #endif // LEAP_SUPPORT //
1721
1722                 if (pAd->CommonCfg.bAggregationCapable)
1723                 {
1724                         if ((pAd->CommonCfg.bPiggyBackCapable) && (pAd->MlmeAux.APRalinkIe & 0x00000003) == 3)
1725                         {
1726
1727                                 OPSTATUS_SET_FLAG(pAd, fOP_STATUS_PIGGYBACK_INUSED);
1728                                 OPSTATUS_SET_FLAG(pAd, fOP_STATUS_AGGREGATION_INUSED);
1729                 RTMPSetPiggyBack(pAd, TRUE);
1730                                 DBGPRINT(RT_DEBUG_TRACE, ("Turn on Piggy-Back\n"));
1731                         }
1732                         else if (pAd->MlmeAux.APRalinkIe & 0x00000001)
1733                         {
1734                                 OPSTATUS_SET_FLAG(pAd, fOP_STATUS_AGGREGATION_INUSED);
1735                         }
1736                 }
1737
1738                 if (pAd->MlmeAux.APRalinkIe != 0x0)
1739                 {
1740 #ifdef DOT11_N_SUPPORT
1741                         if (CLIENT_STATUS_TEST_FLAG(&pAd->MacTab.Content[BSSID_WCID], fCLIENT_STATUS_RDG_CAPABLE))
1742                         {
1743                                 AsicEnableRDG(pAd);
1744                         }
1745 #endif // DOT11_N_SUPPORT //
1746                         OPSTATUS_SET_FLAG(pAd, fCLIENT_STATUS_RALINK_CHIPSET);
1747                         CLIENT_STATUS_SET_FLAG(&pAd->MacTab.Content[BSSID_WCID], fCLIENT_STATUS_RALINK_CHIPSET);
1748                 }
1749                 else
1750                 {
1751                         OPSTATUS_CLEAR_FLAG(pAd, fCLIENT_STATUS_RALINK_CHIPSET);
1752                         CLIENT_STATUS_CLEAR_FLAG(&pAd->MacTab.Content[BSSID_WCID], fCLIENT_STATUS_RALINK_CHIPSET);
1753                 }
1754         }
1755
1756 #ifdef DOT11_N_SUPPORT
1757         DBGPRINT(RT_DEBUG_TRACE, ("NDIS_STATUS_MEDIA_CONNECT Event B!.BACapability = %x. ClientStatusFlags = %lx\n", pAd->CommonCfg.BACapability.word, pAd->MacTab.Content[BSSID_WCID].ClientStatusFlags));
1758 #endif // DOT11_N_SUPPORT //
1759
1760         // Set LED
1761         RTMPSetLED(pAd, LED_LINK_UP);
1762
1763         pAd->Mlme.PeriodicRound = 0;
1764         pAd->Mlme.OneSecPeriodicRound = 0;
1765         pAd->bConfigChanged = FALSE;        // Reset config flag
1766         pAd->ExtraInfo = GENERAL_LINK_UP;   // Update extra information to link is up
1767
1768         // Set asic auto fall back
1769         {
1770                 PUCHAR                                  pTable;
1771                 UCHAR                                   TableSize = 0;
1772
1773                 MlmeSelectTxRateTable(pAd, &pAd->MacTab.Content[BSSID_WCID], &pTable, &TableSize, &pAd->CommonCfg.TxRateIndex);
1774                 AsicUpdateAutoFallBackTable(pAd, pTable);
1775         }
1776
1777         NdisAcquireSpinLock(&pAd->MacTabLock);
1778     pEntry->HTPhyMode.word = pAd->StaCfg.HTPhyMode.word;
1779     pEntry->MaxHTPhyMode.word = pAd->StaCfg.HTPhyMode.word;
1780         if (pAd->StaCfg.bAutoTxRateSwitch == FALSE)
1781         {
1782                 pEntry->bAutoTxRateSwitch = FALSE;
1783 #ifdef DOT11_N_SUPPORT
1784                 if (pEntry->HTPhyMode.field.MCS == 32)
1785                         pEntry->HTPhyMode.field.ShortGI = GI_800;
1786
1787                 if ((pEntry->HTPhyMode.field.MCS > MCS_7) || (pEntry->HTPhyMode.field.MCS == 32))
1788                         pEntry->HTPhyMode.field.STBC = STBC_NONE;
1789 #endif // DOT11_N_SUPPORT //
1790                 // If the legacy mode is set, overwrite the transmit setting of this entry.
1791                 if (pEntry->HTPhyMode.field.MODE <= MODE_OFDM)
1792                         RTMPUpdateLegacyTxSetting((UCHAR)pAd->StaCfg.DesiredTransmitSetting.field.FixedTxMode, pEntry);
1793         }
1794         else
1795                 pEntry->bAutoTxRateSwitch = TRUE;
1796         NdisReleaseSpinLock(&pAd->MacTabLock);
1797
1798         //  Let Link Status Page display first initial rate.
1799         pAd->LastTxRate = (USHORT)(pEntry->HTPhyMode.word);
1800         // Select DAC according to HT or Legacy
1801         if (pAd->StaActive.SupportedPhyInfo.MCSSet[0] != 0x00)
1802         {
1803                 RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R1, &Value);
1804                 Value &= (~0x18);
1805                 if (pAd->Antenna.field.TxPath == 2)
1806                 {
1807                     Value |= 0x10;
1808                 }
1809                 RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R1, Value);
1810         }
1811         else
1812         {
1813                 RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R1, &Value);
1814                 Value &= (~0x18);
1815                 RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R1, Value);
1816         }
1817
1818 #ifdef DOT11_N_SUPPORT
1819         if (pAd->StaActive.SupportedPhyInfo.bHtEnable == FALSE)
1820         {
1821         }
1822         else if (pEntry->MaxRAmpduFactor == 0)
1823         {
1824             // If HT AP doesn't support MaxRAmpduFactor = 1, we need to set max PSDU to 0.
1825             // Because our Init value is 1 at MACRegTable.
1826                 RTMP_IO_WRITE32(pAd, MAX_LEN_CFG, 0x0fff);
1827         }
1828 #endif // DOT11_N_SUPPORT //
1829
1830         // Patch for Marvel AP to gain high throughput
1831         // Need to set as following,
1832         // 1. Set txop in register-EDCA_AC0_CFG as 0x60
1833         // 2. Set EnTXWriteBackDDONE in register-WPDMA_GLO_CFG as zero
1834         // 3. PBF_MAX_PCNT as 0x1F3FBF9F
1835         // 4. kick per two packets when dequeue
1836         //
1837         // Txop can only be modified when RDG is off, WMM is disable and TxBurst is enable
1838         //
1839         // if 1. Legacy AP WMM on,  or 2. 11n AP, AMPDU disable.  Force turn off burst no matter what bEnableTxBurst is.
1840 #ifdef DOT11_N_SUPPORT
1841         if (((pAd->StaActive.SupportedPhyInfo.bHtEnable == FALSE) && (OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_WMM_INUSED)))
1842                 || ((pAd->StaActive.SupportedPhyInfo.bHtEnable == TRUE) && (pAd->CommonCfg.BACapability.field.Policy == BA_NOTUSE)))
1843         {
1844                 RTMP_IO_READ32(pAd, EDCA_AC0_CFG, &Data);
1845                 Data  &= 0xFFFFFF00;
1846                 RTMP_IO_WRITE32(pAd, EDCA_AC0_CFG, Data);
1847
1848                 RTMP_IO_WRITE32(pAd, PBF_MAX_PCNT, 0x1F3F7F9F);
1849                 DBGPRINT(RT_DEBUG_TRACE, ("Txburst 1\n"));
1850         }
1851         else
1852 #endif // DOT11_N_SUPPORT //
1853         if (pAd->CommonCfg.bEnableTxBurst)
1854         {
1855                 RTMP_IO_READ32(pAd, EDCA_AC0_CFG, &Data);
1856                 Data  &= 0xFFFFFF00;
1857                 Data  |= 0x60;
1858                 RTMP_IO_WRITE32(pAd, EDCA_AC0_CFG, Data);
1859                 pAd->CommonCfg.IOTestParm.bNowAtherosBurstOn = TRUE;
1860
1861                 RTMP_IO_WRITE32(pAd, PBF_MAX_PCNT, 0x1F3FBF9F);
1862                 DBGPRINT(RT_DEBUG_TRACE, ("Txburst 2\n"));
1863         }
1864         else
1865         {
1866                 RTMP_IO_READ32(pAd, EDCA_AC0_CFG, &Data);
1867                 Data  &= 0xFFFFFF00;
1868                 RTMP_IO_WRITE32(pAd, EDCA_AC0_CFG, Data);
1869
1870                 RTMP_IO_WRITE32(pAd, PBF_MAX_PCNT, 0x1F3F7F9F);
1871                 DBGPRINT(RT_DEBUG_TRACE, ("Txburst 3\n"));
1872         }
1873
1874 #ifdef DOT11_N_SUPPORT
1875         // Re-check to turn on TX burst or not.
1876         if ((pAd->CommonCfg.IOTestParm.bLastAtheros == TRUE) && ((STA_WEP_ON(pAd))||(STA_TKIP_ON(pAd))))
1877         {
1878                 pAd->CommonCfg.IOTestParm.bNextDisableRxBA = TRUE;
1879                 if (pAd->CommonCfg.bEnableTxBurst)
1880                 {
1881                     UINT32 MACValue = 0;
1882                         // Force disable  TXOP value in this case. The same action in MLMEUpdateProtect too.
1883                         // I didn't change PBF_MAX_PCNT setting.
1884                         RTMP_IO_READ32(pAd, EDCA_AC0_CFG, &MACValue);
1885                         MACValue  &= 0xFFFFFF00;
1886                         RTMP_IO_WRITE32(pAd, EDCA_AC0_CFG, MACValue);
1887                         pAd->CommonCfg.IOTestParm.bNowAtherosBurstOn = FALSE;
1888                 }
1889         }
1890         else
1891         {
1892                 pAd->CommonCfg.IOTestParm.bNextDisableRxBA = FALSE;
1893         }
1894 #endif // DOT11_N_SUPPORT //
1895
1896         pAd->CommonCfg.IOTestParm.bLastAtheros = FALSE;
1897         COPY_MAC_ADDR(pAd->CommonCfg.LastBssid, pAd->CommonCfg.Bssid);
1898         DBGPRINT(RT_DEBUG_TRACE, ("!!!pAd->bNextDisableRxBA= %d \n", pAd->CommonCfg.IOTestParm.bNextDisableRxBA));
1899         // BSSID add in one MAC entry too.  Because in Tx, ASIC need to check Cipher and IV/EIV, BAbitmap
1900         // Pther information in MACTab.Content[BSSID_WCID] is not necessary for driver.
1901         // Note: As STA, The MACTab.Content[BSSID_WCID]. PairwiseKey and Shared Key for BSS0 are the same.
1902
1903     if (pAd->StaCfg.WepStatus <= Ndis802_11WEPDisabled)
1904     {
1905         pAd->StaCfg.PortSecured = WPA_802_1X_PORT_SECURED;
1906                 pAd->StaCfg.PrivacyFilter = Ndis802_11PrivFilterAcceptAll;
1907         }
1908
1909         NdisAcquireSpinLock(&pAd->MacTabLock);
1910         pEntry->PortSecured = pAd->StaCfg.PortSecured;
1911         NdisReleaseSpinLock(&pAd->MacTabLock);
1912
1913     //
1914         // Patch Atheros AP TX will breakdown issue.
1915         // AP Model: DLink DWL-8200AP
1916         //
1917         if (INFRA_ON(pAd) && OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_WMM_INUSED) && STA_TKIP_ON(pAd))
1918         {
1919                 RTMP_IO_WRITE32(pAd, RX_PARSER_CFG, 0x01);
1920         }
1921         else
1922         {
1923                 RTMP_IO_WRITE32(pAd, RX_PARSER_CFG, 0x00);
1924         }
1925
1926         RTMP_CLEAR_FLAG(pAd, fRTMP_ADAPTER_BSS_SCAN_IN_PROGRESS);
1927         RTMP_CLEAR_PSFLAG(pAd, fRTMP_PS_GO_TO_SLEEP_NOW);
1928
1929 #ifdef DOT11_N_SUPPORT
1930 #ifdef DOT11N_DRAFT3
1931         if ((pAd->CommonCfg.BACapability.field.b2040CoexistScanSup) && (pAd->CommonCfg.Channel <= 11))
1932         {
1933                 OPSTATUS_SET_FLAG(pAd, fOP_STATUS_SCAN_2040);
1934                 BuildEffectedChannelList(pAd);
1935         }
1936 #endif // DOT11N_DRAFT3 //
1937 #endif // DOT11_N_SUPPORT //
1938 }
1939
1940 /*
1941         ==========================================================================
1942
1943         Routine Description:
1944                 Disconnect current BSSID
1945
1946         Arguments:
1947                 pAd                             - Pointer to our adapter
1948                 IsReqFromAP             - Request from AP
1949
1950         Return Value:
1951                 None
1952
1953         IRQL = DISPATCH_LEVEL
1954
1955         Note:
1956                 We need more information to know it's this requst from AP.
1957                 If yes! we need to do extra handling, for example, remove the WPA key.
1958                 Otherwise on 4-way handshaking will faied, since the WPA key didn't be
1959                 remove while auto reconnect.
1960                 Disconnect request from AP, it means we will start afresh 4-way handshaking
1961                 on WPA mode.
1962
1963         ==========================================================================
1964 */
1965 VOID LinkDown(
1966         IN PRTMP_ADAPTER pAd,
1967         IN  BOOLEAN      IsReqFromAP)
1968 {
1969         UCHAR                       i, ByteValue = 0;
1970         BOOLEAN         Cancelled;
1971
1972         // Do nothing if monitor mode is on
1973         if (MONITOR_ON(pAd))
1974                 return;
1975
1976 #ifdef RALINK_ATE
1977         // Nothing to do in ATE mode.
1978         if (ATE_ON(pAd))
1979                 return;
1980 #endif // RALINK_ATE //
1981
1982         RTMP_CLEAR_PSFLAG(pAd, fRTMP_PS_GO_TO_SLEEP_NOW);
1983         RTMPCancelTimer(&pAd->Mlme.PsPollTimer,         &Cancelled);
1984
1985         // Not allow go to sleep within linkdown function.
1986         RTMP_CLEAR_PSFLAG(pAd, fRTMP_PS_CAN_GO_SLEEP);
1987
1988     if (pAd->CommonCfg.bWirelessEvent)
1989         {
1990                 RTMPSendWirelessEvent(pAd, IW_STA_LINKDOWN_EVENT_FLAG, pAd->MacTab.Content[BSSID_WCID].Addr, BSS0, 0);
1991         }
1992
1993         DBGPRINT(RT_DEBUG_TRACE, ("!!! LINK DOWN !!!\n"));
1994         OPSTATUS_CLEAR_FLAG(pAd, fOP_STATUS_AGGREGATION_INUSED);
1995
1996     if (OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_ADVANCE_POWER_SAVE_PCIE_DEVICE))
1997     {
1998             BOOLEAN Cancelled;
1999         pAd->Mlme.bPsPollTimerRunning = FALSE;
2000         RTMPCancelTimer(&pAd->Mlme.PsPollTimer, &Cancelled);
2001     }
2002
2003     if (OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_DOZE) ||
2004                 RTMP_TEST_PSFLAG(pAd, fRTMP_PS_SET_PCI_CLK_OFF_COMMAND) ||
2005                 RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_IDLE_RADIO_OFF))
2006     {
2007                 AsicForceWakeup(pAd, RTMP_HALT);
2008         OPSTATUS_CLEAR_FLAG(pAd, fOP_STATUS_DOZE);
2009     }
2010
2011     pAd->bPCIclkOff = FALSE;
2012         if (ADHOC_ON(pAd))              // Adhoc mode link down
2013         {
2014                 DBGPRINT(RT_DEBUG_TRACE, ("!!! LINK DOWN 1!!!\n"));
2015
2016                 OPSTATUS_CLEAR_FLAG(pAd, fOP_STATUS_ADHOC_ON);
2017                 OPSTATUS_CLEAR_FLAG(pAd, fOP_STATUS_MEDIA_STATE_CONNECTED);
2018                 pAd->IndicateMediaState = NdisMediaStateDisconnected;
2019                 RTMP_IndicateMediaState(pAd);
2020         pAd->ExtraInfo = GENERAL_LINK_DOWN;
2021                 BssTableDeleteEntry(&pAd->ScanTab, pAd->CommonCfg.Bssid, pAd->CommonCfg.Channel);
2022                 DBGPRINT(RT_DEBUG_TRACE, ("!!! MacTab.Size=%d !!!\n", pAd->MacTab.Size));
2023         }
2024         else                                    // Infra structure mode
2025         {
2026                 DBGPRINT(RT_DEBUG_TRACE, ("!!! LINK DOWN 2!!!\n"));
2027
2028 #ifdef QOS_DLS_SUPPORT
2029                 // DLS tear down frame must be sent before link down
2030                 // send DLS-TEAR_DOWN message
2031                 if (pAd->CommonCfg.bDLSCapable)
2032                 {
2033                         // tear down local dls table entry
2034                         for (i=0; i<MAX_NUM_OF_INIT_DLS_ENTRY; i++)
2035                         {
2036                                 if (pAd->StaCfg.DLSEntry[i].Valid && (pAd->StaCfg.DLSEntry[i].Status == DLS_FINISH))
2037                                 {
2038                                         pAd->StaCfg.DLSEntry[i].Status = DLS_NONE;
2039                                         RTMPSendDLSTearDownFrame(pAd, pAd->StaCfg.DLSEntry[i].MacAddr);
2040                                 }
2041                         }
2042
2043                         // tear down peer dls table entry
2044                         for (i=MAX_NUM_OF_INIT_DLS_ENTRY; i<MAX_NUM_OF_DLS_ENTRY; i++)
2045                         {
2046                                 if (pAd->StaCfg.DLSEntry[i].Valid && (pAd->StaCfg.DLSEntry[i].Status ==  DLS_FINISH))
2047                                 {
2048                                         pAd->StaCfg.DLSEntry[i].Status = DLS_NONE;
2049                                         RTMPSendDLSTearDownFrame(pAd, pAd->StaCfg.DLSEntry[i].MacAddr);
2050                                 }
2051                         }
2052                 }
2053 #endif // QOS_DLS_SUPPORT //
2054
2055                 OPSTATUS_CLEAR_FLAG(pAd, fOP_STATUS_INFRA_ON);
2056                 OPSTATUS_CLEAR_FLAG(pAd, fOP_STATUS_MEDIA_STATE_CONNECTED);
2057
2058                 // Saved last SSID for linkup comparison
2059                 pAd->CommonCfg.LastSsidLen = pAd->CommonCfg.SsidLen;
2060                 NdisMoveMemory(pAd->CommonCfg.LastSsid, pAd->CommonCfg.Ssid, pAd->CommonCfg.LastSsidLen);
2061                 COPY_MAC_ADDR(pAd->CommonCfg.LastBssid, pAd->CommonCfg.Bssid);
2062                 if (pAd->MlmeAux.CurrReqIsFromNdis == TRUE)
2063                 {
2064                         pAd->IndicateMediaState = NdisMediaStateDisconnected;
2065                         RTMP_IndicateMediaState(pAd);
2066             pAd->ExtraInfo = GENERAL_LINK_DOWN;
2067                         DBGPRINT(RT_DEBUG_TRACE, ("NDIS_STATUS_MEDIA_DISCONNECT Event A!\n"));
2068                         pAd->MlmeAux.CurrReqIsFromNdis = FALSE;
2069                 }
2070                 else
2071                 {
2072             //
2073                         // If disassociation request is from NDIS, then we don't need to delete BSSID from entry.
2074                         // Otherwise lost beacon or receive De-Authentication from AP,
2075                         // then we should delete BSSID from BssTable.
2076                         // If we don't delete from entry, roaming will fail.
2077                         //
2078                         BssTableDeleteEntry(&pAd->ScanTab, pAd->CommonCfg.Bssid, pAd->CommonCfg.Channel);
2079                 }
2080
2081                 // restore back to -
2082                 //      1. long slot (20 us) or short slot (9 us) time
2083                 //      2. turn on/off RTS/CTS and/or CTS-to-self protection
2084                 //      3. short preamble
2085                 OPSTATUS_CLEAR_FLAG(pAd, fOP_STATUS_BG_PROTECTION_INUSED);
2086
2087                 if (pAd->StaCfg.CCXAdjacentAPReportFlag == TRUE)
2088                 {
2089                         //
2090                         // Record current AP's information.
2091                         // for later used reporting Adjacent AP report.
2092                         //
2093                         pAd->StaCfg.CCXAdjacentAPChannel = pAd->CommonCfg.Channel;
2094                         pAd->StaCfg.CCXAdjacentAPSsidLen = pAd->CommonCfg.SsidLen;
2095                         NdisMoveMemory(pAd->StaCfg.CCXAdjacentAPSsid, pAd->CommonCfg.Ssid, pAd->StaCfg.CCXAdjacentAPSsidLen);
2096                         COPY_MAC_ADDR(pAd->StaCfg.CCXAdjacentAPBssid, pAd->CommonCfg.Bssid);
2097                 }
2098
2099 #ifdef EXT_BUILD_CHANNEL_LIST
2100                 // Country IE of the AP will be evaluated and will be used.
2101                 if (pAd->StaCfg.IEEE80211dClientMode != Rt802_11_D_None)
2102                 {
2103                         NdisMoveMemory(&pAd->CommonCfg.CountryCode[0], &pAd->StaCfg.StaOriCountryCode[0], 2);
2104                         pAd->CommonCfg.Geography = pAd->StaCfg.StaOriGeography;
2105                         BuildChannelListEx(pAd);
2106                 }
2107 #endif // EXT_BUILD_CHANNEL_LIST //
2108
2109         }
2110
2111         for (i=1; i<MAX_LEN_OF_MAC_TABLE; i++)
2112         {
2113                 if (pAd->MacTab.Content[i].ValidAsCLI == TRUE)
2114                         MacTableDeleteEntry(pAd, pAd->MacTab.Content[i].Aid, pAd->MacTab.Content[i].Addr);
2115         }
2116
2117         pAd->StaCfg.CCXQosECWMin        = 4;
2118         pAd->StaCfg.CCXQosECWMax        = 10;
2119
2120         AsicSetSlotTime(pAd, TRUE); //FALSE);
2121         AsicSetEdcaParm(pAd, NULL);
2122
2123         // Set LED
2124         RTMPSetLED(pAd, LED_LINK_DOWN);
2125     pAd->LedIndicatorStregth = 0xF0;
2126     RTMPSetSignalLED(pAd, -100);        // Force signal strength Led to be turned off, firmware is not done it.
2127
2128                 AsicDisableSync(pAd);
2129
2130         pAd->Mlme.PeriodicRound = 0;
2131         pAd->Mlme.OneSecPeriodicRound = 0;
2132
2133         if (pAd->StaCfg.BssType == BSS_INFRA)
2134         {
2135                 // Remove StaCfg Information after link down
2136                 NdisZeroMemory(pAd->CommonCfg.Bssid, MAC_ADDR_LEN);
2137                 NdisZeroMemory(pAd->CommonCfg.Ssid, MAX_LEN_OF_SSID);
2138                 pAd->CommonCfg.SsidLen = 0;
2139         }
2140 #ifdef DOT11_N_SUPPORT
2141         NdisZeroMemory(&pAd->MlmeAux.HtCapability, sizeof(HT_CAPABILITY_IE));
2142         NdisZeroMemory(&pAd->MlmeAux.AddHtInfo, sizeof(ADD_HT_INFO_IE));
2143         pAd->MlmeAux.HtCapabilityLen = 0;
2144         pAd->MlmeAux.NewExtChannelOffset = 0xff;
2145 #endif // DOT11_N_SUPPORT //
2146
2147         // Reset WPA-PSK state. Only reset when supplicant enabled
2148         if (pAd->StaCfg.WpaState != SS_NOTUSE)
2149         {
2150                 pAd->StaCfg.WpaState = SS_START;
2151                 // Clear Replay counter
2152                 NdisZeroMemory(pAd->StaCfg.ReplayCounter, 8);
2153
2154 #ifdef QOS_DLS_SUPPORT
2155                 if (pAd->CommonCfg.bDLSCapable)
2156                         NdisZeroMemory(pAd->StaCfg.DlsReplayCounter, 8);
2157 #endif // QOS_DLS_SUPPORT //
2158         }
2159
2160
2161         //
2162         // if link down come from AP, we need to remove all WPA keys on WPA mode.
2163         // otherwise will cause 4-way handshaking failed, since the WPA key not empty.
2164         //
2165         if ((IsReqFromAP) && (pAd->StaCfg.AuthMode >= Ndis802_11AuthModeWPA))
2166         {
2167                 // Remove all WPA keys
2168                 RTMPWPARemoveAllKeys(pAd);
2169         }
2170
2171         // 802.1x port control
2172 #ifdef WPA_SUPPLICANT_SUPPORT
2173         // Prevent clear PortSecured here with static WEP
2174         // NetworkManger set security policy first then set SSID to connect AP.
2175         if (pAd->StaCfg.WpaSupplicantUP &&
2176                 (pAd->StaCfg.WepStatus == Ndis802_11WEPEnabled) &&
2177                 (pAd->StaCfg.IEEE8021X == FALSE))
2178         {
2179                 pAd->StaCfg.PortSecured = WPA_802_1X_PORT_SECURED;
2180         }
2181         else
2182 #endif // WPA_SUPPLICANT_SUPPORT //
2183         {
2184                 pAd->StaCfg.PortSecured = WPA_802_1X_PORT_NOT_SECURED;
2185                 pAd->StaCfg.PrivacyFilter = Ndis802_11PrivFilter8021xWEP;
2186         }
2187
2188         NdisAcquireSpinLock(&pAd->MacTabLock);
2189         pAd->MacTab.Content[BSSID_WCID].PortSecured = pAd->StaCfg.PortSecured;
2190         NdisReleaseSpinLock(&pAd->MacTabLock);
2191
2192         pAd->StaCfg.MicErrCnt = 0;
2193
2194         // Turn off Ckip control flag
2195         pAd->StaCfg.bCkipOn = FALSE;
2196         pAd->StaCfg.CCXEnable = FALSE;
2197
2198     pAd->IndicateMediaState = NdisMediaStateDisconnected;
2199         // Update extra information to link is up
2200         pAd->ExtraInfo = GENERAL_LINK_DOWN;
2201
2202     pAd->StaCfg.AdhocBOnlyJoined = FALSE;
2203         pAd->StaCfg.AdhocBGJoined = FALSE;
2204         pAd->StaCfg.Adhoc20NJoined = FALSE;
2205     pAd->StaActive.SupportedPhyInfo.bHtEnable = FALSE;
2206
2207         // Reset the Current AP's IP address
2208         NdisZeroMemory(pAd->StaCfg.AironetIPAddress, 4);
2209
2210         // Clean association information
2211         NdisZeroMemory(&pAd->StaCfg.AssocInfo, sizeof(NDIS_802_11_ASSOCIATION_INFORMATION));
2212         pAd->StaCfg.AssocInfo.Length = sizeof(NDIS_802_11_ASSOCIATION_INFORMATION);
2213         pAd->StaCfg.ReqVarIELen = 0;
2214         pAd->StaCfg.ResVarIELen = 0;
2215
2216         //
2217         // Reset RSSI value after link down
2218         //
2219         pAd->StaCfg.RssiSample.AvgRssi0 = 0;
2220         pAd->StaCfg.RssiSample.AvgRssi0X8 = 0;
2221         pAd->StaCfg.RssiSample.AvgRssi1 = 0;
2222         pAd->StaCfg.RssiSample.AvgRssi1X8 = 0;
2223         pAd->StaCfg.RssiSample.AvgRssi2 = 0;
2224         pAd->StaCfg.RssiSample.AvgRssi2X8 = 0;
2225
2226         // Restore MlmeRate
2227         pAd->CommonCfg.MlmeRate = pAd->CommonCfg.BasicMlmeRate;
2228         pAd->CommonCfg.RtsRate = pAd->CommonCfg.BasicMlmeRate;
2229
2230 #ifdef DOT11_N_SUPPORT
2231         //
2232         // After Link down, reset piggy-back setting in ASIC. Disable RDG.
2233         //
2234         if (pAd->CommonCfg.BBPCurrentBW == BW_40)
2235         {
2236                 pAd->CommonCfg.BBPCurrentBW = BW_20;
2237                 RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R4, &ByteValue);
2238                 ByteValue &= (~0x18);
2239                 RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R4, ByteValue);
2240         }
2241 #endif // DOT11_N_SUPPORT //
2242         // Reset DAC
2243         RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R1, &ByteValue);
2244         ByteValue &= (~0x18);
2245         if (pAd->Antenna.field.TxPath == 2)
2246         {
2247                 ByteValue |= 0x10;
2248         }
2249         RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R1, ByteValue);
2250
2251         RTMPSetPiggyBack(pAd,FALSE);
2252         OPSTATUS_CLEAR_FLAG(pAd, fOP_STATUS_PIGGYBACK_INUSED);
2253
2254 #ifdef DOT11_N_SUPPORT
2255         pAd->CommonCfg.BACapability.word = pAd->CommonCfg.REGBACapability.word;
2256 #endif // DOT11_N_SUPPORT //
2257
2258         // Restore all settings in the following.
2259         AsicUpdateProtect(pAd, 0, (ALLN_SETPROTECT|CCKSETPROTECT|OFDMSETPROTECT), TRUE, FALSE);
2260         AsicDisableRDG(pAd);
2261         pAd->CommonCfg.IOTestParm.bCurrentAtheros = FALSE;
2262         pAd->CommonCfg.IOTestParm.bNowAtherosBurstOn = FALSE;
2263
2264 #ifdef DOT11_N_SUPPORT
2265 #ifdef DOT11N_DRAFT3
2266         OPSTATUS_CLEAR_FLAG(pAd, fOP_STATUS_SCAN_2040);
2267         pAd->CommonCfg.BSSCoexist2040.word = 0;
2268         TriEventInit(pAd);
2269         for (i = 0; i < (pAd->ChannelListNum - 1); i++)
2270         {
2271                 pAd->ChannelList[i].bEffectedChannel = FALSE;
2272         }
2273 #endif // DOT11N_DRAFT3 //
2274 #endif // DOT11_N_SUPPORT //
2275
2276         RTMP_IO_WRITE32(pAd, MAX_LEN_CFG, 0x1fff);
2277         RTMP_CLEAR_FLAG(pAd, fRTMP_ADAPTER_BSS_SCAN_IN_PROGRESS);
2278
2279         // Allow go to sleep after linkdown steps.
2280         RTMP_SET_PSFLAG(pAd, fRTMP_PS_CAN_GO_SLEEP);
2281
2282 #ifdef WPA_SUPPLICANT_SUPPORT
2283 #ifndef NATIVE_WPA_SUPPLICANT_SUPPORT
2284         if (pAd->StaCfg.WpaSupplicantUP) {
2285                 union iwreq_data    wrqu;
2286                 //send disassociate event to wpa_supplicant
2287                 memset(&wrqu, 0, sizeof(wrqu));
2288                 wrqu.data.flags = RT_DISASSOC_EVENT_FLAG;
2289                 wireless_send_event(pAd->net_dev, IWEVCUSTOM, &wrqu, NULL);
2290         }
2291 #endif // NATIVE_WPA_SUPPLICANT_SUPPORT //
2292 #endif // WPA_SUPPLICANT_SUPPORT //
2293
2294 #ifdef NATIVE_WPA_SUPPLICANT_SUPPORT
2295         {
2296                 union iwreq_data    wrqu;
2297                 memset(wrqu.ap_addr.sa_data, 0, MAC_ADDR_LEN);
2298                 wireless_send_event(pAd->net_dev, SIOCGIWAP, &wrqu, NULL);
2299         }
2300 #endif // NATIVE_WPA_SUPPLICANT_SUPPORT //
2301 }
2302
2303 /*
2304         ==========================================================================
2305         Description:
2306
2307         IRQL = DISPATCH_LEVEL
2308
2309         ==========================================================================
2310 */
2311 VOID IterateOnBssTab(
2312         IN PRTMP_ADAPTER pAd)
2313 {
2314         MLME_START_REQ_STRUCT   StartReq;
2315         MLME_JOIN_REQ_STRUCT    JoinReq;
2316         ULONG                   BssIdx;
2317
2318         // Change the wepstatus to original wepstatus
2319         pAd->StaCfg.WepStatus   = pAd->StaCfg.OrigWepStatus;
2320         pAd->StaCfg.PairCipher  = pAd->StaCfg.OrigWepStatus;
2321         pAd->StaCfg.GroupCipher = pAd->StaCfg.OrigWepStatus;
2322
2323         BssIdx = pAd->MlmeAux.BssIdx;
2324         if (BssIdx < pAd->MlmeAux.SsidBssTab.BssNr)
2325         {
2326                 // Check cipher suite, AP must have more secured cipher than station setting
2327                 // Set the Pairwise and Group cipher to match the intended AP setting
2328                 // We can only connect to AP with less secured cipher setting
2329                 if ((pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPA) || (pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPAPSK))
2330                 {
2331                         pAd->StaCfg.GroupCipher = pAd->MlmeAux.SsidBssTab.BssEntry[BssIdx].WPA.GroupCipher;
2332
2333                         if (pAd->StaCfg.WepStatus == pAd->MlmeAux.SsidBssTab.BssEntry[BssIdx].WPA.PairCipher)
2334                                 pAd->StaCfg.PairCipher = pAd->MlmeAux.SsidBssTab.BssEntry[BssIdx].WPA.PairCipher;
2335                         else if (pAd->MlmeAux.SsidBssTab.BssEntry[BssIdx].WPA.PairCipherAux != Ndis802_11WEPDisabled)
2336                                 pAd->StaCfg.PairCipher = pAd->MlmeAux.SsidBssTab.BssEntry[BssIdx].WPA.PairCipherAux;
2337                         else    // There is no PairCipher Aux, downgrade our capability to TKIP
2338                                 pAd->StaCfg.PairCipher = Ndis802_11Encryption2Enabled;
2339                 }
2340                 else if ((pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPA2) || (pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPA2PSK))
2341                 {
2342                         pAd->StaCfg.GroupCipher = pAd->MlmeAux.SsidBssTab.BssEntry[BssIdx].WPA2.GroupCipher;
2343
2344                         if (pAd->StaCfg.WepStatus == pAd->MlmeAux.SsidBssTab.BssEntry[BssIdx].WPA2.PairCipher)
2345                                 pAd->StaCfg.PairCipher = pAd->MlmeAux.SsidBssTab.BssEntry[BssIdx].WPA2.PairCipher;
2346                         else if (pAd->MlmeAux.SsidBssTab.BssEntry[BssIdx].WPA2.PairCipherAux != Ndis802_11WEPDisabled)
2347                                 pAd->StaCfg.PairCipher = pAd->MlmeAux.SsidBssTab.BssEntry[BssIdx].WPA2.PairCipherAux;
2348                         else    // There is no PairCipher Aux, downgrade our capability to TKIP
2349                                 pAd->StaCfg.PairCipher = Ndis802_11Encryption2Enabled;
2350
2351                         // RSN capability
2352                         pAd->StaCfg.RsnCapability = pAd->MlmeAux.SsidBssTab.BssEntry[BssIdx].WPA2.RsnCapability;
2353                 }
2354
2355                 // Set Mix cipher flag
2356                 pAd->StaCfg.bMixCipher = (pAd->StaCfg.PairCipher == pAd->StaCfg.GroupCipher) ? FALSE : TRUE;
2357                 if (pAd->StaCfg.bMixCipher == TRUE)
2358                 {
2359                         // If mix cipher, re-build RSNIE
2360                         RTMPMakeRSNIE(pAd, pAd->StaCfg.AuthMode, pAd->StaCfg.WepStatus, 0);
2361                 }
2362
2363                 DBGPRINT(RT_DEBUG_TRACE, ("CNTL - iterate BSS %ld of %d\n", BssIdx, pAd->MlmeAux.SsidBssTab.BssNr));
2364                 JoinParmFill(pAd, &JoinReq, BssIdx);
2365                 MlmeEnqueue(pAd, SYNC_STATE_MACHINE, MT2_MLME_JOIN_REQ, sizeof(MLME_JOIN_REQ_STRUCT),
2366                                         &JoinReq);
2367                 pAd->Mlme.CntlMachine.CurrState = CNTL_WAIT_JOIN;
2368         }
2369         else if (pAd->StaCfg.BssType == BSS_ADHOC)
2370         {
2371                 DBGPRINT(RT_DEBUG_TRACE, ("CNTL - All BSS fail; start a new ADHOC (Ssid=%s)...\n",pAd->MlmeAux.Ssid));
2372                 StartParmFill(pAd, &StartReq, pAd->MlmeAux.Ssid, pAd->MlmeAux.SsidLen);
2373                 MlmeEnqueue(pAd, SYNC_STATE_MACHINE, MT2_MLME_START_REQ, sizeof(MLME_START_REQ_STRUCT), &StartReq);
2374                 pAd->Mlme.CntlMachine.CurrState = CNTL_WAIT_START;
2375         }
2376         else // no more BSS
2377         {
2378                 DBGPRINT(RT_DEBUG_TRACE, ("CNTL - All roaming failed, stay @ ch #%d\n", pAd->CommonCfg.Channel));
2379                 AsicSwitchChannel(pAd, pAd->CommonCfg.Channel, FALSE);
2380                 AsicLockChannel(pAd, pAd->CommonCfg.Channel);
2381                 pAd->Mlme.CntlMachine.CurrState = CNTL_IDLE;
2382         }
2383 }
2384
2385 // for re-association only
2386 // IRQL = DISPATCH_LEVEL
2387 VOID IterateOnBssTab2(
2388         IN PRTMP_ADAPTER pAd)
2389 {
2390         MLME_REASSOC_REQ_STRUCT ReassocReq;
2391         ULONG                   BssIdx;
2392         BSS_ENTRY               *pBss;
2393
2394         BssIdx = pAd->MlmeAux.RoamIdx;
2395         pBss = &pAd->MlmeAux.RoamTab.BssEntry[BssIdx];
2396
2397         if (BssIdx < pAd->MlmeAux.RoamTab.BssNr)
2398         {
2399                 DBGPRINT(RT_DEBUG_TRACE, ("CNTL - iterate BSS %ld of %d\n", BssIdx, pAd->MlmeAux.RoamTab.BssNr));
2400
2401                 AsicSwitchChannel(pAd, pBss->Channel, FALSE);
2402                 AsicLockChannel(pAd, pBss->Channel);
2403
2404                 // reassociate message has the same structure as associate message
2405                 AssocParmFill(pAd, &ReassocReq, pBss->Bssid, pBss->CapabilityInfo,
2406                                           ASSOC_TIMEOUT, pAd->StaCfg.DefaultListenCount);
2407                 MlmeEnqueue(pAd, ASSOC_STATE_MACHINE, MT2_MLME_REASSOC_REQ,
2408                                         sizeof(MLME_REASSOC_REQ_STRUCT), &ReassocReq);
2409
2410                 pAd->Mlme.CntlMachine.CurrState = CNTL_WAIT_REASSOC;
2411         }
2412         else // no more BSS
2413         {
2414                 DBGPRINT(RT_DEBUG_TRACE, ("CNTL - All fast roaming failed, back to ch #%d\n",pAd->CommonCfg.Channel));
2415                 AsicSwitchChannel(pAd, pAd->CommonCfg.Channel, FALSE);
2416                 AsicLockChannel(pAd, pAd->CommonCfg.Channel);
2417                 pAd->Mlme.CntlMachine.CurrState = CNTL_IDLE;
2418         }
2419 }
2420
2421 /*
2422         ==========================================================================
2423         Description:
2424
2425         IRQL = DISPATCH_LEVEL
2426
2427         ==========================================================================
2428 */
2429 VOID JoinParmFill(
2430         IN PRTMP_ADAPTER pAd,
2431         IN OUT MLME_JOIN_REQ_STRUCT *JoinReq,
2432         IN ULONG BssIdx)
2433 {
2434         JoinReq->BssIdx = BssIdx;
2435 }
2436
2437 /*
2438         ==========================================================================
2439         Description:
2440
2441         IRQL = DISPATCH_LEVEL
2442
2443         ==========================================================================
2444 */
2445 VOID ScanParmFill(
2446         IN PRTMP_ADAPTER pAd,
2447         IN OUT MLME_SCAN_REQ_STRUCT *ScanReq,
2448         IN CHAR Ssid[],
2449         IN UCHAR SsidLen,
2450         IN UCHAR BssType,
2451         IN UCHAR ScanType)
2452 {
2453     NdisZeroMemory(ScanReq->Ssid, MAX_LEN_OF_SSID);
2454         ScanReq->SsidLen = SsidLen;
2455         NdisMoveMemory(ScanReq->Ssid, Ssid, SsidLen);
2456         ScanReq->BssType = BssType;
2457         ScanReq->ScanType = ScanType;
2458 }
2459
2460 #ifdef QOS_DLS_SUPPORT
2461 /*
2462         ==========================================================================
2463         Description:
2464
2465         IRQL = DISPATCH_LEVEL
2466
2467         ==========================================================================
2468 */
2469 VOID DlsParmFill(
2470         IN PRTMP_ADAPTER pAd,
2471         IN OUT MLME_DLS_REQ_STRUCT *pDlsReq,
2472         IN PRT_802_11_DLS pDls,
2473         IN USHORT reason)
2474 {
2475         pDlsReq->pDLS = pDls;
2476         pDlsReq->Reason = reason;
2477 }
2478 #endif // QOS_DLS_SUPPORT //
2479
2480 /*
2481         ==========================================================================
2482         Description:
2483
2484         IRQL = DISPATCH_LEVEL
2485
2486         ==========================================================================
2487 */
2488 VOID StartParmFill(
2489         IN PRTMP_ADAPTER pAd,
2490         IN OUT MLME_START_REQ_STRUCT *StartReq,
2491         IN CHAR Ssid[],
2492         IN UCHAR SsidLen)
2493 {
2494         ASSERT(SsidLen <= MAX_LEN_OF_SSID);
2495         NdisMoveMemory(StartReq->Ssid, Ssid, SsidLen);
2496         StartReq->SsidLen = SsidLen;
2497 }
2498
2499 /*
2500         ==========================================================================
2501         Description:
2502
2503         IRQL = DISPATCH_LEVEL
2504
2505         ==========================================================================
2506 */
2507 VOID AuthParmFill(
2508         IN PRTMP_ADAPTER pAd,
2509         IN OUT MLME_AUTH_REQ_STRUCT *AuthReq,
2510         IN PUCHAR pAddr,
2511         IN USHORT Alg)
2512 {
2513         COPY_MAC_ADDR(AuthReq->Addr, pAddr);
2514         AuthReq->Alg = Alg;
2515         AuthReq->Timeout = AUTH_TIMEOUT;
2516 }
2517
2518 /*
2519         ==========================================================================
2520         Description:
2521
2522         IRQL = DISPATCH_LEVEL
2523
2524         ==========================================================================
2525  */
2526 VOID ComposePsPoll(
2527         IN PRTMP_ADAPTER pAd)
2528 {
2529         NdisZeroMemory(&pAd->PsPollFrame, sizeof(PSPOLL_FRAME));
2530         pAd->PsPollFrame.FC.Type = BTYPE_CNTL;
2531         pAd->PsPollFrame.FC.SubType = SUBTYPE_PS_POLL;
2532         pAd->PsPollFrame.Aid = pAd->StaActive.Aid | 0xC000;
2533         COPY_MAC_ADDR(pAd->PsPollFrame.Bssid, pAd->CommonCfg.Bssid);
2534         COPY_MAC_ADDR(pAd->PsPollFrame.Ta, pAd->CurrentAddress);
2535 }
2536
2537 // IRQL = DISPATCH_LEVEL
2538 VOID ComposeNullFrame(
2539         IN PRTMP_ADAPTER pAd)
2540 {
2541         NdisZeroMemory(&pAd->NullFrame, sizeof(HEADER_802_11));
2542         pAd->NullFrame.FC.Type = BTYPE_DATA;
2543         pAd->NullFrame.FC.SubType = SUBTYPE_NULL_FUNC;
2544         pAd->NullFrame.FC.ToDs = 1;
2545         COPY_MAC_ADDR(pAd->NullFrame.Addr1, pAd->CommonCfg.Bssid);
2546         COPY_MAC_ADDR(pAd->NullFrame.Addr2, pAd->CurrentAddress);
2547         COPY_MAC_ADDR(pAd->NullFrame.Addr3, pAd->CommonCfg.Bssid);
2548 }
2549
2550
2551
2552
2553 /*
2554         ==========================================================================
2555         Description:
2556                 Pre-build a BEACON frame in the shared memory
2557
2558         IRQL = PASSIVE_LEVEL
2559         IRQL = DISPATCH_LEVEL
2560
2561         ==========================================================================
2562 */
2563 ULONG MakeIbssBeacon(
2564         IN PRTMP_ADAPTER pAd)
2565 {
2566         UCHAR         DsLen = 1, IbssLen = 2;
2567         UCHAR         LocalErpIe[3] = {IE_ERP, 1, 0x04};
2568         HEADER_802_11 BcnHdr;
2569         USHORT        CapabilityInfo;
2570         LARGE_INTEGER FakeTimestamp;
2571         ULONG         FrameLen = 0;
2572         PTXWI_STRUC       pTxWI = &pAd->BeaconTxWI;
2573         CHAR         *pBeaconFrame = pAd->BeaconBuf;
2574         BOOLEAN       Privacy;
2575         UCHAR         SupRate[MAX_LEN_OF_SUPPORTED_RATES];
2576         UCHAR         SupRateLen = 0;
2577         UCHAR         ExtRate[MAX_LEN_OF_SUPPORTED_RATES];
2578         UCHAR         ExtRateLen = 0;
2579         UCHAR         RSNIe = IE_WPA;
2580
2581         if ((pAd->CommonCfg.PhyMode == PHY_11B) && (pAd->CommonCfg.Channel <= 14))
2582         {
2583                 SupRate[0] = 0x82; // 1 mbps
2584                 SupRate[1] = 0x84; // 2 mbps
2585                 SupRate[2] = 0x8b; // 5.5 mbps
2586                 SupRate[3] = 0x96; // 11 mbps
2587                 SupRateLen = 4;
2588                 ExtRateLen = 0;
2589         }
2590         else if (pAd->CommonCfg.Channel > 14)
2591         {
2592                 SupRate[0]  = 0x8C;    // 6 mbps, in units of 0.5 Mbps, basic rate
2593                 SupRate[1]  = 0x12;    // 9 mbps, in units of 0.5 Mbps
2594                 SupRate[2]  = 0x98;    // 12 mbps, in units of 0.5 Mbps, basic rate
2595                 SupRate[3]  = 0x24;    // 18 mbps, in units of 0.5 Mbps
2596                 SupRate[4]  = 0xb0;    // 24 mbps, in units of 0.5 Mbps, basic rate
2597                 SupRate[5]  = 0x48;    // 36 mbps, in units of 0.5 Mbps
2598                 SupRate[6]  = 0x60;    // 48 mbps, in units of 0.5 Mbps
2599                 SupRate[7]  = 0x6c;    // 54 mbps, in units of 0.5 Mbps
2600                 SupRateLen  = 8;
2601                 ExtRateLen  = 0;
2602
2603                 //
2604                 // Also Update MlmeRate & RtsRate for G only & A only
2605                 //
2606                 pAd->CommonCfg.MlmeRate = RATE_6;
2607                 pAd->CommonCfg.RtsRate = RATE_6;
2608                 pAd->CommonCfg.MlmeTransmit.field.MODE = MODE_OFDM;
2609                 pAd->CommonCfg.MlmeTransmit.field.MCS = OfdmRateToRxwiMCS[pAd->CommonCfg.MlmeRate];
2610                 pAd->MacTab.Content[BSS0Mcast_WCID].HTPhyMode.field.MODE = MODE_OFDM;
2611                 pAd->MacTab.Content[BSS0Mcast_WCID].HTPhyMode.field.MCS = OfdmRateToRxwiMCS[pAd->CommonCfg.MlmeRate];
2612         }
2613         else
2614         {
2615                 SupRate[0] = 0x82; // 1 mbps
2616                 SupRate[1] = 0x84; // 2 mbps
2617                 SupRate[2] = 0x8b; // 5.5 mbps
2618                 SupRate[3] = 0x96; // 11 mbps
2619                 SupRateLen = 4;
2620
2621                 ExtRate[0]  = 0x0C;    // 6 mbps, in units of 0.5 Mbps,
2622                 ExtRate[1]  = 0x12;    // 9 mbps, in units of 0.5 Mbps
2623                 ExtRate[2]  = 0x18;    // 12 mbps, in units of 0.5 Mbps,
2624                 ExtRate[3]  = 0x24;    // 18 mbps, in units of 0.5 Mbps
2625                 ExtRate[4]  = 0x30;    // 24 mbps, in units of 0.5 Mbps,
2626                 ExtRate[5]  = 0x48;    // 36 mbps, in units of 0.5 Mbps
2627                 ExtRate[6]  = 0x60;    // 48 mbps, in units of 0.5 Mbps
2628                 ExtRate[7]  = 0x6c;    // 54 mbps, in units of 0.5 Mbps
2629                 ExtRateLen  = 8;
2630         }
2631
2632         pAd->StaActive.SupRateLen = SupRateLen;
2633         NdisMoveMemory(pAd->StaActive.SupRate, SupRate, SupRateLen);
2634         pAd->StaActive.ExtRateLen = ExtRateLen;
2635         NdisMoveMemory(pAd->StaActive.ExtRate, ExtRate, ExtRateLen);
2636
2637         // compose IBSS beacon frame
2638         MgtMacHeaderInit(pAd, &BcnHdr, SUBTYPE_BEACON, 0, BROADCAST_ADDR, pAd->CommonCfg.Bssid);
2639         Privacy = (pAd->StaCfg.WepStatus == Ndis802_11Encryption1Enabled) ||
2640                           (pAd->StaCfg.WepStatus == Ndis802_11Encryption2Enabled) ||
2641                           (pAd->StaCfg.WepStatus == Ndis802_11Encryption3Enabled);
2642         CapabilityInfo = CAP_GENERATE(0, 1, Privacy, (pAd->CommonCfg.TxPreamble == Rt802_11PreambleShort), 0, 0);
2643
2644         MakeOutgoingFrame(pBeaconFrame,                &FrameLen,
2645                                           sizeof(HEADER_802_11),           &BcnHdr,
2646                                           TIMESTAMP_LEN,                   &FakeTimestamp,
2647                                           2,                               &pAd->CommonCfg.BeaconPeriod,
2648                                           2,                               &CapabilityInfo,
2649                                           1,                               &SsidIe,
2650                                           1,                               &pAd->CommonCfg.SsidLen,
2651                                           pAd->CommonCfg.SsidLen,          pAd->CommonCfg.Ssid,
2652                                           1,                               &SupRateIe,
2653                                           1,                               &SupRateLen,
2654                                           SupRateLen,                      SupRate,
2655                                           1,                               &DsIe,
2656                                           1,                               &DsLen,
2657                                           1,                               &pAd->CommonCfg.Channel,
2658                                           1,                               &IbssIe,
2659                                           1,                               &IbssLen,
2660                                           2,                               &pAd->StaActive.AtimWin,
2661                                           END_OF_ARGS);
2662
2663         // add ERP_IE and EXT_RAE IE of in 802.11g
2664         if (ExtRateLen)
2665         {
2666                 ULONG   tmp;
2667
2668                 MakeOutgoingFrame(pBeaconFrame + FrameLen,         &tmp,
2669                                                   3,                               LocalErpIe,
2670                                                   1,                               &ExtRateIe,
2671                                                   1,                               &ExtRateLen,
2672                                                   ExtRateLen,                      ExtRate,
2673                                                   END_OF_ARGS);
2674                 FrameLen += tmp;
2675         }
2676
2677         // If adhoc secruity is set for WPA-None, append the cipher suite IE
2678         if (pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPANone)
2679         {
2680                 ULONG tmp;
2681         RTMPMakeRSNIE(pAd, pAd->StaCfg.AuthMode, pAd->StaCfg.WepStatus, BSS0);
2682
2683                 MakeOutgoingFrame(pBeaconFrame + FrameLen,              &tmp,
2684                                                   1,                                    &RSNIe,
2685                                                   1,                                    &pAd->StaCfg.RSNIE_Len,
2686                                                   pAd->StaCfg.RSNIE_Len,                pAd->StaCfg.RSN_IE,
2687                                                   END_OF_ARGS);
2688                 FrameLen += tmp;
2689         }
2690
2691 #ifdef DOT11_N_SUPPORT
2692         if ((pAd->CommonCfg.PhyMode >= PHY_11ABGN_MIXED))
2693         {
2694                 ULONG TmpLen;
2695                 UCHAR HtLen, HtLen1;
2696
2697 #ifdef RT_BIG_ENDIAN
2698                 HT_CAPABILITY_IE HtCapabilityTmp;
2699                 ADD_HT_INFO_IE  addHTInfoTmp;
2700                 USHORT  b2lTmp, b2lTmp2;
2701 #endif
2702
2703                 // add HT Capability IE
2704                 HtLen = sizeof(pAd->CommonCfg.HtCapability);
2705                 HtLen1 = sizeof(pAd->CommonCfg.AddHTInfo);
2706 #ifndef RT_BIG_ENDIAN
2707                 MakeOutgoingFrame(pBeaconFrame+FrameLen,        &TmpLen,
2708                                                   1,                                            &HtCapIe,
2709                                                   1,                                            &HtLen,
2710                                                   HtLen,                                        &pAd->CommonCfg.HtCapability,
2711                                                   1,                                            &AddHtInfoIe,
2712                                                   1,                                            &HtLen1,
2713                                                   HtLen1,                                       &pAd->CommonCfg.AddHTInfo,
2714                                                   END_OF_ARGS);
2715 #else
2716                 NdisMoveMemory(&HtCapabilityTmp, &pAd->CommonCfg.HtCapability, HtLen);
2717                 *(USHORT *)(&HtCapabilityTmp.HtCapInfo) = SWAP16(*(USHORT *)(&HtCapabilityTmp.HtCapInfo));
2718                 *(USHORT *)(&HtCapabilityTmp.ExtHtCapInfo) = SWAP16(*(USHORT *)(&HtCapabilityTmp.ExtHtCapInfo));
2719
2720                 NdisMoveMemory(&addHTInfoTmp, &pAd->CommonCfg.AddHTInfo, HtLen1);
2721                 *(USHORT *)(&addHTInfoTmp.AddHtInfo2) = SWAP16(*(USHORT *)(&addHTInfoTmp.AddHtInfo2));
2722                 *(USHORT *)(&addHTInfoTmp.AddHtInfo3) = SWAP16(*(USHORT *)(&addHTInfoTmp.AddHtInfo3));
2723
2724                 MakeOutgoingFrame(pBeaconFrame+FrameLen,        &TmpLen,
2725                                                   1,                                            &HtCapIe,
2726                                                   1,                                            &HtLen,
2727                                                   HtLen,                                        &HtCapabilityTmp,
2728                                                   1,                                            &AddHtInfoIe,
2729                                                   1,                                            &HtLen1,
2730                                                   HtLen1,                                       &addHTInfoTmp,
2731                                                   END_OF_ARGS);
2732 #endif
2733                 FrameLen += TmpLen;
2734         }
2735 #endif // DOT11_N_SUPPORT //
2736
2737         //beacon use reserved WCID 0xff
2738     if (pAd->CommonCfg.Channel > 14)
2739     {
2740         RTMPWriteTxWI(pAd, pTxWI, FALSE, FALSE,  TRUE, FALSE, FALSE, TRUE, 0, 0xff, FrameLen,
2741                 PID_MGMT, PID_BEACON, RATE_1, IFS_HTTXOP, FALSE, &pAd->CommonCfg.MlmeTransmit);
2742     }
2743     else
2744     {
2745         // Set to use 1Mbps for Adhoc beacon.
2746                 HTTRANSMIT_SETTING Transmit;
2747         Transmit.word = 0;
2748         RTMPWriteTxWI(pAd, pTxWI, FALSE, FALSE,  TRUE, FALSE, FALSE, TRUE, 0, 0xff, FrameLen,
2749                 PID_MGMT, PID_BEACON, RATE_1, IFS_HTTXOP, FALSE, &Transmit);
2750     }
2751
2752 #ifdef RT_BIG_ENDIAN
2753         RTMPFrameEndianChange(pAd, pBeaconFrame, DIR_WRITE, FALSE);
2754         RTMPWIEndianChange((PUCHAR)pTxWI, TYPE_TXWI);
2755 #endif
2756
2757     DBGPRINT(RT_DEBUG_TRACE, ("MakeIbssBeacon (len=%ld), SupRateLen=%d, ExtRateLen=%d, Channel=%d, PhyMode=%d\n",
2758                                         FrameLen, SupRateLen, ExtRateLen, pAd->CommonCfg.Channel, pAd->CommonCfg.PhyMode));
2759         return FrameLen;
2760 }
2761
2762