libmemif: fix chain buffer support
[vpp.git] / extras / libmemif / examples / common / packet_handler.c
1 /*
2  *------------------------------------------------------------------
3  * Copyright (c) 2020 Cisco and/or its affiliates.
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at:
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  *------------------------------------------------------------------
16  */
17
18 #include <common.h>
19 #include <icmp_proto.h>
20
21 /* reply with the same data */
22 int
23 basic_packet_handler (memif_connection_t *c)
24 {
25   int i;
26   memif_buffer_t *dest, *src;
27
28   /* in case of zero-copy the tx_buf_num will be zero, so the loop body won't
29    * execute */
30   for (i = 0; i < c->tx_buf_num; i++)
31     {
32       memcpy (c->tx_bufs[i].data, c->rx_bufs[i].data, c->rx_bufs[i].len);
33     }
34
35   return 0;
36 }
37
38 /* ICMPv4 and ARP handler */
39 int
40 icmp_packet_handler (memif_connection_t *c)
41 {
42   int i;
43   memif_buffer_t *dest, *src;
44
45   /* if tx_buf_num > 0 we use non-zero-copy mode */
46   if (c->tx_buf_num > 0)
47     {
48       for (i = 0; i < c->tx_buf_num; i++)
49         {
50           uint32_t len;
51           void *packet = c->rx_bufs[i].data;
52
53           memcpy (c->tx_bufs[i].data, c->rx_bufs[i].data, c->rx_bufs[i].len);
54           c->tx_bufs[i].flags = c->rx_bufs[i].flags;
55           len = c->tx_bufs[i].len = c->rx_bufs[i].len;
56
57           while (c->rx_bufs[i].flags & MEMIF_BUFFER_FLAG_NEXT)
58             {
59               i++;
60               memcpy (c->tx_bufs[i].data, c->rx_bufs[i].data,
61                       c->rx_bufs[i].len);
62               c->tx_bufs[i].flags = c->rx_bufs[i].flags;
63               len += c->tx_bufs[i].len = c->rx_bufs[i].len;
64             }
65
66           resolve_packet (packet, &len, c->ip_addr, c->hw_addr);
67         }
68     }
69   else
70     {
71       for (i = 0; i < c->rx_buf_num; i++)
72         {
73           uint32_t len = c->rx_bufs[i].len;
74           void *packet = c->rx_bufs[i].data;
75           while (c->rx_bufs[i].flags & MEMIF_BUFFER_FLAG_NEXT)
76             {
77               i++;
78               len += c->rx_bufs[i].len;
79             }
80           resolve_packet (packet, &len, c->ip_addr, c->hw_addr);
81         }
82     }
83
84   return 0;
85 }