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