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