xref: /dpdk/examples/server_node_efd/node/node.c (revision d81734ca)
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_ether.h>
61 #include <rte_ethdev.h>
62 #include <rte_string_fns.h>
63 #include <rte_ip.h>
64 
65 #include "common.h"
66 
67 /* Number of packets to attempt to read from queue */
68 #define PKT_READ_SIZE  ((uint16_t)32)
69 
70 /*
71  * Our node id number - tells us which rx queue to read, and NIC TX
72  * queue to write to.
73  */
74 static uint8_t node_id;
75 
76 #define MBQ_CAPACITY 32
77 
78 /* maps input ports to output ports for packets */
79 static uint16_t output_ports[RTE_MAX_ETHPORTS];
80 
81 /* buffers up a set of packet that are ready to send */
82 struct rte_eth_dev_tx_buffer *tx_buffer[RTE_MAX_ETHPORTS];
83 
84 /* shared data from server. We update statistics here */
85 static struct tx_stats *tx_stats;
86 
87 static struct filter_stats *filter_stats;
88 
89 /*
90  * print a usage message
91  */
92 static void
93 usage(const char *progname)
94 {
95 	printf("Usage: %s [EAL args] -- -n <node_id>\n\n", progname);
96 }
97 
98 /*
99  * Convert the node id number from a string to an int.
100  */
101 static int
102 parse_node_num(const char *node)
103 {
104 	char *end = NULL;
105 	unsigned long temp;
106 
107 	if (node == NULL || *node == '\0')
108 		return -1;
109 
110 	temp = strtoul(node, &end, 10);
111 	if (end == NULL || *end != '\0')
112 		return -1;
113 
114 	node_id = (uint8_t)temp;
115 	return 0;
116 }
117 
118 /*
119  * Parse the application arguments to the node app.
120  */
121 static int
122 parse_app_args(int argc, char *argv[])
123 {
124 	int option_index, opt;
125 	char **argvopt = argv;
126 	const char *progname = NULL;
127 	static struct option lgopts[] = { /* no long options */
128 		{NULL, 0, 0, 0 }
129 	};
130 	progname = argv[0];
131 
132 	while ((opt = getopt_long(argc, argvopt, "n:", lgopts,
133 		&option_index)) != EOF) {
134 		switch (opt) {
135 		case 'n':
136 			if (parse_node_num(optarg) != 0) {
137 				usage(progname);
138 				return -1;
139 			}
140 			break;
141 		default:
142 			usage(progname);
143 			return -1;
144 		}
145 	}
146 	return 0;
147 }
148 
149 /*
150  * Tx buffer error callback
151  */
152 static void
153 flush_tx_error_callback(struct rte_mbuf **unsent, uint16_t count,
154 		void *userdata) {
155 	int i;
156 	uint16_t port_id = (uintptr_t)userdata;
157 
158 	tx_stats->tx_drop[port_id] += count;
159 
160 	/* free the mbufs which failed from transmit */
161 	for (i = 0; i < count; i++)
162 		rte_pktmbuf_free(unsent[i]);
163 
164 }
165 
166 static void
167 configure_tx_buffer(uint16_t port_id, uint16_t size)
168 {
169 	int ret;
170 
171 	/* Initialize TX buffers */
172 	tx_buffer[port_id] = rte_zmalloc_socket("tx_buffer",
173 			RTE_ETH_TX_BUFFER_SIZE(size), 0,
174 			rte_eth_dev_socket_id(port_id));
175 	if (tx_buffer[port_id] == NULL)
176 		rte_exit(EXIT_FAILURE,
177 			"Cannot allocate buffer for tx on port %u\n", port_id);
178 
179 	rte_eth_tx_buffer_init(tx_buffer[port_id], size);
180 
181 	ret = rte_eth_tx_buffer_set_err_callback(tx_buffer[port_id],
182 			flush_tx_error_callback, (void *)(intptr_t)port_id);
183 	if (ret < 0)
184 		rte_exit(EXIT_FAILURE,
185 			"Cannot set error callback for tx buffer on port %u\n",
186 			port_id);
187 }
188 
189 /*
190  * set up output ports so that all traffic on port gets sent out
191  * its paired port. Index using actual port numbers since that is
192  * what comes in the mbuf structure.
193  */
194 static void
195 configure_output_ports(const struct shared_info *info)
196 {
197 	int i;
198 
199 	if (info->num_ports > RTE_MAX_ETHPORTS)
200 		rte_exit(EXIT_FAILURE, "Too many ethernet ports. "
201 				"RTE_MAX_ETHPORTS = %u\n",
202 				(unsigned int)RTE_MAX_ETHPORTS);
203 	for (i = 0; i < info->num_ports - 1; i += 2) {
204 		uint8_t p1 = info->id[i];
205 		uint8_t p2 = info->id[i+1];
206 
207 		output_ports[p1] = p2;
208 		output_ports[p2] = p1;
209 
210 		configure_tx_buffer(p1, MBQ_CAPACITY);
211 		configure_tx_buffer(p2, MBQ_CAPACITY);
212 
213 	}
214 }
215 
216 /*
217  * Create the hash table that will contain the flows that
218  * the node will handle, which will be used to decide if packet
219  * is transmitted or dropped.
220  */
221 static struct rte_hash *
222 create_hash_table(const struct shared_info *info)
223 {
224 	uint32_t num_flows_node = info->num_flows / info->num_nodes;
225 	char name[RTE_HASH_NAMESIZE];
226 	struct rte_hash *h;
227 
228 	/* create table */
229 	struct rte_hash_parameters hash_params = {
230 		.entries = num_flows_node * 2, /* table load = 50% */
231 		.key_len = sizeof(uint32_t), /* Store IPv4 dest IP address */
232 		.socket_id = rte_socket_id(),
233 		.hash_func_init_val = 0,
234 	};
235 
236 	snprintf(name, sizeof(name), "hash_table_%d", node_id);
237 	hash_params.name = name;
238 	h = rte_hash_create(&hash_params);
239 
240 	if (h == NULL)
241 		rte_exit(EXIT_FAILURE,
242 				"Problem creating the hash table for node %d\n",
243 				node_id);
244 	return h;
245 }
246 
247 static void
248 populate_hash_table(const struct rte_hash *h, const struct shared_info *info)
249 {
250 	unsigned int i;
251 	int32_t ret;
252 	uint32_t ip_dst;
253 	uint32_t num_flows_node = 0;
254 	uint64_t target_node;
255 
256 	/* Add flows in table */
257 	for (i = 0; i < info->num_flows; i++) {
258 		target_node = i % info->num_nodes;
259 		if (target_node != node_id)
260 			continue;
261 
262 		ip_dst = rte_cpu_to_be_32(i);
263 
264 		ret = rte_hash_add_key(h, (void *) &ip_dst);
265 		if (ret < 0)
266 			rte_exit(EXIT_FAILURE, "Unable to add entry %u "
267 					"in hash table\n", i);
268 		else
269 			num_flows_node++;
270 
271 	}
272 
273 	printf("Hash table: Adding 0x%x keys\n", num_flows_node);
274 }
275 
276 /*
277  * This function performs routing of packets
278  * Just sends each input packet out an output port based solely on the input
279  * port it arrived on.
280  */
281 static inline void
282 transmit_packet(struct rte_mbuf *buf)
283 {
284 	int sent;
285 	const uint16_t in_port = buf->port;
286 	const uint16_t out_port = output_ports[in_port];
287 	struct rte_eth_dev_tx_buffer *buffer = tx_buffer[out_port];
288 
289 	sent = rte_eth_tx_buffer(out_port, node_id, buffer, buf);
290 	if (sent)
291 		tx_stats->tx[out_port] += sent;
292 
293 }
294 
295 static inline void
296 handle_packets(struct rte_hash *h, struct rte_mbuf **bufs, uint16_t num_packets)
297 {
298 	struct ipv4_hdr *ipv4_hdr;
299 	uint32_t ipv4_dst_ip[PKT_READ_SIZE];
300 	const void *key_ptrs[PKT_READ_SIZE];
301 	unsigned int i;
302 	int32_t positions[PKT_READ_SIZE] = {0};
303 
304 	for (i = 0; i < num_packets; i++) {
305 		/* Handle IPv4 header.*/
306 		ipv4_hdr = rte_pktmbuf_mtod_offset(bufs[i], struct ipv4_hdr *,
307 				sizeof(struct ether_hdr));
308 		ipv4_dst_ip[i] = ipv4_hdr->dst_addr;
309 		key_ptrs[i] = &ipv4_dst_ip[i];
310 	}
311 	/* Check if packets belongs to any flows handled by this node */
312 	rte_hash_lookup_bulk(h, key_ptrs, num_packets, positions);
313 
314 	for (i = 0; i < num_packets; i++) {
315 		if (likely(positions[i] >= 0)) {
316 			filter_stats->passed++;
317 			transmit_packet(bufs[i]);
318 		} else {
319 			filter_stats->drop++;
320 			/* Drop packet, as flow is not handled by this node */
321 			rte_pktmbuf_free(bufs[i]);
322 		}
323 	}
324 }
325 
326 /*
327  * Application main function - loops through
328  * receiving and processing packets. Never returns
329  */
330 int
331 main(int argc, char *argv[])
332 {
333 	const struct rte_memzone *mz;
334 	struct rte_ring *rx_ring;
335 	struct rte_hash *h;
336 	struct rte_mempool *mp;
337 	struct shared_info *info;
338 	int need_flush = 0; /* indicates whether we have unsent packets */
339 	int retval;
340 	void *pkts[PKT_READ_SIZE];
341 	uint16_t sent;
342 
343 	retval = rte_eal_init(argc, argv);
344 	if (retval  < 0)
345 		return -1;
346 	argc -= retval;
347 	argv += retval;
348 
349 	if (parse_app_args(argc, argv) < 0)
350 		rte_exit(EXIT_FAILURE, "Invalid command-line arguments\n");
351 
352 	if (rte_eth_dev_count() == 0)
353 		rte_exit(EXIT_FAILURE, "No Ethernet ports - bye\n");
354 
355 	rx_ring = rte_ring_lookup(get_rx_queue_name(node_id));
356 	if (rx_ring == NULL)
357 		rte_exit(EXIT_FAILURE, "Cannot get RX ring - "
358 				"is server process running?\n");
359 
360 	mp = rte_mempool_lookup(PKTMBUF_POOL_NAME);
361 	if (mp == NULL)
362 		rte_exit(EXIT_FAILURE, "Cannot get mempool for mbufs\n");
363 
364 	mz = rte_memzone_lookup(MZ_SHARED_INFO);
365 	if (mz == NULL)
366 		rte_exit(EXIT_FAILURE, "Cannot get port info structure\n");
367 	info = mz->addr;
368 	tx_stats = &(info->tx_stats[node_id]);
369 	filter_stats = &(info->filter_stats[node_id]);
370 
371 	configure_output_ports(info);
372 
373 	h = create_hash_table(info);
374 
375 	populate_hash_table(h, info);
376 
377 	RTE_LOG(INFO, APP, "Finished Process Init.\n");
378 
379 	printf("\nNode process %d handling packets\n", node_id);
380 	printf("[Press Ctrl-C to quit ...]\n");
381 
382 	for (;;) {
383 		uint16_t  rx_pkts = PKT_READ_SIZE;
384 		uint16_t port;
385 
386 		/*
387 		 * Try dequeuing max possible packets first, if that fails,
388 		 * get the most we can. Loop body should only execute once,
389 		 * maximum
390 		 */
391 		while (rx_pkts > 0 &&
392 				unlikely(rte_ring_dequeue_bulk(rx_ring, pkts,
393 					rx_pkts, NULL) == 0))
394 			rx_pkts = (uint16_t)RTE_MIN(rte_ring_count(rx_ring),
395 					PKT_READ_SIZE);
396 
397 		if (unlikely(rx_pkts == 0)) {
398 			if (need_flush)
399 				for (port = 0; port < info->num_ports; port++) {
400 					sent = rte_eth_tx_buffer_flush(
401 							info->id[port],
402 							node_id,
403 							tx_buffer[port]);
404 					if (unlikely(sent))
405 						tx_stats->tx[port] += sent;
406 				}
407 			need_flush = 0;
408 			continue;
409 		}
410 
411 		handle_packets(h, (struct rte_mbuf **)pkts, rx_pkts);
412 
413 		need_flush = 1;
414 	}
415 }
416