staging: csr: netdev.c: Clean up KERNEL_VERSION checks: 2.6.29
[firefly-linux-kernel-4.4.55.git] / drivers / staging / csr / netdev.c
1 /*
2  * ---------------------------------------------------------------------------
3  * FILE:     netdev.c
4  *
5  * PURPOSE:
6  *      This file provides the upper edge interface to the linux netdevice
7  *      and wireless extensions.
8  *      It is part of the porting exercise.
9  *
10  * Copyright (C) 2005-2010 by Cambridge Silicon Radio Ltd.
11  *
12  * Refer to LICENSE.txt included with this source code for details on
13  * the license terms.
14  *
15  * ---------------------------------------------------------------------------
16  */
17
18 /*
19  * Porting Notes:
20  * This file implements the data plane of the UniFi linux driver.
21  *
22  * All the Tx packets are passed to the HIP core lib, using the
23  * unifi_send_signal() API. For EAPOL packets use the MLME-EAPOL.req
24  * signal, for all other use the MLME-UNITDATA.req. The unifi_send_signal()
25  * expects the wire-formatted (packed) signal. For convenience, in the OS
26  * layer we only use the native (unpacked) signal structures. The HIP core lib
27  * provides the write_pack() helper function to convert to the packed signal.
28  * The packet is stored in the bulk data of the signal. We do not need to
29  * allocate new memory to store the packet, because unifi_net_data_malloc()
30  * is implemented to return a skb, which is the format of packet in Linux.
31  * The HIP core lib frees the bulk data buffers, so we do not need to do
32  * this in the OS layer.
33  *
34  * All the Rx packets are MLME-UNITDATA.ind signals, passed by the HIP core lib
35  * in unifi_receive_event(). We do not need to allocate an skb and copy the
36  * received packet because the HIP core lib has stored in memory allocated by
37  * unifi_net_data_malloc(). Also, we can perform the 802.11 to Ethernet
38  * translation in-place because we allocate the extra memory allocated in
39  * unifi_net_data_malloc().
40  *
41  * If possible, the porting exercise should appropriately implement
42  * unifi_net_data_malloc() and unifi_net_data_free() to save copies between
43  * network and driver buffers.
44  */
45
46 #include <linux/types.h>
47 #include <linux/etherdevice.h>
48 #include <linux/mutex.h>
49 #include <linux/semaphore.h>
50 #include <linux/version.h>
51 #include <linux/vmalloc.h>
52 #include "csr_wifi_hip_unifi.h"
53 #include "csr_wifi_hip_conversions.h"
54 #include "unifi_priv.h"
55 #include <net/pkt_sched.h>
56
57
58 /* ALLOW_Q_PAUSE: Pre 2.6.28 kernels do not support multiple driver queues (required for QoS).
59  * In order to support QoS in these kernels, multiple queues are implemented in the driver. But since
60  * there is only a single queue in the kernel (leading to multiple queues in the driver) there is no possibility
61  * of stopping a particular queue in the kernel. Stopping the single kernel queue leads to undesirable starvation
62  * of driver queues. One of the proposals is to not stop the kernel queue but to prevent dequeuing from the
63  * 'stopped' driver queue. Allow q pause is an experimental implementation of this scheme for pre 2.6.28 kernels.
64  * When NOT defined, queues are paused locally in the driver and packets are dequeued for transmission only from the
65  * unpaused queues. When Allow q pause is defined the kernel queue is stopped whenever any driver queue is paused.
66  */
67 #define ALLOW_Q_PAUSE
68
69 #ifdef UNIFI_NET_NAME
70 #define UF_ALLOC_NETDEV(_dev, _size, _name, _setup, _num_of_queues)     \
71     do {                                                                \
72         static char name[8];                                           \
73         sprintf(name, "%s%s", UNIFI_NET_NAME, _name);                   \
74         _dev = alloc_netdev_mq(_size, name, _setup, _num_of_queues);    \
75     } while (0);
76 #else
77 #define UF_ALLOC_NETDEV(_dev, _size, _name, _setup, _num_of_queues)     \
78     do {                                                                \
79         _dev = alloc_etherdev_mq(_size, _num_of_queues);                \
80     } while (0);
81 #endif /* UNIFI_NET_NAME */
82
83
84 /* Wext handler is suported only if CSR_SUPPORT_WEXT is defined */
85 #ifdef CSR_SUPPORT_WEXT
86 extern struct iw_handler_def unifi_iw_handler_def;
87 #endif /* CSR_SUPPORT_WEXT */
88 static void check_ba_frame_age_timeout( unifi_priv_t *priv,
89                                             netInterface_priv_t *interfacePriv,
90                                             ba_session_rx_struct *ba_session);
91 static void process_ba_frame(unifi_priv_t *priv,
92                              netInterface_priv_t *interfacePriv,
93                              ba_session_rx_struct *ba_session,
94                              frame_desc_struct *frame_desc);
95 static void process_ba_complete(unifi_priv_t *priv, netInterface_priv_t *interfacePriv);
96 static void process_ma_packet_error_ind(unifi_priv_t *priv, CSR_SIGNAL *signal, bulk_data_param_t *bulkdata);
97 static void process_amsdu(unifi_priv_t *priv, CSR_SIGNAL *signal, bulk_data_param_t *bulkdata);
98 static int uf_net_open(struct net_device *dev);
99 static int uf_net_ioctl(struct net_device *dev, struct ifreq *rq, int cmd);
100 static int uf_net_stop(struct net_device *dev);
101 static struct net_device_stats *uf_net_get_stats(struct net_device *dev);
102 static u16 uf_net_select_queue(struct net_device *dev, struct sk_buff *skb);
103 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,32)
104 static netdev_tx_t uf_net_xmit(struct sk_buff *skb, struct net_device *dev);
105 #else
106 static int uf_net_xmit(struct sk_buff *skb, struct net_device *dev);
107 #ifndef NETDEV_TX_OK
108 #define NETDEV_TX_OK        0
109 #endif
110 #ifndef NETDEV_TX_BUSY
111 #define NETDEV_TX_BUSY      1
112 #endif
113 #endif
114 static void uf_set_multicast_list(struct net_device *dev);
115
116
117 typedef int (*tx_signal_handler)(unifi_priv_t *priv, struct sk_buff *skb, const struct ethhdr *ehdr, CSR_PRIORITY priority);
118
119 #ifdef CONFIG_NET_SCHED
120 /*
121  * Queueing Discipline Interface
122  * Only used if kernel is configured with CONFIG_NET_SCHED
123  */
124
125 /*
126  * The driver uses the qdisc interface to buffer and control all
127  * outgoing traffic. We create a root qdisc, register our qdisc operations
128  * and later we create two subsiduary pfifo queues for the uncontrolled
129  * and controlled ports.
130  *
131  * The network stack delivers all outgoing packets in our enqueue handler.
132  * There, we classify the packet and decide whether to store it or drop it
133  * (if the controlled port state is set to "discard").
134  * If the packet is enqueued, the network stack call our dequeue handler.
135  * There, we decide whether we can send the packet, delay it or drop it
136  * (the controlled port configuration might have changed meanwhile).
137  * If a packet is dequeued, then the network stack calls our hard_start_xmit
138  * handler where finally we send the packet.
139  *
140  * If the hard_start_xmit handler fails to send the packet, we return
141  * NETDEV_TX_BUSY and the network stack call our requeue handler where
142  * we put the packet back in the same queue in came from.
143  *
144  */
145
146 struct uf_sched_data
147 {
148     /* Traffic Classifier TBD */
149     struct tcf_proto *filter_list;
150     /* Our two queues */
151     struct Qdisc *queues[UNIFI_TRAFFIC_Q_MAX];
152 };
153
154 struct uf_tx_packet_data {
155     /* Queue the packet is stored in */
156     unifi_TrafficQueue queue;
157     /* QoS Priority determined when enqueing packet */
158     CSR_PRIORITY priority;
159     /* Debug */
160     unsigned long host_tag;
161 };
162
163 #endif /* CONFIG_NET_SCHED */
164
165 static const struct net_device_ops uf_netdev_ops =
166 {
167     .ndo_open = uf_net_open,
168     .ndo_stop = uf_net_stop,
169     .ndo_start_xmit = uf_net_xmit,
170     .ndo_do_ioctl = uf_net_ioctl,
171     .ndo_get_stats = uf_net_get_stats, /* called by /proc/net/dev */
172     .ndo_set_rx_mode = uf_set_multicast_list,
173     .ndo_select_queue = uf_net_select_queue,
174 };
175
176 static u8 oui_rfc1042[P80211_OUI_LEN] = { 0x00, 0x00, 0x00 };
177 static u8 oui_8021h[P80211_OUI_LEN]   = { 0x00, 0x00, 0xf8 };
178
179
180 /* Callback for event logging to blocking clients */
181 static void netdev_mlme_event_handler(ul_client_t  *client,
182                                       const u8 *sig_packed, int sig_len,
183                                       const bulk_data_param_t *bulkdata,
184                                       int dir);
185
186 #ifdef CSR_SUPPORT_WEXT
187 /* Declare netdev_notifier block which will contain the state change
188  * handler callback function
189  */
190 static struct notifier_block uf_netdev_notifier;
191 #endif
192
193 /*
194  * ---------------------------------------------------------------------------
195  *  uf_alloc_netdevice
196  *
197  *      Allocate memory for the net_device and device private structs
198  *      for this interface.
199  *      Fill in the fields, but don't register the interface yet.
200  *      We need to configure the UniFi first.
201  *
202  *  Arguments:
203  *      sdio_dev        Pointer to SDIO context handle to use for all
204  *                      SDIO ops.
205  *      bus_id          A small number indicating the SDIO card position on the
206  *                      bus. Typically this is the slot number, e.g. 0, 1 etc.
207  *                      Valid values are 0 to MAX_UNIFI_DEVS-1.
208  *
209  *  Returns:
210  *      Pointer to device private struct.
211  *
212  *  Notes:
213  *      The net_device and device private structs are allocated together
214  *      and should be freed by freeing the net_device pointer.
215  * ---------------------------------------------------------------------------
216  */
217 unifi_priv_t *
218 uf_alloc_netdevice(CsrSdioFunction *sdio_dev, int bus_id)
219 {
220     struct net_device *dev;
221     unifi_priv_t *priv;
222     netInterface_priv_t *interfacePriv;
223 #ifdef CSR_SUPPORT_WEXT
224     int rc;
225 #endif
226     unsigned char i; /* loop index */
227
228     /*
229      * Allocate netdevice struct, assign name template and
230      * setup as an ethernet device.
231      * The net_device and private structs are zeroed. Ether_setup() then
232      * sets up ethernet handlers and values.
233      * The RedHat 9 redhat-config-network tool doesn't recognise wlan* devices,
234      * so use "eth*" (like other wireless extns drivers).
235      */
236     UF_ALLOC_NETDEV(dev, sizeof(unifi_priv_t)+sizeof(netInterface_priv_t), "%d", ether_setup, UNIFI_TRAFFIC_Q_MAX);
237
238     if (dev == NULL) {
239         return NULL;
240     }
241
242     /* Set up back pointer from priv to netdev */
243     interfacePriv = (netInterface_priv_t *)netdev_priv(dev);
244     priv = (unifi_priv_t *)(interfacePriv + 1);
245     interfacePriv->privPtr = priv;
246     interfacePriv->InterfaceTag = 0;
247
248
249     /* Initialize all supported netdev interface to be NULL */
250     for(i=0; i<CSR_WIFI_NUM_INTERFACES; i++) {
251         priv->netdev[i] = NULL;
252         priv->interfacePriv[i] = NULL;
253     }
254     priv->netdev[0] = dev;
255     priv->interfacePriv[0] = interfacePriv;
256
257     /* Setup / override net_device fields */
258     dev->netdev_ops = &uf_netdev_ops;
259
260 #ifdef CSR_SUPPORT_WEXT
261     dev->wireless_handlers = &unifi_iw_handler_def;
262 #if IW_HANDLER_VERSION < 6
263     dev->get_wireless_stats = unifi_get_wireless_stats;
264 #endif /* IW_HANDLER_VERSION */
265 #endif /* CSR_SUPPORT_WEXT */
266
267     /* This gives us enough headroom to add the 802.11 header */
268     dev->needed_headroom = 32;
269
270     /* Use bus_id as instance number */
271     priv->instance = bus_id;
272     /* Store SDIO pointer to pass in the core */
273     priv->sdio = sdio_dev;
274
275     sdio_dev->driverData = (void*)priv;
276     /* Consider UniFi to be uninitialised */
277     priv->init_progress = UNIFI_INIT_NONE;
278
279     priv->prev_queue = 0;
280
281     /*
282      * Initialise the clients structure array.
283      * We do not need protection around ul_init_clients() because
284      * the character device can not be used until uf_alloc_netdevice()
285      * returns and Unifi_instances[bus_id]=priv is set, since unifi_open()
286      * will return -ENODEV.
287      */
288     ul_init_clients(priv);
289
290     /*
291      * Register a new ul client to send the multicast list signals.
292      * Note: priv->instance must be set before calling this.
293      */
294     priv->netdev_client = ul_register_client(priv,
295             0,
296             netdev_mlme_event_handler);
297     if (priv->netdev_client == NULL) {
298         unifi_error(priv,
299                 "Failed to register a unifi client for background netdev processing\n");
300         free_netdev(priv->netdev[0]);
301         return NULL;
302     }
303     unifi_trace(priv, UDBG2, "Netdev %p client (id:%d s:0x%X) is registered\n",
304             dev, priv->netdev_client->client_id, priv->netdev_client->sender_id);
305
306     priv->sta_wmm_capabilities = 0;
307
308 #if (defined(CSR_WIFI_SECURITY_WAPI_ENABLE) && defined(CSR_SUPPORT_SME))
309     priv->wapi_multicast_filter = 0;
310     priv->wapi_unicast_filter = 0;
311     priv->wapi_unicast_queued_pkt_filter = 0;
312 #ifdef CSR_WIFI_SECURITY_WAPI_QOSCTRL_MIC_WORKAROUND
313     priv->isWapiConnection = FALSE;
314 #endif
315 #endif
316
317     /* Enable all queues by default */
318     interfacePriv->queueEnabled[0] = 1;
319     interfacePriv->queueEnabled[1] = 1;
320     interfacePriv->queueEnabled[2] = 1;
321     interfacePriv->queueEnabled[3] = 1;
322
323 #ifdef CSR_SUPPORT_SME
324     priv->allPeerDozing = 0;
325 #endif
326     /*
327      * Initialise the OS private struct.
328      */
329     /*
330      * Instead of deciding in advance to use 11bg or 11a, we could do a more
331      * clever scan on both radios.
332      */
333     if (use_5g) {
334         priv->if_index = CSR_INDEX_5G;
335         unifi_info(priv, "Using the 802.11a radio\n");
336     } else {
337         priv->if_index = CSR_INDEX_2G4;
338     }
339
340     /* Initialise bh thread structure */
341     priv->bh_thread.thread_task = NULL;
342     priv->bh_thread.block_thread = 1;
343     init_waitqueue_head(&priv->bh_thread.wakeup_q);
344     priv->bh_thread.wakeup_flag = 0;
345     sprintf(priv->bh_thread.name, "uf_bh_thread");
346
347     /* reset the connected state for the interface */
348     interfacePriv->connected = UnifiConnectedUnknown;  /* -1 unknown, 0 no, 1 yes */
349
350 #ifdef USE_DRIVER_LOCK
351 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 37)
352     sema_init(&priv->lock, 1);
353 #else
354     init_MUTEX(&priv->lock);
355 #endif
356 #endif /* USE_DRIVER_LOCK */
357
358     spin_lock_init(&priv->send_signal_lock);
359
360     spin_lock_init(&priv->m4_lock);
361 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 37)
362     sema_init(&priv->ba_mutex, 1);
363 #else
364     init_MUTEX(&priv->ba_mutex);
365 #endif
366
367 #if (defined(CSR_WIFI_SECURITY_WAPI_ENABLE) && defined(CSR_WIFI_SECURITY_WAPI_SW_ENCRYPTION))
368     spin_lock_init(&priv->wapi_lock);
369 #endif
370
371 #ifdef CSR_SUPPORT_SME
372     spin_lock_init(&priv->staRecord_lock);
373     spin_lock_init(&priv->tx_q_lock);
374 #endif
375
376     /* Create the Traffic Analysis workqueue */
377     priv->unifi_workqueue = create_singlethread_workqueue("unifi_workq");
378     if (priv->unifi_workqueue == NULL) {
379         /* Deregister priv->netdev_client */
380         ul_deregister_client(priv->netdev_client);
381         free_netdev(priv->netdev[0]);
382         return NULL;
383     }
384
385 #ifdef CSR_SUPPORT_SME
386     /* Create the Multicast Addresses list work structure */
387     INIT_WORK(&priv->multicast_list_task, uf_multicast_list_wq);
388
389     /* Create m4 buffering work structure */
390     INIT_WORK(&interfacePriv->send_m4_ready_task, uf_send_m4_ready_wq);
391
392 #if (defined(CSR_WIFI_SECURITY_WAPI_ENABLE) && defined(CSR_WIFI_SECURITY_WAPI_SW_ENCRYPTION))
393     /* Create work structure to buffer the WAPI data packets to be sent to SME for encryption */
394     INIT_WORK(&interfacePriv->send_pkt_to_encrypt, uf_send_pkt_to_encrypt);
395 #endif
396 #endif
397
398     priv->ref_count = 1;
399
400     priv->amp_client = NULL;
401     priv->coredump_mode = 0;
402     priv->ptest_mode = 0;
403     priv->wol_suspend = FALSE;
404     INIT_LIST_HEAD(&interfacePriv->rx_uncontrolled_list);
405     INIT_LIST_HEAD(&interfacePriv->rx_controlled_list);
406     sema_init(&priv->rx_q_sem, 1);
407
408 #ifdef CSR_SUPPORT_WEXT
409     interfacePriv->netdev_callback_registered = FALSE;
410     interfacePriv->wait_netdev_change = FALSE;
411     /* Register callback for netdevice state changes */
412     if ((rc = register_netdevice_notifier(&uf_netdev_notifier)) == 0) {
413         interfacePriv->netdev_callback_registered = TRUE;
414     }
415     else {
416         unifi_warning(priv, "Failed to register netdevice notifier : %d %p\n", rc, dev);
417     }
418 #endif /* CSR_SUPPORT_WEXT */
419
420 #ifdef CSR_WIFI_SPLIT_PATCH
421     /* set it to some invalid value */
422     priv->pending_mode_set.common.destination = 0xaaaa;
423 #endif
424
425     return priv;
426 } /* uf_alloc_netdevice() */
427
428 /*
429  *---------------------------------------------------------------------------
430  *  uf_alloc_netdevice_for_other_interfaces
431  *
432  *      Allocate memory for the net_device and device private structs
433  *      for this interface.
434  *      Fill in the fields, but don't register the interface yet.
435  *      We need to configure the UniFi first.
436  *
437  *  Arguments:
438  *      interfaceTag   Interface number.
439  *      sdio_dev        Pointer to SDIO context handle to use for all
440  *                      SDIO ops.
441  *      bus_id          A small number indicating the SDIO card position on the
442  *                      bus. Typically this is the slot number, e.g. 0, 1 etc.
443  *                      Valid values are 0 to MAX_UNIFI_DEVS-1.
444  *
445  *  Returns:
446  *      Pointer to device private struct.
447  *
448  *  Notes:
449  *      The device private structure contains the interfaceTag and pointer to the unifi_priv
450  *      structure created allocated by net_device od interface0.
451  *      The net_device and device private structs are allocated together
452  *      and should be freed by freeing the net_device pointer.
453  * ---------------------------------------------------------------------------
454  */
455 u8
456 uf_alloc_netdevice_for_other_interfaces(unifi_priv_t *priv, u16 interfaceTag)
457 {
458     struct net_device *dev;
459     netInterface_priv_t *interfacePriv;
460
461     /*
462      * Allocate netdevice struct, assign name template and
463      * setup as an ethernet device.
464      * The net_device and private structs are zeroed. Ether_setup() then
465      * sets up ethernet handlers and values.
466      * The RedHat 9 redhat-config-network tool doesn't recognise wlan* devices,
467      * so use "eth*" (like other wireless extns drivers).
468      */
469     UF_ALLOC_NETDEV(dev, sizeof(netInterface_priv_t), "%d", ether_setup, 1);
470     if (dev == NULL) {
471         return FALSE;
472     }
473
474     if (interfaceTag >= CSR_WIFI_NUM_INTERFACES) {
475         unifi_error(priv, "uf_alloc_netdevice_for_other_interfaces bad interfaceTag\n");
476         return FALSE;
477     }
478
479     /* Set up back pointer from priv to netdev */
480     interfacePriv = (netInterface_priv_t *)netdev_priv(dev);
481     interfacePriv->privPtr = priv;
482     interfacePriv->InterfaceTag = interfaceTag;
483     priv->netdev[interfaceTag] = dev;
484     priv->interfacePriv[interfacePriv->InterfaceTag] = interfacePriv;
485
486     /* reset the connected state for the interface */
487     interfacePriv->connected = UnifiConnectedUnknown;  /* -1 unknown, 0 no, 1 yes */
488     INIT_LIST_HEAD(&interfacePriv->rx_uncontrolled_list);
489     INIT_LIST_HEAD(&interfacePriv->rx_controlled_list);
490
491     /* Setup / override net_device fields */
492     dev->netdev_ops = &uf_netdev_ops;
493
494 #ifdef CSR_SUPPORT_WEXT
495     dev->wireless_handlers = &unifi_iw_handler_def;
496 #if IW_HANDLER_VERSION < 6
497     dev->get_wireless_stats = unifi_get_wireless_stats;
498 #endif /* IW_HANDLER_VERSION */
499 #endif /* CSR_SUPPORT_WEXT */
500     return TRUE;
501 } /* uf_alloc_netdevice() */
502
503
504
505 /*
506  * ---------------------------------------------------------------------------
507  *  uf_free_netdevice
508  *
509  *      Unregister the network device and free the memory allocated for it.
510  *      NB This includes the memory for the priv struct.
511  *
512  *  Arguments:
513  *      priv            Device private pointer.
514  *
515  *  Returns:
516  *      None.
517  * ---------------------------------------------------------------------------
518  */
519 int
520 uf_free_netdevice(unifi_priv_t *priv)
521 {
522     int i;
523     unsigned long flags;
524
525     func_enter();
526
527     unifi_trace(priv, UDBG1, "uf_free_netdevice\n");
528
529     if (!priv) {
530         return -EINVAL;
531     }
532
533     /*
534      * Free any buffers used for holding firmware
535      */
536     uf_release_firmware_files(priv);
537
538 #if (defined CSR_SUPPORT_SME) && (defined CSR_SUPPORT_WEXT)
539     if (priv->connection_config.mlmeAssociateReqInformationElements) {
540         kfree(priv->connection_config.mlmeAssociateReqInformationElements);
541     }
542     priv->connection_config.mlmeAssociateReqInformationElements = NULL;
543     priv->connection_config.mlmeAssociateReqInformationElementsLength = 0;
544
545     if (priv->mib_data.length) {
546         vfree(priv->mib_data.data);
547     }
548     priv->mib_data.data = NULL;
549     priv->mib_data.length = 0;
550
551 #endif /* CSR_SUPPORT_SME && CSR_SUPPORT_WEXT*/
552
553     /* Free any bulkdata buffers allocated for M4 caching */
554     spin_lock_irqsave(&priv->m4_lock, flags);
555     for (i = 0; i < CSR_WIFI_NUM_INTERFACES; i++) {
556         netInterface_priv_t *interfacePriv = priv->interfacePriv[i];
557         if (interfacePriv->m4_bulk_data.data_length > 0) {
558             unifi_trace(priv, UDBG5, "uf_free_netdevice: free M4 bulkdata %d\n", i);
559             unifi_net_data_free(priv, &interfacePriv->m4_bulk_data);
560         }
561     }
562     spin_unlock_irqrestore(&priv->m4_lock, flags);
563
564 #if (defined(CSR_WIFI_SECURITY_WAPI_ENABLE) && defined(CSR_WIFI_SECURITY_WAPI_SW_ENCRYPTION))
565     /* Free any bulkdata buffers allocated for M4 caching */
566     spin_lock_irqsave(&priv->wapi_lock, flags);
567     for (i = 0; i < CSR_WIFI_NUM_INTERFACES; i++) {
568         netInterface_priv_t *interfacePriv = priv->interfacePriv[i];
569         if (interfacePriv->wapi_unicast_bulk_data.data_length > 0) {
570             unifi_trace(priv, UDBG5, "uf_free_netdevice: free WAPI PKT bulk data %d\n", i);
571             unifi_net_data_free(priv, &interfacePriv->wapi_unicast_bulk_data);
572         }
573     }
574     spin_unlock_irqrestore(&priv->wapi_lock, flags);
575 #endif
576
577 #ifdef CSR_SUPPORT_WEXT
578     /* Unregister callback for netdevice state changes */
579     unregister_netdevice_notifier(&uf_netdev_notifier);
580 #endif /* CSR_SUPPORT_WEXT */
581
582 #ifdef CSR_SUPPORT_SME
583     /* Cancel work items and destroy the workqueue */
584     cancel_work_sync(&priv->multicast_list_task);
585 #endif
586 /* Destroy the workqueues. */
587     flush_workqueue(priv->unifi_workqueue);
588     destroy_workqueue(priv->unifi_workqueue);
589
590     /* Free up netdev in reverse order: priv is allocated with netdev[0].
591      * So, netdev[0] should be freed after all other netdevs are freed up
592      */
593     for (i=CSR_WIFI_NUM_INTERFACES-1; i>=0; i--) {
594         /*Free the netdev struct and priv, which are all one lump*/
595         if (priv->netdev[i]) {
596             unifi_error(priv, "uf_free_netdevice: netdev %d %p\n", i, priv->netdev[i]);
597             free_netdev(priv->netdev[i]);
598         }
599     }
600
601     func_exit();
602     return 0;
603 } /* uf_free_netdevice() */
604
605
606 /*
607  * ---------------------------------------------------------------------------
608  *  uf_net_open
609  *
610  *      Called when userland does "ifconfig wlan0 up".
611  *
612  *  Arguments:
613  *      dev             Device pointer.
614  *
615  *  Returns:
616  *      None.
617  * ---------------------------------------------------------------------------
618  */
619 static int
620 uf_net_open(struct net_device *dev)
621 {
622     netInterface_priv_t *interfacePriv = (netInterface_priv_t *)netdev_priv(dev);
623     unifi_priv_t *priv = interfacePriv->privPtr;
624
625     func_enter();
626
627     /* If we haven't finished UniFi initialisation, we can't start */
628     if (priv->init_progress != UNIFI_INIT_COMPLETED) {
629         unifi_warning(priv, "%s: unifi not ready, failing net_open\n", __FUNCTION__);
630         return -EINVAL;
631     }
632
633 #if (defined CSR_NATIVE_LINUX) && (defined UNIFI_SNIFF_ARPHRD) && defined(CSR_SUPPORT_WEXT)
634     /*
635      * To sniff, the user must do "iwconfig mode monitor", which sets
636      * priv->wext_conf.mode to IW_MODE_MONITOR.
637      * Then he/she must do "ifconfig ethn up", which calls this fn.
638      * There is no point in starting the sniff with SNIFFJOIN until
639      * this point.
640      */
641     if (priv->wext_conf.mode == IW_MODE_MONITOR) {
642         int err;
643         err = uf_start_sniff(priv);
644         if (err) {
645             return err;
646         }
647         netif_carrier_on(dev);
648     }
649 #endif
650
651 #ifdef CSR_SUPPORT_WEXT
652     if (interfacePriv->wait_netdev_change) {
653         unifi_trace(priv, UDBG1, "%s: Waiting for NETDEV_CHANGE, assume connected\n",
654                     __FUNCTION__);
655         interfacePriv->connected = UnifiConnected;
656         interfacePriv->wait_netdev_change = FALSE;
657     }
658 #endif
659
660     UF_NETIF_TX_START_ALL_QUEUES(dev);
661
662     func_exit();
663     return 0;
664 } /* uf_net_open() */
665
666
667 static int
668 uf_net_stop(struct net_device *dev)
669 {
670 #if defined(CSR_NATIVE_LINUX) && defined(UNIFI_SNIFF_ARPHRD) && defined(CSR_SUPPORT_WEXT)
671     netInterface_priv_t *interfacePriv = (netInterface_priv_t*)netdev_priv(dev);
672     unifi_priv_t *priv = interfacePriv->privPtr;
673
674     func_enter();
675
676     /* Stop sniffing if in Monitor mode */
677     if (priv->wext_conf.mode == IW_MODE_MONITOR) {
678         if (priv->card) {
679             int err;
680             err = unifi_reset_state(priv, dev->dev_addr, 1);
681             if (err) {
682                 return err;
683             }
684         }
685     }
686 #else
687     func_enter();
688 #endif
689
690     UF_NETIF_TX_STOP_ALL_QUEUES(dev);
691
692     func_exit();
693     return 0;
694 } /* uf_net_stop() */
695
696
697 /* This is called after the WE handlers */
698 static int
699 uf_net_ioctl(struct net_device *dev, struct ifreq *rq, int cmd)
700 {
701     int rc;
702
703     rc = -EOPNOTSUPP;
704
705     return rc;
706 } /* uf_net_ioctl() */
707
708
709
710 static struct net_device_stats *
711 uf_net_get_stats(struct net_device *dev)
712 {
713     netInterface_priv_t *interfacePriv = (netInterface_priv_t *)netdev_priv(dev);
714
715     return &interfacePriv->stats;
716 } /* uf_net_get_stats() */
717
718 static CSR_PRIORITY uf_get_packet_priority(unifi_priv_t *priv, netInterface_priv_t *interfacePriv, struct sk_buff *skb, const int proto)
719 {
720     CSR_PRIORITY priority = CSR_CONTENTION;
721
722     func_enter();
723     priority = (CSR_PRIORITY) (skb->priority >> 5);
724
725     if (priority == CSR_QOS_UP0) { /* 0 */
726
727         unifi_trace(priv, UDBG5, "uf_get_packet_priority: proto = 0x%.4X\n", proto);
728
729         switch (proto) {
730             case 0x0800:        /* IPv4 */
731             case 0x814C:        /* SNMP */
732             case 0x880C:        /* GSMP */
733                 priority = (CSR_PRIORITY) (skb->data[1 + ETH_HLEN] >> 5);
734                 break;
735
736             case 0x8100:        /* VLAN */
737                 priority = (CSR_PRIORITY) (skb->data[0 + ETH_HLEN] >> 5);
738                 break;
739
740             case 0x86DD:        /* IPv6 */
741                 priority = (CSR_PRIORITY) ((skb->data[0 + ETH_HLEN] & 0x0E) >> 1);
742                 break;
743
744             default:
745                 priority = CSR_QOS_UP0;
746                 break;
747         }
748     }
749
750     /* Check if we are allowed to transmit on this AC. Because of ACM we may have to downgrade to a lower
751      * priority */
752     if (interfacePriv->interfaceMode == CSR_WIFI_ROUTER_CTRL_MODE_STA ||
753         interfacePriv->interfaceMode == CSR_WIFI_ROUTER_CTRL_MODE_P2PCLI) {
754         unifi_TrafficQueue queue;
755
756         /* Keep trying lower priorities until we find a queue
757          * Priority to queue mapping is 1,2 - BK, 0,3 - BE, 4,5 - VI, 6,7 - VO */
758         queue = unifi_frame_priority_to_queue(priority);
759
760         while (queue > UNIFI_TRAFFIC_Q_BK && !interfacePriv->queueEnabled[queue]) {
761             queue--;
762             priority = unifi_get_default_downgrade_priority(queue);
763         }
764     }
765
766     unifi_trace(priv, UDBG5, "Packet priority = %d\n", priority);
767
768     func_exit();
769     return priority;
770 }
771
772 /*
773  */
774 /*
775  * ---------------------------------------------------------------------------
776  *  get_packet_priority
777  *
778  *  Arguments:
779  *      priv             private data area of functional driver
780  *      skb              socket buffer
781  *      ehdr             ethernet header to fetch protocol
782  *      interfacePriv    For accessing station record database
783  *
784  *
785  *  Returns:
786  *      CSR_PRIORITY.
787  * ---------------------------------------------------------------------------
788  */
789 CSR_PRIORITY
790 get_packet_priority(unifi_priv_t *priv, struct sk_buff *skb, const struct ethhdr *ehdr, netInterface_priv_t *interfacePriv)
791 {
792     CSR_PRIORITY priority = CSR_CONTENTION;
793     const int proto = ntohs(ehdr->h_proto);
794
795     u8 interfaceMode = interfacePriv->interfaceMode;
796
797     func_enter();
798
799     /* Priority Mapping for all the Modes */
800     switch(interfaceMode)
801     {
802         case CSR_WIFI_ROUTER_CTRL_MODE_STA:
803         case CSR_WIFI_ROUTER_CTRL_MODE_P2PCLI:
804             unifi_trace(priv, UDBG4, "mode is STA \n");
805             if ((priv->sta_wmm_capabilities & QOS_CAPABILITY_WMM_ENABLED) == 1) {
806                 priority = uf_get_packet_priority(priv, interfacePriv, skb, proto);
807             } else {
808                 priority = CSR_CONTENTION;
809             }
810             break;
811 #ifdef CSR_SUPPORT_SME
812         case CSR_WIFI_ROUTER_CTRL_MODE_AP:
813         case CSR_WIFI_ROUTER_CTRL_MODE_P2PGO:
814         case CSR_WIFI_ROUTER_CTRL_MODE_IBSS:
815             {
816                 CsrWifiRouterCtrlStaInfo_t * dstStaInfo =
817                     CsrWifiRouterCtrlGetStationRecordFromPeerMacAddress(priv,ehdr->h_dest, interfacePriv->InterfaceTag);
818                 unifi_trace(priv, UDBG4, "mode is AP \n");
819                 if (!(ehdr->h_dest[0] & 0x01) && dstStaInfo && dstStaInfo->wmmOrQosEnabled) {
820                     /* If packet is not Broadcast/multicast */
821                     priority = uf_get_packet_priority(priv, interfacePriv, skb, proto);
822                 } else {
823                     /* Since packet destination is not QSTA, set priority to CSR_CONTENTION */
824                     unifi_trace(priv, UDBG4, "Destination is not QSTA or BroadCast/Multicast\n");
825                     priority = CSR_CONTENTION;
826                 }
827             }
828             break;
829 #endif
830         default:
831             unifi_trace(priv, UDBG3, " mode unknown in %s func, mode=%x\n", __FUNCTION__, interfaceMode);
832     }
833     unifi_trace(priv, UDBG5, "priority = %x\n", priority);
834
835     func_exit();
836     return priority;
837 }
838
839 /*
840  * ---------------------------------------------------------------------------
841  *  uf_net_select_queue
842  *
843  *      Called by the kernel to select which queue to put the packet in
844  *
845  *  Arguments:
846  *      dev             Device pointer
847  *      skb             Packet
848  *
849  *  Returns:
850  *      Queue index
851  * ---------------------------------------------------------------------------
852  */
853 static u16
854 uf_net_select_queue(struct net_device *dev, struct sk_buff *skb)
855 {
856     netInterface_priv_t *interfacePriv = (netInterface_priv_t *)netdev_priv(dev);
857     unifi_priv_t *priv = (unifi_priv_t *)interfacePriv->privPtr;
858     struct ethhdr ehdr;
859     unifi_TrafficQueue queue;
860     int proto;
861     CSR_PRIORITY priority;
862
863     func_enter();
864
865     memcpy(&ehdr, skb->data, ETH_HLEN);
866     proto = ntohs(ehdr.h_proto);
867
868     /* 802.1x - apply controlled/uncontrolled port rules */
869     if ((proto != ETH_P_PAE)
870 #ifdef CSR_WIFI_SECURITY_WAPI_ENABLE
871             && (proto != ETH_P_WAI)
872 #endif
873        ) {
874         /* queues 0 - 3 */
875         priority = get_packet_priority(priv, skb, &ehdr, interfacePriv);
876         queue = unifi_frame_priority_to_queue(priority);
877     } else {
878         /* queue 4 */
879         queue = UNIFI_TRAFFIC_Q_EAPOL;
880     }
881
882
883     func_exit();
884     return (u16)queue;
885 } /* uf_net_select_queue() */
886
887 int
888 skb_add_llc_snap(struct net_device *dev, struct sk_buff *skb, int proto)
889 {
890     llc_snap_hdr_t *snap;
891     netInterface_priv_t *interfacePriv = (netInterface_priv_t *)netdev_priv(dev);
892     unifi_priv_t *priv = interfacePriv->privPtr;
893     int headroom;
894
895     /* get the headroom available in skb */
896     headroom = skb_headroom(skb);
897     /* step 1: classify ether frame, DIX or 802.3? */
898
899     if (proto < 0x600) {
900         /* codes <= 1500 reserved for 802.3 lengths */
901         /* it's 802.3, pass ether payload unchanged,  */
902         unifi_trace(priv, UDBG3, "802.3 len: %d\n", skb->len);
903
904         /*   leave off any PAD octets.  */
905         skb_trim(skb, proto);
906     } else if (proto == ETH_P_8021Q) {
907
908         /* Store the VLAN SNAP (should be 87-65). */
909         u16 vlan_snap = *(u16*)skb->data;
910         /* check for headroom availability before skb_push 14 = (4 + 10) */
911         if (headroom < 14) {
912             unifi_trace(priv, UDBG3, "cant append vlan snap: debug\n");
913             return -1;
914         }
915         /* Add AA-AA-03-00-00-00 */
916         snap = (llc_snap_hdr_t *)skb_push(skb, 4);
917         snap->dsap = snap->ssap = 0xAA;
918         snap->ctrl = 0x03;
919         memcpy(snap->oui, oui_rfc1042, P80211_OUI_LEN);
920
921         /* Add AA-AA-03-00-00-00 */
922         snap = (llc_snap_hdr_t *)skb_push(skb, 10);
923         snap->dsap = snap->ssap = 0xAA;
924         snap->ctrl = 0x03;
925         memcpy(snap->oui, oui_rfc1042, P80211_OUI_LEN);
926
927         /* Add the VLAN specific information */
928         snap->protocol = htons(proto);
929         *(u16*)(snap + 1) = vlan_snap;
930
931     } else
932     {
933         /* it's DIXII, time for some conversion */
934         unifi_trace(priv, UDBG3, "DIXII len: %d\n", skb->len);
935
936         /* check for headroom availability before skb_push */
937         if (headroom < sizeof(llc_snap_hdr_t)) {
938             unifi_trace(priv, UDBG3, "cant append snap: debug\n");
939             return -1;
940         }
941         /* tack on SNAP */
942         snap = (llc_snap_hdr_t *)skb_push(skb, sizeof(llc_snap_hdr_t));
943         snap->dsap = snap->ssap = 0xAA;
944         snap->ctrl = 0x03;
945         /* Use the appropriate OUI. */
946         if ((proto == ETH_P_AARP) || (proto == ETH_P_IPX)) {
947             memcpy(snap->oui, oui_8021h, P80211_OUI_LEN);
948         } else {
949             memcpy(snap->oui, oui_rfc1042, P80211_OUI_LEN);
950         }
951         snap->protocol = htons(proto);
952     }
953
954     return 0;
955 } /* skb_add_llc_snap() */
956
957 #ifdef CSR_SUPPORT_SME
958 static int
959 _identify_sme_ma_pkt_ind(unifi_priv_t *priv,
960                          const s8 *oui, u16 protocol,
961                          const CSR_SIGNAL *signal,
962                          bulk_data_param_t *bulkdata,
963                          const unsigned char *daddr,
964                          const unsigned char *saddr)
965 {
966     CSR_MA_PACKET_INDICATION *pkt_ind = (CSR_MA_PACKET_INDICATION*)&signal->u.MaPacketIndication;
967     int r;
968     u8 i;
969
970     unifi_trace(priv, UDBG5,
971             "_identify_sme_ma_pkt_ind -->\n");
972     for (i = 0; i < MAX_MA_UNIDATA_IND_FILTERS; i++) {
973         if (priv->sme_unidata_ind_filters[i].in_use) {
974             if (!memcmp(oui, priv->sme_unidata_ind_filters[i].oui, 3) &&
975                     (protocol == priv->sme_unidata_ind_filters[i].protocol)) {
976
977                 /* Send to client */
978                 if (priv->sme_cli) {
979                     /*
980                      * Pass the packet to the SME, using unifi_sys_ma_unitdata_ind().
981                      * The frame needs to be converted according to the encapsulation.
982                      */
983                     unifi_trace(priv, UDBG1,
984                             "_identify_sme_ma_pkt_ind: handle=%d, encap=%d, proto=%x\n",
985                             i, priv->sme_unidata_ind_filters[i].encapsulation,
986                             priv->sme_unidata_ind_filters[i].protocol);
987                     if (priv->sme_unidata_ind_filters[i].encapsulation == CSR_WIFI_ROUTER_ENCAPSULATION_ETHERNET) {
988                         struct sk_buff *skb;
989                         /* The translation is performed on skb... */
990                         skb = (struct sk_buff*)bulkdata->d[0].os_net_buf_ptr;
991                         skb->len = bulkdata->d[0].data_length;
992
993                         unifi_trace(priv, UDBG1,
994                                 "_identify_sme_ma_pkt_ind: skb_80211_to_ether -->\n");
995                         r = skb_80211_to_ether(priv, skb, daddr, saddr,
996                                 signal, bulkdata);
997                         unifi_trace(priv, UDBG1,
998                                 "_identify_sme_ma_pkt_ind: skb_80211_to_ether <--\n");
999                         if (r) {
1000                             return -EINVAL;
1001                         }
1002
1003                         /* ... but we indicate buffer and length */
1004                         bulkdata->d[0].os_data_ptr = skb->data;
1005                         bulkdata->d[0].data_length = skb->len;
1006                     } else {
1007                         /* Add the MAC addresses before the SNAP */
1008                         bulkdata->d[0].os_data_ptr -= 2*ETH_ALEN;
1009                         bulkdata->d[0].data_length += 2*ETH_ALEN;
1010                         memcpy((void*)bulkdata->d[0].os_data_ptr, daddr, ETH_ALEN);
1011                         memcpy((void*)bulkdata->d[0].os_data_ptr + ETH_ALEN, saddr, ETH_ALEN);
1012                     }
1013
1014                     unifi_trace(priv, UDBG1,
1015                             "_identify_sme_ma_pkt_ind: unifi_sys_ma_pkt_ind -->\n");
1016                     CsrWifiRouterMaPacketIndSend(priv->sme_unidata_ind_filters[i].appHandle,
1017                             (pkt_ind->VirtualInterfaceIdentifier & 0xff),
1018                             i,
1019                             pkt_ind->ReceptionStatus,
1020                             bulkdata->d[0].data_length,
1021                             (u8*)bulkdata->d[0].os_data_ptr,
1022                             NULL,
1023                             pkt_ind->Rssi,
1024                             pkt_ind->Snr,
1025                             pkt_ind->ReceivedRate);
1026
1027
1028                     unifi_trace(priv, UDBG1,
1029                             "_identify_sme_ma_pkt_ind: unifi_sys_ma_pkt_ind <--\n");
1030                 }
1031
1032                 return 1;
1033             }
1034         }
1035     }
1036
1037     return -1;
1038 }
1039 #endif /* CSR_SUPPORT_SME */
1040
1041 /*
1042  * ---------------------------------------------------------------------------
1043  *  skb_80211_to_ether
1044  *
1045  *      Make sure the received frame is in Ethernet (802.3) form.
1046  *      De-encapsulates SNAP if necessary, adds a ethernet header.
1047  *      The source buffer should not contain an 802.11 MAC header
1048  *
1049  *  Arguments:
1050  *      payload         Pointer to packet data received from UniFi.
1051  *      payload_length  Number of bytes of data received from UniFi.
1052  *      daddr           Destination MAC address.
1053  *      saddr           Source MAC address.
1054  *
1055  *  Returns:
1056  *      0 on success, -1 if the packet is bad and should be dropped,
1057  *      1 if the packet was forwarded to the SME or AMP client.
1058  * ---------------------------------------------------------------------------
1059  */
1060 int
1061 skb_80211_to_ether(unifi_priv_t *priv, struct sk_buff *skb,
1062                    const unsigned char *daddr, const unsigned char *saddr,
1063                    const CSR_SIGNAL *signal,
1064                    bulk_data_param_t *bulkdata)
1065 {
1066     unsigned char *payload;
1067     int payload_length;
1068     struct ethhdr *eth;
1069     llc_snap_hdr_t *snap;
1070     int headroom;
1071 #define UF_VLAN_LLC_HEADER_SIZE     18
1072     static const u8 vlan_inner_snap[] = { 0xAA, 0xAA, 0x03, 0x00, 0x00, 0x00 };
1073 #if defined(CSR_NATIVE_SOFTMAC) && defined(CSR_SUPPORT_SME)
1074     const CSR_MA_PACKET_INDICATION *pkt_ind = &signal->u.MaPacketIndication;
1075 #endif
1076
1077     if(skb== NULL || daddr == NULL || saddr == NULL){
1078         unifi_error(priv,"skb_80211_to_ether: PBC fail\n");
1079         return 1;
1080     }
1081
1082     payload = skb->data;
1083     payload_length = skb->len;
1084
1085     snap = (llc_snap_hdr_t *)payload;
1086     eth  = (struct ethhdr *)payload;
1087
1088     /* get the skb headroom size */
1089     headroom = skb_headroom(skb);
1090
1091     /*
1092      * Test for the various encodings
1093      */
1094     if ((payload_length >= sizeof(llc_snap_hdr_t)) &&
1095             (snap->dsap == 0xAA) &&
1096             (snap->ssap == 0xAA) &&
1097             (snap->ctrl == 0x03) &&
1098             (snap->oui[0] == 0) &&
1099             (snap->oui[1] == 0) &&
1100             ((snap->oui[2] == 0) || (snap->oui[2] == 0xF8)))
1101     {
1102         /* AppleTalk AARP (2) or IPX SNAP */
1103         if ((snap->oui[2] == 0) &&
1104                 ((ntohs(snap->protocol) == ETH_P_AARP) || (ntohs(snap->protocol) == ETH_P_IPX)))
1105         {
1106             u16 len;
1107
1108             unifi_trace(priv, UDBG3, "%s len: %d\n",
1109                     (ntohs(snap->protocol) == ETH_P_AARP) ? "ETH_P_AARP" : "ETH_P_IPX",
1110                     payload_length);
1111
1112             /* check for headroom availability before skb_push */
1113             if (headroom < (2 * ETH_ALEN + 2)) {
1114                 unifi_warning(priv, "headroom not available to skb_push ether header\n");
1115                 return -1;
1116             }
1117
1118             /* Add 802.3 header and leave full payload */
1119             len = htons(skb->len);
1120             memcpy(skb_push(skb, 2), &len, 2);
1121             memcpy(skb_push(skb, ETH_ALEN), saddr, ETH_ALEN);
1122             memcpy(skb_push(skb, ETH_ALEN), daddr, ETH_ALEN);
1123
1124             return 0;
1125         }
1126         /* VLAN-tagged IP */
1127         if ((snap->oui[2] == 0) && (ntohs(snap->protocol) == ETH_P_8021Q))
1128         {
1129             /*
1130              * The translation doesn't change the packet length, so is done in-place.
1131              *
1132              * Example header (from Std 802.11-2007 Annex M):
1133              * AA-AA-03-00-00-00-81-00-87-65-AA-AA-03-00-00-00-08-06
1134              * -------SNAP-------p1-p1-ll-ll-------SNAP--------p2-p2
1135              * dd-dd-dd-dd-dd-dd-aa-aa-aa-aa-aa-aa-p1-p1-ll-ll-p2-p2
1136              * dd-dd-dd-dd-dd-dd-aa-aa-aa-aa-aa-aa-81-00-87-65-08-06
1137              */
1138             u16 vlan_snap;
1139
1140             if (payload_length < UF_VLAN_LLC_HEADER_SIZE) {
1141                 unifi_warning(priv, "VLAN SNAP header too short: %d bytes\n", payload_length);
1142                 return -1;
1143             }
1144
1145             if (memcmp(payload + 10, vlan_inner_snap, 6)) {
1146                 unifi_warning(priv, "VLAN malformatted SNAP header.\n");
1147                 return -1;
1148             }
1149
1150             unifi_trace(priv, UDBG3, "VLAN SNAP: %02x-%02x\n", payload[8], payload[9]);
1151             unifi_trace(priv, UDBG3, "VLAN len: %d\n", payload_length);
1152
1153             /* Create the 802.3 header */
1154
1155             vlan_snap = *((u16*)(payload + 8));
1156
1157             /* Create LLC header without byte-swapping */
1158             eth->h_proto = snap->protocol;
1159
1160             memcpy(eth->h_dest, daddr, ETH_ALEN);
1161             memcpy(eth->h_source, saddr, ETH_ALEN);
1162             *(u16*)(eth + 1) = vlan_snap;
1163             return 0;
1164         }
1165
1166         /* it's a SNAP + RFC1042 frame */
1167         unifi_trace(priv, UDBG3, "SNAP+RFC1042 len: %d\n", payload_length);
1168
1169         /* chop SNAP+llc header from skb. */
1170         skb_pull(skb, sizeof(llc_snap_hdr_t));
1171
1172         /* Since skb_pull called above to chop snap+llc, no need to check for headroom
1173          * availability before skb_push
1174          */
1175         /* create 802.3 header at beginning of skb. */
1176         eth = (struct ethhdr *)skb_push(skb, ETH_HLEN);
1177         memcpy(eth->h_dest, daddr, ETH_ALEN);
1178         memcpy(eth->h_source, saddr, ETH_ALEN);
1179         /* Copy protocol field without byte-swapping */
1180         eth->h_proto = snap->protocol;
1181     } else {
1182         u16 len;
1183
1184         /* check for headroom availability before skb_push */
1185         if (headroom < (2 * ETH_ALEN + 2)) {
1186             unifi_warning(priv, "headroom not available to skb_push ether header\n");
1187             return -1;
1188         }
1189         /* Add 802.3 header and leave full payload */
1190         len = htons(skb->len);
1191         memcpy(skb_push(skb, 2), &len, 2);
1192         memcpy(skb_push(skb, ETH_ALEN), saddr, ETH_ALEN);
1193         memcpy(skb_push(skb, ETH_ALEN), daddr, ETH_ALEN);
1194
1195         return 1;
1196     }
1197
1198     return 0;
1199 } /* skb_80211_to_ether() */
1200
1201
1202 static CsrWifiRouterCtrlPortAction verify_port(unifi_priv_t *priv, unsigned char *address, int queue, u16 interfaceTag)
1203 {
1204 #ifdef CSR_NATIVE_LINUX
1205 #ifdef CSR_SUPPORT_WEXT
1206     if (queue == UF_CONTROLLED_PORT_Q) {
1207         return priv->wext_conf.block_controlled_port;
1208     } else {
1209         return CSR_WIFI_ROUTER_CTRL_PORT_ACTION_8021X_PORT_OPEN;
1210     }
1211 #else
1212     return CSR_WIFI_ROUTER_CTRL_PORT_ACTION_8021X_PORT_OPEN; /* default to open for softmac dev */
1213 #endif
1214 #else
1215     return uf_sme_port_state(priv, address, queue, interfaceTag);
1216 #endif
1217 }
1218
1219 /*
1220  * ---------------------------------------------------------------------------
1221  *  prepare_and_add_macheader
1222  *
1223  *
1224  *      These functions adds mac header for packet from netdev
1225  *      to UniFi for transmission.
1226  *      EAP protocol packets are also appended with Mac header &
1227  *      sent using send_ma_pkt_request().
1228  *
1229  *  Arguments:
1230  *      priv            Pointer to device private context struct
1231  *      skb             Socket buffer containing data packet to transmit
1232  *      newSkb          Socket buffer containing data packet + Mac header if no sufficient headroom in skb
1233  *      serviceClass    to append QOS control header in Mac header
1234  *      bulkdata        if newSkb allocated then bulkdata updated to send to unifi
1235  *      interfaceTag    the interfaceID on which activity going on
1236  *      daddr           destination address
1237  *      saddr           source address
1238  *      protection      protection bit set in framce control of mac header
1239  *
1240  *  Returns:
1241  *      Zero on success or error code.
1242  * ---------------------------------------------------------------------------
1243  */
1244
1245 int prepare_and_add_macheader(unifi_priv_t *priv, struct sk_buff *skb, struct sk_buff *newSkb,
1246                               CSR_PRIORITY priority,
1247                               bulk_data_param_t *bulkdata,
1248                               u16 interfaceTag,
1249                               const u8 *daddr,
1250                               const u8 *saddr,
1251                               u8 protection)
1252 {
1253     u16 fc = 0;
1254     u8 qc = 0;
1255     u8 macHeaderLengthInBytes = MAC_HEADER_SIZE, *bufPtr = NULL;
1256     bulk_data_param_t data_ptrs;
1257     CsrResult csrResult;
1258     int headroom =0;
1259     u8 direction = 0;
1260     netInterface_priv_t *interfacePriv = priv->interfacePriv[interfaceTag];
1261     u8 *addressOne;
1262     u8 bQosNull = false;
1263
1264     if (skb == NULL) {
1265         unifi_error(priv,"prepare_and_add_macheader: Invalid SKB reference\n");
1266         return -1;
1267     }
1268
1269     /* add a MAC header refer: 7.1.3.1 Frame Control field in P802.11REVmb.book */
1270     if (priority != CSR_CONTENTION) {
1271         /* EAPOL packets don't go as QOS_DATA */
1272         if (priority == CSR_MANAGEMENT) {
1273             fc |= cpu_to_le16(IEEE802_11_FC_TYPE_DATA);
1274         } else {
1275             /* Qos Control Field */
1276             macHeaderLengthInBytes += QOS_CONTROL_HEADER_SIZE;
1277
1278             if (skb->len) {
1279
1280                 fc |= cpu_to_le16(IEEE802_11_FC_TYPE_QOS_DATA);
1281             } else {
1282                 fc |= cpu_to_le16(IEEE802_11_FC_TYPE_QOS_NULL);
1283                 bQosNull = true;
1284             }
1285         }
1286     } else {
1287         if(skb->len == 0) {
1288             fc |= cpu_to_le16(IEEE802_11_FC_TYPE_NULL);
1289         } else {
1290             fc |= cpu_to_le16(IEEE802_11_FC_TYPE_DATA);
1291         }
1292     }
1293
1294     switch (interfacePriv->interfaceMode)
1295     {
1296         case  CSR_WIFI_ROUTER_CTRL_MODE_STA:
1297         case CSR_WIFI_ROUTER_CTRL_MODE_P2PCLI:
1298             direction = 2;
1299             fc |= cpu_to_le16(IEEE802_11_FC_TO_DS_MASK);
1300             break;
1301         case  CSR_WIFI_ROUTER_CTRL_MODE_IBSS:
1302             direction = 0;
1303             break;
1304         case  CSR_WIFI_ROUTER_CTRL_MODE_AP:
1305         case CSR_WIFI_ROUTER_CTRL_MODE_P2PGO:
1306             direction = 1;
1307             fc |= cpu_to_le16(IEEE802_11_FC_FROM_DS_MASK);
1308             break;
1309         case CSR_WIFI_ROUTER_CTRL_MODE_AMP:
1310             if (priority == CSR_MANAGEMENT ) {
1311
1312                 direction = 2;
1313                 fc |= cpu_to_le16(IEEE802_11_FC_TO_DS_MASK);
1314             } else {
1315                 /* Data frames have to use WDS 4 address frames */
1316                 direction = 3;
1317                 fc |= cpu_to_le16(IEEE802_11_FC_TO_DS_MASK | IEEE802_11_FC_FROM_DS_MASK);
1318                 macHeaderLengthInBytes += 6;
1319             }
1320             break;
1321         default:
1322             unifi_warning(priv, "prepare_and_add_macheader: Unknown mode %d\n",
1323                           interfacePriv->interfaceMode);
1324     }
1325
1326
1327     /* If Sta is QOS & HTC is supported then need to set 'order' bit */
1328     /* We don't support HT Control for now */
1329
1330     if(protection) {
1331         fc |= cpu_to_le16(IEEE802_11_FC_PROTECTED_MASK);
1332     }
1333
1334     /* check the skb headroom before pushing mac header */
1335     headroom = skb_headroom(skb);
1336
1337     if (headroom < macHeaderLengthInBytes) {
1338         unifi_trace(priv, UDBG5,
1339                     "prepare_and_add_macheader: Allocate headroom extra %d bytes\n",
1340                     macHeaderLengthInBytes);
1341
1342         csrResult = unifi_net_data_malloc(priv, &data_ptrs.d[0], skb->len + macHeaderLengthInBytes);
1343
1344         if (csrResult != CSR_RESULT_SUCCESS) {
1345             unifi_error(priv, " failed to allocate request_data. in %s func\n", __FUNCTION__);
1346             return -1;
1347         }
1348         newSkb = (struct sk_buff *)(data_ptrs.d[0].os_net_buf_ptr);
1349         newSkb->len = skb->len + macHeaderLengthInBytes;
1350
1351         memcpy((void*)data_ptrs.d[0].os_data_ptr + macHeaderLengthInBytes,
1352                 skb->data, skb->len);
1353
1354         bulkdata->d[0].os_data_ptr = newSkb->data;
1355         bulkdata->d[0].os_net_buf_ptr = (unsigned char*)newSkb;
1356         bulkdata->d[0].data_length = newSkb->len;
1357
1358         bufPtr = (u8*)data_ptrs.d[0].os_data_ptr;
1359
1360         /* The old skb will not be used again */
1361             kfree_skb(skb);
1362     } else {
1363
1364         /* headroom has sufficient size, so will get proper pointer */
1365         bufPtr = (u8*)skb_push(skb, macHeaderLengthInBytes);
1366         bulkdata->d[0].os_data_ptr = skb->data;
1367         bulkdata->d[0].os_net_buf_ptr = (unsigned char*)skb;
1368         bulkdata->d[0].data_length = skb->len;
1369     }
1370
1371     /* Frame the actual MAC header */
1372
1373     memset(bufPtr, 0, macHeaderLengthInBytes);
1374
1375     /* copy frameControl field */
1376     memcpy(bufPtr, &fc, sizeof(fc));
1377     bufPtr += sizeof(fc);
1378     macHeaderLengthInBytes -= sizeof(fc);
1379
1380     /* Duration/ID field which is 2 bytes */
1381     bufPtr += 2;
1382     macHeaderLengthInBytes -= 2;
1383
1384     switch(direction)
1385     {
1386         case 0:
1387             /* Its an Ad-Hoc no need to route it through AP */
1388             /* Address1: MAC address of the destination from eth header */
1389             memcpy(bufPtr, daddr, ETH_ALEN);
1390             bufPtr += ETH_ALEN;
1391             macHeaderLengthInBytes -= ETH_ALEN;
1392
1393             /* Address2: MAC address of the source */
1394             memcpy(bufPtr, saddr, ETH_ALEN);
1395             bufPtr += ETH_ALEN;
1396             macHeaderLengthInBytes -= ETH_ALEN;
1397
1398             /* Address3: the BSSID (locally generated in AdHoc (creators Bssid)) */
1399             memcpy(bufPtr, &interfacePriv->bssid, ETH_ALEN);
1400             bufPtr += ETH_ALEN;
1401             macHeaderLengthInBytes -= ETH_ALEN;
1402             break;
1403         case 1:
1404            /* Address1: MAC address of the actual destination */
1405             memcpy(bufPtr, daddr, ETH_ALEN);
1406             bufPtr += ETH_ALEN;
1407             macHeaderLengthInBytes -= ETH_ALEN;
1408             /* Address2: The MAC address of the AP */
1409             memcpy(bufPtr, &interfacePriv->bssid, ETH_ALEN);
1410             bufPtr += ETH_ALEN;
1411             macHeaderLengthInBytes -= ETH_ALEN;
1412
1413             /* Address3: MAC address of the source from eth header */
1414             memcpy(bufPtr, saddr, ETH_ALEN);
1415             bufPtr += ETH_ALEN;
1416             macHeaderLengthInBytes -= ETH_ALEN;
1417             break;
1418         case  2:
1419             /* Address1: To AP is the MAC address of the AP to which its associated */
1420             memcpy(bufPtr, &interfacePriv->bssid, ETH_ALEN);
1421             bufPtr += ETH_ALEN;
1422             macHeaderLengthInBytes -= ETH_ALEN;
1423
1424             /* Address2: MAC address of the source from eth header */
1425             memcpy(bufPtr, saddr, ETH_ALEN);
1426             bufPtr += ETH_ALEN;
1427             macHeaderLengthInBytes -= ETH_ALEN;
1428
1429             /* Address3: MAC address of the actual destination on the distribution system */
1430             memcpy(bufPtr, daddr, ETH_ALEN);
1431             bufPtr += ETH_ALEN;
1432             macHeaderLengthInBytes -= ETH_ALEN;
1433             break;
1434         case 3:
1435             memcpy(bufPtr, &interfacePriv->bssid, ETH_ALEN);
1436             bufPtr += ETH_ALEN;
1437             macHeaderLengthInBytes -= ETH_ALEN;
1438
1439             /* Address2: MAC address of the source from eth header */
1440             memcpy(bufPtr, saddr, ETH_ALEN);
1441             bufPtr += ETH_ALEN;
1442             macHeaderLengthInBytes -= ETH_ALEN;
1443
1444             /* Address3: MAC address of the actual destination on the distribution system */
1445             memcpy(bufPtr, daddr, ETH_ALEN);
1446             bufPtr += ETH_ALEN;
1447             macHeaderLengthInBytes -= ETH_ALEN;
1448             break;
1449         default:
1450             unifi_error(priv,"Unknown direction =%d : Not handled now\n",direction);
1451             return -1;
1452     }
1453     /* 2 bytes of frame control field, appended by firmware */
1454     bufPtr += 2;
1455     macHeaderLengthInBytes -= 2;
1456
1457     if (3 == direction) {
1458         /* Address4: MAC address of the source */
1459         memcpy(bufPtr, saddr, ETH_ALEN);
1460         bufPtr += ETH_ALEN;
1461         macHeaderLengthInBytes -= ETH_ALEN;
1462     }
1463
1464     /* IF Qos Data or Qos Null Data then set QosControl field */
1465     if ((priority != CSR_CONTENTION) && (macHeaderLengthInBytes >= QOS_CONTROL_HEADER_SIZE)) {
1466
1467         if (priority > 7) {
1468             unifi_trace(priv, UDBG1, "data packets priority is more than 7, priority = %x\n", priority);
1469             qc |= 7;
1470         } else {
1471             qc |= priority;
1472         }
1473         /*assigning address1
1474         * Address1 offset taken fromm bufPtr(currently bufPtr pointing to Qos contorl) variable in reverse direction
1475         * Address4 don't exit
1476         */
1477
1478         addressOne = bufPtr- ADDRESS_ONE_OFFSET;
1479
1480         if (addressOne[0] & 0x1) {
1481             /* multicast/broadcast frames, no acknowledgement needed */
1482             qc |= 1 << 5;
1483         }
1484         /* non-AP mode only for now */
1485         if(interfacePriv->interfaceMode == CSR_WIFI_ROUTER_CTRL_MODE_STA ||
1486            interfacePriv->interfaceMode == CSR_WIFI_ROUTER_CTRL_MODE_IBSS ||
1487            interfacePriv->interfaceMode == CSR_WIFI_ROUTER_CTRL_MODE_P2PCLI) {
1488            /* In case of STA and IBSS case eosp and txop limit is 0. */
1489         } else {
1490             if(bQosNull) {
1491                 qc |= 1 << 4;
1492             }
1493         }
1494
1495         /* append Qos control field to mac header */
1496         bufPtr[0] = qc;
1497         /* txop limit is 0 */
1498         bufPtr[1] = 0;
1499         macHeaderLengthInBytes -= QOS_CONTROL_HEADER_SIZE;
1500     }
1501     if (macHeaderLengthInBytes) {
1502         unifi_warning(priv, " Mac header not appended properly\n");
1503         return -1;
1504     }
1505     return 0;
1506 }
1507
1508 /*
1509  * ---------------------------------------------------------------------------
1510  *  send_ma_pkt_request
1511  *
1512  *      These functions send a data packet to UniFi for transmission.
1513  *      EAP protocol packets are also sent as send_ma_pkt_request().
1514  *
1515  *  Arguments:
1516  *      priv            Pointer to device private context struct
1517  *      skb             Socket buffer containing data packet to transmit
1518  *      ehdr            Pointer to Ethernet header within skb.
1519  *
1520  *  Returns:
1521  *      Zero on success or error code.
1522  * ---------------------------------------------------------------------------
1523  */
1524
1525 static int
1526 send_ma_pkt_request(unifi_priv_t *priv, struct sk_buff *skb, const struct ethhdr *ehdr, CSR_PRIORITY priority)
1527 {
1528     int r;
1529     u16 i;
1530     u8 eapolStore = FALSE;
1531     struct sk_buff *newSkb = NULL;
1532     bulk_data_param_t bulkdata;
1533     const int proto = ntohs(ehdr->h_proto);
1534     u16 interfaceTag;
1535     CsrWifiMacAddress peerAddress;
1536     CSR_TRANSMISSION_CONTROL transmissionControl = CSR_NO_CONFIRM_REQUIRED;
1537     s8 protection;
1538     netInterface_priv_t *interfacePriv = NULL;
1539     CSR_RATE TransmitRate = (CSR_RATE)0;
1540
1541     unifi_trace(priv, UDBG5, "entering send_ma_pkt_request\n");
1542
1543     /* Get the interface Tag by means of source Mac address */
1544     for (i = 0; i < CSR_WIFI_NUM_INTERFACES; i++) {
1545         if (!memcmp(priv->netdev[i]->dev_addr, ehdr->h_source, ETH_ALEN)) {
1546             interfaceTag = i;
1547             interfacePriv = priv->interfacePriv[interfaceTag];
1548             break;
1549         }
1550     }
1551
1552     if (interfacePriv == NULL) {
1553         /* No match found - error */
1554         interfaceTag = 0;
1555         interfacePriv = priv->interfacePriv[interfaceTag];
1556         unifi_warning(priv, "Mac address not matching ... debugging needed\n");
1557         interfacePriv->stats.tx_dropped++;
1558         kfree_skb(skb);
1559         return -1;
1560     }
1561
1562     /* Add a SNAP header if necessary */
1563     if (skb_add_llc_snap(priv->netdev[interfaceTag], skb, proto) != 0) {
1564         /* convert failed */
1565         unifi_error(priv, "skb_add_llc_snap failed.\n");
1566         kfree_skb(skb);
1567         return -1;
1568     }
1569
1570     bulkdata.d[0].os_data_ptr = skb->data;
1571     bulkdata.d[0].os_net_buf_ptr = (unsigned char*)skb;
1572     bulkdata.d[0].net_buf_length = bulkdata.d[0].data_length = skb->len;
1573     bulkdata.d[1].os_data_ptr = NULL;
1574     bulkdata.d[1].os_net_buf_ptr = NULL;
1575     bulkdata.d[1].net_buf_length = bulkdata.d[1].data_length = 0;
1576
1577 #ifdef CSR_SUPPORT_SME
1578     /* Notify the TA module for the Tx frame  for non AP/P2PGO mode*/
1579     if ((interfacePriv->interfaceMode != CSR_WIFI_ROUTER_CTRL_MODE_AP) &&
1580         (interfacePriv->interfaceMode != CSR_WIFI_ROUTER_CTRL_MODE_P2PGO)) {
1581         unifi_ta_sample(priv->card, CSR_WIFI_ROUTER_CTRL_PROTOCOL_DIRECTION_TX,
1582                         &bulkdata.d[0], ehdr->h_source,
1583                         priv->netdev[interfaceTag]->dev_addr,
1584                         jiffies_to_msecs(jiffies),
1585                         0);     /* rate is unknown on tx */
1586     }
1587 #endif /* CSR_SUPPORT_SME */
1588
1589     if ((proto == ETH_P_PAE)
1590 #ifdef CSR_WIFI_SECURITY_WAPI_ENABLE
1591             || (proto == ETH_P_WAI)
1592 #endif
1593        )
1594     {
1595         /* check for m4 detection */
1596         if (0 == uf_verify_m4(priv, bulkdata.d[0].os_data_ptr, bulkdata.d[0].data_length)) {
1597             eapolStore = TRUE;
1598         }
1599     }
1600
1601 #ifdef CSR_WIFI_SECURITY_WAPI_ENABLE
1602     if (proto == ETH_P_WAI)
1603      {
1604         protection = 0; /*WAI packets always sent unencrypted*/
1605      }
1606    else
1607      {
1608 #endif
1609 #ifdef CSR_SUPPORT_SME
1610     if ((protection = uf_get_protection_bit_from_interfacemode(priv, interfaceTag, ehdr->h_dest)) < 0) {
1611         unifi_warning(priv, "unicast address, but destination not in station record database\n");
1612         unifi_net_data_free(priv, &bulkdata.d[0]);
1613         return -1;
1614     }
1615 #else
1616     protection = 0;
1617 #endif
1618 #ifdef CSR_WIFI_SECURITY_WAPI_ENABLE
1619    }
1620 #endif
1621
1622     /* append Mac header for Eapol as well as data packet */
1623     if (prepare_and_add_macheader(priv, skb, newSkb, priority, &bulkdata, interfaceTag, ehdr->h_dest, ehdr->h_source, protection)) {
1624         unifi_error(priv, "failed to create MAC header\n");
1625         unifi_net_data_free(priv, &bulkdata.d[0]);
1626         return -1;
1627     }
1628
1629     /* RA adrress must contain the immediate destination MAC address that is similiar to
1630      * the Address 1 field of 802.11 Mac header here 4 is: (sizeof(framecontrol) + sizeof (durationID))
1631      * which is address 1 field
1632      */
1633     memcpy(peerAddress.a, ((u8 *) bulkdata.d[0].os_data_ptr) + 4, ETH_ALEN);
1634
1635     unifi_trace(priv, UDBG5, "RA[0]=%x, RA[1]=%x, RA[2]=%x, RA[3]=%x, RA[4]=%x, RA[5]=%x\n",
1636                 peerAddress.a[0],peerAddress.a[1], peerAddress.a[2], peerAddress.a[3],
1637                 peerAddress.a[4],peerAddress.a[5]);
1638
1639
1640     if ((proto == ETH_P_PAE)
1641 #ifdef CSR_WIFI_SECURITY_WAPI_ENABLE
1642             || (proto == ETH_P_WAI)
1643 #endif
1644        )
1645     {
1646         CSR_SIGNAL signal;
1647         CSR_MA_PACKET_REQUEST *req = &signal.u.MaPacketRequest;
1648
1649         /* initialize signal to zero */
1650         memset(&signal, 0, sizeof(CSR_SIGNAL));
1651
1652         /* Frame MA_PACKET request */
1653         signal.SignalPrimitiveHeader.SignalId = CSR_MA_PACKET_REQUEST_ID;
1654         signal.SignalPrimitiveHeader.ReceiverProcessId = 0;
1655         signal.SignalPrimitiveHeader.SenderProcessId = priv->netdev_client->sender_id;
1656
1657         transmissionControl = req->TransmissionControl = 0;
1658 #ifdef CSR_SUPPORT_SME
1659         if (eapolStore)
1660         {
1661             netInterface_priv_t *netpriv = (netInterface_priv_t *)netdev_priv(priv->netdev[interfaceTag]);
1662
1663             /* Fill the MA-PACKET.req */
1664
1665             req->Priority = priority;
1666             unifi_trace(priv, UDBG3, "Tx Frame with Priority: %x\n", req->Priority);
1667
1668             /* rate selected by firmware */
1669             req->TransmitRate = 0;
1670             req->HostTag = CSR_WIFI_EAPOL_M4_HOST_TAG;
1671             /* RA address matching with address 1 of Mac header */
1672             memcpy(req->Ra.x, ((u8 *) bulkdata.d[0].os_data_ptr) + 4, ETH_ALEN);
1673
1674             spin_lock(&priv->m4_lock);
1675             /* Store the M4-PACKET.req for later */
1676             interfacePriv->m4_signal = signal;
1677             interfacePriv->m4_bulk_data.net_buf_length = bulkdata.d[0].net_buf_length;
1678             interfacePriv->m4_bulk_data.data_length = bulkdata.d[0].data_length;
1679             interfacePriv->m4_bulk_data.os_data_ptr = bulkdata.d[0].os_data_ptr;
1680             interfacePriv->m4_bulk_data.os_net_buf_ptr = bulkdata.d[0].os_net_buf_ptr;
1681             spin_unlock(&priv->m4_lock);
1682
1683             /* Signal the workqueue to call CsrWifiRouterCtrlM4ReadyToSendIndSend().
1684              * It cannot be called directly from the tx path because it
1685              * does a non-atomic kmalloc via the framework's CsrPmemAlloc().
1686              */
1687             queue_work(priv->unifi_workqueue, &netpriv->send_m4_ready_task);
1688
1689             return 0;
1690         }
1691 #endif
1692     }/*EAPOL or WAI packet*/
1693
1694 #if (defined(CSR_WIFI_SECURITY_WAPI_ENABLE) && defined(CSR_WIFI_SECURITY_WAPI_SW_ENCRYPTION))
1695     if ((CSR_WIFI_ROUTER_CTRL_MODE_STA == interfacePriv->interfaceMode) && \
1696         (priv->wapi_unicast_filter) && \
1697         (proto != ETH_P_PAE) && \
1698         (proto != ETH_P_WAI) && \
1699         (skb->len > 0))
1700     {
1701         CSR_SIGNAL signal;
1702         CSR_MA_PACKET_REQUEST *req = &signal.u.MaPacketRequest;
1703         netInterface_priv_t *netpriv = (netInterface_priv_t *)netdev_priv(priv->netdev[interfaceTag]);
1704
1705         unifi_trace(priv, UDBG4, "send_ma_pkt_request() - WAPI unicast data packet when USKID = 1 \n");
1706
1707         /* initialize signal to zero */
1708         memset(&signal, 0, sizeof(CSR_SIGNAL));
1709         /* Frame MA_PACKET request */
1710         signal.SignalPrimitiveHeader.SignalId = CSR_MA_PACKET_REQUEST_ID;
1711         signal.SignalPrimitiveHeader.ReceiverProcessId = 0;
1712         signal.SignalPrimitiveHeader.SenderProcessId = priv->netdev_client->sender_id;
1713
1714         /* Fill the MA-PACKET.req */
1715         req->TransmissionControl = 0;
1716         req->Priority = priority;
1717         unifi_trace(priv, UDBG3, "Tx Frame with Priority: %x\n", req->Priority);
1718         req->TransmitRate = (CSR_RATE) 0; /* rate selected by firmware */
1719         req->HostTag = 0xffffffff;        /* Ask for a new HostTag */
1720         /* RA address matching with address 1 of Mac header */
1721         memcpy(req->Ra.x, ((u8 *) bulkdata.d[0].os_data_ptr) + 4, ETH_ALEN);
1722
1723         /* Store the M4-PACKET.req for later */
1724         spin_lock(&priv->wapi_lock);
1725         interfacePriv->wapi_unicast_ma_pkt_sig = signal;
1726         interfacePriv->wapi_unicast_bulk_data.net_buf_length = bulkdata.d[0].net_buf_length;
1727         interfacePriv->wapi_unicast_bulk_data.data_length = bulkdata.d[0].data_length;
1728         interfacePriv->wapi_unicast_bulk_data.os_data_ptr = bulkdata.d[0].os_data_ptr;
1729         interfacePriv->wapi_unicast_bulk_data.os_net_buf_ptr = bulkdata.d[0].os_net_buf_ptr;
1730         spin_unlock(&priv->wapi_lock);
1731
1732         /* Signal the workqueue to call CsrWifiRouterCtrlWapiUnicastTxEncryptIndSend().
1733          * It cannot be called directly from the tx path because it
1734          * does a non-atomic kmalloc via the framework's CsrPmemAlloc().
1735          */
1736         queue_work(priv->unifi_workqueue, &netpriv->send_pkt_to_encrypt);
1737
1738         return 0;
1739     }
1740 #endif
1741
1742     if(priv->cmanrTestMode)
1743     {
1744         TransmitRate = priv->cmanrTestModeTransmitRate;
1745         unifi_trace(priv, UDBG2, "send_ma_pkt_request: cmanrTestModeTransmitRate = %d TransmitRate=%d\n",
1746                     priv->cmanrTestModeTransmitRate,
1747                     TransmitRate
1748                    );
1749     }
1750
1751     /* Send UniFi msg */
1752     /* Here hostTag is been sent as 0xffffffff, its been appended properly while framing MA-Packet request in pdu_processing.c file */
1753     r = uf_process_ma_packet_req(priv,
1754                                  peerAddress.a,
1755                                  0xffffffff,  /* Ask for a new HostTag */
1756                                  interfaceTag,
1757                                  transmissionControl,
1758                                  TransmitRate,
1759                                  priority,
1760                                  priv->netdev_client->sender_id,
1761                                  &bulkdata);
1762
1763     if (r) {
1764         unifi_trace(priv, UDBG1, "(HIP validation failure) r = %x\n", r);
1765         unifi_net_data_free(priv, &bulkdata.d[0]);
1766         return -1;
1767     }
1768
1769     unifi_trace(priv, UDBG3, "leaving send_ma_pkt_request, UNITDATA result code = %d\n", r);
1770
1771     return r;
1772 } /* send_ma_pkt_request() */
1773
1774 /*
1775  * ---------------------------------------------------------------------------
1776  *  uf_net_xmit
1777  *
1778  *      This function is called by the higher level stack to transmit an
1779  *      ethernet packet.
1780  *
1781  *  Arguments:
1782  *      skb     Ethernet packet to send.
1783  *      dev     Pointer to the linux net device.
1784  *
1785  *  Returns:
1786  *      0   on success (packet was consumed, not necessarily transmitted)
1787  *      1   if packet was requeued
1788  *     -1   on error
1789  *
1790  *
1791  *  Notes:
1792  *      The controlled port is handled in the qdisc dequeue handler.
1793  * ---------------------------------------------------------------------------
1794  */
1795 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,32)
1796 static netdev_tx_t
1797 #else
1798 static int
1799 #endif
1800 uf_net_xmit(struct sk_buff *skb, struct net_device *dev)
1801 {
1802     netInterface_priv_t *interfacePriv = (netInterface_priv_t *)netdev_priv(dev);
1803     unifi_priv_t *priv = interfacePriv->privPtr;
1804     struct ethhdr ehdr;
1805     int proto, port;
1806     int result;
1807     static tx_signal_handler tx_handler;
1808     CSR_PRIORITY priority;
1809     CsrWifiRouterCtrlPortAction port_action;
1810
1811     func_enter();
1812
1813     unifi_trace(priv, UDBG5, "unifi_net_xmit: skb = %x\n", skb);
1814
1815     memcpy(&ehdr, skb->data, ETH_HLEN);
1816     proto = ntohs(ehdr.h_proto);
1817     priority = get_packet_priority(priv, skb, &ehdr, interfacePriv);
1818
1819     /* All frames are sent as MA-PACKET.req (EAPOL also) */
1820     tx_handler = send_ma_pkt_request;
1821
1822     /* 802.1x - apply controlled/uncontrolled port rules */
1823     if ((proto != ETH_P_PAE)
1824 #ifdef CSR_WIFI_SECURITY_WAPI_ENABLE
1825             && (proto != ETH_P_WAI)
1826 #endif
1827        ) {
1828         port = UF_CONTROLLED_PORT_Q;
1829     } else {
1830         /* queue 4 */
1831         port = UF_UNCONTROLLED_PORT_Q;
1832     }
1833
1834     /* Uncontrolled port rules apply */
1835     port_action = verify_port(priv
1836         , (((CSR_WIFI_ROUTER_CTRL_MODE_STA == interfacePriv->interfaceMode)||(CSR_WIFI_ROUTER_CTRL_MODE_P2PCLI== interfacePriv->interfaceMode))? interfacePriv->bssid.a: ehdr.h_dest)
1837         , port
1838         , interfacePriv->InterfaceTag);
1839
1840     if (port_action == CSR_WIFI_ROUTER_CTRL_PORT_ACTION_8021X_PORT_OPEN) {
1841         unifi_trace(priv, UDBG5,
1842                     "uf_net_xmit: %s controlled port open\n",
1843                     port ? "" : "un");
1844         /* Remove the ethernet header */
1845         skb_pull(skb, ETH_HLEN);
1846         result = tx_handler(priv, skb, &ehdr, priority);
1847     } else {
1848
1849         /* Discard the packet if necessary */
1850         unifi_trace(priv, UDBG2,
1851                 "uf_net_xmit: %s controlled port %s\n",
1852                 port ? "" : "un", port_action==CSR_WIFI_ROUTER_CTRL_PORT_ACTION_8021X_PORT_CLOSED_BLOCK ? "blocked" : "closed");
1853         interfacePriv->stats.tx_dropped++;
1854         kfree_skb(skb);
1855
1856         func_exit();
1857         return NETDEV_TX_OK;
1858     }
1859
1860     if (result == NETDEV_TX_OK) {
1861 #if (defined(CSR_WIFI_SECURITY_WAPI_ENABLE) && defined(CSR_WIFI_SECURITY_WAPI_SW_ENCRYPTION))
1862         /* Don't update the tx stats when the pkt is to be sent for sw encryption*/
1863         if (!((CSR_WIFI_ROUTER_CTRL_MODE_STA == interfacePriv->interfaceMode) &&
1864               (priv->wapi_unicast_filter == 1)))
1865         {
1866             dev->trans_start = jiffies;
1867             /* Should really count tx stats in the UNITDATA.status signal but
1868              * that doesn't have the length.
1869              */
1870             interfacePriv->stats.tx_packets++;
1871             /* count only the packet payload */
1872             interfacePriv->stats.tx_bytes += skb->len;
1873
1874         }
1875 #else
1876         dev->trans_start = jiffies;
1877
1878         /*
1879          * Should really count tx stats in the UNITDATA.status signal but
1880          * that doesn't have the length.
1881          */
1882         interfacePriv->stats.tx_packets++;
1883         /* count only the packet payload */
1884         interfacePriv->stats.tx_bytes += skb->len;
1885 #endif
1886     } else if (result < 0) {
1887
1888         /* Failed to send: fh queue was full, and the skb was discarded.
1889          * Return OK to indicate that the buffer was consumed, to stop the
1890          * kernel re-transmitting the freed buffer.
1891          */
1892         interfacePriv->stats.tx_dropped++;
1893         unifi_trace(priv, UDBG1, "unifi_net_xmit: (Packet Drop), dropped count = %x\n", interfacePriv->stats.tx_dropped);
1894         result = NETDEV_TX_OK;
1895     }
1896
1897     /* The skb will have been freed by send_XXX_request() */
1898
1899     func_exit();
1900     return result;
1901 } /* uf_net_xmit() */
1902
1903 /*
1904  * ---------------------------------------------------------------------------
1905  *  unifi_pause_xmit
1906  *  unifi_restart_xmit
1907  *
1908  *      These functions are called from the UniFi core to control the flow
1909  *      of packets from the upper layers.
1910  *      unifi_pause_xmit() is called when the internal queue is full and
1911  *      should take action to stop unifi_ma_unitdata() being called.
1912  *      When the queue has drained, unifi_restart_xmit() will be called to
1913  *      re-enable the flow of packets for transmission.
1914  *
1915  *  Arguments:
1916  *      ospriv          OS private context pointer.
1917  *
1918  *  Returns:
1919  *      unifi_pause_xmit() is called from interrupt context.
1920  * ---------------------------------------------------------------------------
1921  */
1922 void
1923 unifi_pause_xmit(void *ospriv, unifi_TrafficQueue queue)
1924 {
1925     unifi_priv_t *priv = ospriv;
1926     int i; /* used as a loop counter */
1927
1928     func_enter();
1929     unifi_trace(priv, UDBG2, "Stopping queue %d\n", queue);
1930
1931     for(i=0;i<CSR_WIFI_NUM_INTERFACES;i++)
1932     {
1933         if (netif_running(priv->netdev[i]))
1934         {
1935             netif_stop_subqueue(priv->netdev[i], (u16)queue);
1936         }
1937     }
1938
1939 #ifdef CSR_SUPPORT_SME
1940     if(queue<=3) {
1941         routerStartBuffering(priv,queue);
1942         unifi_trace(priv,UDBG2,"Start buffering %d\n", queue);
1943      } else {
1944         routerStartBuffering(priv,0);
1945         unifi_error(priv, "Start buffering %d defaulting to 0\n", queue);
1946      }
1947 #endif
1948     func_exit();
1949
1950 } /* unifi_pause_xmit() */
1951
1952 void
1953 unifi_restart_xmit(void *ospriv, unifi_TrafficQueue queue)
1954 {
1955     unifi_priv_t *priv = ospriv;
1956     int i=0; /* used as a loop counter */
1957
1958     func_enter();
1959     unifi_trace(priv, UDBG2, "Waking queue %d\n", queue);
1960
1961     for(i=0;i<CSR_WIFI_NUM_INTERFACES;i++)
1962     {
1963         if (netif_running(priv->netdev[i]))
1964         {
1965             netif_wake_subqueue(priv->netdev[i], (u16)queue);
1966         }
1967     }
1968
1969 #ifdef CSR_SUPPORT_SME
1970     if(queue <=3) {
1971         routerStopBuffering(priv,queue);
1972         uf_send_buffered_frames(priv,queue);
1973     } else {
1974         routerStopBuffering(priv,0);
1975         uf_send_buffered_frames(priv,0);
1976     }
1977 #endif
1978     func_exit();
1979 } /* unifi_restart_xmit() */
1980
1981
1982 static void
1983 indicate_rx_skb(unifi_priv_t *priv, u16 ifTag, u8* dst_a, u8* src_a, struct sk_buff *skb, CSR_SIGNAL *signal,
1984                 bulk_data_param_t *bulkdata)
1985 {
1986     int r, sr = 0;
1987     struct net_device *dev;
1988
1989 #ifdef CSR_SUPPORT_SME
1990     llc_snap_hdr_t *snap;
1991
1992     snap = (llc_snap_hdr_t *)skb->data;
1993
1994     sr = _identify_sme_ma_pkt_ind(priv,
1995                                   snap->oui, ntohs(snap->protocol),
1996                                   signal,
1997                                   bulkdata,
1998                                   dst_a, src_a );
1999 #endif
2000
2001     /*
2002      * Decapsulate any SNAP header and
2003      * prepend an ethernet header so that the skb manipulation and ARP
2004      * stuff works.
2005      */
2006     r = skb_80211_to_ether(priv, skb, dst_a, src_a,
2007                            signal, bulkdata);
2008     if (r == -1) {
2009         /* Drop the packet and return */
2010         priv->interfacePriv[ifTag]->stats.rx_errors++;
2011         priv->interfacePriv[ifTag]->stats.rx_frame_errors++;
2012         unifi_net_data_free(priv, &bulkdata->d[0]);
2013         unifi_notice(priv, "indicate_rx_skb: Discard unknown frame.\n");
2014         func_exit();
2015         return;
2016     }
2017
2018     /* Handle the case where packet is sent up through the subscription
2019      * API but should not be given to the network stack (AMP PAL case)
2020      * LLC header is different from WiFi and the packet has been subscribed for
2021      */
2022     if (r == 1 && sr == 1) {
2023         unifi_net_data_free(priv, &bulkdata->d[0]);
2024         unifi_trace(priv, UDBG5, "indicate_rx_skb: Data given to subscription"
2025                 "API, not being given to kernel\n");
2026         func_exit();
2027         return;
2028     }
2029
2030     dev = priv->netdev[ifTag];
2031     /* Now we look like a regular ethernet frame */
2032     /* Fill in SKB meta data */
2033     skb->dev = dev;
2034     skb->protocol = eth_type_trans(skb, dev);
2035     skb->ip_summed = CHECKSUM_UNNECESSARY;
2036
2037     /* Test for an overlength frame */
2038     if (skb->len > (dev->mtu + ETH_HLEN)) {
2039         /* A bogus length ethfrm has been encap'd. */
2040         /* Is someone trying an oflow attack? */
2041         unifi_error(priv, "%s: oversize frame (%d > %d)\n",
2042                     dev->name,
2043                     skb->len, dev->mtu + ETH_HLEN);
2044
2045         /* Drop the packet and return */
2046         priv->interfacePriv[ifTag]->stats.rx_errors++;
2047         priv->interfacePriv[ifTag]->stats.rx_length_errors++;
2048         unifi_net_data_free(priv, &bulkdata->d[0]);
2049         func_exit();
2050         return;
2051     }
2052
2053
2054     if(priv->cmanrTestMode)
2055     {
2056         const CSR_MA_PACKET_INDICATION *pkt_ind = &signal->u.MaPacketIndication;
2057         priv->cmanrTestModeTransmitRate = pkt_ind->ReceivedRate;
2058         unifi_trace(priv, UDBG2, "indicate_rx_skb: cmanrTestModeTransmitRate=%d\n", priv->cmanrTestModeTransmitRate);
2059     }
2060
2061     /* Pass SKB up the stack */
2062 #ifdef CSR_WIFI_USE_NETIF_RX
2063         netif_rx(skb);
2064 #else
2065         netif_rx_ni(skb);
2066 #endif
2067
2068     if (dev != NULL) {
2069         dev->last_rx = jiffies;
2070     }
2071
2072     /* Bump rx stats */
2073     priv->interfacePriv[ifTag]->stats.rx_packets++;
2074     priv->interfacePriv[ifTag]->stats.rx_bytes += bulkdata->d[0].data_length;
2075
2076     func_exit();
2077     return;
2078 }
2079
2080 void
2081 uf_process_rx_pending_queue(unifi_priv_t *priv, int queue,
2082                             CsrWifiMacAddress source_address,
2083                             int indicate, u16 interfaceTag)
2084 {
2085     rx_buffered_packets_t *rx_q_item;
2086     struct list_head *rx_list;
2087     struct list_head *n;
2088     struct list_head *l_h;
2089     static const CsrWifiMacAddress broadcast_address = {{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}};
2090     netInterface_priv_t *interfacePriv = priv->interfacePriv[interfaceTag];
2091
2092     if (interfaceTag >= CSR_WIFI_NUM_INTERFACES) {
2093         unifi_error(priv, "uf_process_rx_pending_queue bad interfaceTag\n");
2094         return;
2095     }
2096
2097     if (queue == UF_CONTROLLED_PORT_Q) {
2098         rx_list = &interfacePriv->rx_controlled_list;
2099     } else {
2100         rx_list = &interfacePriv->rx_uncontrolled_list;
2101     }
2102
2103     down(&priv->rx_q_sem);
2104     list_for_each_safe(l_h, n, rx_list) {
2105         rx_q_item = list_entry(l_h, rx_buffered_packets_t, q);
2106
2107         /* Validate against the source address */
2108         if (memcmp(broadcast_address.a, source_address.a, ETH_ALEN) &&
2109                 memcmp(rx_q_item->sa.a, source_address.a, ETH_ALEN)) {
2110
2111             unifi_trace(priv, UDBG2,
2112                         "uf_process_rx_pending_queue: Skipping sa=%02X%02X%02X%02X%02X%02X skb=%p, bulkdata=%p\n",
2113                         rx_q_item->sa.a[0], rx_q_item->sa.a[1],
2114                         rx_q_item->sa.a[2], rx_q_item->sa.a[3],
2115                         rx_q_item->sa.a[4], rx_q_item->sa.a[5],
2116                         rx_q_item->skb, &rx_q_item->bulkdata.d[0]);
2117             continue;
2118         }
2119
2120         list_del(l_h);
2121
2122
2123         unifi_trace(priv, UDBG2,
2124                     "uf_process_rx_pending_queue: Was Blocked skb=%p, bulkdata=%p\n",
2125                     rx_q_item->skb, &rx_q_item->bulkdata);
2126
2127         if (indicate) {
2128             indicate_rx_skb(priv, interfaceTag, rx_q_item->da.a, rx_q_item->sa.a, rx_q_item->skb, &rx_q_item->signal, &rx_q_item->bulkdata);
2129         } else {
2130             interfacePriv->stats.rx_dropped++;
2131             unifi_net_data_free(priv, &rx_q_item->bulkdata.d[0]);
2132         }
2133
2134         /* It is our resposibility to free the Rx structure object. */
2135         kfree(rx_q_item);
2136     }
2137     up(&priv->rx_q_sem);
2138 }
2139
2140 /*
2141  * ---------------------------------------------------------------------------
2142  *  uf_resume_data_plane
2143  *
2144  *      Is called when the (un)controlled port is set to open,
2145  *      to notify the network stack to schedule for transmission
2146  *      any packets queued in the qdisk while port was closed and
2147  *      indicated to the stack any packets buffered in the Rx queues.
2148  *
2149  *  Arguments:
2150  *      priv        Pointer to device private struct
2151  *
2152  *  Returns:
2153  * ---------------------------------------------------------------------------
2154  */
2155 void
2156 uf_resume_data_plane(unifi_priv_t *priv, int queue,
2157                      CsrWifiMacAddress peer_address,
2158                      u16 interfaceTag)
2159 {
2160 #ifdef CSR_SUPPORT_WEXT
2161     netInterface_priv_t *interfacePriv = priv->interfacePriv[interfaceTag];
2162 #endif
2163
2164     if (interfaceTag >= CSR_WIFI_NUM_INTERFACES) {
2165         unifi_error(priv, "uf_resume_data_plane bad interfaceTag\n");
2166         return;
2167     }
2168
2169     unifi_trace(priv, UDBG2, "Resuming netif\n");
2170
2171     /*
2172      * If we are waiting for the net device to enter the up state, don't
2173      * process the rx queue yet as it will be done by the callback when
2174      * the device is ready.
2175      */
2176 #ifdef CSR_SUPPORT_WEXT
2177     if (!interfacePriv->wait_netdev_change)
2178 #endif
2179     {
2180 #ifdef CONFIG_NET_SCHED
2181         if (netif_running(priv->netdev[interfaceTag])) {
2182             netif_tx_schedule_all(priv->netdev[interfaceTag]);
2183         }
2184 #endif
2185         uf_process_rx_pending_queue(priv, queue, peer_address, 1,interfaceTag);
2186     }
2187 } /* uf_resume_data_plane() */
2188
2189
2190 void uf_free_pending_rx_packets(unifi_priv_t *priv, int queue, CsrWifiMacAddress peer_address,u16 interfaceTag)
2191 {
2192     uf_process_rx_pending_queue(priv, queue, peer_address, 0,interfaceTag);
2193
2194 } /* uf_free_pending_rx_packets() */
2195
2196
2197 /*
2198  * ---------------------------------------------------------------------------
2199  *  unifi_rx
2200  *
2201  *      Reformat a UniFi data received packet into a p80211 packet and
2202  *      pass it up the protocol stack.
2203  *
2204  *  Arguments:
2205  *      None.
2206  *
2207  *  Returns:
2208  *      None.
2209  * ---------------------------------------------------------------------------
2210  */
2211 static void
2212 unifi_rx(unifi_priv_t *priv, CSR_SIGNAL *signal, bulk_data_param_t *bulkdata)
2213 {
2214     u16 interfaceTag;
2215     bulk_data_desc_t *pData;
2216     const CSR_MA_PACKET_INDICATION *pkt_ind = &signal->u.MaPacketIndication;
2217     struct sk_buff *skb;
2218     CsrWifiRouterCtrlPortAction port_action;
2219     u8 dataFrameType;
2220     int proto;
2221     int queue;
2222
2223     u8 da[ETH_ALEN], sa[ETH_ALEN];
2224     u8 toDs, fromDs, frameType, macHeaderLengthInBytes = MAC_HEADER_SIZE;
2225     u16 frameControl;
2226     netInterface_priv_t *interfacePriv;
2227     struct ethhdr ehdr;
2228
2229     func_enter();
2230
2231     interfaceTag = (pkt_ind->VirtualInterfaceIdentifier & 0xff);
2232     interfacePriv = priv->interfacePriv[interfaceTag];
2233
2234     /* Sanity check that the VIF refers to a sensible interface */
2235     if (interfaceTag >= CSR_WIFI_NUM_INTERFACES)
2236     {
2237         unifi_error(priv, "%s: MA-PACKET indication with bad interfaceTag %d\n", __FUNCTION__, interfaceTag);
2238         unifi_net_data_free(priv,&bulkdata->d[0]);
2239         func_exit();
2240         return;
2241     }
2242
2243     /* Sanity check that the VIF refers to an allocated netdev */
2244     if (!interfacePriv->netdev_registered)
2245     {
2246         unifi_error(priv, "%s: MA-PACKET indication with unallocated interfaceTag %d\n", __FUNCTION__, interfaceTag);
2247         unifi_net_data_free(priv, &bulkdata->d[0]);
2248         func_exit();
2249         return;
2250     }
2251
2252     if (bulkdata->d[0].data_length == 0) {
2253         unifi_warning(priv, "%s: MA-PACKET indication with zero bulk data\n", __FUNCTION__);
2254         unifi_net_data_free(priv,&bulkdata->d[0]);
2255         func_exit();
2256         return;
2257     }
2258
2259
2260     skb = (struct sk_buff*)bulkdata->d[0].os_net_buf_ptr;
2261     skb->len = bulkdata->d[0].data_length;
2262
2263     /* Point to the addresses */
2264     toDs = (skb->data[1] & 0x01) ? 1 : 0;
2265     fromDs = (skb->data[1] & 0x02) ? 1 : 0;
2266
2267     memcpy(da,(skb->data+4+toDs*12),ETH_ALEN);/* Address1 or 3 */
2268     memcpy(sa,(skb->data+10+fromDs*(6+toDs*8)),ETH_ALEN); /* Address2, 3 or 4 */
2269
2270
2271     pData = &bulkdata->d[0];
2272     frameControl = CSR_GET_UINT16_FROM_LITTLE_ENDIAN(pData->os_data_ptr);
2273     frameType = ((frameControl & 0x000C) >> 2);
2274
2275     dataFrameType =((frameControl & 0x00f0) >> 4);
2276     unifi_trace(priv, UDBG6,
2277                 "%s: Receive Data Frame Type %d \n", __FUNCTION__,dataFrameType);
2278
2279     switch(dataFrameType)
2280     {
2281         case QOS_DATA:
2282         case QOS_DATA_NULL:
2283             /* If both are set then the Address4 exists (only for AP) */
2284             if (fromDs && toDs)
2285             {
2286                 /* 6 is the size of Address4 field */
2287                 macHeaderLengthInBytes += (QOS_CONTROL_HEADER_SIZE + 6);
2288             }
2289             else
2290             {
2291                 macHeaderLengthInBytes += QOS_CONTROL_HEADER_SIZE;
2292             }
2293
2294             /* If order bit set then HT control field is the part of MAC header */
2295             if (frameControl & FRAME_CONTROL_ORDER_BIT)
2296                 macHeaderLengthInBytes += HT_CONTROL_HEADER_SIZE;
2297             break;
2298         default:
2299             if (fromDs && toDs)
2300                 macHeaderLengthInBytes += 6;
2301     }
2302
2303     /* Prepare the ethernet header from snap header of skb data */
2304     switch(dataFrameType)
2305     {
2306         case DATA_NULL:
2307         case QOS_DATA_NULL:
2308             /* This is for only queue info fetching, EAPOL wont come as
2309              * null data so the proto is initialized as zero
2310              */
2311             proto = 0x0;
2312             break;
2313         default:
2314             {
2315                 llc_snap_hdr_t *snap;
2316                 /* Fetch a snap header to find protocol (for IPV4/IPV6 packets
2317                  * the snap header fetching offset is same)
2318                  */
2319                 snap = (llc_snap_hdr_t *) (skb->data + macHeaderLengthInBytes);
2320
2321                 /* prepare the ethernet header from the snap header & addresses */
2322                 ehdr.h_proto = snap->protocol;
2323                 memcpy(ehdr.h_dest, da, ETH_ALEN);
2324                 memcpy(ehdr.h_source, sa, ETH_ALEN);
2325             }
2326             proto = ntohs(ehdr.h_proto);
2327     }
2328     unifi_trace(priv, UDBG3, "in unifi_rx protocol from snap header = 0x%x\n", proto);
2329
2330     if ((proto != ETH_P_PAE)
2331 #ifdef CSR_WIFI_SECURITY_WAPI_ENABLE
2332             && (proto != ETH_P_WAI)
2333 #endif
2334        ) {
2335         queue = UF_CONTROLLED_PORT_Q;
2336     } else {
2337         queue = UF_UNCONTROLLED_PORT_Q;
2338     }
2339
2340     port_action = verify_port(priv, (unsigned char*)sa, queue, interfaceTag);
2341     unifi_trace(priv, UDBG3, "in unifi_rx port action is = 0x%x & queue = %x\n", port_action, queue);
2342
2343 #ifdef CSR_SUPPORT_SME
2344     /* Notify the TA module for the Rx frame for non P2PGO and AP cases*/
2345     if((interfacePriv->interfaceMode != CSR_WIFI_ROUTER_CTRL_MODE_AP) &&
2346             (interfacePriv->interfaceMode != CSR_WIFI_ROUTER_CTRL_MODE_P2PGO))
2347     {
2348         /* Remove MAC header of length(macHeaderLengthInBytes) before sampling */
2349         skb_pull(skb, macHeaderLengthInBytes);
2350         pData->os_data_ptr = skb->data;
2351         pData->data_length -= macHeaderLengthInBytes;
2352
2353         if (pData->data_length) {
2354             unifi_ta_sample(priv->card, CSR_WIFI_ROUTER_CTRL_PROTOCOL_DIRECTION_RX,
2355                             &bulkdata->d[0],
2356                             sa, priv->netdev[interfaceTag]->dev_addr,
2357                             jiffies_to_msecs(jiffies),
2358                             pkt_ind->ReceivedRate);
2359         }
2360     } else {
2361
2362         /* AP/P2PGO specific handling here */
2363         CsrWifiRouterCtrlStaInfo_t * srcStaInfo =
2364             CsrWifiRouterCtrlGetStationRecordFromPeerMacAddress(priv,sa,interfaceTag);
2365
2366         /* Defensive check only; Source address is already checked in
2367         process_ma_packet_ind and we should have a valid source address here */
2368
2369          if(srcStaInfo == NULL) {
2370             CsrWifiMacAddress peerMacAddress;
2371             /* Unknown data PDU */
2372             memcpy(peerMacAddress.a,sa,ETH_ALEN);
2373             unifi_trace(priv, UDBG1, "%s: Unexpected frame from peer = %x:%x:%x:%x:%x:%x\n", __FUNCTION__,
2374             sa[0], sa[1],sa[2], sa[3], sa[4],sa[5]);
2375             CsrWifiRouterCtrlUnexpectedFrameIndSend(priv->CSR_WIFI_SME_IFACEQUEUE,0,interfaceTag,peerMacAddress);
2376             unifi_net_data_free(priv, &bulkdata->d[0]);
2377             func_exit();
2378             return;
2379         }
2380
2381        /* For AP GO mode, don't store the PDUs */
2382         if (port_action != CSR_WIFI_ROUTER_CTRL_PORT_ACTION_8021X_PORT_OPEN) {
2383             /* Drop the packet and return */
2384             CsrWifiMacAddress peerMacAddress;
2385             memcpy(peerMacAddress.a,sa,ETH_ALEN);
2386             unifi_trace(priv, UDBG3, "%s: Port is not open: unexpected frame from peer = %x:%x:%x:%x:%x:%x\n",
2387                         __FUNCTION__, sa[0], sa[1],sa[2], sa[3], sa[4],sa[5]);
2388
2389             CsrWifiRouterCtrlUnexpectedFrameIndSend(priv->CSR_WIFI_SME_IFACEQUEUE,0,interfaceTag,peerMacAddress);
2390             interfacePriv->stats.rx_dropped++;
2391             unifi_net_data_free(priv, &bulkdata->d[0]);
2392             unifi_notice(priv, "%s: Dropping packet, proto=0x%04x, %s port\n", __FUNCTION__,
2393                          proto, queue ? "Controlled" : "Un-controlled");
2394             func_exit();
2395             return;
2396         }
2397
2398          /* Qos NULL/Data NULL  are freed here and not processed further */
2399         if((dataFrameType == QOS_DATA_NULL) || (dataFrameType == DATA_NULL)){
2400             unifi_trace(priv, UDBG5, "%s: Null Frame Received and Freed\n", __FUNCTION__);
2401             unifi_net_data_free(priv, &bulkdata->d[0]);
2402             func_exit();
2403             return;
2404         }
2405
2406         /* Now we have done with MAC header so proceed with the real data part*/
2407         /* This function takes care of appropriate routing for AP/P2PGO case*/
2408         /* the function hadnles following things
2409            2. Routing the PDU to appropriate location
2410            3. Error case handling
2411            */
2412         if(!(uf_ap_process_data_pdu(priv, skb, &ehdr, srcStaInfo,
2413              signal,
2414              bulkdata,
2415              macHeaderLengthInBytes)))
2416         {
2417             func_exit();
2418             return;
2419         }
2420         unifi_trace(priv, UDBG5, "unifi_rx: no specific AP handling process as normal frame, MAC Header len %d\n",macHeaderLengthInBytes);
2421         /* Remove the MAC header for subsequent conversion */
2422         skb_pull(skb, macHeaderLengthInBytes);
2423         pData->os_data_ptr = skb->data;
2424         pData->data_length -= macHeaderLengthInBytes;
2425         pData->os_net_buf_ptr = (unsigned char*)skb;
2426         pData->net_buf_length = skb->len;
2427     }
2428 #endif /* CSR_SUPPORT_SME */
2429
2430
2431     /* Now that the MAC header is removed, null-data frames have zero length
2432      * and can be dropped
2433      */
2434     if (pData->data_length == 0) {
2435         if (((frameControl & 0x00f0) >> 4) != QOS_DATA_NULL &&
2436             ((frameControl & 0x00f0) >> 4) != DATA_NULL) {
2437             unifi_trace(priv, UDBG1, "Zero length frame, but not null-data %04x\n", frameControl);
2438         }
2439         unifi_net_data_free(priv, &bulkdata->d[0]);
2440         func_exit();
2441         return;
2442     }
2443
2444     if (port_action == CSR_WIFI_ROUTER_CTRL_PORT_ACTION_8021X_PORT_CLOSED_DISCARD) {
2445         /* Drop the packet and return */
2446         interfacePriv->stats.rx_dropped++;
2447         unifi_net_data_free(priv, &bulkdata->d[0]);
2448         unifi_notice(priv, "%s: Dropping packet, proto=0x%04x, %s port\n",
2449                      __FUNCTION__, proto, queue ? "controlled" : "uncontrolled");
2450         func_exit();
2451         return;
2452     } else if ( (port_action == CSR_WIFI_ROUTER_CTRL_PORT_ACTION_8021X_PORT_CLOSED_BLOCK) ||
2453                    (interfacePriv->connected != UnifiConnected) ) {
2454
2455         /* Buffer the packet into the Rx queues */
2456         rx_buffered_packets_t *rx_q_item;
2457         struct list_head *rx_list;
2458
2459         rx_q_item = (rx_buffered_packets_t *)kmalloc(sizeof(rx_buffered_packets_t),
2460                 GFP_KERNEL);
2461         if (rx_q_item == NULL) {
2462             unifi_error(priv, "%s: Failed to allocate %d bytes for rx packet record\n",
2463                         __FUNCTION__, sizeof(rx_buffered_packets_t));
2464             interfacePriv->stats.rx_dropped++;
2465             unifi_net_data_free(priv, &bulkdata->d[0]);
2466             func_exit();
2467             return;
2468         }
2469
2470         INIT_LIST_HEAD(&rx_q_item->q);
2471         rx_q_item->bulkdata = *bulkdata;
2472         rx_q_item->skb = skb;
2473         rx_q_item->signal = *signal;
2474         memcpy(rx_q_item->sa.a, sa, ETH_ALEN);
2475         memcpy(rx_q_item->da.a, da, ETH_ALEN);
2476         unifi_trace(priv, UDBG2, "%s: Blocked skb=%p, bulkdata=%p\n",
2477                     __FUNCTION__, rx_q_item->skb, &rx_q_item->bulkdata);
2478
2479         if (queue == UF_CONTROLLED_PORT_Q) {
2480             rx_list = &interfacePriv->rx_controlled_list;
2481         } else {
2482             rx_list = &interfacePriv->rx_uncontrolled_list;
2483         }
2484
2485         /* Add to tail of packets queue */
2486         down(&priv->rx_q_sem);
2487         list_add_tail(&rx_q_item->q, rx_list);
2488         up(&priv->rx_q_sem);
2489
2490         func_exit();
2491         return;
2492
2493     }
2494
2495     indicate_rx_skb(priv, interfaceTag, da, sa, skb, signal, bulkdata);
2496
2497     func_exit();
2498
2499 } /* unifi_rx() */
2500
2501 static void process_ma_packet_cfm(unifi_priv_t *priv, CSR_SIGNAL *signal, bulk_data_param_t *bulkdata)
2502 {
2503     u16 interfaceTag;
2504     const CSR_MA_PACKET_CONFIRM *pkt_cfm = &signal->u.MaPacketConfirm;
2505     netInterface_priv_t *interfacePriv;
2506
2507     func_enter();
2508     interfaceTag = (pkt_cfm->VirtualInterfaceIdentifier & 0xff);
2509     interfacePriv = priv->interfacePriv[interfaceTag];
2510
2511     /* Sanity check that the VIF refers to a sensible interface */
2512     if (interfaceTag >= CSR_WIFI_NUM_INTERFACES)
2513     {
2514         unifi_error(priv, "%s: MA-PACKET confirm with bad interfaceTag %d\n", __FUNCTION__, interfaceTag);
2515         func_exit();
2516         return;
2517     }
2518 #ifdef CSR_SUPPORT_SME
2519     if(interfacePriv->interfaceMode == CSR_WIFI_ROUTER_CTRL_MODE_AP ||
2520        interfacePriv->interfaceMode == CSR_WIFI_ROUTER_CTRL_MODE_P2PGO) {
2521
2522         uf_process_ma_pkt_cfm_for_ap(priv,interfaceTag,pkt_cfm);
2523     } else if (interfacePriv->m4_sent && (pkt_cfm->HostTag == interfacePriv->m4_hostTag)) {
2524         /* Check if this is a confirm for EAPOL M4 frame and we need to send transmistted ind*/
2525         CsrResult result = pkt_cfm->TransmissionStatus == CSR_TX_SUCCESSFUL?CSR_RESULT_SUCCESS:CSR_RESULT_FAILURE;
2526         CsrWifiMacAddress peerMacAddress;
2527         memcpy(peerMacAddress.a, interfacePriv->m4_signal.u.MaPacketRequest.Ra.x, ETH_ALEN);
2528
2529         unifi_trace(priv, UDBG1, "%s: Sending M4 Transmit CFM\n", __FUNCTION__);
2530         CsrWifiRouterCtrlM4TransmittedIndSend(priv->CSR_WIFI_SME_IFACEQUEUE, 0,
2531                                               interfaceTag,
2532                                               peerMacAddress,
2533                                               result);
2534         interfacePriv->m4_sent = FALSE;
2535         interfacePriv->m4_hostTag = 0xffffffff;
2536     }
2537 #endif
2538     func_exit();
2539     return;
2540 }
2541
2542
2543 /*
2544  * ---------------------------------------------------------------------------
2545  *  unifi_rx
2546  *
2547  *      Reformat a UniFi data received packet into a p80211 packet and
2548  *      pass it up the protocol stack.
2549  *
2550  *  Arguments:
2551  *      None.
2552  *
2553  *  Returns:
2554  *      None.
2555  * ---------------------------------------------------------------------------
2556  */
2557 static void process_ma_packet_ind(unifi_priv_t *priv, CSR_SIGNAL *signal, bulk_data_param_t *bulkdata)
2558 {
2559     u16 interfaceTag;
2560     bulk_data_desc_t *pData;
2561     CSR_MA_PACKET_INDICATION *pkt_ind = (CSR_MA_PACKET_INDICATION*)&signal->u.MaPacketIndication;
2562     struct sk_buff *skb;
2563     u16 frameControl;
2564     netInterface_priv_t *interfacePriv;
2565     u8 da[ETH_ALEN], sa[ETH_ALEN];
2566     u8 *bssid = NULL, *ba_addr = NULL;
2567     u8 toDs, fromDs, frameType;
2568     u8 i =0;
2569
2570 #ifdef CSR_SUPPORT_SME
2571     u8 dataFrameType = 0;
2572     u8 powerSaveChanged = FALSE;
2573     u8 pmBit = 0;
2574     CsrWifiRouterCtrlStaInfo_t *srcStaInfo = NULL;
2575     u16 qosControl;
2576
2577 #endif
2578
2579     func_enter();
2580
2581     interfaceTag = (pkt_ind->VirtualInterfaceIdentifier & 0xff);
2582     interfacePriv = priv->interfacePriv[interfaceTag];
2583
2584
2585     /* Sanity check that the VIF refers to a sensible interface */
2586     if (interfaceTag >= CSR_WIFI_NUM_INTERFACES)
2587     {
2588         unifi_error(priv, "%s: MA-PACKET indication with bad interfaceTag %d\n", __FUNCTION__, interfaceTag);
2589         unifi_net_data_free(priv,&bulkdata->d[0]);
2590         func_exit();
2591         return;
2592     }
2593
2594     /* Sanity check that the VIF refers to an allocated netdev */
2595     if (!interfacePriv->netdev_registered)
2596     {
2597         unifi_error(priv, "%s: MA-PACKET indication with unallocated interfaceTag %d\n", __FUNCTION__, interfaceTag);
2598         unifi_net_data_free(priv, &bulkdata->d[0]);
2599         func_exit();
2600         return;
2601     }
2602
2603     if (bulkdata->d[0].data_length == 0) {
2604         unifi_warning(priv, "%s: MA-PACKET indication with zero bulk data\n", __FUNCTION__);
2605         unifi_net_data_free(priv,&bulkdata->d[0]);
2606         func_exit();
2607         return;
2608     }
2609     /* For monitor mode we need to pass this indication to the registered application
2610     handle this seperately*/
2611     /* MIC failure is already taken care of so no need to send the PDUs which are not successfully received in non-monitor mode*/
2612     if(pkt_ind->ReceptionStatus != CSR_RX_SUCCESS)
2613     {
2614         unifi_warning(priv, "%s: MA-PACKET indication with status = %d\n",__FUNCTION__, pkt_ind->ReceptionStatus);
2615         unifi_net_data_free(priv,&bulkdata->d[0]);
2616         func_exit();
2617         return;
2618     }
2619
2620
2621     skb = (struct sk_buff*)bulkdata->d[0].os_net_buf_ptr;
2622     skb->len = bulkdata->d[0].data_length;
2623
2624     /* Point to the addresses */
2625     toDs = (skb->data[1] & 0x01) ? 1 : 0;
2626     fromDs = (skb->data[1] & 0x02) ? 1 : 0;
2627
2628     memcpy(da,(skb->data+4+toDs*12),ETH_ALEN);/* Address1 or 3 */
2629     memcpy(sa,(skb->data+10+fromDs*(6+toDs*8)),ETH_ALEN); /* Address2, 3 or 4 */
2630
2631     /* Find the BSSID, which will be used to match the BA session */
2632     if (toDs && fromDs)
2633     {
2634         unifi_trace(priv, UDBG6, "4 address frame - don't try to find BSSID\n");
2635         bssid = NULL;
2636     }
2637     else
2638     {
2639         bssid = (u8 *) (skb->data + 4 + 12 - (fromDs * 6) - (toDs * 12));
2640     }
2641
2642     pData = &bulkdata->d[0];
2643     frameControl = CSR_GET_UINT16_FROM_LITTLE_ENDIAN(pData->os_data_ptr);
2644     frameType = ((frameControl & 0x000C) >> 2);
2645
2646     unifi_trace(priv, UDBG3, "Rx Frame Type: %d sn: %d\n",frameType,
2647          (le16_to_cpu(*((u16*)(bulkdata->d[0].os_data_ptr + IEEE802_11_SEQUENCE_CONTROL_OFFSET))) >> 4) & 0xfff);
2648     if(frameType == IEEE802_11_FRAMETYPE_CONTROL){
2649 #ifdef CSR_SUPPORT_SME
2650         unifi_trace(priv, UDBG6, "%s: Received Control Frame\n", __FUNCTION__);
2651
2652         if((frameControl & 0x00f0) == 0x00A0){
2653             /* This is a PS-POLL request */
2654             u8 pmBit = (frameControl & 0x1000)?0x01:0x00;
2655             unifi_trace(priv, UDBG6, "%s: Received PS-POLL Frame\n", __FUNCTION__);
2656
2657             uf_process_ps_poll(priv,sa,da,pmBit,interfaceTag);
2658         }
2659         else {
2660             unifi_warning(priv, "%s: Non PS-POLL control frame is received\n", __FUNCTION__);
2661         }
2662 #endif
2663         unifi_net_data_free(priv,&bulkdata->d[0]);
2664         func_exit();
2665         return;
2666     }
2667     if(frameType != IEEE802_11_FRAMETYPE_DATA) {
2668         unifi_warning(priv, "%s: Non control Non Data frame is received\n",__FUNCTION__);
2669         unifi_net_data_free(priv,&bulkdata->d[0]);
2670         func_exit();
2671         return;
2672     }
2673
2674 #ifdef CSR_SUPPORT_SME
2675     if((interfacePriv->interfaceMode == CSR_WIFI_ROUTER_CTRL_MODE_AP) ||
2676        (interfacePriv->interfaceMode == CSR_WIFI_ROUTER_CTRL_MODE_P2PGO)){
2677
2678         srcStaInfo = CsrWifiRouterCtrlGetStationRecordFromPeerMacAddress(priv,sa,interfaceTag);
2679
2680         if(srcStaInfo == NULL) {
2681             CsrWifiMacAddress peerMacAddress;
2682             /* Unknown data PDU */
2683             memcpy(peerMacAddress.a,sa,ETH_ALEN);
2684             unifi_trace(priv, UDBG1, "%s: Unexpected frame from peer = %x:%x:%x:%x:%x:%x\n", __FUNCTION__,
2685             sa[0], sa[1],sa[2], sa[3], sa[4],sa[5]);
2686             CsrWifiRouterCtrlUnexpectedFrameIndSend(priv->CSR_WIFI_SME_IFACEQUEUE,0,interfaceTag,peerMacAddress);
2687             unifi_net_data_free(priv, &bulkdata->d[0]);
2688             func_exit();
2689             return;
2690         }
2691
2692         /*
2693         verify power management bit here so as to ensure host and unifi are always
2694         in sync with power management status of peer.
2695
2696         If we do it later, it may so happen we have stored the frame in BA re-ordering
2697         buffer and hence host and unifi are out of sync for power management status
2698         */
2699
2700         pmBit = (frameControl & 0x1000)?0x01:0x00;
2701         powerSaveChanged = uf_process_pm_bit_for_peer(priv,srcStaInfo,pmBit,interfaceTag);
2702
2703         /* Update station last activity time */
2704         srcStaInfo->activity_flag = TRUE;
2705
2706         /* For Qos Frame if PM bit is toggled to indicate the change in power save state then it shall not be
2707         considered as Trigger Frame. Enter only if WMM STA and peer is in Power save */
2708
2709         dataFrameType = ((frameControl & 0x00f0) >> 4);
2710
2711         if((powerSaveChanged == FALSE)&&(srcStaInfo->wmmOrQosEnabled == TRUE)&&
2712         (srcStaInfo->currentPeerState == CSR_WIFI_ROUTER_CTRL_PEER_CONNECTED_POWER_SAVE)){
2713
2714             if((dataFrameType == QOS_DATA) || (dataFrameType == QOS_DATA_NULL)){
2715
2716                 /*
2717                  * QoS control field is offset from frame control by 2 (frame control)
2718                  * + 2 (duration/ID) + 2 (sequence control) + 3*ETH_ALEN or 4*ETH_ALEN
2719                  */
2720                 if((frameControl & IEEE802_11_FC_TO_DS_MASK) && (frameControl & IEEE802_11_FC_FROM_DS_MASK)){
2721                     qosControl= CSR_GET_UINT16_FROM_LITTLE_ENDIAN(pData->os_data_ptr + 30);
2722                 }
2723                 else{
2724                     qosControl = CSR_GET_UINT16_FROM_LITTLE_ENDIAN(pData->os_data_ptr + 24);
2725                 }
2726                 unifi_trace(priv, UDBG5, "%s: Check if U-APSD operations are triggered for qosControl: 0x%x\n",__FUNCTION__,qosControl);
2727                 uf_process_wmm_deliver_ac_uapsd(priv,srcStaInfo,qosControl,interfaceTag);
2728             }
2729         }
2730     }
2731
2732 #endif
2733
2734     if( ((frameControl & 0x00f0) >> 4) == QOS_DATA) {
2735         u8 *qos_control_ptr = (u8*)bulkdata->d[0].os_data_ptr + (((frameControl & IEEE802_11_FC_TO_DS_MASK) && (frameControl & IEEE802_11_FC_FROM_DS_MASK))?30: 24);
2736         int tID = *qos_control_ptr & IEEE802_11_QC_TID_MASK; /* using ls octet of qos control */
2737         ba_session_rx_struct *ba_session;
2738         u8 ba_session_idx = 0;
2739         /* Get the BA originator address */
2740         if(interfacePriv->interfaceMode == CSR_WIFI_ROUTER_CTRL_MODE_AP ||
2741            interfacePriv->interfaceMode == CSR_WIFI_ROUTER_CTRL_MODE_P2PGO){
2742             ba_addr = sa;
2743         }else{
2744             ba_addr = bssid;
2745         }
2746
2747         down(&priv->ba_mutex);
2748         for (ba_session_idx=0; ba_session_idx < MAX_SUPPORTED_BA_SESSIONS_RX; ba_session_idx++){
2749             ba_session = interfacePriv->ba_session_rx[ba_session_idx];
2750             if (ba_session){
2751                 unifi_trace(priv, UDBG6, "found ba_session=0x%x ba_session_idx=%d", ba_session, ba_session_idx);
2752                 if ((!memcmp(ba_session->macAddress.a, ba_addr, ETH_ALEN)) && (ba_session->tID == tID)){
2753                         frame_desc_struct frame_desc;
2754                         frame_desc.bulkdata = *bulkdata;
2755                         frame_desc.signal = *signal;
2756                         frame_desc.sn = (le16_to_cpu(*((u16*)(bulkdata->d[0].os_data_ptr + IEEE802_11_SEQUENCE_CONTROL_OFFSET))) >> 4) & 0xfff;
2757                         frame_desc.active = TRUE;
2758                         unifi_trace(priv, UDBG6, "%s: calling process_ba_frame (session=%d)\n", __FUNCTION__, ba_session_idx);
2759                         process_ba_frame(priv, interfacePriv, ba_session, &frame_desc);
2760                         up(&priv->ba_mutex);
2761                         process_ba_complete(priv, interfacePriv);
2762                         break;
2763                 }
2764             }
2765         }
2766         if (ba_session_idx == MAX_SUPPORTED_BA_SESSIONS_RX){
2767             up(&priv->ba_mutex);
2768             unifi_trace(priv, UDBG6, "%s: calling process_amsdu()", __FUNCTION__);
2769             process_amsdu(priv, signal, bulkdata);
2770         }
2771     } else {
2772         unifi_trace(priv, UDBG6, "calling unifi_rx()");
2773         unifi_rx(priv, signal, bulkdata);
2774     }
2775
2776     /* check if the frames in reorder buffer has aged, the check
2777      * is done after receive processing so that if the missing frame
2778      * has arrived in this receive process, then it is handled cleanly.
2779      *
2780      * And also this code here takes care that timeout check is made for all
2781      * the receive indications
2782      */
2783     down(&priv->ba_mutex);
2784     for (i=0; i < MAX_SUPPORTED_BA_SESSIONS_RX; i++){
2785         ba_session_rx_struct *ba_session;
2786         ba_session = interfacePriv->ba_session_rx[i];
2787             if (ba_session){
2788                 check_ba_frame_age_timeout(priv, interfacePriv, ba_session);
2789             }
2790     }
2791     up(&priv->ba_mutex);
2792     process_ba_complete(priv, interfacePriv);
2793
2794     func_exit();
2795 }
2796 /*
2797  * ---------------------------------------------------------------------------
2798  *  uf_set_multicast_list
2799  *
2800  *      This function is called by the higher level stack to set
2801  *      a list of multicast rx addresses.
2802  *
2803  *  Arguments:
2804  *      dev             Network Device pointer.
2805  *
2806  *  Returns:
2807  *      None.
2808  *
2809  *  Notes:
2810  * ---------------------------------------------------------------------------
2811  */
2812
2813 static void
2814 uf_set_multicast_list(struct net_device *dev)
2815 {
2816     netInterface_priv_t *interfacePriv = (netInterface_priv_t *)netdev_priv(dev);
2817     unifi_priv_t *priv = interfacePriv->privPtr;
2818
2819 #ifdef CSR_NATIVE_LINUX
2820     unifi_trace(priv, UDBG3, "uf_set_multicast_list unsupported\n");
2821     return;
2822 #else
2823
2824     u8 *mc_list = interfacePriv->mc_list;
2825 #if LINUX_VERSION_CODE > KERNEL_VERSION(2,6,34)
2826     struct netdev_hw_addr *mc_addr;
2827     int mc_addr_count;
2828 #else
2829     struct dev_mc_list *p;      /* Pointer to the addresses structure. */
2830     int i;
2831 #endif
2832
2833     if (priv->init_progress != UNIFI_INIT_COMPLETED) {
2834         return;
2835     }
2836
2837 #if LINUX_VERSION_CODE > KERNEL_VERSION(2,6,34)
2838     mc_addr_count = netdev_mc_count(dev);
2839
2840     unifi_trace(priv, UDBG3,
2841             "uf_set_multicast_list (count=%d)\n", mc_addr_count);
2842
2843
2844     /* Not enough space? */
2845     if (mc_addr_count > UNIFI_MAX_MULTICAST_ADDRESSES) {
2846         return;
2847     }
2848
2849     /* Store the list to be processed by the work item. */
2850     interfacePriv->mc_list_count = mc_addr_count;
2851     netdev_hw_addr_list_for_each(mc_addr, &dev->mc) {
2852         memcpy(mc_list, mc_addr->addr, ETH_ALEN);
2853         mc_list += ETH_ALEN;
2854     }
2855
2856 #else
2857     unifi_trace(priv, UDBG3,
2858             "uf_set_multicast_list (count=%d)\n", dev->mc_count);
2859
2860     /* Not enough space? */
2861     if (dev->mc_count > UNIFI_MAX_MULTICAST_ADDRESSES) {
2862         return;
2863     }
2864
2865     /* Store the list to be processed by the work item. */
2866     interfacePriv->mc_list_count = dev->mc_count;
2867     p = dev->mc_list;
2868     for (i = 0; i < dev->mc_count; i++) {
2869         memcpy(mc_list, p->dmi_addr, ETH_ALEN);
2870         p = p->next;
2871         mc_list += ETH_ALEN;
2872     }
2873 #endif
2874
2875     /* Send a message to the workqueue */
2876     queue_work(priv->unifi_workqueue, &priv->multicast_list_task);
2877 #endif
2878
2879 } /* uf_set_multicast_list() */
2880
2881 /*
2882  * ---------------------------------------------------------------------------
2883  *  netdev_mlme_event_handler
2884  *
2885  *      Callback function to be used as the udi_event_callback when registering
2886  *      as a netdev client.
2887  *      To use it, a client specifies this function as the udi_event_callback
2888  *      to ul_register_client(). The signal dispatcher in
2889  *      unifi_receive_event() will call this function to deliver a signal.
2890  *
2891  *  Arguments:
2892  *      pcli            Pointer to the client instance.
2893  *      signal          Pointer to the received signal.
2894  *      signal_len      Size of the signal structure in bytes.
2895  *      bulkdata        Pointer to structure containing any associated bulk data.
2896  *      dir             Direction of the signal. Zero means from host,
2897  *                      non-zero means to host.
2898  *
2899  *  Returns:
2900  *      None.
2901  * ---------------------------------------------------------------------------
2902  */
2903 static void
2904 netdev_mlme_event_handler(ul_client_t *pcli, const u8 *sig_packed, int sig_len,
2905                           const bulk_data_param_t *bulkdata_o, int dir)
2906 {
2907     CSR_SIGNAL signal;
2908     unifi_priv_t *priv = uf_find_instance(pcli->instance);
2909     int id, r;
2910     bulk_data_param_t bulkdata;
2911
2912     func_enter();
2913
2914     /* Just a sanity check */
2915     if (sig_packed == NULL) {
2916         return;
2917     }
2918
2919     /*
2920      * This copy is to silence a compiler warning about discarding the
2921      * const qualifier.
2922      */
2923     bulkdata = *bulkdata_o;
2924
2925     /* Get the unpacked signal */
2926     r = read_unpack_signal(sig_packed, &signal);
2927     if (r) {
2928         /*
2929          * The CSR_MLME_CONNECTED_INDICATION_ID has a receiverID=0 so will
2930          * fall through this case. It is safe to ignore this signal.
2931          */
2932         unifi_trace(priv, UDBG1,
2933                     "Netdev - Received unknown signal 0x%.4X.\n",
2934                     CSR_GET_UINT16_FROM_LITTLE_ENDIAN(sig_packed));
2935         return;
2936     }
2937
2938     id = signal.SignalPrimitiveHeader.SignalId;
2939     unifi_trace(priv, UDBG3, "Netdev - Process signal 0x%.4X\n", id);
2940
2941     /*
2942      * Take the appropriate action for the signal.
2943      */
2944     switch (id) {
2945         case CSR_MA_PACKET_ERROR_INDICATION_ID:
2946             process_ma_packet_error_ind(priv, &signal, &bulkdata);
2947             break;
2948         case CSR_MA_PACKET_INDICATION_ID:
2949             process_ma_packet_ind(priv, &signal, &bulkdata);
2950             break;
2951         case  CSR_MA_PACKET_CONFIRM_ID:
2952             process_ma_packet_cfm(priv, &signal, &bulkdata);
2953             break;
2954 #ifdef CSR_SUPPORT_SME
2955         case CSR_MLME_SET_TIM_CONFIRM_ID:
2956             /* Handle TIM confirms from FW & set the station record's TIM state appropriately,
2957              * In case of failures, tries with max_retransmit limit
2958              */
2959             uf_handle_tim_cfm(priv, &signal.u.MlmeSetTimConfirm, signal.SignalPrimitiveHeader.ReceiverProcessId);
2960             break;
2961 #endif
2962         case CSR_DEBUG_STRING_INDICATION_ID:
2963             debug_string_indication(priv, bulkdata.d[0].os_data_ptr, bulkdata.d[0].data_length);
2964             break;
2965
2966         case CSR_DEBUG_WORD16_INDICATION_ID:
2967             debug_word16_indication(priv, &signal);
2968             break;
2969
2970         case CSR_DEBUG_GENERIC_CONFIRM_ID:
2971         case CSR_DEBUG_GENERIC_INDICATION_ID:
2972             debug_generic_indication(priv, &signal);
2973             break;
2974         default:
2975             break;
2976     }
2977
2978     func_exit();
2979 } /* netdev_mlme_event_handler() */
2980
2981
2982 /*
2983  * ---------------------------------------------------------------------------
2984  *  uf_net_get_name
2985  *
2986  *      Retrieve the name (e.g. eth1) associated with this network device
2987  *
2988  *  Arguments:
2989  *      dev             Pointer to the network device.
2990  *      name            Buffer to write name
2991  *      len             Size of buffer in bytes
2992  *
2993  *  Returns:
2994  *      None
2995  *
2996  *  Notes:
2997  * ---------------------------------------------------------------------------
2998  */
2999 void uf_net_get_name(struct net_device *dev, char *name, int len)
3000 {
3001     *name = '\0';
3002     if (dev) {
3003         strlcpy(name, dev->name, (len > IFNAMSIZ) ? IFNAMSIZ : len);
3004     }
3005
3006 } /* uf_net_get_name */
3007
3008 #ifdef CSR_SUPPORT_WEXT
3009
3010 /*
3011  * ---------------------------------------------------------------------------
3012  *  uf_netdev_event
3013  *
3014  *     Callback function to handle netdev state changes
3015  *
3016  *  Arguments:
3017  *      notif           Pointer to a notifier_block.
3018  *      event           Event prompting notification
3019  *      ptr             net_device pointer
3020  *
3021  *  Returns:
3022  *      None
3023  *
3024  *  Notes:
3025  *   The event handler is global, and may occur on non-UniFi netdevs.
3026  * ---------------------------------------------------------------------------
3027  */
3028 static int
3029 uf_netdev_event(struct notifier_block *notif, unsigned long event, void* ptr) {
3030     struct net_device *netdev = ptr;
3031     netInterface_priv_t *interfacePriv = (netInterface_priv_t *)netdev_priv(netdev);
3032     unifi_priv_t *priv = NULL;
3033     static const CsrWifiMacAddress broadcast_address = {{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}};
3034
3035     /* Check that the event is for a UniFi netdev. If it's not, the netdev_priv
3036      * structure is not safe to use.
3037      */
3038     if (uf_find_netdev_priv(interfacePriv) == -1) {
3039         unifi_trace(NULL, UDBG1, "uf_netdev_event: ignore e=%d, ptr=%p, priv=%p %s\n",
3040                     event, ptr, interfacePriv, netdev->name);
3041         return 0;
3042     }
3043
3044     switch(event) {
3045     case NETDEV_CHANGE:
3046         priv = interfacePriv->privPtr;
3047         unifi_trace(priv, UDBG1, "NETDEV_CHANGE: %p %s %s waiting for it\n",
3048                     ptr,
3049                     netdev->name,
3050                     interfacePriv->wait_netdev_change ? "" : "not");
3051
3052         if (interfacePriv->wait_netdev_change) {
3053             UF_NETIF_TX_WAKE_ALL_QUEUES(priv->netdev[interfacePriv->InterfaceTag]);
3054             interfacePriv->connected = UnifiConnected;
3055             interfacePriv->wait_netdev_change = FALSE;
3056             /* Note: passing the broadcast address here will allow anyone to attempt to join our adhoc network */
3057             uf_process_rx_pending_queue(priv, UF_UNCONTROLLED_PORT_Q, broadcast_address, 1,interfacePriv->InterfaceTag);
3058             uf_process_rx_pending_queue(priv, UF_CONTROLLED_PORT_Q, broadcast_address, 1,interfacePriv->InterfaceTag);
3059         }
3060         break;
3061
3062     default:
3063         break;
3064     }
3065     return 0;
3066 }
3067
3068 static struct notifier_block uf_netdev_notifier = {
3069     .notifier_call = uf_netdev_event,
3070 };
3071 #endif /* CSR_SUPPORT_WEXT */
3072
3073
3074 static void
3075         process_amsdu(unifi_priv_t *priv, CSR_SIGNAL *signal, bulk_data_param_t *bulkdata)
3076 {
3077     u32 offset;
3078     u32 length = bulkdata->d[0].data_length;
3079     u32 subframe_length, subframe_body_length, dot11_hdr_size;
3080     u8 *ptr;
3081     bulk_data_param_t subframe_bulkdata;
3082     u8 *dot11_hdr_ptr = (u8*)bulkdata->d[0].os_data_ptr;
3083     CsrResult csrResult;
3084     u16 frameControl;
3085     u8 *qos_control_ptr;
3086
3087     frameControl = le16_to_cpu(*((u16*)dot11_hdr_ptr));
3088     qos_control_ptr = dot11_hdr_ptr + (((frameControl & IEEE802_11_FC_TO_DS_MASK) && (frameControl & IEEE802_11_FC_FROM_DS_MASK))?30: 24);
3089     if(!(*qos_control_ptr & IEEE802_11_QC_A_MSDU_PRESENT)) {
3090         unifi_trace(priv, UDBG6, "%s: calling unifi_rx()", __FUNCTION__);
3091         unifi_rx(priv, signal, bulkdata);
3092         return;
3093     }
3094     *qos_control_ptr &= ~(IEEE802_11_QC_A_MSDU_PRESENT);
3095
3096     ptr = qos_control_ptr + 2;
3097     offset = dot11_hdr_size = ptr - dot11_hdr_ptr;
3098
3099     while(length > (offset + sizeof(struct ethhdr) + sizeof(llc_snap_hdr_t))) {
3100         subframe_body_length = ntohs(((struct ethhdr*)ptr)->h_proto);
3101         if(subframe_body_length > IEEE802_11_MAX_DATA_LEN) {
3102             unifi_error(priv, "%s: bad subframe_body_length = %d\n", __FUNCTION__, subframe_body_length);
3103             break;
3104         }
3105         subframe_length = sizeof(struct ethhdr) + subframe_body_length;
3106         memset(&subframe_bulkdata, 0, sizeof(bulk_data_param_t));
3107
3108         csrResult = unifi_net_data_malloc(priv, &subframe_bulkdata.d[0], dot11_hdr_size + subframe_body_length);
3109
3110         if (csrResult != CSR_RESULT_SUCCESS) {
3111             unifi_error(priv, "%s: unifi_net_data_malloc failed\n", __FUNCTION__);
3112             break;
3113         }
3114
3115         memcpy((u8*)subframe_bulkdata.d[0].os_data_ptr, dot11_hdr_ptr, dot11_hdr_size);
3116
3117
3118         /* When to DS=0 and from DS=0, address 3 will already have BSSID so no need to re-program */
3119         if ((frameControl & IEEE802_11_FC_TO_DS_MASK) && !(frameControl & IEEE802_11_FC_FROM_DS_MASK)){
3120                 memcpy((u8*)subframe_bulkdata.d[0].os_data_ptr + IEEE802_11_ADDR3_OFFSET, ((struct ethhdr*)ptr)->h_dest, ETH_ALEN);
3121         }
3122         else if (!(frameControl & IEEE802_11_FC_TO_DS_MASK) && (frameControl & IEEE802_11_FC_FROM_DS_MASK)){
3123                 memcpy((u8*)subframe_bulkdata.d[0].os_data_ptr + IEEE802_11_ADDR3_OFFSET,
3124                          ((struct ethhdr*)ptr)->h_source,
3125                            ETH_ALEN);
3126         }
3127
3128         memcpy((u8*)subframe_bulkdata.d[0].os_data_ptr + dot11_hdr_size,
3129                 ptr + sizeof(struct ethhdr),
3130                              subframe_body_length);
3131         unifi_trace(priv, UDBG6, "%s: calling unifi_rx. length = %d subframe_length = %d\n", __FUNCTION__, length, subframe_length);
3132         unifi_rx(priv, signal, &subframe_bulkdata);
3133
3134         subframe_length = (subframe_length + 3)&(~0x3);
3135         ptr += subframe_length;
3136         offset += subframe_length;
3137     }
3138     unifi_net_data_free(priv, &bulkdata->d[0]);
3139 }
3140
3141
3142 #define SN_TO_INDEX(__ba_session, __sn) (((__sn - __ba_session->start_sn) & 0xFFF) % __ba_session->wind_size)
3143
3144
3145 #define ADVANCE_EXPECTED_SN(__ba_session) \
3146 { \
3147     __ba_session->expected_sn++; \
3148     __ba_session->expected_sn &= 0xFFF; \
3149 }
3150
3151 #define FREE_BUFFER_SLOT(__ba_session, __index) \
3152 { \
3153     __ba_session->occupied_slots--; \
3154     __ba_session->buffer[__index].active = FALSE; \
3155     ADVANCE_EXPECTED_SN(__ba_session); \
3156 }
3157
3158 static void add_frame_to_ba_complete(unifi_priv_t *priv,
3159                           netInterface_priv_t *interfacePriv,
3160                           frame_desc_struct *frame_desc)
3161 {
3162     interfacePriv->ba_complete[interfacePriv->ba_complete_index] = *frame_desc;
3163     interfacePriv->ba_complete_index++;
3164 }
3165
3166
3167 static void update_expected_sn(unifi_priv_t *priv,
3168                           netInterface_priv_t *interfacePriv,
3169                           ba_session_rx_struct *ba_session,
3170                           u16 sn)
3171 {
3172     int i, j;
3173     u16 gap;
3174
3175     gap = (sn - ba_session->expected_sn) & 0xFFF;
3176     unifi_trace(priv, UDBG6, "%s: proccess the frames up to new_expected_sn = %d gap = %d\n", __FUNCTION__, sn, gap);
3177     for(j = 0; j < gap && j < ba_session->wind_size; j++) {
3178         i = SN_TO_INDEX(ba_session, ba_session->expected_sn);
3179         unifi_trace(priv, UDBG6, "%s: proccess the slot index = %d\n", __FUNCTION__, i);
3180         if(ba_session->buffer[i].active) {
3181             add_frame_to_ba_complete(priv, interfacePriv, &ba_session->buffer[i]);
3182             unifi_trace(priv, UDBG6, "%s: proccess the frame at index = %d expected_sn = %d\n", __FUNCTION__, i, ba_session->expected_sn);
3183             FREE_BUFFER_SLOT(ba_session, i);
3184         } else {
3185             unifi_trace(priv, UDBG6, "%s: empty slot at index = %d\n", __FUNCTION__, i);
3186             ADVANCE_EXPECTED_SN(ba_session);
3187         }
3188     }
3189     ba_session->expected_sn = sn;
3190 }
3191
3192
3193 static void complete_ready_sequence(unifi_priv_t *priv,
3194                                netInterface_priv_t *interfacePriv,
3195                                ba_session_rx_struct *ba_session)
3196 {
3197     int i;
3198
3199     i = SN_TO_INDEX(ba_session, ba_session->expected_sn);
3200     while (ba_session->buffer[i].active) {
3201         add_frame_to_ba_complete(priv, interfacePriv, &ba_session->buffer[i]);
3202         unifi_trace(priv, UDBG6, "%s: completed stored frame(expected_sn=%d) at i = %d\n", __FUNCTION__, ba_session->expected_sn, i);
3203         FREE_BUFFER_SLOT(ba_session, i);
3204         i = SN_TO_INDEX(ba_session, ba_session->expected_sn);
3205     }
3206 }
3207
3208
3209 void scroll_ba_window(unifi_priv_t *priv,
3210                                 netInterface_priv_t *interfacePriv,
3211                                 ba_session_rx_struct *ba_session,
3212                                 u16 sn)
3213 {
3214     if(((sn - ba_session->expected_sn) & 0xFFF) <= 2048) {
3215         update_expected_sn(priv, interfacePriv, ba_session, sn);
3216         complete_ready_sequence(priv, interfacePriv, ba_session);
3217     }
3218 }
3219
3220
3221 static int consume_frame_or_get_buffer_index(unifi_priv_t *priv,
3222                                             netInterface_priv_t *interfacePriv,
3223                                             ba_session_rx_struct *ba_session,
3224                                             u16 sn,
3225                                             frame_desc_struct *frame_desc) {
3226     int i;
3227     u16 sn_temp;
3228
3229     if(((sn - ba_session->expected_sn) & 0xFFF) <= 2048) {
3230
3231         /* once we are in BA window, set the flag for BA trigger */
3232         if(!ba_session->trigger_ba_after_ssn){
3233             ba_session->trigger_ba_after_ssn = TRUE;
3234         }
3235
3236         sn_temp = ba_session->expected_sn + ba_session->wind_size;
3237         unifi_trace(priv, UDBG6, "%s: new frame: sn=%d\n", __FUNCTION__, sn);
3238         if(!(((sn - sn_temp) & 0xFFF) > 2048)) {
3239             u16 new_expected_sn;
3240             unifi_trace(priv, UDBG6, "%s: frame is out of window\n", __FUNCTION__);
3241             sn_temp = (sn - ba_session->wind_size) & 0xFFF;
3242             new_expected_sn = (sn_temp + 1) & 0xFFF;
3243             update_expected_sn(priv, interfacePriv, ba_session, new_expected_sn);
3244         }
3245         i = -1;
3246         if (sn == ba_session->expected_sn) {
3247             unifi_trace(priv, UDBG6, "%s: sn = ba_session->expected_sn = %d\n", __FUNCTION__, sn);
3248             ADVANCE_EXPECTED_SN(ba_session);
3249             add_frame_to_ba_complete(priv, interfacePriv, frame_desc);
3250         } else {
3251             i = SN_TO_INDEX(ba_session, sn);
3252             unifi_trace(priv, UDBG6, "%s: sn(%d) != ba_session->expected_sn(%d), i = %d\n", __FUNCTION__, sn, ba_session->expected_sn, i);
3253             if (ba_session->buffer[i].active) {
3254                 unifi_trace(priv, UDBG6, "%s: free frame at i = %d\n", __FUNCTION__, i);
3255                 i = -1;
3256                 unifi_net_data_free(priv, &frame_desc->bulkdata.d[0]);
3257             }
3258         }
3259     } else {
3260         i = -1;
3261         if(!ba_session->trigger_ba_after_ssn){
3262             unifi_trace(priv, UDBG6, "%s: frame before ssn, pass it up: sn=%d\n", __FUNCTION__, sn);
3263             add_frame_to_ba_complete(priv, interfacePriv, frame_desc);
3264         }else{
3265             unifi_trace(priv, UDBG6, "%s: old frame, drop: sn=%d, expected_sn=%d\n", __FUNCTION__, sn, ba_session->expected_sn);
3266             unifi_net_data_free(priv, &frame_desc->bulkdata.d[0]);
3267         }
3268     }
3269     return i;
3270 }
3271
3272
3273
3274 static void process_ba_frame(unifi_priv_t *priv,
3275                                              netInterface_priv_t *interfacePriv,
3276                                              ba_session_rx_struct *ba_session,
3277                                              frame_desc_struct *frame_desc)
3278 {
3279     int i;
3280     u16 sn = frame_desc->sn;
3281
3282     if (ba_session->timeout) {
3283         mod_timer(&ba_session->timer, (jiffies + usecs_to_jiffies((ba_session->timeout) * 1024)));
3284     }
3285     unifi_trace(priv, UDBG6, "%s: got frame(sn=%d)\n", __FUNCTION__, sn);
3286
3287     i = consume_frame_or_get_buffer_index(priv, interfacePriv, ba_session, sn, frame_desc);
3288     if(i >= 0) {
3289         unifi_trace(priv, UDBG6, "%s: store frame(sn=%d) at i = %d\n", __FUNCTION__, sn, i);
3290         ba_session->buffer[i] = *frame_desc;
3291         ba_session->buffer[i].recv_time = CsrTimeGet(NULL);
3292         ba_session->occupied_slots++;
3293     } else {
3294         unifi_trace(priv, UDBG6, "%s: frame consumed - sn = %d\n", __FUNCTION__, sn);
3295     }
3296     complete_ready_sequence(priv, interfacePriv, ba_session);
3297 }
3298
3299
3300 static void process_ba_complete(unifi_priv_t *priv, netInterface_priv_t *interfacePriv)
3301 {
3302     frame_desc_struct *frame_desc;
3303     u8 i;
3304
3305     for(i = 0; i < interfacePriv->ba_complete_index; i++) {
3306         frame_desc = &interfacePriv->ba_complete[i];
3307         unifi_trace(priv, UDBG6, "%s: calling process_amsdu()\n", __FUNCTION__);
3308         process_amsdu(priv, &frame_desc->signal, &frame_desc->bulkdata);
3309     }
3310     interfacePriv->ba_complete_index = 0;
3311
3312 }
3313
3314
3315 /* Check if the frames in BA reoder buffer has aged and
3316  * if so release the frames to upper processes and move
3317  * the window
3318  */
3319 static void check_ba_frame_age_timeout( unifi_priv_t *priv,
3320                                         netInterface_priv_t *interfacePriv,
3321                                         ba_session_rx_struct *ba_session)
3322 {
3323     CsrTime now;
3324     CsrTime age;
3325     u8 i, j;
3326     u16 sn_temp;
3327
3328     /* gap is started at 1 because we have buffered frames and
3329      * hence a minimum gap of 1 exists
3330      */
3331     u8 gap=1;
3332
3333     now = CsrTimeGet(NULL);
3334
3335     if (ba_session->occupied_slots)
3336     {
3337         /* expected sequence has not arrived so start searching from next
3338          * sequence number until a frame is available and determine the gap.
3339          * Check if the frame available has timedout, if so advance the
3340          * expected sequence number and release the frames
3341          */
3342         sn_temp = (ba_session->expected_sn + 1) & 0xFFF;
3343
3344         for(j = 0; j < ba_session->wind_size; j++)
3345         {
3346             i = SN_TO_INDEX(ba_session, sn_temp);
3347
3348             if(ba_session->buffer[i].active)
3349             {
3350                 unifi_trace(priv, UDBG6, "check age at slot index = %d sn = %d recv_time = %u now = %u\n",
3351                                         i,
3352                                         ba_session->buffer[i].sn,
3353                                         ba_session->buffer[i].recv_time,
3354                                         now);
3355
3356                 if (ba_session->buffer[i].recv_time > now)
3357                 {
3358                     /* timer wrap */
3359                     age = CsrTimeAdd((CsrTime)CsrTimeSub(CSR_SCHED_TIME_MAX, ba_session->buffer[i].recv_time), now);
3360                 }
3361                 else
3362                 {
3363                     age = (CsrTime)CsrTimeSub(now, ba_session->buffer[i].recv_time);
3364                 }
3365
3366                 if (age >= CSR_WIFI_BA_MPDU_FRAME_AGE_TIMEOUT)
3367                 {
3368                     unifi_trace(priv, UDBG2, "release the frame at index = %d gap = %d expected_sn = %d sn = %d\n",
3369                                             i,
3370                                             gap,
3371                                             ba_session->expected_sn,
3372                                             ba_session->buffer[i].sn);
3373
3374                     /* if it has timedout don't wait for missing frames, move the window */
3375                     while (gap--)
3376                     {
3377                         ADVANCE_EXPECTED_SN(ba_session);
3378                     }
3379                     add_frame_to_ba_complete(priv, interfacePriv, &ba_session->buffer[i]);
3380                     FREE_BUFFER_SLOT(ba_session, i);
3381                     complete_ready_sequence(priv, interfacePriv, ba_session);
3382                 }
3383                 break;
3384
3385             }
3386             else
3387             {
3388                 /* advance temp sequence number and frame gap */
3389                 sn_temp = (sn_temp + 1) & 0xFFF;
3390                 gap++;
3391             }
3392         }
3393     }
3394 }
3395
3396
3397 static void process_ma_packet_error_ind(unifi_priv_t *priv, CSR_SIGNAL *signal, bulk_data_param_t *bulkdata)
3398 {
3399     u16 interfaceTag;
3400     const CSR_MA_PACKET_ERROR_INDICATION *pkt_err_ind = &signal->u.MaPacketErrorIndication;
3401     netInterface_priv_t *interfacePriv;
3402     ba_session_rx_struct *ba_session;
3403     u8 ba_session_idx = 0;
3404     CSR_PRIORITY        UserPriority;
3405     CSR_SEQUENCE_NUMBER sn;
3406
3407     func_enter();
3408
3409     interfaceTag = (pkt_err_ind->VirtualInterfaceIdentifier & 0xff);
3410
3411
3412     /* Sanity check that the VIF refers to a sensible interface */
3413     if (interfaceTag >= CSR_WIFI_NUM_INTERFACES)
3414     {
3415         unifi_error(priv, "%s: MaPacketErrorIndication indication with bad interfaceTag %d\n", __FUNCTION__, interfaceTag);
3416         func_exit();
3417         return;
3418     }
3419
3420     interfacePriv = priv->interfacePriv[interfaceTag];
3421     UserPriority = pkt_err_ind->UserPriority;
3422     if(UserPriority > 15) {
3423         unifi_error(priv, "%s: MaPacketErrorIndication indication with bad UserPriority=%d\n", __FUNCTION__, UserPriority);
3424         func_exit();
3425     }
3426     sn = pkt_err_ind->SequenceNumber;
3427
3428     down(&priv->ba_mutex);
3429     /* To find the right ba_session loop through the BA sessions, compare MAC address and tID */
3430     for (ba_session_idx=0; ba_session_idx < MAX_SUPPORTED_BA_SESSIONS_RX; ba_session_idx++){
3431         ba_session = interfacePriv->ba_session_rx[ba_session_idx];
3432         if (ba_session){
3433             if ((!memcmp(ba_session->macAddress.a, pkt_err_ind->PeerQstaAddress.x, ETH_ALEN)) && (ba_session->tID == UserPriority)){
3434                 if (ba_session->timeout) {
3435                     mod_timer(&ba_session->timer, (jiffies + usecs_to_jiffies((ba_session->timeout) * 1024)));
3436                 }
3437                 scroll_ba_window(priv, interfacePriv, ba_session, sn);
3438                 break;
3439             }
3440         }
3441     }
3442
3443     up(&priv->ba_mutex);
3444     process_ba_complete(priv, interfacePriv);
3445     func_exit();
3446 }
3447
3448