source: ReferenceDesigns/w3_802.11/c/wlan_mac_low_dcf/wlan_mac_dcf.c @ 5562

Last change on this file since 5562 was 5549, checked in by chunter, 8 years ago

Dealt with remaining FIXMEs

File size: 89.1 KB
Line 
1/** @file wlan_mac_dcf.c
2 *  @brief Distributed Coordination Function
3 *
4 *  This contains code to implement the 802.11 DCF.
5 *
6 *  @copyright Copyright 2013-2016, Mango Communications. All rights reserved.
7 *          Distributed under the Mango Communications Reference Design License
8 *              See LICENSE.txt included in the design archive or
9 *              at http://mangocomm.com/802.11/license
10 *
11 *  This file is part of the Mango 802.11 Reference Design (https://mangocomm.com/802.11)
12 */
13/***************************** Include Files *********************************/
14// Xilinx SDK includes
15#include "xparameters.h"
16#include <stdio.h>
17#include <stdlib.h>
18#include <string.h>
19#include "xio.h"
20#include "math.h"
21
22// WARP includes
23#include "w3_userio.h"
24#include "radio_controller.h"
25
26// WLAN includes
27#include "wlan_mac_low.h"
28#include "wlan_mac_802_11_defs.h"
29#include "wlan_mac_time_util.h"
30#include "wlan_phy_util.h"
31#include "wlan_mac_dcf.h"
32
33// WLAN Exp includes
34#include "wlan_exp.h"
35
36
37/*************************** Constant Definitions ****************************/
38#define DBG_PRINT                                          0
39
40#define WLAN_EXP_TYPE_DESIGN_80211_CPU_LOW                 WLAN_EXP_TYPE_DESIGN_80211_CPU_LOW_DCF
41
42#define DEFAULT_TX_ANTENNA_MODE                            TX_ANTMODE_SISO_ANTA
43
44#define NUM_LEDS                                           4
45
46#define RX_LEN_THRESH                                      200
47
48
49/*********************** Global Variable Definitions *************************/
50volatile static mac_timing             gl_mac_timing_values;
51volatile static u32                    gl_stationShortRetryCount;
52volatile static u32                    gl_stationLongRetryCount;
53volatile static u32                    gl_cw_exp;
54volatile static u8                     gl_cw_exp_min;
55volatile static u8                     gl_cw_exp_max;
56
57volatile static u32                    gl_dot11RTSThreshold;
58
59volatile static u8                     gl_eeprom_addr[MAC_ADDR_LEN];
60
61volatile static u8                     gl_mpdu_pkt_buf;
62
63volatile static u32                    gl_dot11ShortRetryLimit;
64volatile static u32                    gl_dot11LongRetryLimit;
65
66volatile u8                            gl_red_led_index;
67volatile u8                            gl_green_led_index;
68
69volatile beacon_txrx_configure_t       gl_beacon_txrx_configure;
70
71volatile static u8                     gl_waiting_for_response;
72
73/*************************** Functions Prototypes ****************************/
74
75int process_low_param(u8 mode, u32* payload);
76
77
78/******************************** Functions **********************************/
79
80int main(){
81
82    wlan_mac_hw_info_t* hw_info;
83
84    xil_printf("\f");
85    xil_printf("----- Mango 802.11 Reference Design -----\n");
86    xil_printf("----- v1.5.2 ----------------------------\n");
87    xil_printf("----- wlan_mac_dcf ----------------------\n");
88    xil_printf("Compiled %s %s\n\n", __DATE__, __TIME__);
89
90    xil_printf("Note: this UART is currently printing from CPU_LOW. To view prints from\n");
91    xil_printf("and interact with CPU_HIGH, raise the right-most User I/O DIP switch bit.\n");
92    xil_printf("This switch can be toggled any time while the design is running.\n\n");
93    xil_printf("------------------------\n");
94
95    gl_mpdu_pkt_buf = PKT_BUF_INVALID;
96    gl_waiting_for_response = 0;
97
98
99    gl_beacon_txrx_configure.beacon_tx_mode = NO_BEACON_TX;
100    gl_beacon_txrx_configure.ts_update_mode = NEVER_UPDATE;
101    bzero((void*)gl_beacon_txrx_configure.bssid_match, MAC_ADDR_LEN);
102
103    gl_dot11ShortRetryLimit      = 7;
104    gl_dot11LongRetryLimit       = 4;
105
106    gl_cw_exp_min                = 4;
107    gl_cw_exp_max                = 10;
108
109    gl_dot11RTSThreshold         = 2000;
110
111    gl_stationShortRetryCount    = 0;
112    gl_stationLongRetryCount     = 0;
113
114    gl_red_led_index             = 0;
115    gl_green_led_index           = 0;
116    userio_write_leds_green(USERIO_BASEADDR, (1 << gl_green_led_index));
117    userio_write_leds_red(USERIO_BASEADDR, (1 << gl_red_led_index));
118
119    wlan_mac_low_init(WLAN_EXP_TYPE_DESIGN_80211_CPU_LOW);
120
121    gl_cw_exp = gl_cw_exp_min;
122
123    hw_info = get_mac_hw_info();
124    memcpy((void*)gl_eeprom_addr, hw_info->hw_addr_wlan, MAC_ADDR_LEN);
125
126    wlan_mac_low_set_frame_rx_callback((void*)frame_receive);
127    wlan_mac_low_set_frame_tx_callback((void*)frame_transmit);
128    wlan_mac_low_set_beacon_txrx_config_callback((void*)configure_beacon_txrx);
129    wlan_mac_low_set_mactime_change_callback((void*)handle_mactime_change);
130    wlan_mac_low_set_ipc_low_param_callback((void*)process_low_param);
131    wlan_mac_low_set_sample_rate_change_callback((void*)handle_sample_rate_change);
132
133
134    // wlan_mac_low_init() has placed a mutex lock on TX_PKT_BUF_ACK_CTS and
135    // TX_PKT_BUF_RTS already. We should set their packet buffer states to LOW_CTRL
136    ((tx_frame_info_t*)TX_PKT_BUF_TO_ADDR(TX_PKT_BUF_ACK_CTS))->tx_pkt_buf_state = TX_PKT_BUF_LOW_CTRL;
137    ((tx_frame_info_t*)TX_PKT_BUF_TO_ADDR(TX_PKT_BUF_RTS))->tx_pkt_buf_state = TX_PKT_BUF_LOW_CTRL;
138
139    wlan_mac_low_init_finish();
140
141    // Print DCF information to the terminal
142    xil_printf("------------------------\n");
143    xil_printf("WLAN MAC DCF boot complete: \n");
144    xil_printf("  Serial Number     : W3-a-%05d\n", hw_info->serial_number);
145    xil_printf("  Wireless MAC Addr : %02x:%02x:%02x:%02x:%02x:%02x\n\n", gl_eeprom_addr[0], gl_eeprom_addr[1], gl_eeprom_addr[2], gl_eeprom_addr[3], gl_eeprom_addr[4], gl_eeprom_addr[5]);
146
147    while(1){
148        // Poll PHY RX start
149        gl_waiting_for_response = 0;
150        wlan_mac_low_poll_frame_rx();
151
152        // Poll IPC rx
153        wlan_mac_low_poll_ipc_rx();
154
155        // Poll the timestamp (for periodic transmissions like beacons)
156        poll_tbtt();
157    }
158
159    return 0;
160}
161
162void handle_sample_rate_change(phy_samp_rate_t phy_samp_rate){
163    // TODO: Add an argument to specify the phy_mode in case that changes MAC timings
164
165    switch(phy_samp_rate){
166        default:
167        case PHY_40M:
168        case PHY_20M:
169            gl_mac_timing_values.t_slot = 9;
170            gl_mac_timing_values.t_sifs = 10;
171            gl_mac_timing_values.t_difs = gl_mac_timing_values.t_sifs + (2*gl_mac_timing_values.t_slot);
172            gl_mac_timing_values.t_eifs = 88;
173            gl_mac_timing_values.t_phy_rx_start_dly = 25; //TODO: This is BW dependent. 20/25 is waveform time.
174            gl_mac_timing_values.t_timeout = gl_mac_timing_values.t_sifs + gl_mac_timing_values.t_slot + gl_mac_timing_values.t_phy_rx_start_dly;
175        break;
176        case PHY_10M:
177            gl_mac_timing_values.t_slot = 13;
178            gl_mac_timing_values.t_sifs = 10;
179            gl_mac_timing_values.t_difs = gl_mac_timing_values.t_sifs + (2*gl_mac_timing_values.t_slot);
180            gl_mac_timing_values.t_eifs = 88;
181            gl_mac_timing_values.t_phy_rx_start_dly = 45;
182            gl_mac_timing_values.t_timeout = gl_mac_timing_values.t_sifs + gl_mac_timing_values.t_slot + gl_mac_timing_values.t_phy_rx_start_dly;
183        break;
184    }
185
186    // MAC timing parameters are in terms of units of 100 nanoseconds
187    wlan_mac_set_slot(gl_mac_timing_values.t_slot*10);
188    wlan_mac_set_DIFS((gl_mac_timing_values.t_difs)*10);
189    wlan_mac_set_TxDIFS(((gl_mac_timing_values.t_difs)*10) - (TX_PHY_DLY_100NSEC));
190
191    // Use postTx timer 2 for ACK timeout
192    wlan_mac_set_postTx_timer2(gl_mac_timing_values.t_timeout * 10);
193    wlan_mac_postTx_timer2_en(1);
194
195    // Use postRx timer 1 for SIFS
196    wlan_mac_set_postRx_timer1((gl_mac_timing_values.t_sifs*10)-(TX_PHY_DLY_100NSEC));
197    wlan_mac_postRx_timer1_en(1);
198
199    // TODO: NAV adjust needs verification
200    //     NAV adjust time - signed char (Fix8_0) value
201    wlan_mac_set_NAV_adj(0*10);
202    wlan_mac_set_EIFS(gl_mac_timing_values.t_eifs*10);
203
204    // xil_printf("PHY Sampling Rate set to %d\n", wlan_mac_low_get_phy_samp_rate());
205}
206
207void handle_mactime_change(s64 time_delta_usec){
208    u32 current_tu;
209    if(( gl_beacon_txrx_configure.beacon_tx_mode == AP_BEACON_TX ) ||
210       ( gl_beacon_txrx_configure.beacon_tx_mode == IBSS_BEACON_TX )){
211        //The MAC Time has changed. We should explicitly update the next TU target
212        //for beacon transmission.
213        current_tu = (u32)(get_mac_time_usec()>>10);
214
215        //The current_tu can be anywhere within a beacon interval, so we need
216        //to round up to the next TBTT.
217        wlan_mac_set_tu_target(gl_beacon_txrx_configure.beacon_interval_tu*((current_tu/gl_beacon_txrx_configure.beacon_interval_tu)+1));
218    }
219    return;
220}
221
222void configure_beacon_txrx(beacon_txrx_configure_t* beacon_txrx_configure){
223
224    memcpy((void*)&gl_beacon_txrx_configure, beacon_txrx_configure, sizeof(beacon_txrx_configure_t));
225
226    u32 current_tu;
227
228    if(( gl_beacon_txrx_configure.beacon_tx_mode == AP_BEACON_TX ) ||
229       ( gl_beacon_txrx_configure.beacon_tx_mode == IBSS_BEACON_TX )){
230
231        current_tu = (u32)(get_mac_time_usec()>>10);
232
233        //The current_tu can be anywhere within a beacon interval, so we need
234        //to round up to the next TBTT.
235        wlan_mac_set_tu_target(gl_beacon_txrx_configure.beacon_interval_tu*((current_tu/gl_beacon_txrx_configure.beacon_interval_tu)+1));
236        wlan_mac_reset_tu_target_latch(1);
237        wlan_mac_reset_tu_target_latch(0);
238    }  else {
239        wlan_mac_set_tu_target(0xFFFFFFFF);
240        wlan_mac_reset_tu_target_latch(1);
241    }
242}
243
244inline poll_tbtt_return_t poll_tbtt(){
245    //u32 tu_target;
246    u32 mac_hw_status;
247    poll_tbtt_return_t return_status = TBTT_NOT_ACHIEVED;
248    u32 current_tu;
249
250    if(( gl_beacon_txrx_configure.beacon_tx_mode == AP_BEACON_TX ) ||
251       ( gl_beacon_txrx_configure.beacon_tx_mode == IBSS_BEACON_TX )){
252
253        mac_hw_status = wlan_mac_get_status();
254
255        if(mac_hw_status & WLAN_MAC_STATUS_MASK_TU_LATCH) {
256            // Current TU >= Target TU
257
258            if(send_beacon(gl_beacon_txrx_configure.beacon_template_pkt_buf) != 0){
259                // We were unable to begin the transmission (most likely because the MAC Support Core A was
260                // already actively transmitting something). So we will just return and catch it on the next poll
261                return_status = BEACON_DEFERRED;
262                return return_status;
263            }
264
265            return_status = BEACON_SENT;
266
267            // Update TU target
268            //  Changing TU target automatically resets TU_LATCH
269            //  Latch will assert immediately if Current TU >= new Target TU
270            //tu_target = wlan_mac_get_tu_target();
271            //wlan_mac_set_tu_target(tu_target + gl_beacon_txrx_configure.beacon_interval_tu);
272            current_tu = (u32)(get_mac_time_usec()>>10);
273            wlan_mac_set_tu_target(gl_beacon_txrx_configure.beacon_interval_tu*((current_tu/gl_beacon_txrx_configure.beacon_interval_tu)+1));
274
275            //TODO
276            //If MAC time is adjusted by more than a TU (e.g a wlan_exp reset), then
277            //we can potentially be waiting a while to have the next TBTT fire. We should
278            //update the target when MAC time changes significantly.
279        }
280    }
281    return return_status;
282}
283
284inline int send_beacon(u8 tx_pkt_buf){
285    int return_status = -1;
286    volatile int i = 0;
287
288    wlan_ipc_msg_t                ipc_msg_to_high;
289    wlan_mac_low_tx_details_t     low_tx_details;
290    u32 mac_hw_status;
291    u32 mac_tx_ctrl_status;
292    u16 n_slots;
293    u16 n_slots_readback;
294    int tx_gain;
295    u8 mpdu_tx_ant_mask;
296    //Note: This needs to be a volatile to allow the tx_pkt_buf_state to be re-read in the initial while loop below
297    volatile tx_frame_info_t* tx_frame_info         = (tx_frame_info_t*) (TX_PKT_BUF_TO_ADDR(tx_pkt_buf));
298    mac_header_80211* header                        = (mac_header_80211*)(TX_PKT_BUF_TO_ADDR(tx_pkt_buf) + PHY_TX_PKT_BUF_MPDU_OFFSET);
299    u64 unique_seq;
300    tx_mode_t tx_mode;
301    u32 rx_status;
302
303    // Attempt to pause the backoff counter in Tx controller A
304    wlan_mac_pause_backoff_tx_ctrl_A(1);
305
306    switch(tx_frame_info->tx_pkt_buf_state){
307        case TX_PKT_BUF_READY:
308            mac_tx_ctrl_status = wlan_mac_get_tx_ctrl_status();
309
310            // Check if Tx controller A is deferring (now with a paused backoff) or idle (no Tx pending)
311            if(((mac_tx_ctrl_status & WLAN_MAC_TXCTRL_STATUS_MASK_TX_A_STATE) == WLAN_MAC_TXCTRL_STATUS_TX_A_STATE_DEFER) ||
312               ((mac_tx_ctrl_status & WLAN_MAC_TXCTRL_STATUS_MASK_TX_A_STATE) == WLAN_MAC_TXCTRL_STATUS_TX_A_STATE_IDLE)) {
313
314                i = 0;
315                while( (lock_tx_pkt_buf(tx_pkt_buf) != PKT_BUF_MUTEX_SUCCESS) ){
316                    // We will only continue with the send_beacon state when we are both assured that the
317                    //  tx_pkt_buf_state is READY (i.e. CPU_HIGH is not currently trying to log a beacon transmission)
318                    //  and we are able to lock the tx_pkt_buf. The only reason a lock should fail is that CPU_HIGH
319                    //  is actively modifying the contents of the beacon packet buffer. This is a short duration
320                    //  operation so we should just wait.
321                    if(i > 1000000) {xil_printf("ERROR (send_beacon): stuck waiting for CPU High to unlock Tx pkt buf\n");}
322                    else {i++;}
323                }
324
325                // We've locked the beacon template packet buffer. We should set its state to LOW_CTRL
326                // so CPU_HIGH can know that we are just about to transmit it.
327                tx_frame_info->tx_pkt_buf_state = TX_PKT_BUF_LOW_CTRL;
328
329                // Compare the length of this frame to the RTS Threshold
330                if(tx_frame_info->length <= gl_dot11RTSThreshold) {
331                    tx_mode = TX_MODE_SHORT;
332                } else {
333                    tx_mode = TX_MODE_LONG;
334                }
335
336                // Update the beacon's seq num (in the MAC header) and uniq_seq (in the tx_frame_info)
337                unique_seq = wlan_mac_low_get_unique_seq();
338                wlan_mac_low_set_unique_seq(unique_seq+1);
339                tx_frame_info->unique_seq = unique_seq;
340                header->sequence_control = ((header->sequence_control) & 0xF) | ( (unique_seq&0xFFF)<<4 );
341
342                // Configure the Tx antenna selection
343                mpdu_tx_ant_mask = 0;
344
345                switch(tx_frame_info->params.phy.antenna_mode) {
346                    case TX_ANTMODE_SISO_ANTA:  mpdu_tx_ant_mask |= 0x1;  break;
347                    case TX_ANTMODE_SISO_ANTB:  mpdu_tx_ant_mask |= 0x2;  break;
348                    case TX_ANTMODE_SISO_ANTC:  mpdu_tx_ant_mask |= 0x4;  break;
349                    case TX_ANTMODE_SISO_ANTD:  mpdu_tx_ant_mask |= 0x8;  break;
350                    default:                    mpdu_tx_ant_mask  = 0x1;  break; // Default to RF_A
351                }
352
353                //wlan_mac_tx_ctrl_C_params(pktBuf, antMask, req_backoff, phy_mode, num_slots)
354                switch(gl_beacon_txrx_configure.beacon_tx_mode){
355                    case AP_BEACON_TX:
356                        n_slots = rand_num_slots(RAND_SLOT_REASON_STANDARD_ACCESS);
357                        wlan_mac_tx_ctrl_C_params(tx_pkt_buf, mpdu_tx_ant_mask, 0, tx_frame_info->params.phy.phy_mode, n_slots);
358                    break;
359                    case IBSS_BEACON_TX:
360                        n_slots = rand_num_slots(RAND_SLOT_REASON_IBSS_BEACON);
361                        wlan_mac_tx_ctrl_C_params(tx_pkt_buf, mpdu_tx_ant_mask, 1, tx_frame_info->params.phy.phy_mode, n_slots);
362                    break;
363                    case NO_BEACON_TX:
364                        return -1;
365                    break;
366                }
367
368                tx_gain = wlan_mac_low_dbm_to_gain_target(tx_frame_info->params.phy.power);
369                wlan_mac_tx_ctrl_C_gains(tx_gain, tx_gain, tx_gain, tx_gain);
370
371                write_phy_preamble(tx_pkt_buf,
372                                   tx_frame_info->params.phy.phy_mode,
373                                   tx_frame_info->params.phy.mcs,
374                                   tx_frame_info->length);
375
376
377                wlan_mac_tx_ctrl_C_start(1);
378                wlan_mac_tx_ctrl_C_start(0);
379
380                // Immediately re-read the current slot count.
381                n_slots_readback = wlan_mac_get_backoff_count_C();
382
383                if((n_slots != n_slots_readback)){
384                    // For the first transmission (non-retry) of an MPDU, the number of
385                    // slots used by the backoff process is ambiguous. The n_slots we provided
386                    // to wlan_mac_tx_ctrl_A_params is only a suggestion. If the medium has been
387                    // idle for a DIFS, then there will not be a backoff. Or, if another backoff is
388                    // currently running, the MAC Config Core A will inherit that backoff. By
389                    // immediately reading back the slot count after starting the core, we can
390                    // overwrite the number of slots that we will fill into low_tx_details with
391                    // the correct value
392                    n_slots = n_slots_readback;
393                }
394
395                tx_frame_info->num_tx_attempts   = 1;
396                tx_frame_info->phy_samp_rate     = wlan_mac_low_get_phy_samp_rate();
397
398                // Here, we are overloading the "create" timestamp to mean something subtly different
399                //  than when it is used for data MPDUs since beacons are not created and enqueued in
400                //  CPU_HIGH. By explicitly filling the current MAC time into the create timestamp,
401                //  we allow CPU_HIGH to determine whether or not a backoff occurred before the beacon transmission
402                //  when it is creating the TX_LOW log entry for the beacon.
403                tx_frame_info->timestamp_create  = get_mac_time_usec();
404                tx_frame_info->delay_accept      = 0;
405
406                low_tx_details.tx_details_type  = TX_DETAILS_MPDU;
407                low_tx_details.phy_params_mpdu.mcs          = tx_frame_info->params.phy.mcs;
408                low_tx_details.phy_params_mpdu.phy_mode     = tx_frame_info->params.phy.phy_mode;
409                low_tx_details.phy_params_mpdu.power        = tx_frame_info->params.phy.power;
410                low_tx_details.phy_params_mpdu.antenna_mode = tx_frame_info->params.phy.antenna_mode;
411
412                low_tx_details.chan_num    = wlan_mac_low_get_active_channel();
413                low_tx_details.cw          = (1 << gl_cw_exp)-1; //(2^(gl_cw_exp) - 1)
414                low_tx_details.ssrc        = gl_stationShortRetryCount;
415                low_tx_details.slrc        = gl_stationLongRetryCount;
416                low_tx_details.src         = 0;
417                low_tx_details.lrc         = 0;
418                low_tx_details.flags       = 0;
419
420                // The pre-Tx backoff may not occur for the initial transmission attempt. If the medium has been idle for >DIFS when
421                //  the first Tx occurs the DCF state machine will not start a backoff. The upper-level MAC should compare the num_slots value
422                //  to the time delta between the accept and start times of the first transmission to determine whether the pre-Tx backoff
423                //  actually occurred.
424                low_tx_details.num_slots   = n_slots;
425
426                 // Wait for the MPDU Tx to finish
427                do { // while(tx_status & WLAN_MAC_STATUS_MASK_TX_C_PENDING)
428
429                    // Poll the DCF core status register
430                    mac_hw_status = wlan_mac_get_status();
431
432                    if((tx_frame_info->flags) & TX_FRAME_INFO_FLAGS_FILL_TIMESTAMP){
433                        if( mac_hw_status & WLAN_MAC_STATUS_MASK_TX_PHY_ACTIVE ){
434                            // Insert the TX START timestamp
435                            *((u32*)((u8*)header + 24)) =  Xil_In32(WLAN_MAC_REG_TX_TIMESTAMP_LSB);
436                            *((u32*)((u8*)header + 28)) =  Xil_In32(WLAN_MAC_REG_TX_TIMESTAMP_MSB);
437
438                            // The below u64 approach also works, but takes 100ns longer than just dealing with the LSB and MSB separately.
439                            //*((u64*)((TX_PKT_BUF_TO_ADDR(mpdu_pkt_buf) + PHY_TX_PKT_BUF_MPDU_OFFSET + 24))) = (u64)wlan_mac_low_get_tx_start_timestamp();
440                        }
441                    }
442
443                    if( mac_hw_status & WLAN_MAC_STATUS_MASK_TX_C_DONE ) {
444                        // Transmission is complete
445
446                        switch(tx_mode) {
447                        //TODO: Resetting the SSRC and/or SLRC needs to be checked back against the standard
448                            case TX_MODE_SHORT:
449                                reset_ssrc();
450                                reset_cw();
451                            break;
452                            case TX_MODE_LONG:
453                                reset_slrc();
454                                reset_cw();
455                            break;
456                        }
457
458                        low_tx_details.tx_start_timestamp_mpdu = wlan_mac_low_get_tx_start_timestamp();
459                        low_tx_details.tx_start_timestamp_frac_mpdu = wlan_mac_low_get_tx_start_timestamp_frac();
460
461                        // Start a post-Tx backoff using the updated contention window
462                        //  If MAC Tx controller A backoff has been paused this backoff request will
463                        //   successfully be ignored. If Tx A is idle then this backoff
464                        //   will execute and future submission to Tx A may inherit the
465                        //   this backoff.
466                        // TODO: We should double check whether post-Tx backoffs are appropriate
467                        n_slots = rand_num_slots(RAND_SLOT_REASON_STANDARD_ACCESS);
468                        wlan_mac_dcf_hw_start_backoff(n_slots);
469                    } else {
470                        // Poll the MAC Rx state to check if a packet was received while our Tx was deferring
471                        if (mac_hw_status & WLAN_MAC_STATUS_MASK_RX_PHY_STARTED) {
472                            gl_waiting_for_response = 0;
473                            rx_status = wlan_mac_low_poll_frame_rx();
474                            // Check if the new reception met the conditions to cancel the already-submitted transmission
475                            if (((rx_status & POLL_MAC_CANCEL_TX) != 0)) {
476                                // The Rx handler killed this transmission already by resetting the MAC core
477                                // Our return_status should still be considered a success -- we successfully did not
478                                // transmit the beacon. This will tell the TBTT logic to move on to the next beacon interval
479                                // before attempting another beacon transmission.
480                                return_status = 0;
481                                // We will not sent a BEACON_DONE IPC message to CPU_HIGH, so
482                                // tx_frame_info->tx_pkt_buf_state should remain READY
483                                tx_frame_info->tx_pkt_buf_state = TX_PKT_BUF_READY;
484                                if(unlock_tx_pkt_buf(tx_pkt_buf) != PKT_BUF_MUTEX_SUCCESS){
485                                    xil_printf("Error: Unable to unlock Beacon packet buffer (beacon cancel)\n");
486                                }
487                                wlan_mac_pause_backoff_tx_ctrl_A(0);
488                                return return_status;
489                            }
490
491                        }
492                    } // END if(Tx A state machine done)
493                } while( mac_hw_status & WLAN_MAC_STATUS_MASK_TX_C_PENDING );
494
495                return_status = 0;
496                tx_frame_info->tx_pkt_buf_state = TX_PKT_BUF_DONE;
497                if(unlock_tx_pkt_buf(tx_pkt_buf) != PKT_BUF_MUTEX_SUCCESS) {
498                    xil_printf("Error: Unable to unlock Beacon packet buffer (beacon sent) %d\n", unlock_tx_pkt_buf(tx_pkt_buf));
499                }
500
501                ipc_msg_to_high.msg_id            = IPC_MBOX_MSG_ID(IPC_MBOX_TX_BEACON_DONE);
502                ipc_msg_to_high.num_payload_words = sizeof(wlan_mac_low_tx_details_t)/4;
503                ipc_msg_to_high.arg0              = tx_pkt_buf;
504                ipc_msg_to_high.payload_ptr       = (u32*)&low_tx_details;
505
506                write_mailbox_msg(&ipc_msg_to_high);
507            }
508        break;
509        case TX_PKT_BUF_UNINITIALIZED:
510        case TX_PKT_BUF_HIGH_CTRL:
511            //  The status was set to HIGH_CTRL because CPU_HIGH is in the process of stopping beacon
512            //  transmissions. If so, we should expect configure_beacon_txrx() that will prevent
513            //  future calls to this function on TBTT intervals. In this case, we will return a
514            //  "success" to the calling function. We successfully did not send this beacon because
515            //  we were informed by CPU_HIGH that we should stop.
516            return_status = 0;
517        break;
518        case TX_PKT_BUF_LOW_CTRL:
519            xil_printf("ERROR (send_beacon): unexpected packet buffer status of TX_PKT_BUF_LOW_CTRL\n");
520        case TX_PKT_BUF_DONE:
521            //  CPU_HIGH is lagging behind. The previous beacon we sent is still being processed
522            //  and hasn't been returned to us. We will exit this context rather than block and try
523            //  again later.
524            return_status = -1;
525        break;
526    }
527
528    wlan_mac_pause_backoff_tx_ctrl_A(0);
529
530    return return_status;
531}
532
533/*****************************************************************************/
534/**
535 * @brief Handles reception of a wireless packet
536 *
537 * This function is called after a good SIGNAL field is detected by either PHY (OFDM or DSSS)
538 *
539 * It is the responsibility of this function to wait until a sufficient number of bytes have been received
540 * before it can start to process those bytes. When this function is called the eventual checksum status is
541 * unknown. The packet contents can be provisionally processed (e.g. prepare an ACK for fast transmission),
542 * but post-reception actions must be conditioned on the eventual FCS status (good or bad).
543 *
544 * NOTE: The timing of this function is critical for correct operation of the 802.11 DCF. It is not
545 *     safe to add large delays to this function (e.g. xil_printf or usleep)
546 *
547 * Two primary job responsibilities of this function:
548 *  (1): Prepare outgoing ACK packets and instruct the MAC_DCF_HW core whether or not to send ACKs
549 *  (2): Pass up MPDUs (FCS valid or invalid) to CPU_HIGH
550 *
551 * @param   rx_pkt_buf       - Index of the Rx packet buffer containing the newly received packet
552 * @param   phy_details      - Pointer to phy_rx_details struct containing PHY mode, MCS, and Length
553 * @return  u32              - Bit mask of flags indicating various results of the reception
554 */
555u32 frame_receive(u8 rx_pkt_buf, phy_rx_details_t* phy_details) {
556
557    // RX_LEN_THRESH is used to manage a potential pipeline bubble that can be used during a reception
558    // for processing:
559    //   - If the ongoing reception is >RX_LEN_THRESH, we will start
560    //     processing the frame and filling in metadata into the packet
561    //     buffer prior to calling wlan_mac_hw_rx_finish().
562    //   - If the ongoing reception is <RX_LEN_THRESH, we'll immediately
563    //     start polling the PHY with wlan_mac_hw_rx_finish() and,
564    //     if need be, configure a MAC Tx core to send a response.
565    //
566    // This structure handles any risk of response packets (e.g. an ACK) not being configured in time
567    // for the hard SIFS boundary.
568    //
569
570    int                 i;
571    u32                 return_value             = 0;
572    u32                 tx_length;
573    u8                  tx_mcs;
574    u16                 cts_duration;
575    u8                  unicast_to_me, to_multicast;
576    u16                 rssi;
577    u8                  lna_gain;
578    u8                  active_rx_ant;
579    u32                 rx_filter;
580    u8                  report_to_mac_high;
581    int                 curr_tx_pow;
582    u8                  ctrl_tx_gain;
583    u32                 mac_tx_ctrl_status;
584    s64                 time_delta;
585    u32                 current_tu;
586
587    u8                  mpdu_tx_ant_mask         = 0;
588    u8                  ack_tx_ant               = 0;
589    u8                  tx_ant_mask              = 0;
590    u8                  num_resp_failures        = 0;
591
592    rx_finish_state_t   rx_finish_state     = RX_FINISH_SEND_NONE;
593    tx_pending_state_t  tx_pending_state    = TX_PENDING_NONE;
594
595    rx_frame_info_t   * rx_frame_info;
596    tx_frame_info_t   * tx_frame_info;
597    mac_header_80211  * rx_header;
598    u8                * mac_payload_ptr_u8;
599
600    // Translate Rx pkt buf index into actual memory address
601    void* pkt_buf_addr = (void *) RX_PKT_BUF_TO_ADDR(rx_pkt_buf);
602
603    // Get pointer to MPDU info struct (stored at 0 offset in the pkt buffer)
604    rx_frame_info = (rx_frame_info_t*) pkt_buf_addr;
605
606    // Clear the MPDU info flags
607    rx_frame_info->flags = 0;
608
609    // Apply the mac_header_80211 template to the first bytes of the received MPDU
610    rx_header = (mac_header_80211*)((void*)(pkt_buf_addr + PHY_RX_PKT_BUF_MPDU_OFFSET));
611    mac_payload_ptr_u8 = (u8*)rx_header;
612
613    // Sanity check length value - anything shorter than an ACK must be bogus
614    if((phy_details->length) < (sizeof(mac_header_80211_ACK) + WLAN_PHY_FCS_NBYTES)) {
615        return return_value;
616    }
617
618    // Translate the rate index into the rate code used by the Tx PHY
619    //     This translation is required in case this reception needs to send an ACK, as the ACK
620    //     rate is a function of the rate of the received packet
621    //     The mapping of Rx rate to ACK rate is given in 9.7.6.5.2 of 802.11-2012
622    //
623    tx_mcs      = wlan_mac_low_mcs_to_ctrl_resp_mcs(phy_details->mcs, phy_details->phy_mode);
624
625    // Determine which antenna the ACK will be sent from
626    //     The current implementation transmits ACKs from the same antenna over which the previous packet was received
627    //
628    active_rx_ant = (wlan_phy_rx_get_active_rx_ant());
629    tx_ant_mask   = 0;
630
631    switch(active_rx_ant){
632        case RX_ACTIVE_ANTA:  tx_ant_mask |= 0x1;  break;
633        case RX_ACTIVE_ANTB:  tx_ant_mask |= 0x2;  break;
634        case RX_ACTIVE_ANTC:  tx_ant_mask |= 0x4;  break;
635        case RX_ACTIVE_ANTD:  tx_ant_mask |= 0x8;  break;
636        default:              tx_ant_mask  = 0x1;  break;            // Default to RF_A
637    }
638
639    // Wait until the PHY has written enough bytes so that the first address field can be processed
640    i = 0;
641    while(wlan_mac_get_last_byte_index() < MAC_HW_LASTBYTE_ADDR1) {
642        if(i++ > 1000000) {xil_printf("Stuck waiting for MAC_HW_LASTBYTE_ADDR1: wlan_mac_get_last_byte_index() = %d\n", wlan_mac_get_last_byte_index());}
643    };
644
645    // Check the destination address
646    unicast_to_me = wlan_addr_eq(rx_header->address_1, gl_eeprom_addr);
647    to_multicast  = wlan_addr_mcast(rx_header->address_1);
648
649    // Prep outgoing ACK just in case it needs to be sent
650    //     ACKs are only sent for non-control frames addressed to this node
651    if(unicast_to_me && !WLAN_IS_CTRL_FRAME(rx_header)) {
652        // Auto TX Delay is in units of 100ns. This delay runs from RXEND of the preceding reception.
653        //     wlan_mac_tx_ctrl_B_params(pktBuf, antMask, req_zeroNAV, preWait_postRxTimer1, preWait_postRxTimer2, preWait_postTxTimer1, phy_mode)
654        wlan_mac_tx_ctrl_B_params(TX_PKT_BUF_ACK_CTS, tx_ant_mask, 0, 1, 0, 0, PHY_MODE_NONHT);
655
656        // ACKs are transmitted with a nominal Tx power used for all control packets
657        ctrl_tx_gain = wlan_mac_low_dbm_to_gain_target(wlan_mac_low_get_current_ctrl_tx_pow());
658        wlan_mac_tx_ctrl_B_gains(ctrl_tx_gain, ctrl_tx_gain, ctrl_tx_gain, ctrl_tx_gain);
659
660
661        if((phy_details->length) >= MAC_HW_LASTBYTE_ADDR2){
662            // Wait until the PHY has written enough bytes so that the second address field can be processed
663            // If this is a short reception that does not have a second address, it is still possible to get
664            // to this line of code if there is an FCS error and the WLAN_IS_CTRL_FRAME check above fails.
665            // As such, we sanity check the length of the reception before getting into a potentially infinite
666            // loop.
667            i = 0;
668            while(wlan_mac_get_last_byte_index() < MAC_HW_LASTBYTE_ADDR2) {
669                if(i++ > 1000000) {xil_printf("Stuck waiting for MAC_HW_LASTBYTE_ADDR2: wlan_mac_get_last_byte_index() = %d\n", wlan_mac_get_last_byte_index());}
670            };
671        }
672
673        // Construct the ACK frame in the dedicated Tx pkt buf
674        tx_length = wlan_create_ack_frame((void*)(TX_PKT_BUF_TO_ADDR(TX_PKT_BUF_ACK_CTS) + PHY_TX_PKT_BUF_MPDU_OFFSET), rx_header->address_2);
675
676        // Write the SIGNAL field for the ACK
677        write_phy_preamble(TX_PKT_BUF_ACK_CTS, PHY_MODE_NONHT, tx_mcs, tx_length);
678
679        rx_finish_state = RX_FINISH_SEND_B;
680
681        rx_frame_info->resp_low_tx_details.tx_details_type      = TX_DETAILS_ACK;
682        rx_frame_info->resp_low_tx_details.phy_params_ctrl.mcs = tx_mcs;
683
684        // We let "duration" be equal to the duration field of an ACK. This value is provided explicitly to CPU_HIGH
685        // in the low_tx_details struct such that CPU_HIGH has can reconstruct the RTS in its log. This isn't critical
686        // to the operation of the DCF, but is critical for the logging framework.
687        //
688        rx_frame_info->resp_low_tx_details.duration = 0;
689
690        // This element remains unused during MPDU-only transmissions
691        rx_frame_info->resp_low_tx_details.phy_params_ctrl.phy_mode     = phy_details->phy_mode;
692        rx_frame_info->resp_low_tx_details.phy_params_ctrl.power        = wlan_mac_low_get_current_ctrl_tx_pow();
693
694        switch(tx_ant_mask) {
695            case 0x1:  ack_tx_ant = TX_ANTMODE_SISO_ANTA; break;
696            case 0x2:  ack_tx_ant = TX_ANTMODE_SISO_ANTB; break;
697            case 0x4:  ack_tx_ant = TX_ANTMODE_SISO_ANTC; break;
698            case 0x8:  ack_tx_ant = TX_ANTMODE_SISO_ANTD; break;
699            default:   ack_tx_ant = TX_ANTMODE_SISO_ANTA; break;   // Default to RF_A
700        }
701
702        rx_frame_info->resp_low_tx_details.phy_params_ctrl.antenna_mode = ack_tx_ant;
703
704    } else if(unicast_to_me && (rx_header->frame_control_1 == MAC_FRAME_CTRL1_SUBTYPE_CTS)){
705        if(gl_mpdu_pkt_buf != PKT_BUF_INVALID) {
706            // We have an outgoing data frame we should send
707            //     - Configure the Tx antenna selection
708            //     - The frame_transmit() context already configured the SIGNAL field,
709            //       so we do not have to worry about it in this context
710            //
711            tx_frame_info = (tx_frame_info_t*) (TX_PKT_BUF_TO_ADDR(gl_mpdu_pkt_buf));
712
713            switch(tx_frame_info->params.phy.antenna_mode) {
714                case TX_ANTMODE_SISO_ANTA:  mpdu_tx_ant_mask |= 0x1;  break;
715                case TX_ANTMODE_SISO_ANTB:  mpdu_tx_ant_mask |= 0x2;  break;
716                case TX_ANTMODE_SISO_ANTC:  mpdu_tx_ant_mask |= 0x4;  break;
717                case TX_ANTMODE_SISO_ANTD:  mpdu_tx_ant_mask |= 0x8;  break;
718                default:                    mpdu_tx_ant_mask  = 0x1;  break;   // Default to RF_A
719            }
720
721            // Configure the Tx power - update all antennas, even though only one will be used
722            curr_tx_pow = wlan_mac_low_dbm_to_gain_target(tx_frame_info->params.phy.power);
723            wlan_mac_tx_ctrl_A_gains(curr_tx_pow, curr_tx_pow, curr_tx_pow, curr_tx_pow);
724            wlan_mac_tx_ctrl_A_params(gl_mpdu_pkt_buf, mpdu_tx_ant_mask, 0, 1, 0, 1, tx_frame_info->params.phy.phy_mode); //Use postRx timer 1 and postTx_timer2
725
726            rx_finish_state = RX_FINISH_SEND_A;
727
728            return_value |= POLL_MAC_TYPE_CTS;
729        } else {
730            //Unexpected CTS to me.
731            //This clause can execute on a bad FCS (e.g. it's actually a bad FCS ACK)
732        }
733    } else if(unicast_to_me && (rx_header->frame_control_1 == MAC_FRAME_CTRL1_SUBTYPE_RTS)){
734        // We need to send a CTS
735        //     Auto TX Delay is in units of 100ns. This delay runs from RXEND of the preceding reception.
736        //     wlan_mac_tx_ctrl_B_params(pktBuf, antMask, req_zeroNAV, preWait_postRxTimer1, preWait_postRxTimer2, preWait_postTxTimer1, phy_mode)
737        //
738        wlan_mac_tx_ctrl_B_params(TX_PKT_BUF_ACK_CTS, tx_ant_mask, 1, 1, 0, 0, PHY_MODE_NONHT);
739
740        // CTSs are transmitted with a nominal Tx power used for all control packets
741        ctrl_tx_gain = wlan_mac_low_dbm_to_gain_target(wlan_mac_low_get_current_ctrl_tx_pow());
742        wlan_mac_tx_ctrl_B_gains(ctrl_tx_gain, ctrl_tx_gain, ctrl_tx_gain, ctrl_tx_gain);
743
744        cts_duration = sat_sub(rx_header->duration_id, (gl_mac_timing_values.t_sifs) +
745                    wlan_ofdm_calc_txtime(sizeof(mac_header_80211_CTS) + WLAN_PHY_FCS_NBYTES, tx_mcs, PHY_MODE_NONHT, wlan_mac_low_get_phy_samp_rate()));
746
747        // Construct the ACK frame in the dedicated Tx pkt buf
748        tx_length = wlan_create_cts_frame((void*)(TX_PKT_BUF_TO_ADDR(TX_PKT_BUF_ACK_CTS) + PHY_TX_PKT_BUF_MPDU_OFFSET),
749                                          rx_header->address_2,
750                                          cts_duration);
751
752        // Write the SIGNAL field for the CTS
753        write_phy_preamble(TX_PKT_BUF_ACK_CTS, PHY_MODE_NONHT, tx_mcs, tx_length);
754
755        rx_finish_state = RX_FINISH_SEND_B;
756
757        rx_frame_info->resp_low_tx_details.tx_details_type     = TX_DETAILS_CTS;
758        rx_frame_info->resp_low_tx_details.phy_params_ctrl.mcs = tx_mcs;
759
760        // We let "duration" be equal to the duration field of an CTS. This value is provided explicitly to CPU_HIGH
761        // in the low_tx_details struct such that CPU_HIGH has can reconstruct the RTS in its log. This isn't critical
762        // to the operation of the DCF, but is critical for the logging framework.
763        rx_frame_info->resp_low_tx_details.duration = cts_duration;
764
765        // This element remains unused during MPDU-only transmissions
766        rx_frame_info->resp_low_tx_details.phy_params_ctrl.phy_mode     = phy_details->phy_mode;
767        rx_frame_info->resp_low_tx_details.phy_params_ctrl.power        = wlan_mac_low_get_current_ctrl_tx_pow();
768
769        switch(tx_ant_mask) {
770            case 0x1:  ack_tx_ant = TX_ANTMODE_SISO_ANTA; break;
771            case 0x2:  ack_tx_ant = TX_ANTMODE_SISO_ANTB; break;
772            case 0x4:  ack_tx_ant = TX_ANTMODE_SISO_ANTC; break;
773            case 0x8:  ack_tx_ant = TX_ANTMODE_SISO_ANTD; break;
774            default:   ack_tx_ant = TX_ANTMODE_SISO_ANTA; break;   // Default to RF_A
775        }
776
777        rx_frame_info->resp_low_tx_details.phy_params_ctrl.antenna_mode = ack_tx_ant;
778    }
779
780    // Based on the RX length threshold, determine processing order
781    if((phy_details->length) <= RX_LEN_THRESH) {
782        if(wlan_mac_hw_rx_finish() == 1){
783            //FCS was good
784            rx_frame_info->flags |= RX_FRAME_INFO_FLAGS_FCS_GOOD;
785        } else {
786            //FCS was bad
787            rx_frame_info->flags &= ~RX_FRAME_INFO_FLAGS_FCS_GOOD;
788        }
789
790        if(rx_frame_info->flags & RX_FRAME_INFO_FLAGS_FCS_GOOD){
791            switch(rx_finish_state) {
792                case RX_FINISH_SEND_A:
793                    wlan_mac_tx_ctrl_A_start(1);
794                    wlan_mac_tx_ctrl_A_start(0);
795                    tx_pending_state = TX_PENDING_A;
796                break;
797
798                case RX_FINISH_SEND_B:
799                    wlan_mac_tx_ctrl_B_start(1);
800                    wlan_mac_tx_ctrl_B_start(0);
801                    tx_pending_state = TX_PENDING_B;
802                break;
803
804                default:
805                case RX_FINISH_SEND_NONE:
806                    // Do nothing
807                break;
808            }
809        }
810        rx_finish_state = RX_FINISH_SEND_NONE;
811    }
812
813    // Check if this reception is an ACK
814    //TODO: we could add a unicast to me check here. It should be redundant. Then again, the POLL_MAC_TYPE_CTS does have the unicast requirement
815    if((rx_header->frame_control_1) == MAC_FRAME_CTRL1_SUBTYPE_ACK){
816        return_value |= POLL_MAC_TYPE_ACK;
817    }
818
819    // Update metadata about this reception
820    rx_frame_info->phy_details = *phy_details;
821
822    // This reception was a re-transmission by the other node
823    if ((rx_header->frame_control_2) & MAC_FRAME_CTRL2_FLAG_RETRY) {
824        rx_frame_info->flags |= RX_FRAME_INFO_FLAGS_RETRY;
825    }
826
827    // Record information about the reception in the RX packet metadata
828    rx_frame_info->channel        = wlan_mac_low_get_active_channel();
829    rx_frame_info->phy_samp_rate  = (u8)wlan_mac_low_get_phy_samp_rate();
830    rx_frame_info->timestamp      = wlan_mac_low_get_rx_start_timestamp();
831    rx_frame_info->timestamp_frac = wlan_mac_low_get_rx_start_timestamp_frac();
832    rx_frame_info->ant_mode       = active_rx_ant;
833    rx_frame_info->cfo_est        = wlan_phy_rx_get_cfo_est();
834    rx_frame_info->rf_gain        = wlan_phy_rx_get_agc_RFG(active_rx_ant);
835    rx_frame_info->bb_gain        = wlan_phy_rx_get_agc_BBG(active_rx_ant);
836
837    lna_gain                  = wlan_phy_rx_get_agc_RFG(active_rx_ant);
838    rssi                      = wlan_phy_rx_get_pkt_rssi(active_rx_ant);
839    rx_frame_info->rx_power   = wlan_mac_low_calculate_rx_power(rssi, lna_gain);
840
841    // Block until the reception is complete, storing the checksum status in the frame_info struct
842    if ((phy_details->length) > RX_LEN_THRESH) {
843        if(wlan_mac_hw_rx_finish() == 1){
844            //FCS was good
845            rx_frame_info->flags |= RX_FRAME_INFO_FLAGS_FCS_GOOD;
846        } else {
847            //FCS was bad
848            rx_frame_info->flags &= ~RX_FRAME_INFO_FLAGS_FCS_GOOD;
849        }
850    }
851
852    // Received packet had good checksum
853    if(rx_frame_info->flags & RX_FRAME_INFO_FLAGS_FCS_GOOD) {
854        if(unicast_to_me &&
855                (gl_waiting_for_response == 0) &&
856                ( (return_value & POLL_MAC_TYPE_CTS) || (return_value & POLL_MAC_TYPE_ACK) )){
857            rx_frame_info->flags |= RX_FRAME_INFO_UNEXPECTED_RESPONSE;
858        } else {
859            rx_frame_info->flags &= ~RX_FRAME_INFO_UNEXPECTED_RESPONSE;
860        }
861
862
863        // Increment green LEDs
864        gl_green_led_index = (gl_green_led_index + 1) % NUM_LEDS;
865        userio_write_leds_green(USERIO_BASEADDR, (1<<gl_green_led_index));
866
867        return_value |= POLL_MAC_STATUS_GOOD;
868
869        // Check if this packet should be passed up to CPU High for further processing
870        rx_filter = wlan_mac_low_get_current_rx_filter();
871
872        switch (rx_filter & RX_FILTER_HDR_MASK) {
873            default:
874            case RX_FILTER_HDR_ADDR_MATCH_MPDU:
875                // Non-control packet either addressed to me or addressed to multicast address
876                report_to_mac_high = (unicast_to_me || to_multicast) && !WLAN_IS_CTRL_FRAME(rx_header);
877            break;
878            case RX_FILTER_HDR_ALL_MPDU:
879                // Any non-control packet
880                report_to_mac_high = !WLAN_IS_CTRL_FRAME(rx_header);
881            break;
882            case RX_FILTER_HDR_ALL:
883                // All packets (data, management and control; no type or address filtering)
884                report_to_mac_high = 1;
885            break;
886        }
887
888        // Sanity check packet length - if the header says non-control but the length is shorter than a full MAC header
889        // it must be invalid; this should never happen, but better to catch rare events here than corrupt state in CPU High
890        if (!WLAN_IS_CTRL_FRAME(rx_header) && (phy_details->length < sizeof(mac_header_80211))) {
891            report_to_mac_high = 0;
892        }
893
894        if(unicast_to_me) {
895            return_value |= POLL_MAC_ADDR_MATCH;
896        }
897
898        if ((phy_details->length) > RX_LEN_THRESH) {
899            switch (rx_finish_state) {
900                case RX_FINISH_SEND_A:
901                    wlan_mac_tx_ctrl_A_start(1);
902                    wlan_mac_tx_ctrl_A_start(0);
903                    tx_pending_state = TX_PENDING_A;
904                break;
905
906                case RX_FINISH_SEND_B:
907                    wlan_mac_tx_ctrl_B_start(1);
908                    wlan_mac_tx_ctrl_B_start(0);
909                    tx_pending_state = TX_PENDING_B;
910                break;
911
912                default:
913                case RX_FINISH_SEND_NONE:
914                break;
915            }
916        }
917
918
919        // Check to see if this was a beacon or probe response frame and update the MAC time if appropriate
920        switch(rx_header->frame_control_1) {
921            //---------------------------------------------------------------------
922            case (MAC_FRAME_CTRL1_SUBTYPE_BEACON):
923            case (MAC_FRAME_CTRL1_SUBTYPE_PROBE_RESP):
924                // Beacon Packet / Probe Response Packet
925                //   -
926                //
927
928                // If this packet was from our BSS
929                if(wlan_addr_eq(gl_beacon_txrx_configure.bssid_match, rx_header->address_3)){
930
931                    if(gl_beacon_txrx_configure.beacon_tx_mode == IBSS_BEACON_TX){
932                        // Reset all state in the DCF core - this cancels deferrals and pending transmissions
933                        wlan_mac_reset_tx_ctrl_C(1);
934                        wlan_mac_reset_tx_ctrl_C(0);
935                        return_value |= POLL_MAC_CANCEL_TX;
936                    }
937
938                    // Move the packet pointer to after the header
939                    mac_payload_ptr_u8 += sizeof(mac_header_80211);
940
941                    // Calculate the difference between the beacon timestamp and the packet timestamp
942                    time_delta = (s64)(((beacon_probe_frame*)mac_payload_ptr_u8)->timestamp) - (s64)(rx_frame_info->timestamp) + gl_mac_timing_values.t_phy_rx_start_dly;
943
944                    // Update the MAC time
945                    switch(gl_beacon_txrx_configure.ts_update_mode){
946                        // TODO: notify the MAC Low Framework of this change so that TBTT can be updated (if necessary)
947                        case NEVER_UPDATE:
948                        break;
949                        case ALWAYS_UPDATE:
950                            apply_mac_time_delta_usec(time_delta);
951                            //handle_mactime_change(time_delta); //This call is actually not necessary here since, whether or not we adopt the
952                                                                 //new MAC time, we will update next TBTT target anyway
953                        break;
954                        case FUTURE_ONLY_UPDATE:
955                            if(time_delta > 0){
956                                apply_mac_time_delta_usec(time_delta);
957                                //handle_mactime_change(time_delta); //This call is actually not necessary here since, whether or not we adopt the
958                                                                     //new MAC time, we will update next TBTT target anyway
959                            }
960                        break;
961                    }
962
963                    if(( gl_beacon_txrx_configure.beacon_tx_mode == AP_BEACON_TX ) ||
964                       ( gl_beacon_txrx_configure.beacon_tx_mode == IBSS_BEACON_TX )){
965                        current_tu = (u32)(get_mac_time_usec()>>10);
966
967                        //The current_tu can be anywhere within a beacon interval, so we need
968                        //to round up to the next TBTT.
969                        wlan_mac_set_tu_target(gl_beacon_txrx_configure.beacon_interval_tu*((current_tu/gl_beacon_txrx_configure.beacon_interval_tu)+1));
970                    }
971                }
972
973            break;
974        }
975
976
977    // Received checksum was bad
978    } else {
979        // Increment red LEDs
980        gl_red_led_index = (gl_red_led_index + 1) % NUM_LEDS;
981        userio_write_leds_red(USERIO_BASEADDR, (1<<gl_red_led_index));
982
983        // Check if this packet should be passed up to CPU High for further processing
984        rx_filter = wlan_mac_low_get_current_rx_filter();
985
986        switch (rx_filter & RX_FILTER_FCS_MASK) {
987            default:
988            case RX_FILTER_FCS_GOOD:
989                report_to_mac_high = 0;
990            break;
991            case RX_FILTER_FCS_ALL:
992                report_to_mac_high = 1;
993            break;
994        }
995    }
996
997    // Wait for MAC CFG A or B to finish starting a response transmission
998    switch(tx_pending_state){
999        case TX_PENDING_NONE:
1000            // With the new CPU_LOW beacon structure, it is possible to reach this point in the code
1001            // while MAC Support Core A is currently pending on an unrelated MPDU. We should not wait for this
1002            // pending state to clear if tx_pending_state is TX_PENDING_NONE because it never will. A previous
1003            // version of the code relied on the fact that it was impossible for MAC Support Core A to be pending
1004            // At this point
1005        break;
1006
1007        case TX_PENDING_A:
1008
1009            do{
1010                mac_tx_ctrl_status = wlan_mac_get_tx_ctrl_status();
1011
1012                if(((mac_tx_ctrl_status & WLAN_MAC_TXCTRL_STATUS_MASK_TX_A_STATE) == WLAN_MAC_TXCTRL_STATUS_TX_A_STATE_PRE_TX_WAIT) &&
1013                   ((mac_tx_ctrl_status & WLAN_MAC_TXCTRL_STATUS_MASK_POSTRX_TIMER1_RUNNING) == 0)) {
1014                    // This is potentially a bad state. It likely means we were late in processing this reception
1015                    //
1016                    // There is a slight race condition in detecting this state. There is a small 1 or 2 cycle window where this
1017                    // check can inaccurately deem a failed response transmission. As such, we'll require the condition to be met
1018                    // multiple times.
1019                    //
1020                    num_resp_failures++;
1021
1022                    if(num_resp_failures > 2){
1023                        wlan_mac_reset_tx_ctrl_A(1);
1024                        wlan_mac_reset_tx_ctrl_A(0);
1025
1026                        break;
1027                    }
1028                } else if( (mac_tx_ctrl_status & WLAN_MAC_TXCTRL_STATUS_MASK_TX_A_STATE) == WLAN_MAC_TXCTRL_STATUS_TX_A_STATE_DO_TX ){
1029                    // If the PHY is actively running, we can safely quit this context and get back to frame_transmit to get
1030                    // ready for an ACK reception.
1031                    break;
1032                }
1033            } while(mac_tx_ctrl_status & WLAN_MAC_TXCTRL_STATUS_MASK_TX_A_PENDING);
1034
1035        break;
1036
1037        case TX_PENDING_B:
1038            do{
1039                mac_tx_ctrl_status = wlan_mac_get_tx_ctrl_status();
1040
1041                if( mac_tx_ctrl_status & WLAN_MAC_TXCTRL_STATUS_MASK_TX_B_DONE ) {
1042                    if ((mac_tx_ctrl_status & WLAN_MAC_TXCTRL_STATUS_MASK_TX_B_RESULT) == WLAN_MAC_TXCTRL_STATUS_TX_B_RESULT_NO_TX) {
1043                        // The MAC Support Core B has the capability of successfully not transmitting. This is not relevant
1044                        // for ACK transmissions, but it is relevant for CTS transmissions. A CTS will only be sent if the
1045                        // NAV is clear at the time of transmission. This code block handles the case the the support core
1046                        // elected not to transmit the frame.
1047                        //
1048                        rx_frame_info->flags = rx_frame_info->flags & ~RX_FRAME_INFO_FLAGS_CTRL_RESP_TX;
1049                        break;
1050                    }
1051                    if ((mac_tx_ctrl_status & WLAN_MAC_TXCTRL_STATUS_MASK_TX_B_RESULT) == WLAN_MAC_TXCTRL_STATUS_TX_B_RESULT_DID_TX) {
1052                        rx_frame_info->flags |= RX_FRAME_INFO_FLAGS_CTRL_RESP_TX;
1053                        break;
1054                    }
1055                } else if(((mac_tx_ctrl_status & WLAN_MAC_TXCTRL_STATUS_MASK_TX_B_STATE) == WLAN_MAC_TXCTRL_STATUS_TX_B_STATE_PRE_TX_WAIT) &&
1056                          ((mac_tx_ctrl_status & WLAN_MAC_TXCTRL_STATUS_MASK_POSTRX_TIMER1_RUNNING) == 0)){
1057
1058                    // This is potentially a bad state. It likely means we were late in processing this reception
1059                    //
1060                    // There is a slight race condition in detecting this state. There is a small 1 or 2 cycle window where this
1061                    // check can inaccurately deem a failed response transmission. As such, we'll require the condition to be met
1062                    // multiple times.
1063                    //
1064                    num_resp_failures++;
1065
1066                    if(num_resp_failures > 2){
1067                        rx_frame_info->flags = rx_frame_info->flags & ~RX_FRAME_INFO_FLAGS_CTRL_RESP_TX;
1068
1069                        wlan_mac_reset_tx_ctrl_B(1);
1070                        wlan_mac_reset_tx_ctrl_B(0);
1071                        break;
1072                    }
1073                }
1074            } while(mac_tx_ctrl_status & WLAN_MAC_TXCTRL_STATUS_MASK_TX_B_PENDING);
1075        break;
1076    }
1077
1078    if(rx_frame_info->flags & RX_FRAME_INFO_FLAGS_CTRL_RESP_TX) {
1079        rx_frame_info->resp_low_tx_details.tx_start_timestamp_ctrl      = wlan_mac_low_get_tx_start_timestamp();
1080        rx_frame_info->resp_low_tx_details.tx_start_timestamp_frac_ctrl = wlan_mac_low_get_tx_start_timestamp_frac();
1081    }
1082
1083    // This packet should be passed up to CPU_high for further processing
1084    if (report_to_mac_high) {
1085        // Unlock the pkt buf mutex before passing the packet up
1086        //     If this fails, something has gone horribly wrong
1087
1088        rx_frame_info->rx_pkt_buf_state = RX_PKT_BUF_READY;
1089        if (unlock_rx_pkt_buf(rx_pkt_buf) != PKT_BUF_MUTEX_SUCCESS) {
1090            xil_printf("Error: unable to unlock RX pkt_buf %d\n", rx_pkt_buf);
1091            wlan_mac_low_send_exception(WLAN_ERROR_CODE_CPU_LOW_RX_MUTEX);
1092        } else {
1093            wlan_mac_low_frame_ipc_send();
1094
1095            // Find a free packet buffer and begin receiving packets there (blocks until free buf is found)
1096            wlan_mac_low_lock_empty_rx_pkt_buf();
1097        }
1098    }
1099
1100    return return_value;
1101}
1102
1103
1104
1105/*****************************************************************************/
1106/**
1107 * @brief Handles transmission of a wireless packet
1108 *
1109 * This function is called to transmit a new packet via the DCF+PHY. This code interacts with the wlan_mac_dcf_hw core
1110 * to manage MAC and PHY state. This function should be called once per packet and will return after the full transmission
1111 * state machine has executed for that packet. This state machine includes channel access (including carrier sensing,
1112 * deferrals and backoffs), ACK reception, timeouts and re-transmissions.
1113 *
1114 * This function is called once per IPC_MBOX_TX_MPDU_READY message from CPU High. The IPC_MBOX_TX_MPDU_DONE message will be
1115 * sent back to CPU High when this function returns.
1116 *
1117 * @param   mpdu_pkt_buf     - Index of the Tx packet buffer containing the packet to transmit
1118 * @param   mpdu_rate        - Index of PHY rate at which packet will be transmitted
1119 * @param   mpdu_length      - Number of bytes in packet, including MAC header and FCS
1120 * @param   low_tx_details   - Pointer to array of metadata entries to be created for each PHY transmission of this packet
1121 *                             (eventually leading to TX_LOW log entries)
1122 * @return  int              - Transmission result
1123 */
1124//int frame_transmit(u8 mpdu_pkt_buf, u8 mpdu_rate, u16 mpdu_length, wlan_mac_low_tx_details* low_tx_details) {
1125int frame_transmit(u8 pkt_buf, wlan_mac_low_tx_details_t* low_tx_details) {
1126    // The pkt_buf, rate, and length arguments provided to this function specifically relate to
1127    // the MPDU that the WLAN MAC LOW framework wants us to send. We may opt to first send an RTS
1128    // to reserve the medium prior to doing this. The tx_rate, tx_length, and tx_pkt_buf relate
1129    // to whatever the next waveform will be. That waveform could be an RTS, or it could be the
1130    // MPDU itself.
1131
1132    u8  mac_cfg_mcs;
1133    u16 mac_cfg_length;
1134    u8  mac_cfg_pkt_buf;
1135    u8  ack_phy_mode;
1136    u8  ack_mcs;
1137
1138    u16 rts_header_duration;
1139    u16 cts_header_duration;
1140
1141    u8 req_timeout;
1142
1143    u32 rx_status;
1144    u32 mac_hw_status;
1145    u32 mac_tx_ctrl_status;
1146
1147    int curr_tx_pow;
1148
1149    u32 low_tx_details_num;
1150    u8  tx_has_started;
1151
1152    tx_wait_state_t     tx_wait_state;
1153    tx_mode_t           tx_mode;
1154
1155    u16                 short_retry_count   = 0;
1156    u16                 long_retry_count    = 0;
1157    u16                 n_slots             = 0;
1158    u16                 n_slots_readback    = 0;
1159    u8                  mpdu_tx_ant_mask    = 0;
1160    tx_frame_info_t   * tx_frame_info       = (tx_frame_info_t*) (TX_PKT_BUF_TO_ADDR(pkt_buf));
1161    mac_header_80211  * header              = (mac_header_80211*)(TX_PKT_BUF_TO_ADDR(pkt_buf) + PHY_TX_PKT_BUF_MPDU_OFFSET);
1162
1163    poll_tbtt_return_t  poll_tbtt_return = TBTT_NOT_ACHIEVED;
1164
1165
1166    // Extract waveform params from the tx_frame_info
1167    u8  mcs      = tx_frame_info->params.phy.mcs;
1168    u8  phy_mode = (tx_frame_info->params.phy.phy_mode & (PHY_MODE_HTMF | PHY_MODE_NONHT));
1169    u16 length   = tx_frame_info->length;
1170
1171    // This state variable will inform the rest of the frame_transmit function
1172    // on whether the code is actively waiting for an ACK, for an RTS, or not
1173    // waiting for anything.
1174    tx_wait_state = TX_WAIT_NONE;
1175
1176    tx_frame_info->num_tx_attempts   = 0;
1177    tx_frame_info->phy_samp_rate      = (u8)wlan_mac_low_get_phy_samp_rate();
1178
1179    // Compare the length of this frame to the RTS Threshold
1180    if(length <= gl_dot11RTSThreshold) {
1181        tx_mode = TX_MODE_SHORT;
1182    } else {
1183        tx_mode = TX_MODE_LONG;
1184    }
1185
1186
1187    if((tx_frame_info->flags) & TX_FRAME_INFO_FLAGS_FILL_DURATION){
1188        // ACK_N_DBPS is used to calculate duration of the ACK waveform which might be received in response to this transmission
1189        //  The ACK duration is used to calculate the DURATION field in the MAC header
1190        //  The selection of ACK rate for a given DATA rate is specified in IEEE 802.11-2012 9.7.6.5.2
1191        ack_mcs = wlan_mac_low_mcs_to_ctrl_resp_mcs(tx_frame_info->params.phy.mcs, tx_frame_info->params.phy.phy_mode);
1192        ack_phy_mode = PHY_MODE_HTMF;
1193
1194        // Compute and fill in the duration of any time-on-air following this packet's transmission
1195        //     For DATA Tx, DURATION = T_SIFS + T_ACK, where T_ACK is function of the ACK Tx rate
1196        header->duration_id = wlan_ofdm_calc_txtime(sizeof(mac_header_80211_ACK) + WLAN_PHY_FCS_NBYTES, ack_mcs, ack_phy_mode, wlan_mac_low_get_phy_samp_rate()) + gl_mac_timing_values.t_sifs;
1197    }
1198
1199
1200    // Retry loop
1201    while(1) {
1202        tx_has_started = 0;
1203
1204        (tx_frame_info->num_tx_attempts)++;
1205
1206        // Check if the higher-layer MAC requires this transmission have a post-Tx timeout
1207        req_timeout = ((tx_frame_info->flags) & TX_FRAME_INFO_FLAGS_REQ_TO) != 0;
1208
1209        // Write the SIGNAL field (interpreted by the PHY during Tx waveform generation)
1210        // This is the SIGNAL field for the MPDU we will eventually transmit. It's possible
1211        // the next waveform we send will be an RTS with its own independent SIGNAL
1212
1213        //wlan_phy_set_tx_signal(mpdu_pkt_buf, mpdu_rate, mpdu_length);
1214        write_phy_preamble(pkt_buf, phy_mode, mcs, length);
1215
1216
1217        if ((tx_mode == TX_MODE_LONG) && (req_timeout == 1)) {
1218            // This is a long MPDU that requires an RTS/CTS handshake prior to the MPDU transmission.
1219            tx_wait_state   = TX_WAIT_CTS;
1220
1221            // This is a global pkt_buf index that can be seen by the frame_receive() context.
1222            // frame_receive() needs this to figure out what to send in the event that it receives
1223            // a valid CTS.
1224            gl_mpdu_pkt_buf = pkt_buf;
1225
1226            mac_cfg_pkt_buf = TX_PKT_BUF_RTS;
1227
1228            // The rate given to us in the argument of frame_transmit applies to the MPDU. Several
1229            // elements depend on this rate:
1230            //
1231            // 1) The rate of the RTS we will send (fixed NONHT phy mode for CTRL response)
1232            // 2) The rate of the CTS we expect to receive (fixed NONHT phy mode for CTRL response)
1233            // 3) The duration of the RTS/CTS/DATA frames a long with the IFS periods between them
1234            //
1235            // The below switch() sets these elements accordingly.
1236            //
1237            switch (mcs) {
1238                default:
1239                case 0:
1240                    mac_cfg_mcs         = 0;
1241                    cts_header_duration = TX_TIME_CTS_R6;
1242                    low_tx_details[(tx_frame_info->num_tx_attempts) - 1].phy_params_ctrl.mcs = 0;
1243                break;
1244                case 1:
1245                    mac_cfg_mcs         = 0;
1246                    cts_header_duration = TX_TIME_CTS_R6;
1247                    low_tx_details[(tx_frame_info->num_tx_attempts) - 1].phy_params_ctrl.mcs = 0;
1248                break;
1249                case 2:
1250                    mac_cfg_mcs         = 2;
1251                    cts_header_duration = TX_TIME_CTS_R12;
1252                    low_tx_details[(tx_frame_info->num_tx_attempts) - 1].phy_params_ctrl.mcs = 2;
1253                break;
1254                case 3:
1255                    mac_cfg_mcs         = 2;
1256                    cts_header_duration = TX_TIME_CTS_R12;
1257                    low_tx_details[(tx_frame_info->num_tx_attempts) - 1].phy_params_ctrl.mcs = 2;
1258                break;
1259                case 4:
1260                    mac_cfg_mcs         = 4;
1261                    cts_header_duration = TX_TIME_CTS_R24;
1262                    low_tx_details[(tx_frame_info->num_tx_attempts) - 1].phy_params_ctrl.mcs = 4;
1263                break;
1264                case 5:
1265                    mac_cfg_mcs         = 4;
1266                    cts_header_duration = TX_TIME_CTS_R24;
1267                    low_tx_details[(tx_frame_info->num_tx_attempts) - 1].phy_params_ctrl.mcs = 4;
1268                break;
1269                case 6:
1270                    mac_cfg_mcs         = 4;
1271                    cts_header_duration = TX_TIME_CTS_R24;
1272                    low_tx_details[(tx_frame_info->num_tx_attempts) - 1].phy_params_ctrl.mcs = 4;
1273                break;
1274                case 7:
1275                    mac_cfg_mcs         = 4;
1276                    cts_header_duration = TX_TIME_CTS_R24;
1277                    low_tx_details[(tx_frame_info->num_tx_attempts) - 1].phy_params_ctrl.mcs = 4;
1278                break;
1279            }
1280
1281            rts_header_duration = (gl_mac_timing_values.t_sifs) + cts_header_duration +
1282                                  (gl_mac_timing_values.t_sifs) + wlan_ofdm_calc_txtime(length, tx_frame_info->params.phy.mcs, tx_frame_info->params.phy.phy_mode, wlan_mac_low_get_phy_samp_rate()) +
1283                                  header->duration_id;
1284
1285            // We let "duration" be equal to the duration field of an RTS. This value is provided explicitly to CPU_HIGH
1286            // in the low_tx_details struct such that CPU_HIGH has can reconstruct the RTS in its log. This isn't critical
1287            // to the operation of the DCF, but is critical for the logging framework.
1288            low_tx_details[(tx_frame_info->num_tx_attempts) - 1].duration = rts_header_duration;
1289
1290            // Construct the RTS frame in the dedicated Tx pkt buf for control frames
1291            mac_cfg_length = wlan_create_rts_frame((void*)(TX_PKT_BUF_TO_ADDR(TX_PKT_BUF_RTS) + PHY_TX_PKT_BUF_MPDU_OFFSET),
1292                                                   header->address_1,
1293                                                   header->address_2,
1294                                                   rts_header_duration);
1295
1296            // Write SIGNAL for RTS
1297            //wlan_phy_set_tx_signal(mac_cfg_pkt_buf, mac_cfg_rate, mac_cfg_length);
1298            write_phy_preamble(mac_cfg_pkt_buf, PHY_MODE_NONHT, mac_cfg_mcs, mac_cfg_length);
1299
1300        } else if((tx_mode == TX_MODE_SHORT) && (req_timeout == 1)) {
1301            // Unicast, no RTS
1302            tx_wait_state   = TX_WAIT_ACK;
1303            mac_cfg_mcs     = mcs;
1304            mac_cfg_length  = length;
1305            mac_cfg_pkt_buf = pkt_buf;
1306        } else {
1307            // Multicast, short or long
1308            tx_wait_state   = TX_WAIT_NONE;
1309            mac_cfg_mcs     = mcs;
1310            mac_cfg_length  = length;
1311            mac_cfg_pkt_buf = pkt_buf;
1312        }
1313
1314        // Configure the Tx antenna selection
1315        mpdu_tx_ant_mask    = 0;
1316
1317        switch(tx_frame_info->params.phy.antenna_mode) {
1318            case TX_ANTMODE_SISO_ANTA:  mpdu_tx_ant_mask |= 0x1;  break;
1319            case TX_ANTMODE_SISO_ANTB:  mpdu_tx_ant_mask |= 0x2;  break;
1320            case TX_ANTMODE_SISO_ANTC:  mpdu_tx_ant_mask |= 0x4;  break;
1321            case TX_ANTMODE_SISO_ANTD:  mpdu_tx_ant_mask |= 0x8;  break;
1322            default:                    mpdu_tx_ant_mask  = 0x1;  break;       // Default to RF_A
1323        }
1324
1325        // Configure the Tx power - update all antennas, even though only one will be used
1326        curr_tx_pow = wlan_mac_low_dbm_to_gain_target(tx_frame_info->params.phy.power);
1327        wlan_mac_tx_ctrl_A_gains(curr_tx_pow, curr_tx_pow, curr_tx_pow, curr_tx_pow);
1328
1329        if ((tx_frame_info->num_tx_attempts) == 1) {
1330            // This is the first transmission, so we speculatively draw a backoff in case
1331            // the backoff counter is currently 0 but the medium is busy. Prior to all other
1332            // (re)transmissions, an explicit backoff will have been started at the end of
1333            // the previous iteration of this loop.
1334            //
1335            n_slots = rand_num_slots(RAND_SLOT_REASON_STANDARD_ACCESS);
1336
1337
1338
1339            // Configure the DCF core Tx state machine for this transmission
1340            // wlan_mac_tx_ctrl_A_params(pktBuf, antMask, preTx_backoff_slots, preWait_postRxTimer1, preWait_postTxTimer1, postWait_postTxTimer2, phy_mode)
1341            wlan_mac_tx_ctrl_A_params(mac_cfg_pkt_buf, mpdu_tx_ant_mask, n_slots, 0, 0, req_timeout, phy_mode);
1342
1343        } else {
1344            // This is a retry. We will inherit whatever backoff that is currently running.
1345            // Configure the DCF core Tx state machine for this transmission
1346            // preTx_backoff_slots is 0 here, since the core will have started a post-timeout backoff automatically
1347            wlan_mac_tx_ctrl_A_params(mac_cfg_pkt_buf, mpdu_tx_ant_mask, 0, 0, 0, req_timeout, phy_mode);
1348        }
1349
1350        // Wait for the Tx PHY to be idle
1351        // Actually waiting here is rare, but handles corner cases like a background ACK transmission at a low rate
1352        // overlapping the attempt to start a new packet transmission
1353        do{
1354            mac_hw_status = wlan_mac_get_status();
1355        } while(mac_hw_status & WLAN_MAC_STATUS_MASK_TX_PHY_ACTIVE);
1356
1357        // Submit the MPDU for transmission - this starts the MAC hardware's MPDU Tx state machine
1358        wlan_mac_tx_ctrl_A_start(1);
1359        wlan_mac_tx_ctrl_A_start(0);
1360
1361        // Immediately re-read the current slot count.
1362        n_slots_readback = wlan_mac_get_backoff_count_A();
1363
1364        // While waiting, fill in the metadata about this transmission attempt, to be used by CPU High in creating TX_LOW log entries
1365        // The phy_params (as opposed to phy_params2) element is used for the MPDU itself. If we are waiting for a CTS and we do not
1366        // receive one, CPU_HIGH will know to ignore this element of low_tx_details (since the MPDU will not be transmitted).
1367        low_tx_details_num = (tx_frame_info->num_tx_attempts) - 1;
1368
1369        if((low_tx_details_num == 0) && (n_slots != n_slots_readback)){
1370            // For the first transmission (non-retry) of an MPDU, the number of
1371            // slots used by the backoff process is ambiguous. The n_slots we provided
1372            // to wlan_mac_tx_ctrl_A_params is only a suggestion. If the medium has been
1373            // idle for a DIFS, then there will not be a backoff. Or, if another backoff is
1374            // currently running, the MAC Config Core A will inherit that backoff. By
1375            // immediately reading back the slot count after starting the core, we can
1376            // overwrite the number of slots that we will fill into low_tx_details with
1377            // the correct value
1378            n_slots = n_slots_readback;
1379        }
1380
1381
1382        low_tx_details[low_tx_details_num].flags                        = 0;
1383        low_tx_details[low_tx_details_num].phy_params_mpdu.mcs          = tx_frame_info->params.phy.mcs;
1384        low_tx_details[low_tx_details_num].phy_params_mpdu.phy_mode     = tx_frame_info->params.phy.phy_mode;
1385        low_tx_details[low_tx_details_num].phy_params_mpdu.power        = tx_frame_info->params.phy.power;
1386        low_tx_details[low_tx_details_num].phy_params_mpdu.antenna_mode = tx_frame_info->params.phy.antenna_mode;
1387
1388        // If RTS/CTS isn't used, these fields should just be ignored
1389        low_tx_details[low_tx_details_num].phy_params_ctrl.power        = tx_frame_info->params.phy.power;
1390        low_tx_details[low_tx_details_num].phy_params_ctrl.antenna_mode = tx_frame_info->params.phy.antenna_mode;
1391
1392        low_tx_details[low_tx_details_num].chan_num    = wlan_mac_low_get_active_channel();
1393        low_tx_details[low_tx_details_num].cw          = (1 << gl_cw_exp)-1; //(2^(gl_cw_exp) - 1)
1394        low_tx_details[low_tx_details_num].ssrc        = gl_stationShortRetryCount;
1395        low_tx_details[low_tx_details_num].slrc        = gl_stationLongRetryCount;
1396        low_tx_details[low_tx_details_num].src         = short_retry_count;
1397        low_tx_details[low_tx_details_num].lrc         = long_retry_count;
1398
1399        // NOTE: the pre-Tx backoff may not occur for the initial transmission attempt. If the medium has been idle for >DIFS when
1400        // the first Tx occurs the DCF state machine will not start a backoff. The upper-level MAC should compare the num_slots value
1401        // to the time delta between the accept and start times of the first transmission to determine whether the pre-Tx backoff
1402        // actually occurred.
1403        low_tx_details[low_tx_details_num].num_slots   = n_slots;
1404
1405        // Wait for the MPDU Tx to finish
1406        do { // while(tx_status & WLAN_MAC_STATUS_MASK_TX_A_PENDING)
1407
1408            // Poll the DCF core status register
1409            mac_hw_status = wlan_mac_get_status();
1410
1411            // Fill in the timestamp if indicated by the flags, only possible after Tx PHY has started
1412            if (mac_hw_status & WLAN_MAC_STATUS_MASK_TX_PHY_ACTIVE) {
1413
1414                tx_has_started = 1;
1415
1416                if(req_timeout){
1417                    gl_waiting_for_response = 1;
1418                }
1419
1420                if ((tx_frame_info->flags) & TX_FRAME_INFO_FLAGS_FILL_TIMESTAMP) {
1421                    // Insert the TX START timestamp
1422                    *((u32*)((u8*)header + 24)) =  Xil_In32(WLAN_MAC_REG_TX_TIMESTAMP_LSB);
1423                    *((u32*)((u8*)header + 28)) =  Xil_In32(WLAN_MAC_REG_TX_TIMESTAMP_MSB);
1424                }
1425            }
1426
1427
1428
1429            // Transmission is complete
1430            if( mac_hw_status & WLAN_MAC_STATUS_MASK_TX_A_DONE ) {
1431                if(tx_wait_state == TX_WAIT_CTS) {
1432                    // This will potentially be overwritten with TX_DETAILS_RTS_MPDU should we make it that far.
1433                    low_tx_details[low_tx_details_num].tx_details_type  = TX_DETAILS_RTS_ONLY;
1434                    low_tx_details[low_tx_details_num].tx_start_timestamp_ctrl = wlan_mac_low_get_tx_start_timestamp();
1435                    low_tx_details[low_tx_details_num].tx_start_timestamp_frac_ctrl = wlan_mac_low_get_tx_start_timestamp_frac();
1436
1437                } else if ((tx_mode == TX_MODE_LONG) && (tx_wait_state == TX_WAIT_ACK)) {
1438                    // NOTE: this clause will overwrite the previous TX_DETAILS_RTS_ONLY state in the event a CTS is received.
1439                    low_tx_details[low_tx_details_num].tx_details_type  = TX_DETAILS_RTS_MPDU;
1440                    low_tx_details[low_tx_details_num].tx_start_timestamp_mpdu = wlan_mac_low_get_tx_start_timestamp();
1441                    low_tx_details[low_tx_details_num].tx_start_timestamp_frac_mpdu = wlan_mac_low_get_tx_start_timestamp_frac();
1442
1443                } else {
1444                    // This is a non-RTS/CTS-protected MPDU transmission
1445                    low_tx_details[low_tx_details_num].tx_details_type  = TX_DETAILS_MPDU;
1446                    low_tx_details[low_tx_details_num].tx_start_timestamp_mpdu = wlan_mac_low_get_tx_start_timestamp();
1447                    low_tx_details[low_tx_details_num].tx_start_timestamp_frac_mpdu = wlan_mac_low_get_tx_start_timestamp_frac();
1448                }
1449
1450
1451                // Switch on the result of the transmission attempt
1452                //  Safe to read tx_ctrl_status here - TX_A_RESULT is only valid after TX_A_DONE asserts, which just happened
1453                mac_tx_ctrl_status = wlan_mac_get_tx_ctrl_status();
1454                switch (mac_tx_ctrl_status & WLAN_MAC_TXCTRL_STATUS_MASK_TX_A_RESULT) {
1455
1456                    //---------------------------------------------------------------------
1457                    case WLAN_MAC_TXCTRL_STATUS_TX_A_RESULT_NONE:
1458                        // Transmission was immediately successful - this implies no post-Tx timeout was required,
1459                        // so the core didn't wait for any post-Tx receptions (i.e. multicast/broadcast transmission)
1460                        //
1461                        switch(tx_mode) {
1462                            case TX_MODE_SHORT:
1463                                reset_ssrc();
1464                                reset_cw();
1465                            break;
1466                            case TX_MODE_LONG:
1467                                reset_slrc();
1468                                reset_cw();
1469                            break;
1470                        }
1471
1472                        // Start a post-Tx backoff using the updated contention window
1473                        n_slots = rand_num_slots(RAND_SLOT_REASON_STANDARD_ACCESS);
1474                        wlan_mac_dcf_hw_start_backoff(n_slots);
1475                        gl_waiting_for_response = 0;
1476                        return 0;
1477                    break;
1478
1479                    //---------------------------------------------------------------------
1480                    case WLAN_MAC_TXCTRL_STATUS_TX_A_RESULT_RX_STARTED:
1481                        // Transmission ended, followed by a new reception (hopefully a CTS or ACK)
1482
1483                        // Handle the new reception
1484                        rx_status       = wlan_mac_low_poll_frame_rx();
1485                        gl_waiting_for_response = 0;
1486
1487                        gl_mpdu_pkt_buf = PKT_BUF_INVALID;
1488
1489                        // Check if the reception is an ACK addressed to this node, received with a valid checksum
1490                        if ((tx_wait_state == TX_WAIT_CTS) &&
1491                            (rx_status & POLL_MAC_STATUS_RECEIVED_PKT) &&
1492                            (rx_status & POLL_MAC_TYPE_CTS) &&
1493                            (rx_status & POLL_MAC_STATUS_GOOD) &&
1494                            (rx_status & POLL_MAC_ADDR_MATCH)) {
1495
1496                            low_tx_details[low_tx_details_num].flags |= TX_DETAILS_FLAGS_RECEIVED_RESPONSE;
1497
1498                            tx_wait_state = TX_WAIT_ACK;
1499
1500                            // We received the CTS, so we can reset our SSRC
1501                            //     NOTE: as per 9.3.3 of 802.11-2012, we do not reset our CW
1502                            //
1503                            reset_ssrc();
1504
1505                            // At this point, the MAC tx state machine has started anew to send a the MPDU itself.
1506                            // This was triggered by the frame_receive() context.  We know that the frame_receive context
1507                            // has started the transmission of the MPDU.  This ensures we are not kicked out of the
1508                            // do-while loop.
1509                            //
1510                            // NOTE: This assignment is better than re-reading wlan_mac_get_status() in the case of a short
1511                            // MPDU, where we may skip the PENDING state directly to DONE without this code context seeing it.
1512                            //
1513                            mac_hw_status |= WLAN_MAC_STATUS_MASK_TX_A_PENDING;
1514
1515                            continue;
1516
1517                        } else if ((tx_wait_state == TX_WAIT_ACK) &&
1518                                   (rx_status & POLL_MAC_STATUS_RECEIVED_PKT) &&
1519                                   (rx_status & POLL_MAC_TYPE_ACK) &&
1520                                   (rx_status & POLL_MAC_STATUS_GOOD) &&
1521                                   (rx_status & POLL_MAC_ADDR_MATCH)) {
1522
1523                                low_tx_details[low_tx_details_num].flags |= TX_DETAILS_FLAGS_RECEIVED_RESPONSE;
1524
1525                                // Update contention window
1526                                switch(tx_mode) {
1527                                    case TX_MODE_SHORT:
1528                                        reset_ssrc();
1529                                        reset_cw();
1530                                    break;
1531                                    case TX_MODE_LONG:
1532                                        reset_slrc();
1533                                        reset_cw();
1534                                    break;
1535                                }
1536
1537                                // Start a post-Tx backoff using the updated contention window
1538                                n_slots = rand_num_slots(RAND_SLOT_REASON_STANDARD_ACCESS);
1539                                wlan_mac_dcf_hw_start_backoff(n_slots);
1540                                return TX_FRAME_INFO_RESULT_SUCCESS;
1541
1542                        } else {
1543                            // Received a packet immediately after transmitting, but it wasn't the ACK we wanted
1544                            // It could have been our ACK with a bad checksum or a different packet altogether
1545                            switch(tx_wait_state) {
1546                                case TX_WAIT_ACK:
1547                                    // We were waiting for an ACK
1548                                    //   - Depending on the size of the MPDU, we will increment either the SRC or the LRC
1549                                    //
1550                                    header->frame_control_2 = (header->frame_control_2) | MAC_FRAME_CTRL2_FLAG_RETRY;
1551
1552                                    switch(tx_mode) {
1553                                        case TX_MODE_SHORT:
1554                                            increment_src(&short_retry_count);
1555                                        break;
1556                                        case TX_MODE_LONG:
1557                                            increment_lrc(&long_retry_count);
1558                                        break;
1559                                    }
1560                                break;
1561
1562                                case TX_WAIT_CTS:
1563                                    // We were waiting for a CTS but did not get it.
1564                                    //     - Increment the SRC
1565                                    //
1566                                    increment_src(&short_retry_count);
1567                                break;
1568
1569                                case TX_WAIT_NONE:
1570                                    xil_printf("Error: unexpected state");
1571                                break;
1572                            }
1573
1574                            // Start the post-Tx backoff
1575                            n_slots = rand_num_slots(RAND_SLOT_REASON_STANDARD_ACCESS);
1576                            wlan_mac_dcf_hw_start_backoff(n_slots);
1577                            // Now we evaluate the SRC and LRC to see if either has reached its maximum
1578                            //     NOTE:  Use >= here to handle unlikely case of retryLimit values changing mid-Tx
1579                            if ((short_retry_count >= gl_dot11ShortRetryLimit) ||
1580                                (long_retry_count >= gl_dot11LongRetryLimit )) {
1581                                gl_waiting_for_response = 0;
1582                                return TX_FRAME_INFO_RESULT_FAILURE;
1583                            }
1584                            if(poll_tbtt_return == BEACON_DEFERRED) {
1585                                poll_tbtt_return = poll_tbtt();
1586                            }
1587                            // Jump to next loop iteration
1588                            continue;
1589                        }
1590                    break;
1591
1592                    //---------------------------------------------------------------------
1593                    case WLAN_MAC_TXCTRL_STATUS_TX_A_RESULT_TIMEOUT:
1594                        // Tx required timeout, timeout expired with no receptions
1595                        gl_waiting_for_response = 0;
1596
1597                        gl_mpdu_pkt_buf = PKT_BUF_INVALID;
1598
1599                        switch (tx_wait_state) {
1600                            case TX_WAIT_ACK:
1601                                // We were waiting for an ACK
1602                                //     - Depending on the size of the MPDU, we will increment either the SRC or the LRC
1603                                //
1604                                header->frame_control_2 = (header->frame_control_2) | MAC_FRAME_CTRL2_FLAG_RETRY;
1605
1606                                switch(tx_mode){
1607                                    case TX_MODE_SHORT:
1608                                        increment_src(&short_retry_count);
1609                                    break;
1610                                    case TX_MODE_LONG:
1611                                        increment_lrc(&long_retry_count);
1612                                    break;
1613                                }
1614                            break;
1615
1616                            case TX_WAIT_CTS:
1617                                // We were waiting for a CTS but did not get it.
1618                                //     - Increment the SRC
1619                                increment_src(&short_retry_count);
1620                            break;
1621
1622                            case TX_WAIT_NONE:
1623                                xil_printf("Error: unexpected state");
1624                            break;
1625                        }
1626
1627                        // Start the post-Tx backoff
1628                        n_slots = rand_num_slots(RAND_SLOT_REASON_STANDARD_ACCESS);
1629                        wlan_mac_dcf_hw_start_backoff(n_slots);
1630
1631                        // Now we evaluate the SRC and LRC to see if either has reached its maximum
1632                        if ((short_retry_count == gl_dot11ShortRetryLimit) ||
1633                            (long_retry_count  == gl_dot11LongRetryLimit )) {
1634                            return TX_FRAME_INFO_RESULT_FAILURE;
1635                        }
1636                        if(poll_tbtt_return == BEACON_DEFERRED) {
1637                            poll_tbtt_return = poll_tbtt();
1638                        }
1639                        // Jump to next loop iteration
1640                        continue;
1641                    break;
1642                }
1643
1644            // else for if(mac_hw_status & WLAN_MAC_STATUS_MASK_TX_A_DONE)
1645            } else if (tx_has_started == 0) {
1646                //  This is the same MAC status check performed in the framework wlan_mac_low_poll_frame_rx()
1647                //  It is critical to check the Rx status here using the same status register read that was
1648                //  used in the Tx state checking above. Skipping this and calling wlan_mac_low_poll_frame_rx()
1649                //  directly leads to a race between the Tx status checking above and Rx status checking
1650                if (mac_hw_status & WLAN_MAC_STATUS_MASK_RX_PHY_STARTED) {
1651                    gl_waiting_for_response = 0;
1652                    rx_status = wlan_mac_low_poll_frame_rx();
1653                } else if(poll_tbtt_return != BEACON_DEFERRED) {
1654                    poll_tbtt_return = poll_tbtt();
1655                }
1656            } // END if(Tx A state machine done)
1657        } while( mac_hw_status & WLAN_MAC_STATUS_MASK_TX_A_PENDING );
1658    } // end retransmission loop
1659    gl_waiting_for_response = 0;
1660    return 0;
1661}
1662
1663
1664
1665/*****************************************************************************/
1666/**
1667 * @brief Increment Short Retry Count
1668 *
1669 * This function increments the short retry count. According to Section 9.3.3
1670 * of 802.11-2012, incrementing the short retry count also causes the
1671 * the following:
1672 *      1) An increment of the station short retry count
1673 *      2) An increase of the contention window (which is technically dependent
1674 *         on the station count incremented in the first step)
1675 *
1676 * @param   src_ptr          - Pointer to short retry count
1677 * @return  None
1678 */
1679inline void increment_src(u16* src_ptr){
1680    // Increment the Short Retry Count
1681    (*src_ptr)++;
1682
1683    gl_stationShortRetryCount = sat_add32(gl_stationShortRetryCount, 1);
1684
1685    if (gl_stationShortRetryCount == gl_dot11ShortRetryLimit) {
1686        reset_cw();
1687    } else {
1688        gl_cw_exp = min(gl_cw_exp + 1, gl_cw_exp_max);
1689    }
1690}
1691
1692
1693
1694/*****************************************************************************/
1695/**
1696 * @brief Increment Long Retry Count
1697 *
1698 * This function increments the long retry count. According to Section 9.3.3
1699 * of 802.11-2012, incrementing the long retry count also causes the
1700 * the following:
1701 *      1) An increment of the station long retry count
1702 *      2) An increase of the contention window (which is technically dependent
1703 *         on the station count incremented in the first step)
1704 *
1705 * @param   src_ptr          - Pointer to long retry count
1706 * @return  None
1707 */
1708inline void increment_lrc(u16* lrc_ptr){
1709    // Increment the Long Retry Count
1710    (*lrc_ptr)++;
1711
1712    gl_stationLongRetryCount = sat_add32(gl_stationLongRetryCount, 1);
1713
1714    if(gl_stationLongRetryCount == gl_dot11LongRetryLimit){
1715        reset_cw();
1716    } else {
1717        gl_cw_exp = min(gl_cw_exp + 1, gl_cw_exp_max);
1718    }
1719}
1720
1721
1722
1723/*****************************************************************************/
1724/**
1725 * @brief Reset Station Short Retry Count
1726 *
1727 * @param   None
1728 * @return  None
1729 *
1730 * @note    Resetting the SSRC does not necessarily indicate that the contention window should be reset.
1731 *     e.g., the reception of a valid CTS.
1732 */
1733inline void reset_ssrc(){
1734    gl_stationShortRetryCount = 0;
1735}
1736
1737
1738
1739/*****************************************************************************/
1740/**
1741 * @brief Reset Station Long Retry Count
1742 *
1743 * @param   None
1744 * @return  None
1745 */
1746inline void reset_slrc(){
1747    gl_stationLongRetryCount = 0;
1748}
1749
1750
1751
1752/*****************************************************************************/
1753/**
1754 * @brief Reset Contention Window
1755 *
1756 * @param   None
1757 * @return  None
1758 */
1759inline void reset_cw(){
1760    gl_cw_exp = gl_cw_exp_min;
1761}
1762
1763
1764
1765/*****************************************************************************/
1766/**
1767 * @brief Generate a random number in the range set by the current contention window
1768 *
1769 * When reason is RAND_SLOT_REASON_IBSS_BEACON the random draw is taken from the range
1770 * [0, 2*CWmin], used for pre-beacon backoffs in IBSS (per 802.11-2012 10.1.3.3)
1771 *
1772 * @param   reason           - Code for the random draw; must be RAND_SLOT_REASON_STANDARD_ACCESS or RAND_SLOT_REASON_IBSS_BEACON
1773 * @return  u32              - Random integer based on reason
1774 */
1775inline u32 rand_num_slots(u8 reason){
1776    // Generates a uniform random value between [0, (2^(gl_cw_exp) - 1)], where gl_cw_exp is a positive integer
1777    // This function assumed RAND_MAX = 2^31.
1778    // | gl_cw_exp |    CW       |
1779    // |     4     |  [0,   15]  |
1780    // |     5     |  [0,   31]  |
1781    // |     6     |  [0,   63]  |
1782    // |     7     |  [0,  123]  |
1783    // |     8     |  [0,  255]  |
1784    // |     9     |  [0,  511]  |
1785    // |    10     |  [0, 1023]  |
1786    //
1787    volatile u32 n_slots;
1788
1789    switch(reason) {
1790        case RAND_SLOT_REASON_STANDARD_ACCESS:
1791            n_slots = ((unsigned int)rand() >> (32 - (gl_cw_exp + 1)));
1792        break;
1793
1794        case RAND_SLOT_REASON_IBSS_BEACON:
1795            // Section 10.1.3.3 of 802.11-2012: Backoffs prior to IBSS beacons are drawn from [0, 2*CWmin]
1796            n_slots = ((unsigned int)rand() >> (32 - (gl_cw_exp_min + 1 + 1)));
1797        break;
1798    }
1799
1800    return n_slots;
1801}
1802
1803
1804
1805/*****************************************************************************/
1806/**
1807 * @brief Start a backoff
1808 *
1809 * This function will start a backoff.  If a backoff is already running, the backoff-start attempt
1810 * will be safely ignored and the function will do nothing.
1811 *
1812 * @param   num_slots        - Duration of backoff interval, in units of slots
1813 * @return  None
1814 */
1815void wlan_mac_dcf_hw_start_backoff(u16 num_slots) {
1816    // WLAN_MAC_REG_SW_BACKOFF_CTRL:
1817    //     b[15:0] : Num slots
1818    //     b[31]   : Start backoff
1819
1820    // Write num_slots and toggle start
1821    Xil_Out32(WLAN_MAC_REG_SW_BACKOFF_CTRL, (num_slots & 0xFFFF) | 0x80000000);
1822    Xil_Out32(WLAN_MAC_REG_SW_BACKOFF_CTRL, (num_slots & 0xFFFF));
1823}
1824
1825
1826
1827/*****************************************************************************/
1828/**
1829 * @brief Construct an ACK frame
1830 *
1831 * @param   pkt_buf_addr     - Address of Tx packet buffer where to construct new ACK packet
1832 * @param   address_ra       - Pointer to 6-byte MAC address of receiving node
1833 * @return  int              - Number of bytes in the frame
1834 */
1835int wlan_create_ack_frame(void* pkt_buf_addr, u8* address_ra) {
1836
1837    mac_header_80211_ACK* ack_header;
1838
1839    ack_header = (mac_header_80211_ACK*)(pkt_buf_addr);
1840
1841    ack_header->frame_control_1 = MAC_FRAME_CTRL1_SUBTYPE_ACK;
1842    ack_header->frame_control_2 = 0;
1843    ack_header->duration_id     = 0;
1844
1845    memcpy(ack_header->address_ra, address_ra, 6);
1846
1847    // Include FCS in packet size (MAC accounts for FCS, even though the PHY calculates it)
1848    return (sizeof(mac_header_80211_ACK) + WLAN_PHY_FCS_NBYTES);
1849}
1850
1851
1852
1853/*****************************************************************************/
1854/**
1855 * @brief Construct a CTS frame
1856 *
1857 * @param   pkt_buf_addr     - Address of Tx packet buffer where to construct new ACK packet
1858 * @param   address_ra       - Pointer to 6-byte MAC address of receiving node
1859 * @param   duration         - Duration of the CTS
1860 * @return  int              - Number of bytes in the frame
1861 */
1862int wlan_create_cts_frame(void* pkt_buf_addr, u8* address_ra, u16 duration) {
1863
1864    mac_header_80211_CTS* cts_header;
1865
1866    cts_header = (mac_header_80211_CTS*)(pkt_buf_addr);
1867
1868    cts_header->frame_control_1 = MAC_FRAME_CTRL1_SUBTYPE_CTS;
1869    cts_header->frame_control_2 = 0;
1870    cts_header->duration_id     = duration;
1871
1872    memcpy(cts_header->address_ra, address_ra, 6);
1873
1874    // Include FCS in packet size (MAC accounts for FCS, even though the PHY calculates it)
1875    return (sizeof(mac_header_80211_CTS) + WLAN_PHY_FCS_NBYTES);
1876}
1877
1878
1879
1880/*****************************************************************************/
1881/**
1882 * @brief Construct an RTS frame
1883 *
1884 * @param   pkt_buf_addr     - Address of Tx packet buffer where to construct new ACK packet
1885 * @param   address_ra       - Pointer to 6-byte MAC address of receiving node
1886 * @param   address_ta       - Pointer to 6-byte MAC address of transmitting node
1887 * @param   duration         - Duration of the RTS
1888 * @return  int              - Number of bytes in the frame
1889 */
1890int wlan_create_rts_frame(void* pkt_buf_addr, u8* address_ra, u8* address_ta, u16 duration) {
1891
1892    mac_header_80211_RTS* rts_header;
1893
1894    rts_header = (mac_header_80211_RTS*)(pkt_buf_addr);
1895
1896    rts_header->frame_control_1 = MAC_FRAME_CTRL1_SUBTYPE_RTS;
1897    rts_header->frame_control_2 = 0;
1898    rts_header->duration_id     = duration;
1899
1900    memcpy(rts_header->address_ra, address_ra, MAC_ADDR_LEN);
1901    memcpy(rts_header->address_ta, address_ta, MAC_ADDR_LEN);
1902
1903    // Include FCS in packet size (MAC accounts for FCS, even though the PHY calculates it)
1904    return (sizeof(mac_header_80211_RTS) + WLAN_PHY_FCS_NBYTES);
1905}
1906
1907
1908
1909/*****************************************************************************/
1910/**
1911 * @brief Process DCF Low Parameters
1912 *
1913 * This method is part of the IPC_MBOX_LOW_PARAM parameter processing in the low framework.  It
1914 * will process DCF specific low parameters.
1915 *
1916 * @param   mode             - Mode to process parameter:  IPC_REG_WRITE_MODE or IPC_REG_READ_MODE
1917 * @param   payload          - Pointer to parameter and arguments
1918 * @return  int              - Status
1919 */
1920int process_low_param(u8 mode, u32* payload){
1921
1922    switch(mode){
1923        case IPC_REG_WRITE_MODE: {
1924            switch(payload[0]){
1925
1926                //---------------------------------------------------------------------
1927                case LOW_PARAM_DCF_PHYSICAL_CS_THRESH: {
1928                    if(payload[1] < 1023){
1929                        wlan_phy_rx_set_cca_thresh(payload[1] * PHY_RX_RSSI_SUM_LEN);
1930                    } else {
1931                        wlan_phy_rx_set_cca_thresh(0xFFFF);
1932                    }
1933                }
1934                break;
1935
1936                //---------------------------------------------------------------------
1937                case LOW_PARAM_DCF_RTS_THRESH: {
1938                    gl_dot11RTSThreshold = payload[1];
1939                }
1940                break;
1941
1942                //---------------------------------------------------------------------
1943                case LOW_PARAM_DCF_DOT11SHORTRETRY: {
1944                    gl_dot11ShortRetryLimit = payload[1];
1945                }
1946                break;
1947
1948                //---------------------------------------------------------------------
1949                case LOW_PARAM_DCF_DOT11LONGRETRY: {
1950                    gl_dot11LongRetryLimit = payload[1];
1951                }
1952                break;
1953
1954                //---------------------------------------------------------------------
1955                case LOW_PARAM_DCF_CW_EXP_MIN: {
1956                    gl_cw_exp_min = payload[1];
1957                }
1958                break;
1959
1960                //---------------------------------------------------------------------
1961                case LOW_PARAM_DCF_CW_EXP_MAX: {
1962                    gl_cw_exp_max = payload[1];
1963                }
1964                break;
1965
1966                //---------------------------------------------------------------------
1967                default: {
1968                    xil_printf("Unknown param 0x%08x\n", payload[0]);
1969                }
1970                break;
1971            }
1972        }
1973        break;
1974
1975        case IPC_REG_READ_MODE: {
1976            // Not supported.  See comment in wlan_mac_low.c for IPC_REG_READ_MODE mode.
1977        }
1978        break;
1979
1980        default: {
1981            xil_printf("Unknown mode 0x%08x\n", mode);
1982        }
1983        break;
1984    }
1985
1986    return 0;
1987}
Note: See TracBrowser for help on using the repository browser.