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