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