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