New upstream version 18.02
[deb_dpdk.git] / examples / multi_process / l2fwd_fork / main.c
1 /* SPDX-License-Identifier: BSD-3-Clause
2  * Copyright(c) 2010-2016 Intel Corporation
3  */
4 #define _GNU_SOURCE
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <unistd.h>
8 #include <string.h>
9 #include <stdint.h>
10 #include <sched.h>
11 #include <inttypes.h>
12 #include <sys/types.h>
13 #include <sys/queue.h>
14 #include <netinet/in.h>
15 #include <setjmp.h>
16 #include <stdarg.h>
17 #include <ctype.h>
18 #include <errno.h>
19 #include <getopt.h>
20
21 #include <rte_common.h>
22 #include <rte_log.h>
23 #include <rte_memory.h>
24 #include <rte_memcpy.h>
25 #include <rte_eal.h>
26 #include <rte_launch.h>
27 #include <rte_atomic.h>
28 #include <rte_spinlock.h>
29 #include <rte_cycles.h>
30 #include <rte_prefetch.h>
31 #include <rte_lcore.h>
32 #include <rte_per_lcore.h>
33 #include <rte_branch_prediction.h>
34 #include <rte_interrupts.h>
35 #include <rte_random.h>
36 #include <rte_debug.h>
37 #include <rte_ether.h>
38 #include <rte_ethdev.h>
39 #include <rte_ring.h>
40 #include <rte_mempool.h>
41 #include <rte_mbuf.h>
42 #include <rte_malloc.h>
43
44 #include "flib.h"
45
46 #define RTE_LOGTYPE_L2FWD RTE_LOGTYPE_USER1
47 #define MBUF_NAME       "mbuf_pool_%d"
48 #define MBUF_DATA_SIZE  RTE_MBUF_DEFAULT_BUF_SIZE
49 #define NB_MBUF   8192
50 #define RING_MASTER_NAME        "l2fwd_ring_m2s_"
51 #define RING_SLAVE_NAME         "l2fwd_ring_s2m_"
52 #define MAX_NAME_LEN    32
53 /* RECREATE flag indicate needs initialize resource and launch slave_core again */
54 #define SLAVE_RECREATE_FLAG 0x1
55 /* RESTART flag indicate needs restart port and send START command again */
56 #define SLAVE_RESTART_FLAG 0x2
57 #define INVALID_MAPPING_ID      ((unsigned)LCORE_ID_ANY)
58 /* Maximum message buffer per slave */
59 #define NB_CORE_MSGBUF  32
60 enum l2fwd_cmd{
61         CMD_START,
62         CMD_STOP,
63 };
64
65 #define MAX_PKT_BURST 32
66 #define BURST_TX_DRAIN_US 100 /* TX drain every ~100us */
67
68 /*
69  * Configurable number of RX/TX ring descriptors
70  */
71 #define RTE_TEST_RX_DESC_DEFAULT 1024
72 #define RTE_TEST_TX_DESC_DEFAULT 1024
73 static uint16_t nb_rxd = RTE_TEST_RX_DESC_DEFAULT;
74 static uint16_t nb_txd = RTE_TEST_TX_DESC_DEFAULT;
75
76 /* ethernet addresses of ports */
77 static struct ether_addr l2fwd_ports_eth_addr[RTE_MAX_ETHPORTS];
78
79 /* mask of enabled ports */
80 static uint32_t l2fwd_enabled_port_mask = 0;
81
82 /* list of enabled ports */
83 static uint32_t l2fwd_dst_ports[RTE_MAX_ETHPORTS];
84
85 static unsigned int l2fwd_rx_queue_per_lcore = 1;
86
87 struct mbuf_table {
88         unsigned len;
89         struct rte_mbuf *m_table[MAX_PKT_BURST];
90 };
91
92 #define MAX_RX_QUEUE_PER_LCORE 16
93 #define MAX_TX_QUEUE_PER_PORT 16
94 struct lcore_queue_conf {
95         unsigned n_rx_port;
96         unsigned rx_port_list[MAX_RX_QUEUE_PER_LCORE];
97 } __rte_cache_aligned;
98 struct lcore_queue_conf lcore_queue_conf[RTE_MAX_LCORE];
99
100 struct rte_eth_dev_tx_buffer *tx_buffer[RTE_MAX_ETHPORTS];
101
102 struct lcore_resource_struct {
103         int enabled;    /* Only set in case this lcore involved into packet forwarding */
104         int flags;          /* Set only slave need to restart or recreate */
105         unsigned lcore_id;  /*  lcore ID */
106         unsigned pair_id;       /* dependency lcore ID on port */
107         char ring_name[2][MAX_NAME_LEN];
108         /* ring[0] for master send cmd, slave read */
109         /* ring[1] for slave send ack, master read */
110         struct rte_ring *ring[2];
111         int port_num;                                   /* Total port numbers */
112         /* Port id for that lcore to receive packets */
113         uint16_t port[RTE_MAX_ETHPORTS];
114 }__attribute__((packed)) __rte_cache_aligned;
115
116 static struct lcore_resource_struct lcore_resource[RTE_MAX_LCORE];
117 static struct rte_mempool *message_pool;
118 static rte_spinlock_t res_lock = RTE_SPINLOCK_INITIALIZER;
119 /* use floating processes */
120 static int float_proc = 0;
121 /* Save original cpu affinity */
122 struct cpu_aff_arg{
123         cpu_set_t set;
124         size_t size;
125 }cpu_aff;
126
127 static const struct rte_eth_conf port_conf = {
128         .rxmode = {
129                 .split_hdr_size = 0,
130                 .ignore_offload_bitfield = 1,
131                 .offloads = DEV_RX_OFFLOAD_CRC_STRIP,
132         },
133         .txmode = {
134                 .mq_mode = ETH_MQ_TX_NONE,
135         },
136 };
137
138 static struct rte_mempool * l2fwd_pktmbuf_pool[RTE_MAX_ETHPORTS];
139
140 /* Per-port statistics struct */
141 struct l2fwd_port_statistics {
142         uint64_t tx;
143         uint64_t rx;
144         uint64_t dropped;
145 } __rte_cache_aligned;
146 struct l2fwd_port_statistics *port_statistics;
147 /**
148  * pointer to lcore ID mapping array, used to return lcore id in case slave
149  * process exited unexpectedly, use only floating process option applied
150  **/
151 unsigned *mapping_id;
152
153 /* A tsc-based timer responsible for triggering statistics printout */
154 #define TIMER_MILLISECOND 2000000ULL /* around 1ms at 2 Ghz */
155 #define MAX_TIMER_PERIOD 86400 /* 1 day max */
156 static int64_t timer_period = 10 * TIMER_MILLISECOND * 1000; /* default period is 10 seconds */
157
158 static int l2fwd_launch_one_lcore(void *dummy);
159
160 /* Print out statistics on packets dropped */
161 static void
162 print_stats(void)
163 {
164         uint64_t total_packets_dropped, total_packets_tx, total_packets_rx;
165         unsigned portid;
166
167         total_packets_dropped = 0;
168         total_packets_tx = 0;
169         total_packets_rx = 0;
170
171         const char clr[] = { 27, '[', '2', 'J', '\0' };
172         const char topLeft[] = { 27, '[', '1', ';', '1', 'H','\0' };
173
174                 /* Clear screen and move to top left */
175         printf("%s%s", clr, topLeft);
176
177         printf("\nPort statistics ====================================");
178
179         for (portid = 0; portid < RTE_MAX_ETHPORTS; portid++) {
180                 /* skip disabled ports */
181                 if ((l2fwd_enabled_port_mask & (1 << portid)) == 0)
182                         continue;
183                 printf("\nStatistics for port %u ------------------------------"
184                            "\nPackets sent: %24"PRIu64
185                            "\nPackets received: %20"PRIu64
186                            "\nPackets dropped: %21"PRIu64,
187                            portid,
188                            port_statistics[portid].tx,
189                            port_statistics[portid].rx,
190                            port_statistics[portid].dropped);
191
192                 total_packets_dropped += port_statistics[portid].dropped;
193                 total_packets_tx += port_statistics[portid].tx;
194                 total_packets_rx += port_statistics[portid].rx;
195         }
196         printf("\nAggregate statistics ==============================="
197                    "\nTotal packets sent: %18"PRIu64
198                    "\nTotal packets received: %14"PRIu64
199                    "\nTotal packets dropped: %15"PRIu64,
200                    total_packets_tx,
201                    total_packets_rx,
202                    total_packets_dropped);
203         printf("\n====================================================\n");
204 }
205
206 static int
207 clear_cpu_affinity(void)
208 {
209         int s;
210
211         s = sched_setaffinity(0, cpu_aff.size, &cpu_aff.set);
212         if (s != 0) {
213                 printf("sched_setaffinity failed:%s\n", strerror(errno));
214                 return -1;
215         }
216
217         return 0;
218 }
219
220 static int
221 get_cpu_affinity(void)
222 {
223         int s;
224
225         cpu_aff.size = sizeof(cpu_set_t);
226         CPU_ZERO(&cpu_aff.set);
227
228         s = sched_getaffinity(0, cpu_aff.size, &cpu_aff.set);
229         if (s != 0) {
230                 printf("sched_getaffinity failed:%s\n", strerror(errno));
231                 return -1;
232         }
233
234         return 0;
235 }
236
237 /**
238  * This fnciton demonstrates the approach to create ring in first instance
239  * or re-attach an existed ring in later instance.
240  **/
241 static struct rte_ring *
242 create_ring(const char *name, unsigned count,
243                                         int socket_id,unsigned flags)
244 {
245         struct rte_ring *ring;
246
247         if (name == NULL)
248                 return NULL;
249
250         /* If already create, just attached it */
251         if (likely((ring = rte_ring_lookup(name)) != NULL))
252                 return ring;
253
254         /* First call it, create one */
255         return rte_ring_create(name, count, socket_id, flags);
256 }
257
258 /* Malloc with rte_malloc on structures that shared by master and slave */
259 static int
260 l2fwd_malloc_shared_struct(void)
261 {
262         port_statistics = rte_zmalloc("port_stat",
263                                                 sizeof(struct l2fwd_port_statistics) * RTE_MAX_ETHPORTS,
264                                                 0);
265         if (port_statistics == NULL)
266                 return -1;
267
268         /* allocate  mapping_id array */
269         if (float_proc) {
270                 int i;
271                 mapping_id = rte_malloc("mapping_id", sizeof(unsigned) * RTE_MAX_LCORE,
272                                                                 0);
273
274                 if (mapping_id == NULL)
275                         return -1;
276
277                 for (i = 0 ;i < RTE_MAX_LCORE; i++)
278                         mapping_id[i] = INVALID_MAPPING_ID;
279         }
280         return 0;
281 }
282
283 /* Create ring which used for communicate among master and slave */
284 static int
285 create_ms_ring(unsigned slaveid)
286 {
287         unsigned flag = RING_F_SP_ENQ | RING_F_SC_DEQ;
288         struct lcore_resource_struct *res = &lcore_resource[slaveid];
289         unsigned socketid = rte_socket_id();
290
291         /* Always assume create ring on master socket_id */
292         /* Default only create a ring size 32 */
293         snprintf(res->ring_name[0], MAX_NAME_LEN, "%s%u",
294                         RING_MASTER_NAME, slaveid);
295         if ((res->ring[0] = create_ring(res->ring_name[0], NB_CORE_MSGBUF,
296                                 socketid, flag)) == NULL) {
297                 printf("Create m2s ring %s failed\n", res->ring_name[0]);
298                 return -1;
299         }
300
301         snprintf(res->ring_name[1], MAX_NAME_LEN, "%s%u",
302                         RING_SLAVE_NAME, slaveid);
303         if ((res->ring[1] = create_ring(res->ring_name[1], NB_CORE_MSGBUF,
304                 socketid, flag)) == NULL) {
305                 printf("Create s2m ring %s failed\n", res->ring_name[1]);
306                 return -1;
307         }
308
309         return 0;
310 }
311
312 /* send command to pair in paired master and slave ring */
313 static inline int
314 sendcmd(unsigned slaveid, enum l2fwd_cmd cmd, int is_master)
315 {
316         struct lcore_resource_struct *res = &lcore_resource[slaveid];
317         void *msg;
318         int fd = !is_master;
319
320         /* Only check master, it must be enabled and running if it is slave */
321         if (is_master && !res->enabled)
322                 return -1;
323
324         if (res->ring[fd] == NULL)
325                 return -1;
326
327         if (rte_mempool_get(message_pool, &msg) < 0) {
328                 printf("Error to get message buffer\n");
329                 return -1;
330         }
331
332         *(enum l2fwd_cmd *)msg = cmd;
333
334         if (rte_ring_enqueue(res->ring[fd], msg) != 0) {
335                 printf("Enqueue error\n");
336                 rte_mempool_put(message_pool, msg);
337                 return -1;
338         }
339
340         return 0;
341 }
342
343 /* Get command from pair in paired master and slave ring */
344 static inline int
345 getcmd(unsigned slaveid, enum l2fwd_cmd *cmd, int is_master)
346 {
347         struct lcore_resource_struct *res = &lcore_resource[slaveid];
348         void *msg;
349         int fd = !!is_master;
350         int ret;
351         /* Only check master, it must be enabled and running if it is slave */
352         if (is_master && (!res->enabled))
353                 return -1;
354
355         if (res->ring[fd] == NULL)
356                 return -1;
357
358         ret = rte_ring_dequeue(res->ring[fd], &msg);
359
360         if (ret == 0) {
361                 *cmd = *(enum l2fwd_cmd *)msg;
362                 rte_mempool_put(message_pool, msg);
363         }
364         return ret;
365 }
366
367 /* Master send command to slave and wait until ack received or error met */
368 static int
369 master_sendcmd_with_ack(unsigned slaveid, enum l2fwd_cmd cmd)
370 {
371         enum l2fwd_cmd ack_cmd;
372         int ret = -1;
373
374         if (sendcmd(slaveid, cmd, 1) != 0)
375                 rte_exit(EXIT_FAILURE, "Failed to send message\n");
376
377         /* Get ack */
378         while (1) {
379                 ret = getcmd(slaveid, &ack_cmd, 1);
380                 if (ret == 0 && cmd == ack_cmd)
381                         break;
382
383                 /* If slave not running yet, return an error */
384                 if (flib_query_slave_status(slaveid) != ST_RUN) {
385                         ret = -ENOENT;
386                         break;
387                 }
388         }
389
390         return ret;
391 }
392
393 /* restart all port that assigned to that slave lcore */
394 static int
395 reset_slave_all_ports(unsigned slaveid)
396 {
397         struct lcore_resource_struct *slave = &lcore_resource[slaveid];
398         int i, ret = 0;
399
400         /* stop/start port */
401         for (i = 0; i < slave->port_num; i++) {
402                 char buf_name[RTE_MEMPOOL_NAMESIZE];
403                 struct rte_mempool *pool;
404                 printf("Stop port :%d\n", slave->port[i]);
405                 rte_eth_dev_stop(slave->port[i]);
406                 snprintf(buf_name, RTE_MEMPOOL_NAMESIZE, MBUF_NAME, slave->port[i]);
407                 pool = rte_mempool_lookup(buf_name);
408                 if (pool)
409                         printf("Port %d mempool free object is %u(%u)\n", slave->port[i],
410                                 rte_mempool_avail_count(pool),
411                                 (unsigned int)NB_MBUF);
412                 else
413                         printf("Can't find mempool %s\n", buf_name);
414
415                 printf("Start port :%d\n", slave->port[i]);
416                 ret = rte_eth_dev_start(slave->port[i]);
417                 if (ret != 0)
418                         break;
419         }
420         return ret;
421 }
422
423 static int
424 reset_shared_structures(unsigned slaveid)
425 {
426         int ret;
427         /* Only port are shared resource here */
428         ret = reset_slave_all_ports(slaveid);
429
430         return ret;
431 }
432
433 /**
434  * Call this function to re-create resource that needed for slave process that
435  * exited in last instance
436  **/
437 static int
438 init_slave_res(unsigned slaveid)
439 {
440         struct lcore_resource_struct *slave = &lcore_resource[slaveid];
441         enum l2fwd_cmd cmd;
442
443         if (!slave->enabled) {
444                 printf("Something wrong with lcore=%u enabled=%d\n",slaveid,
445                         slave->enabled);
446                 return -1;
447         }
448
449         /* Initialize ring */
450         if (create_ms_ring(slaveid) != 0)
451                 rte_exit(EXIT_FAILURE, "failed to create ring for slave %u\n",
452                                 slaveid);
453
454         /* drain un-read buffer if have */
455         while (getcmd(slaveid, &cmd, 1) == 0);
456         while (getcmd(slaveid, &cmd, 0) == 0);
457
458         return 0;
459 }
460
461 static int
462 recreate_one_slave(unsigned slaveid)
463 {
464         int ret = 0;
465         /* Re-initialize resource for stalled slave */
466         if ((ret = init_slave_res(slaveid)) != 0) {
467                 printf("Init slave=%u failed\n", slaveid);
468                 return ret;
469         }
470
471         if ((ret = flib_remote_launch(l2fwd_launch_one_lcore, NULL, slaveid))
472                 != 0)
473                 printf("Launch slave %u failed\n", slaveid);
474
475         return ret;
476 }
477
478 /**
479  * remapping resource belong to slave_id to new lcore that gets from flib_assign_lcore_id(),
480  * used only floating process option applied.
481  *
482  * @param slaveid
483  *   original lcore_id that apply for remapping
484  */
485 static void
486 remapping_slave_resource(unsigned slaveid, unsigned map_id)
487 {
488
489         /* remapping lcore_resource */
490         memcpy(&lcore_resource[map_id], &lcore_resource[slaveid],
491                         sizeof(struct lcore_resource_struct));
492
493         /* remapping lcore_queue_conf */
494         memcpy(&lcore_queue_conf[map_id], &lcore_queue_conf[slaveid],
495                         sizeof(struct lcore_queue_conf));
496 }
497
498 static int
499 reset_pair(unsigned slaveid, unsigned pairid)
500 {
501         int ret;
502         if ((ret = reset_shared_structures(slaveid)) != 0)
503                 goto back;
504
505         if((ret = reset_shared_structures(pairid)) != 0)
506                 goto back;
507
508         if (float_proc) {
509                 unsigned map_id = mapping_id[slaveid];
510
511                 if (map_id != INVALID_MAPPING_ID) {
512                         printf("%u return mapping id %u\n", slaveid, map_id);
513                         flib_free_lcore_id(map_id);
514                         mapping_id[slaveid] = INVALID_MAPPING_ID;
515                 }
516
517                 map_id = mapping_id[pairid];
518                 if (map_id != INVALID_MAPPING_ID) {
519                         printf("%u return mapping id %u\n", pairid, map_id);
520                         flib_free_lcore_id(map_id);
521                         mapping_id[pairid] = INVALID_MAPPING_ID;
522                 }
523         }
524
525         if((ret = recreate_one_slave(slaveid)) != 0)
526                 goto back;
527
528         ret = recreate_one_slave(pairid);
529
530 back:
531         return ret;
532 }
533
534 static void
535 slave_exit_cb(unsigned slaveid, __attribute__((unused))int stat)
536 {
537         struct lcore_resource_struct *slave = &lcore_resource[slaveid];
538
539         printf("Get slave %u leave info\n", slaveid);
540         if (!slave->enabled) {
541                 printf("Lcore=%u not registered for it's exit\n", slaveid);
542                 return;
543         }
544         rte_spinlock_lock(&res_lock);
545
546         /* Change the state and wait master to start them */
547         slave->flags = SLAVE_RECREATE_FLAG;
548
549         rte_spinlock_unlock(&res_lock);
550 }
551
552 static void
553 l2fwd_simple_forward(struct rte_mbuf *m, unsigned portid)
554 {
555         struct ether_hdr *eth;
556         void *tmp;
557         unsigned dst_port;
558         int sent;
559         struct rte_eth_dev_tx_buffer *buffer;
560
561         dst_port = l2fwd_dst_ports[portid];
562         eth = rte_pktmbuf_mtod(m, struct ether_hdr *);
563
564         /* 02:00:00:00:00:xx */
565         tmp = &eth->d_addr.addr_bytes[0];
566         *((uint64_t *)tmp) = 0x000000000002 + ((uint64_t)dst_port << 40);
567
568         /* src addr */
569         ether_addr_copy(&l2fwd_ports_eth_addr[dst_port], &eth->s_addr);
570
571         buffer = tx_buffer[dst_port];
572         sent = rte_eth_tx_buffer(dst_port, 0, buffer, m);
573         if (sent)
574                 port_statistics[dst_port].tx += sent;
575 }
576
577 /* main processing loop */
578 static void
579 l2fwd_main_loop(void)
580 {
581         struct rte_mbuf *pkts_burst[MAX_PKT_BURST];
582         struct rte_mbuf *m;
583         int sent;
584         unsigned lcore_id;
585         uint64_t prev_tsc, diff_tsc, cur_tsc;
586         unsigned i, j, portid, nb_rx;
587         struct lcore_queue_conf *qconf;
588         const uint64_t drain_tsc = (rte_get_tsc_hz() + US_PER_S - 1) / US_PER_S *
589                         BURST_TX_DRAIN_US;
590         struct rte_eth_dev_tx_buffer *buffer;
591
592         prev_tsc = 0;
593
594         lcore_id = rte_lcore_id();
595
596         qconf = &lcore_queue_conf[lcore_id];
597
598         if (qconf->n_rx_port == 0) {
599                 RTE_LOG(INFO, L2FWD, "lcore %u has nothing to do\n", lcore_id);
600                 return;
601         }
602
603         RTE_LOG(INFO, L2FWD, "entering main loop on lcore %u\n", lcore_id);
604
605         for (i = 0; i < qconf->n_rx_port; i++) {
606                 portid = qconf->rx_port_list[i];
607                 RTE_LOG(INFO, L2FWD, " -- lcoreid=%u portid=%u\n", lcore_id,
608                         portid);
609         }
610
611         while (1) {
612                 enum l2fwd_cmd cmd;
613                 cur_tsc = rte_rdtsc();
614
615                 if (unlikely(getcmd(lcore_id, &cmd, 0) == 0)) {
616                         sendcmd(lcore_id, cmd, 0);
617
618                         /* If get stop command, stop forwarding and exit */
619                         if (cmd == CMD_STOP) {
620                                 return;
621                         }
622                 }
623
624                 /*
625                  * TX burst queue drain
626                  */
627                 diff_tsc = cur_tsc - prev_tsc;
628                 if (unlikely(diff_tsc > drain_tsc)) {
629
630                         for (i = 0; i < qconf->n_rx_port; i++) {
631
632                                 portid = l2fwd_dst_ports[qconf->rx_port_list[i]];
633                                 buffer = tx_buffer[portid];
634
635                                 sent = rte_eth_tx_buffer_flush(portid, 0, buffer);
636                                 if (sent)
637                                         port_statistics[portid].tx += sent;
638
639                         }
640
641                         prev_tsc = cur_tsc;
642                 }
643
644                 /*
645                  * Read packet from RX queues
646                  */
647                 for (i = 0; i < qconf->n_rx_port; i++) {
648
649                         portid = qconf->rx_port_list[i];
650                         nb_rx = rte_eth_rx_burst((uint8_t) portid, 0,
651                                                  pkts_burst, MAX_PKT_BURST);
652
653                         port_statistics[portid].rx += nb_rx;
654
655                         for (j = 0; j < nb_rx; j++) {
656                                 m = pkts_burst[j];
657                                 rte_prefetch0(rte_pktmbuf_mtod(m, void *));
658                                 l2fwd_simple_forward(m, portid);
659                         }
660                 }
661         }
662 }
663
664 static int
665 l2fwd_launch_one_lcore(__attribute__((unused)) void *dummy)
666 {
667         unsigned lcore_id = rte_lcore_id();
668
669         if (float_proc) {
670                 unsigned flcore_id;
671
672                 /* Change it to floating process, also change it's lcore_id */
673                 clear_cpu_affinity();
674                 RTE_PER_LCORE(_lcore_id) = 0;
675                 /* Get a lcore_id */
676                 if (flib_assign_lcore_id() < 0 ) {
677                         printf("flib_assign_lcore_id failed\n");
678                         return -1;
679                 }
680                 flcore_id = rte_lcore_id();
681                 /* Set mapping id, so master can return it after slave exited */
682                 mapping_id[lcore_id] = flcore_id;
683                 printf("Org lcore_id = %u, cur lcore_id = %u\n",
684                                 lcore_id, flcore_id);
685                 remapping_slave_resource(lcore_id, flcore_id);
686         }
687
688         l2fwd_main_loop();
689
690         /* return lcore_id before return */
691         if (float_proc) {
692                 flib_free_lcore_id(rte_lcore_id());
693                 mapping_id[lcore_id] = INVALID_MAPPING_ID;
694         }
695         return 0;
696 }
697
698 /* display usage */
699 static void
700 l2fwd_usage(const char *prgname)
701 {
702         printf("%s [EAL options] -- -p PORTMASK -s COREMASK [-q NQ] -f\n"
703                "  -p PORTMASK: hexadecimal bitmask of ports to configure\n"
704                "  -q NQ: number of queue (=ports) per lcore (default is 1)\n"
705                "  -f use floating process which won't bind to any core to run\n"
706                    "  -T PERIOD: statistics will be refreshed each PERIOD seconds (0 to disable, 10 default, 86400 maximum)\n",
707                prgname);
708 }
709
710 static int
711 l2fwd_parse_portmask(const char *portmask)
712 {
713         char *end = NULL;
714         unsigned long pm;
715
716         /* parse hexadecimal string */
717         pm = strtoul(portmask, &end, 16);
718         if ((portmask[0] == '\0') || (end == NULL) || (*end != '\0'))
719                 return -1;
720
721         if (pm == 0)
722                 return -1;
723
724         return pm;
725 }
726
727 static unsigned int
728 l2fwd_parse_nqueue(const char *q_arg)
729 {
730         char *end = NULL;
731         unsigned long n;
732
733         /* parse hexadecimal string */
734         n = strtoul(q_arg, &end, 10);
735         if ((q_arg[0] == '\0') || (end == NULL) || (*end != '\0'))
736                 return 0;
737         if (n == 0)
738                 return 0;
739         if (n >= MAX_RX_QUEUE_PER_LCORE)
740                 return 0;
741
742         return n;
743 }
744
745 static int
746 l2fwd_parse_timer_period(const char *q_arg)
747 {
748         char *end = NULL;
749         int n;
750
751         /* parse number string */
752         n = strtol(q_arg, &end, 10);
753         if ((q_arg[0] == '\0') || (end == NULL) || (*end != '\0'))
754                 return -1;
755         if (n >= MAX_TIMER_PERIOD)
756                 return -1;
757
758         return n;
759 }
760
761 /* Parse the argument given in the command line of the application */
762 static int
763 l2fwd_parse_args(int argc, char **argv)
764 {
765         int opt, ret;
766         char **argvopt;
767         int option_index;
768         char *prgname = argv[0];
769         static struct option lgopts[] = {
770                 {NULL, 0, 0, 0}
771         };
772         int has_pmask = 0;
773
774         argvopt = argv;
775
776         while ((opt = getopt_long(argc, argvopt, "p:q:T:f",
777                                   lgopts, &option_index)) != EOF) {
778
779                 switch (opt) {
780                 /* portmask */
781                 case 'p':
782                         l2fwd_enabled_port_mask = l2fwd_parse_portmask(optarg);
783                         if (l2fwd_enabled_port_mask == 0) {
784                                 printf("invalid portmask\n");
785                                 l2fwd_usage(prgname);
786                                 return -1;
787                         }
788                         has_pmask = 1;
789                         break;
790
791                 /* nqueue */
792                 case 'q':
793                         l2fwd_rx_queue_per_lcore = l2fwd_parse_nqueue(optarg);
794                         if (l2fwd_rx_queue_per_lcore == 0) {
795                                 printf("invalid queue number\n");
796                                 l2fwd_usage(prgname);
797                                 return -1;
798                         }
799                         break;
800
801                 /* timer period */
802                 case 'T':
803                         timer_period = l2fwd_parse_timer_period(optarg) * 1000 * TIMER_MILLISECOND;
804                         if (timer_period < 0) {
805                                 printf("invalid timer period\n");
806                                 l2fwd_usage(prgname);
807                                 return -1;
808                         }
809                         break;
810
811                 /* use floating process */
812                 case 'f':
813                         float_proc = 1;
814                         break;
815
816                 /* long options */
817                 case 0:
818                         l2fwd_usage(prgname);
819                         return -1;
820
821                 default:
822                         l2fwd_usage(prgname);
823                         return -1;
824                 }
825         }
826
827         if (optind >= 0)
828                 argv[optind-1] = prgname;
829
830         if (!has_pmask) {
831                 l2fwd_usage(prgname);
832                 return -1;
833         }
834         ret = optind-1;
835         optind = 1; /* reset getopt lib */
836         return ret;
837 }
838
839 /* Check the link status of all ports in up to 9s, and print them finally */
840 static void
841 check_all_ports_link_status(uint16_t port_num, uint32_t port_mask)
842 {
843 #define CHECK_INTERVAL 100 /* 100ms */
844 #define MAX_CHECK_TIME 90 /* 9s (90 * 100ms) in total */
845         uint16_t portid;
846         uint8_t count, all_ports_up, print_flag = 0;
847         struct rte_eth_link link;
848
849         printf("\nChecking link status");
850         fflush(stdout);
851         for (count = 0; count <= MAX_CHECK_TIME; count++) {
852                 all_ports_up = 1;
853                 for (portid = 0; portid < port_num; portid++) {
854                         if ((port_mask & (1 << portid)) == 0)
855                                 continue;
856                         memset(&link, 0, sizeof(link));
857                         rte_eth_link_get_nowait(portid, &link);
858                         /* print link status if flag set */
859                         if (print_flag == 1) {
860                                 if (link.link_status)
861                                         printf(
862                                         "Port%d Link Up- speed %u Mbps- %s\n",
863                                         portid, link.link_speed,
864                                 (link.link_duplex == ETH_LINK_FULL_DUPLEX) ?
865                                         ("full-duplex") : ("half-duplex\n"));
866                                 else
867                                         printf("Port %d Link Down\n", portid);
868                                 continue;
869                         }
870                         /* clear all_ports_up flag if any link down */
871                         if (link.link_status == ETH_LINK_DOWN) {
872                                 all_ports_up = 0;
873                                 break;
874                         }
875                 }
876                 /* after finally printing all link status, get out */
877                 if (print_flag == 1)
878                         break;
879
880                 if (all_ports_up == 0) {
881                         printf(".");
882                         fflush(stdout);
883                         rte_delay_ms(CHECK_INTERVAL);
884                 }
885
886                 /* set the print_flag if all ports up or timeout */
887                 if (all_ports_up == 1 || count == (MAX_CHECK_TIME - 1)) {
888                         print_flag = 1;
889                         printf("done\n");
890                 }
891         }
892 }
893
894 int
895 main(int argc, char **argv)
896 {
897         struct lcore_queue_conf *qconf;
898         int ret;
899         uint16_t nb_ports;
900         uint16_t nb_ports_available;
901         uint16_t portid, last_port;
902         unsigned rx_lcore_id;
903         unsigned nb_ports_in_mask = 0;
904         unsigned i;
905         uint64_t prev_tsc, diff_tsc, cur_tsc, timer_tsc;
906
907         /* Save cpu_affinity first, restore it in case it's floating process option */
908         if (get_cpu_affinity() != 0)
909                 rte_exit(EXIT_FAILURE, "get_cpu_affinity error\n");
910
911         /* Also tries to set cpu affinity to detect whether  it will fail in child process */
912         if(clear_cpu_affinity() != 0)
913                 rte_exit(EXIT_FAILURE, "clear_cpu_affinity error\n");
914
915         /* init EAL */
916         ret = rte_eal_init(argc, argv);
917         if (ret < 0)
918                 rte_exit(EXIT_FAILURE, "Invalid EAL arguments\n");
919         argc -= ret;
920         argv += ret;
921
922         /* parse application arguments (after the EAL ones) */
923         ret = l2fwd_parse_args(argc, argv);
924         if (ret < 0)
925                 rte_exit(EXIT_FAILURE, "Invalid L2FWD arguments\n");
926
927         /*flib init */
928         if (flib_init() != 0)
929                 rte_exit(EXIT_FAILURE, "flib init error");
930
931         /**
932           * Allocated structures that slave lcore would change. For those that slaves are
933           * read only, needn't use malloc to share and global or static variables is ok since
934           * slave inherit all the knowledge that master initialized.
935           **/
936         if (l2fwd_malloc_shared_struct() != 0)
937                 rte_exit(EXIT_FAILURE, "malloc mem failed\n");
938
939         /* Initialize lcore_resource structures */
940         memset(lcore_resource, 0, sizeof(lcore_resource));
941         for (i = 0; i < RTE_MAX_LCORE; i++)
942                 lcore_resource[i].lcore_id = i;
943
944         nb_ports = rte_eth_dev_count();
945         if (nb_ports == 0)
946                 rte_exit(EXIT_FAILURE, "No Ethernet ports - bye\n");
947
948         /* create the mbuf pool */
949         for (portid = 0; portid < nb_ports; portid++) {
950                 /* skip ports that are not enabled */
951                 if ((l2fwd_enabled_port_mask & (1 << portid)) == 0)
952                         continue;
953                 char buf_name[RTE_MEMPOOL_NAMESIZE];
954                 snprintf(buf_name, RTE_MEMPOOL_NAMESIZE, MBUF_NAME, portid);
955                 l2fwd_pktmbuf_pool[portid] =
956                         rte_pktmbuf_pool_create(buf_name, NB_MBUF, 32,
957                                 0, MBUF_DATA_SIZE, rte_socket_id());
958                 if (l2fwd_pktmbuf_pool[portid] == NULL)
959                         rte_exit(EXIT_FAILURE, "Cannot create mbuf pool\n");
960
961                 printf("Create mbuf %s\n", buf_name);
962         }
963
964         /* reset l2fwd_dst_ports */
965         for (portid = 0; portid < RTE_MAX_ETHPORTS; portid++)
966                 l2fwd_dst_ports[portid] = 0;
967         last_port = 0;
968
969         /*
970          * Each logical core is assigned a dedicated TX queue on each port.
971          */
972         for (portid = 0; portid < nb_ports; portid++) {
973                 /* skip ports that are not enabled */
974                 if ((l2fwd_enabled_port_mask & (1 << portid)) == 0)
975                         continue;
976
977                 if (nb_ports_in_mask % 2) {
978                         l2fwd_dst_ports[portid] = last_port;
979                         l2fwd_dst_ports[last_port] = portid;
980                 }
981                 else
982                         last_port = portid;
983
984                 nb_ports_in_mask++;
985         }
986         if (nb_ports_in_mask % 2) {
987                 printf("Notice: odd number of ports in portmask.\n");
988                 l2fwd_dst_ports[last_port] = last_port;
989         }
990
991         rx_lcore_id = 0;
992         qconf = NULL;
993
994         /* Initialize the port/queue configuration of each logical core */
995         for (portid = 0; portid < nb_ports; portid++) {
996                 struct lcore_resource_struct *res;
997                 /* skip ports that are not enabled */
998                 if ((l2fwd_enabled_port_mask & (1 << portid)) == 0)
999                         continue;
1000
1001                 /* get the lcore_id for this port */
1002                 /* skip master lcore */
1003                 while (rte_lcore_is_enabled(rx_lcore_id) == 0 ||
1004                            rte_get_master_lcore() == rx_lcore_id ||
1005                        lcore_queue_conf[rx_lcore_id].n_rx_port ==
1006                        l2fwd_rx_queue_per_lcore) {
1007
1008                         rx_lcore_id++;
1009                         if (rx_lcore_id >= RTE_MAX_LCORE)
1010                                 rte_exit(EXIT_FAILURE, "Not enough cores\n");
1011                 }
1012
1013                 if (qconf != &lcore_queue_conf[rx_lcore_id])
1014                         /* Assigned a new logical core in the loop above. */
1015                         qconf = &lcore_queue_conf[rx_lcore_id];
1016
1017                 qconf->rx_port_list[qconf->n_rx_port] = portid;
1018                 qconf->n_rx_port++;
1019
1020                 /* Save the port resource info into lcore_resource strucutres */
1021                 res = &lcore_resource[rx_lcore_id];
1022                 res->enabled = 1;
1023                 res->port[res->port_num++] = portid;
1024
1025                 printf("Lcore %u: RX port %u\n", rx_lcore_id, (unsigned) portid);
1026         }
1027
1028         nb_ports_available = nb_ports;
1029
1030         /* Initialise each port */
1031         for (portid = 0; portid < nb_ports; portid++) {
1032                 struct rte_eth_rxconf rxq_conf;
1033                 struct rte_eth_txconf txq_conf;
1034                 struct rte_eth_conf local_port_conf = port_conf;
1035
1036                 /* skip ports that are not enabled */
1037                 if ((l2fwd_enabled_port_mask & (1 << portid)) == 0) {
1038                         printf("Skipping disabled port %u\n", (unsigned) portid);
1039                         nb_ports_available--;
1040                         continue;
1041                 }
1042                 /* init port */
1043                 printf("Initializing port %u... ", (unsigned) portid);
1044                 fflush(stdout);
1045                 rte_eth_dev_info_get(portid, &dev_info);
1046                 if (dev_info.tx_offload_capa & DEV_TX_OFFLOAD_MBUF_FAST_FREE)
1047                         local_port_conf.txmode.offloads |=
1048                                 DEV_TX_OFFLOAD_MBUF_FAST_FREE;
1049                 ret = rte_eth_dev_configure(portid, 1, 1, &local_port_conf);
1050                 if (ret < 0)
1051                         rte_exit(EXIT_FAILURE, "Cannot configure device: err=%d, port=%u\n",
1052                                   ret, (unsigned) portid);
1053
1054                 ret = rte_eth_dev_adjust_nb_rx_tx_desc(portid, &nb_rxd,
1055                                                        &nb_txd);
1056                 if (ret < 0)
1057                         rte_exit(EXIT_FAILURE,
1058                                  "rte_eth_dev_adjust_nb_rx_tx_desc: err=%d, port=%u\n",
1059                                  ret, (unsigned) portid);
1060
1061                 rte_eth_macaddr_get(portid,&l2fwd_ports_eth_addr[portid]);
1062
1063                 /* init one RX queue */
1064                 fflush(stdout);
1065                 rxq_conf = dev_info.default_rxconf;
1066                 rxq_conf.offloads = local_port_conf.rxmode.offloads;
1067                 ret = rte_eth_rx_queue_setup(portid, 0, nb_rxd,
1068                                              rte_eth_dev_socket_id(portid),
1069                                              &rxq_conf,
1070                                              l2fwd_pktmbuf_pool[portid]);
1071                 if (ret < 0)
1072                         rte_exit(EXIT_FAILURE, "rte_eth_rx_queue_setup:err=%d, port=%u\n",
1073                                   ret, (unsigned) portid);
1074
1075                 /* init one TX queue on each port */
1076                 fflush(stdout);
1077                 txq_conf = dev_info.default_txconf;
1078                 txq_conf.txq_flags = ETH_TXQ_FLAGS_IGNORE;
1079                 txq_conf.tx_offloads = local_port_conf.txmode.offloads;
1080                 ret = rte_eth_tx_queue_setup(portid, 0, nb_txd,
1081                                 rte_eth_dev_socket_id(portid),
1082                                 &txq_conf);
1083                 if (ret < 0)
1084                         rte_exit(EXIT_FAILURE, "rte_eth_tx_queue_setup:err=%d, port=%u\n",
1085                                 ret, (unsigned) portid);
1086
1087                 /* Initialize TX buffers */
1088                 tx_buffer[portid] = rte_zmalloc_socket("tx_buffer",
1089                                 RTE_ETH_TX_BUFFER_SIZE(MAX_PKT_BURST), 0,
1090                                 rte_eth_dev_socket_id(portid));
1091                 if (tx_buffer[portid] == NULL)
1092                         rte_exit(EXIT_FAILURE, "Cannot allocate buffer for tx on port %u\n",
1093                                         (unsigned) portid);
1094
1095                 rte_eth_tx_buffer_init(tx_buffer[portid], MAX_PKT_BURST);
1096
1097                 ret = rte_eth_tx_buffer_set_err_callback(tx_buffer[portid],
1098                                 rte_eth_tx_buffer_count_callback,
1099                                 &port_statistics[portid].dropped);
1100                 if (ret < 0)
1101                                 rte_exit(EXIT_FAILURE, "Cannot set error callback for "
1102                                                 "tx buffer on port %u\n", (unsigned) portid);
1103
1104                 /* Start device */
1105                 ret = rte_eth_dev_start(portid);
1106                 if (ret < 0)
1107                         rte_exit(EXIT_FAILURE, "rte_eth_dev_start:err=%d, port=%u\n",
1108                                   ret, (unsigned) portid);
1109
1110                 printf("done: \n");
1111
1112                 rte_eth_promiscuous_enable(portid);
1113
1114                 printf("Port %u, MAC address: %02X:%02X:%02X:%02X:%02X:%02X\n\n",
1115                                 (unsigned) portid,
1116                                 l2fwd_ports_eth_addr[portid].addr_bytes[0],
1117                                 l2fwd_ports_eth_addr[portid].addr_bytes[1],
1118                                 l2fwd_ports_eth_addr[portid].addr_bytes[2],
1119                                 l2fwd_ports_eth_addr[portid].addr_bytes[3],
1120                                 l2fwd_ports_eth_addr[portid].addr_bytes[4],
1121                                 l2fwd_ports_eth_addr[portid].addr_bytes[5]);
1122
1123                 /* initialize port stats */
1124                 //memset(&port_statistics, 0, sizeof(port_statistics));
1125         }
1126
1127         if (!nb_ports_available) {
1128                 rte_exit(EXIT_FAILURE,
1129                         "All available ports are disabled. Please set portmask.\n");
1130         }
1131
1132         check_all_ports_link_status(nb_ports, l2fwd_enabled_port_mask);
1133
1134         /* Record pair lcore */
1135         /**
1136          * Since l2fwd example would create pair between different neighbour port, that's
1137          * port 0 receive and forward to port 1, the same to port 1, these 2 ports will have
1138          * dependency. If one port stopped working (killed, for example), the port need to
1139          * be stopped/started again. During the time, another port need to wait until stop/start
1140          * procedure completed. So, record the pair relationship for those lcores working
1141          * on ports.
1142          **/
1143         for (portid = 0; portid < nb_ports; portid++) {
1144                 uint32_t pair_port;
1145                 unsigned lcore = 0, pair_lcore = 0;
1146                 unsigned j, find_lcore, find_pair_lcore;
1147                 /* skip ports that are not enabled */
1148                 if ((l2fwd_enabled_port_mask & (1 << portid)) == 0)
1149                         continue;
1150
1151                 /* Find pair ports' lcores */
1152                 find_lcore = find_pair_lcore = 0;
1153                 pair_port = l2fwd_dst_ports[portid];
1154                 for (i = 0; i < RTE_MAX_LCORE; i++) {
1155                         if (!rte_lcore_is_enabled(i))
1156                                 continue;
1157                         for (j = 0; j < lcore_queue_conf[i].n_rx_port;j++) {
1158                                 if (lcore_queue_conf[i].rx_port_list[j] == portid) {
1159                                         lcore = i;
1160                                         find_lcore = 1;
1161                                         break;
1162                                 }
1163                                 if (lcore_queue_conf[i].rx_port_list[j] == pair_port) {
1164                                         pair_lcore = i;
1165                                         find_pair_lcore = 1;
1166                                         break;
1167                                 }
1168                         }
1169                         if (find_lcore && find_pair_lcore)
1170                                 break;
1171                 }
1172                 if (!find_lcore || !find_pair_lcore)
1173                         rte_exit(EXIT_FAILURE, "Not find port=%d pair\n", portid);
1174
1175                 printf("lcore %u and %u paired\n", lcore, pair_lcore);
1176                 lcore_resource[lcore].pair_id = pair_lcore;
1177                 lcore_resource[pair_lcore].pair_id = lcore;
1178         }
1179
1180         /* Create message buffer for all master and slave */
1181         message_pool = rte_mempool_create("ms_msg_pool",
1182                            NB_CORE_MSGBUF * RTE_MAX_LCORE,
1183                            sizeof(enum l2fwd_cmd), NB_CORE_MSGBUF / 2,
1184                            0, NULL, NULL, NULL, NULL, rte_socket_id(), 0);
1185
1186         if (message_pool == NULL)
1187                 rte_exit(EXIT_FAILURE, "Create msg mempool failed\n");
1188
1189         /* Create ring for each master and slave pair, also register cb when slave leaves */
1190         for (i = 0; i < RTE_MAX_LCORE; i++) {
1191                 /**
1192                  * Only create ring and register slave_exit cb in case that core involved into
1193                  * packet forwarding
1194                  **/
1195                 if (lcore_resource[i].enabled) {
1196                         /* Create ring for master and slave communication */
1197                         ret = create_ms_ring(i);
1198                         if (ret != 0)
1199                                 rte_exit(EXIT_FAILURE, "Create ring for lcore=%u failed",
1200                                 i);
1201
1202                         if (flib_register_slave_exit_notify(i,
1203                                 slave_exit_cb) != 0)
1204                                 rte_exit(EXIT_FAILURE,
1205                                                 "Register master_trace_slave_exit failed");
1206                 }
1207         }
1208
1209         /* launch per-lcore init on every lcore except master */
1210         flib_mp_remote_launch(l2fwd_launch_one_lcore, NULL, SKIP_MASTER);
1211
1212         /* print statistics 10 second */
1213         prev_tsc = cur_tsc = rte_rdtsc();
1214         timer_tsc = 0;
1215         while (1) {
1216                 sleep(1);
1217                 cur_tsc = rte_rdtsc();
1218                 diff_tsc = cur_tsc - prev_tsc;
1219                 /* if timer is enabled */
1220                 if (timer_period > 0) {
1221
1222                         /* advance the timer */
1223                         timer_tsc += diff_tsc;
1224
1225                         /* if timer has reached its timeout */
1226                         if (unlikely(timer_tsc >= (uint64_t) timer_period)) {
1227
1228                                 print_stats();
1229                                 /* reset the timer */
1230                                 timer_tsc = 0;
1231                         }
1232                 }
1233
1234                 prev_tsc = cur_tsc;
1235
1236                 /* Check any slave need restart or recreate */
1237                 rte_spinlock_lock(&res_lock);
1238                 for (i = 0; i < RTE_MAX_LCORE; i++) {
1239                         struct lcore_resource_struct *res  = &lcore_resource[i];
1240                         struct lcore_resource_struct *pair = &lcore_resource[res->pair_id];
1241
1242                         /* If find slave exited, try to reset pair */
1243                         if (res->enabled && res->flags && pair->enabled) {
1244                                 if (!pair->flags) {
1245                                         master_sendcmd_with_ack(pair->lcore_id, CMD_STOP);
1246                                         rte_spinlock_unlock(&res_lock);
1247                                         sleep(1);
1248                                         rte_spinlock_lock(&res_lock);
1249                                         if (pair->flags)
1250                                                 continue;
1251                                 }
1252                                 if (reset_pair(res->lcore_id, pair->lcore_id) != 0)
1253                                         rte_exit(EXIT_FAILURE, "failed to reset slave");
1254                                 res->flags  = 0;
1255                                 pair->flags = 0;
1256                         }
1257                 }
1258                 rte_spinlock_unlock(&res_lock);
1259         }
1260
1261 }