c8ce391f13818b638146a0b50361df40fc65e59f
[dpdk.git] / examples / server_node_efd / node / node.c
1 /*-
2  *   BSD LICENSE
3  *
4  *   Copyright(c) 2016-2017 Intel Corporation. All rights reserved.
5  *   All rights reserved.
6  *
7  *   Redistribution and use in source and binary forms, with or without
8  *   modification, are permitted provided that the following conditions
9  *   are met:
10  *
11  *     * Redistributions of source code must retain the above copyright
12  *       notice, this list of conditions and the following disclaimer.
13  *     * Redistributions in binary form must reproduce the above copyright
14  *       notice, this list of conditions and the following disclaimer in
15  *       the documentation and/or other materials provided with the
16  *       distribution.
17  *     * Neither the name of Intel Corporation nor the names of its
18  *       contributors may be used to endorse or promote products derived
19  *       from this software without specific prior written permission.
20  *
21  *   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22  *   "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23  *   LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
24  *   A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
25  *   OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
26  *   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
27  *   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
28  *   DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
29  *   THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
30  *   (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
31  *   OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32  */
33
34 #include <stdint.h>
35 #include <stdio.h>
36 #include <inttypes.h>
37 #include <stdarg.h>
38 #include <errno.h>
39 #include <sys/queue.h>
40 #include <stdlib.h>
41 #include <getopt.h>
42 #include <string.h>
43
44 #include <rte_common.h>
45 #include <rte_malloc.h>
46 #include <rte_memory.h>
47 #include <rte_memzone.h>
48 #include <rte_eal.h>
49 #include <rte_atomic.h>
50 #include <rte_branch_prediction.h>
51 #include <rte_log.h>
52 #include <rte_per_lcore.h>
53 #include <rte_launch.h>
54 #include <rte_lcore.h>
55 #include <rte_ring.h>
56 #include <rte_debug.h>
57 #include <rte_mempool.h>
58 #include <rte_mbuf.h>
59 #include <rte_interrupts.h>
60 #include <rte_pci.h>
61 #include <rte_ether.h>
62 #include <rte_ethdev.h>
63 #include <rte_string_fns.h>
64 #include <rte_ip.h>
65
66 #include "common.h"
67
68 /* Number of packets to attempt to read from queue */
69 #define PKT_READ_SIZE  ((uint16_t)32)
70
71 /*
72  * Our node id number - tells us which rx queue to read, and NIC TX
73  * queue to write to.
74  */
75 static uint8_t node_id;
76
77 #define MBQ_CAPACITY 32
78
79 /* maps input ports to output ports for packets */
80 static uint16_t output_ports[RTE_MAX_ETHPORTS];
81
82 /* buffers up a set of packet that are ready to send */
83 struct rte_eth_dev_tx_buffer *tx_buffer[RTE_MAX_ETHPORTS];
84
85 /* shared data from server. We update statistics here */
86 static struct tx_stats *tx_stats;
87
88 static struct filter_stats *filter_stats;
89
90 /*
91  * print a usage message
92  */
93 static void
94 usage(const char *progname)
95 {
96         printf("Usage: %s [EAL args] -- -n <node_id>\n\n", progname);
97 }
98
99 /*
100  * Convert the node id number from a string to an int.
101  */
102 static int
103 parse_node_num(const char *node)
104 {
105         char *end = NULL;
106         unsigned long temp;
107
108         if (node == NULL || *node == '\0')
109                 return -1;
110
111         temp = strtoul(node, &end, 10);
112         if (end == NULL || *end != '\0')
113                 return -1;
114
115         node_id = (uint8_t)temp;
116         return 0;
117 }
118
119 /*
120  * Parse the application arguments to the node app.
121  */
122 static int
123 parse_app_args(int argc, char *argv[])
124 {
125         int option_index, opt;
126         char **argvopt = argv;
127         const char *progname = NULL;
128         static struct option lgopts[] = { /* no long options */
129                 {NULL, 0, 0, 0 }
130         };
131         progname = argv[0];
132
133         while ((opt = getopt_long(argc, argvopt, "n:", lgopts,
134                 &option_index)) != EOF) {
135                 switch (opt) {
136                 case 'n':
137                         if (parse_node_num(optarg) != 0) {
138                                 usage(progname);
139                                 return -1;
140                         }
141                         break;
142                 default:
143                         usage(progname);
144                         return -1;
145                 }
146         }
147         return 0;
148 }
149
150 /*
151  * Tx buffer error callback
152  */
153 static void
154 flush_tx_error_callback(struct rte_mbuf **unsent, uint16_t count,
155                 void *userdata) {
156         int i;
157         uint16_t port_id = (uintptr_t)userdata;
158
159         tx_stats->tx_drop[port_id] += count;
160
161         /* free the mbufs which failed from transmit */
162         for (i = 0; i < count; i++)
163                 rte_pktmbuf_free(unsent[i]);
164
165 }
166
167 static void
168 configure_tx_buffer(uint16_t port_id, uint16_t size)
169 {
170         int ret;
171
172         /* Initialize TX buffers */
173         tx_buffer[port_id] = rte_zmalloc_socket("tx_buffer",
174                         RTE_ETH_TX_BUFFER_SIZE(size), 0,
175                         rte_eth_dev_socket_id(port_id));
176         if (tx_buffer[port_id] == NULL)
177                 rte_exit(EXIT_FAILURE,
178                         "Cannot allocate buffer for tx on port %u\n", port_id);
179
180         rte_eth_tx_buffer_init(tx_buffer[port_id], size);
181
182         ret = rte_eth_tx_buffer_set_err_callback(tx_buffer[port_id],
183                         flush_tx_error_callback, (void *)(intptr_t)port_id);
184         if (ret < 0)
185                 rte_exit(EXIT_FAILURE,
186                         "Cannot set error callback for tx buffer on port %u\n",
187                         port_id);
188 }
189
190 /*
191  * set up output ports so that all traffic on port gets sent out
192  * its paired port. Index using actual port numbers since that is
193  * what comes in the mbuf structure.
194  */
195 static void
196 configure_output_ports(const struct shared_info *info)
197 {
198         int i;
199
200         if (info->num_ports > RTE_MAX_ETHPORTS)
201                 rte_exit(EXIT_FAILURE, "Too many ethernet ports. "
202                                 "RTE_MAX_ETHPORTS = %u\n",
203                                 (unsigned int)RTE_MAX_ETHPORTS);
204         for (i = 0; i < info->num_ports - 1; i += 2) {
205                 uint8_t p1 = info->id[i];
206                 uint8_t p2 = info->id[i+1];
207
208                 output_ports[p1] = p2;
209                 output_ports[p2] = p1;
210
211                 configure_tx_buffer(p1, MBQ_CAPACITY);
212                 configure_tx_buffer(p2, MBQ_CAPACITY);
213
214         }
215 }
216
217 /*
218  * Create the hash table that will contain the flows that
219  * the node will handle, which will be used to decide if packet
220  * is transmitted or dropped.
221  */
222 static struct rte_hash *
223 create_hash_table(const struct shared_info *info)
224 {
225         uint32_t num_flows_node = info->num_flows / info->num_nodes;
226         char name[RTE_HASH_NAMESIZE];
227         struct rte_hash *h;
228
229         /* create table */
230         struct rte_hash_parameters hash_params = {
231                 .entries = num_flows_node * 2, /* table load = 50% */
232                 .key_len = sizeof(uint32_t), /* Store IPv4 dest IP address */
233                 .socket_id = rte_socket_id(),
234                 .hash_func_init_val = 0,
235         };
236
237         snprintf(name, sizeof(name), "hash_table_%d", node_id);
238         hash_params.name = name;
239         h = rte_hash_create(&hash_params);
240
241         if (h == NULL)
242                 rte_exit(EXIT_FAILURE,
243                                 "Problem creating the hash table for node %d\n",
244                                 node_id);
245         return h;
246 }
247
248 static void
249 populate_hash_table(const struct rte_hash *h, const struct shared_info *info)
250 {
251         unsigned int i;
252         int32_t ret;
253         uint32_t ip_dst;
254         uint32_t num_flows_node = 0;
255         uint64_t target_node;
256
257         /* Add flows in table */
258         for (i = 0; i < info->num_flows; i++) {
259                 target_node = i % info->num_nodes;
260                 if (target_node != node_id)
261                         continue;
262
263                 ip_dst = rte_cpu_to_be_32(i);
264
265                 ret = rte_hash_add_key(h, (void *) &ip_dst);
266                 if (ret < 0)
267                         rte_exit(EXIT_FAILURE, "Unable to add entry %u "
268                                         "in hash table\n", i);
269                 else
270                         num_flows_node++;
271
272         }
273
274         printf("Hash table: Adding 0x%x keys\n", num_flows_node);
275 }
276
277 /*
278  * This function performs routing of packets
279  * Just sends each input packet out an output port based solely on the input
280  * port it arrived on.
281  */
282 static inline void
283 transmit_packet(struct rte_mbuf *buf)
284 {
285         int sent;
286         const uint16_t in_port = buf->port;
287         const uint16_t out_port = output_ports[in_port];
288         struct rte_eth_dev_tx_buffer *buffer = tx_buffer[out_port];
289
290         sent = rte_eth_tx_buffer(out_port, node_id, buffer, buf);
291         if (sent)
292                 tx_stats->tx[out_port] += sent;
293
294 }
295
296 static inline void
297 handle_packets(struct rte_hash *h, struct rte_mbuf **bufs, uint16_t num_packets)
298 {
299         struct ipv4_hdr *ipv4_hdr;
300         uint32_t ipv4_dst_ip[PKT_READ_SIZE];
301         const void *key_ptrs[PKT_READ_SIZE];
302         unsigned int i;
303         int32_t positions[PKT_READ_SIZE] = {0};
304
305         for (i = 0; i < num_packets; i++) {
306                 /* Handle IPv4 header.*/
307                 ipv4_hdr = rte_pktmbuf_mtod_offset(bufs[i], struct ipv4_hdr *,
308                                 sizeof(struct ether_hdr));
309                 ipv4_dst_ip[i] = ipv4_hdr->dst_addr;
310                 key_ptrs[i] = &ipv4_dst_ip[i];
311         }
312         /* Check if packets belongs to any flows handled by this node */
313         rte_hash_lookup_bulk(h, key_ptrs, num_packets, positions);
314
315         for (i = 0; i < num_packets; i++) {
316                 if (likely(positions[i] >= 0)) {
317                         filter_stats->passed++;
318                         transmit_packet(bufs[i]);
319                 } else {
320                         filter_stats->drop++;
321                         /* Drop packet, as flow is not handled by this node */
322                         rte_pktmbuf_free(bufs[i]);
323                 }
324         }
325 }
326
327 /*
328  * Application main function - loops through
329  * receiving and processing packets. Never returns
330  */
331 int
332 main(int argc, char *argv[])
333 {
334         const struct rte_memzone *mz;
335         struct rte_ring *rx_ring;
336         struct rte_hash *h;
337         struct rte_mempool *mp;
338         struct shared_info *info;
339         int need_flush = 0; /* indicates whether we have unsent packets */
340         int retval;
341         void *pkts[PKT_READ_SIZE];
342         uint16_t sent;
343
344         retval = rte_eal_init(argc, argv);
345         if (retval  < 0)
346                 return -1;
347         argc -= retval;
348         argv += retval;
349
350         if (parse_app_args(argc, argv) < 0)
351                 rte_exit(EXIT_FAILURE, "Invalid command-line arguments\n");
352
353         if (rte_eth_dev_count() == 0)
354                 rte_exit(EXIT_FAILURE, "No Ethernet ports - bye\n");
355
356         rx_ring = rte_ring_lookup(get_rx_queue_name(node_id));
357         if (rx_ring == NULL)
358                 rte_exit(EXIT_FAILURE, "Cannot get RX ring - "
359                                 "is server process running?\n");
360
361         mp = rte_mempool_lookup(PKTMBUF_POOL_NAME);
362         if (mp == NULL)
363                 rte_exit(EXIT_FAILURE, "Cannot get mempool for mbufs\n");
364
365         mz = rte_memzone_lookup(MZ_SHARED_INFO);
366         if (mz == NULL)
367                 rte_exit(EXIT_FAILURE, "Cannot get port info structure\n");
368         info = mz->addr;
369         tx_stats = &(info->tx_stats[node_id]);
370         filter_stats = &(info->filter_stats[node_id]);
371
372         configure_output_ports(info);
373
374         h = create_hash_table(info);
375
376         populate_hash_table(h, info);
377
378         RTE_LOG(INFO, APP, "Finished Process Init.\n");
379
380         printf("\nNode process %d handling packets\n", node_id);
381         printf("[Press Ctrl-C to quit ...]\n");
382
383         for (;;) {
384                 uint16_t  rx_pkts = PKT_READ_SIZE;
385                 uint16_t port;
386
387                 /*
388                  * Try dequeuing max possible packets first, if that fails,
389                  * get the most we can. Loop body should only execute once,
390                  * maximum
391                  */
392                 while (rx_pkts > 0 &&
393                                 unlikely(rte_ring_dequeue_bulk(rx_ring, pkts,
394                                         rx_pkts, NULL) == 0))
395                         rx_pkts = (uint16_t)RTE_MIN(rte_ring_count(rx_ring),
396                                         PKT_READ_SIZE);
397
398                 if (unlikely(rx_pkts == 0)) {
399                         if (need_flush)
400                                 for (port = 0; port < info->num_ports; port++) {
401                                         sent = rte_eth_tx_buffer_flush(
402                                                         info->id[port],
403                                                         node_id,
404                                                         tx_buffer[port]);
405                                         if (unlikely(sent))
406                                                 tx_stats->tx[port] += sent;
407                                 }
408                         need_flush = 0;
409                         continue;
410                 }
411
412                 handle_packets(h, (struct rte_mbuf **)pkts, rx_pkts);
413
414                 need_flush = 1;
415         }
416 }