New upstream version 17.11-rc3
[deb_dpdk.git] / examples / l2fwd-jobstats / 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
34 #include <locale.h>
35 #include <stdlib.h>
36 #include <string.h>
37 #include <stdint.h>
38 #include <ctype.h>
39 #include <getopt.h>
40
41 #include <rte_common.h>
42 #include <rte_log.h>
43 #include <rte_malloc.h>
44 #include <rte_memory.h>
45 #include <rte_memcpy.h>
46 #include <rte_eal.h>
47 #include <rte_launch.h>
48 #include <rte_atomic.h>
49 #include <rte_cycles.h>
50 #include <rte_prefetch.h>
51 #include <rte_lcore.h>
52 #include <rte_per_lcore.h>
53 #include <rte_branch_prediction.h>
54 #include <rte_interrupts.h>
55 #include <rte_debug.h>
56 #include <rte_ether.h>
57 #include <rte_ethdev.h>
58 #include <rte_mempool.h>
59 #include <rte_mbuf.h>
60 #include <rte_spinlock.h>
61
62 #include <rte_errno.h>
63 #include <rte_jobstats.h>
64 #include <rte_timer.h>
65 #include <rte_alarm.h>
66 #include <rte_pause.h>
67
68 #define RTE_LOGTYPE_L2FWD RTE_LOGTYPE_USER1
69
70 #define NB_MBUF   8192
71
72 #define MAX_PKT_BURST 32
73 #define BURST_TX_DRAIN_US 100 /* TX drain every ~100us */
74
75 /*
76  * Configurable number of RX/TX ring descriptors
77  */
78 #define RTE_TEST_RX_DESC_DEFAULT 128
79 #define RTE_TEST_TX_DESC_DEFAULT 512
80 static uint16_t nb_rxd = RTE_TEST_RX_DESC_DEFAULT;
81 static uint16_t nb_txd = RTE_TEST_TX_DESC_DEFAULT;
82
83 /* ethernet addresses of ports */
84 static struct ether_addr l2fwd_ports_eth_addr[RTE_MAX_ETHPORTS];
85
86 /* mask of enabled ports */
87 static uint32_t l2fwd_enabled_port_mask;
88
89 /* list of enabled ports */
90 static uint32_t l2fwd_dst_ports[RTE_MAX_ETHPORTS];
91
92 #define UPDATE_STEP_UP 1
93 #define UPDATE_STEP_DOWN 32
94
95 static unsigned int l2fwd_rx_queue_per_lcore = 1;
96
97 #define MAX_RX_QUEUE_PER_LCORE 16
98 #define MAX_TX_QUEUE_PER_PORT 16
99 struct lcore_queue_conf {
100         unsigned n_rx_port;
101         unsigned rx_port_list[MAX_RX_QUEUE_PER_LCORE];
102         uint64_t next_flush_time[RTE_MAX_ETHPORTS];
103
104         struct rte_timer rx_timers[MAX_RX_QUEUE_PER_LCORE];
105         struct rte_jobstats port_fwd_jobs[MAX_RX_QUEUE_PER_LCORE];
106
107         struct rte_timer flush_timer;
108         struct rte_jobstats flush_job;
109         struct rte_jobstats idle_job;
110         struct rte_jobstats_context jobs_context;
111
112         rte_atomic16_t stats_read_pending;
113         rte_spinlock_t lock;
114 } __rte_cache_aligned;
115 struct lcore_queue_conf lcore_queue_conf[RTE_MAX_LCORE];
116
117 struct rte_eth_dev_tx_buffer *tx_buffer[RTE_MAX_ETHPORTS];
118
119 static const struct rte_eth_conf port_conf = {
120         .rxmode = {
121                 .split_hdr_size = 0,
122                 .header_split   = 0, /**< Header Split disabled */
123                 .hw_ip_checksum = 0, /**< IP checksum offload disabled */
124                 .hw_vlan_filter = 0, /**< VLAN filtering disabled */
125                 .jumbo_frame    = 0, /**< Jumbo Frame Support disabled */
126                 .hw_strip_crc   = 1, /**< CRC stripped by hardware */
127         },
128         .txmode = {
129                 .mq_mode = ETH_MQ_TX_NONE,
130         },
131 };
132
133 struct rte_mempool *l2fwd_pktmbuf_pool = NULL;
134
135 /* Per-port statistics struct */
136 struct l2fwd_port_statistics {
137         uint64_t tx;
138         uint64_t rx;
139         uint64_t dropped;
140 } __rte_cache_aligned;
141 struct l2fwd_port_statistics port_statistics[RTE_MAX_ETHPORTS];
142
143 /* 1 day max */
144 #define MAX_TIMER_PERIOD 86400
145 /* default period is 10 seconds */
146 static int64_t timer_period = 10;
147 /* default timer frequency */
148 static double hz;
149 /* BURST_TX_DRAIN_US converted to cycles */
150 uint64_t drain_tsc;
151 /* Convert cycles to ns */
152 static inline double
153 cycles_to_ns(uint64_t cycles)
154 {
155         double t = cycles;
156
157         t *= (double)NS_PER_S;
158         t /= hz;
159         return t;
160 }
161
162 static void
163 show_lcore_stats(unsigned lcore_id)
164 {
165         struct lcore_queue_conf *qconf = &lcore_queue_conf[lcore_id];
166         struct rte_jobstats_context *ctx = &qconf->jobs_context;
167         struct rte_jobstats *job;
168         uint8_t i;
169
170         /* LCore statistics. */
171         uint64_t stats_period, loop_count;
172         uint64_t exec, exec_min, exec_max;
173         uint64_t management, management_min, management_max;
174         uint64_t busy, busy_min, busy_max;
175
176         /* Jobs statistics. */
177         const uint16_t port_cnt = qconf->n_rx_port;
178         uint64_t jobs_exec_cnt[port_cnt], jobs_period[port_cnt];
179         uint64_t jobs_exec[port_cnt], jobs_exec_min[port_cnt],
180                                 jobs_exec_max[port_cnt];
181
182         uint64_t flush_exec_cnt, flush_period;
183         uint64_t flush_exec, flush_exec_min, flush_exec_max;
184
185         uint64_t idle_exec_cnt;
186         uint64_t idle_exec, idle_exec_min, idle_exec_max;
187         uint64_t collection_time = rte_get_timer_cycles();
188
189         /* Ask forwarding thread to give us stats. */
190         rte_atomic16_set(&qconf->stats_read_pending, 1);
191         rte_spinlock_lock(&qconf->lock);
192         rte_atomic16_set(&qconf->stats_read_pending, 0);
193
194         /* Collect context statistics. */
195         stats_period = ctx->state_time - ctx->start_time;
196         loop_count = ctx->loop_cnt;
197
198         exec = ctx->exec_time;
199         exec_min = ctx->min_exec_time;
200         exec_max = ctx->max_exec_time;
201
202         management = ctx->management_time;
203         management_min = ctx->min_management_time;
204         management_max = ctx->max_management_time;
205
206         rte_jobstats_context_reset(ctx);
207
208         for (i = 0; i < port_cnt; i++) {
209                 job = &qconf->port_fwd_jobs[i];
210
211                 jobs_exec_cnt[i] = job->exec_cnt;
212                 jobs_period[i] = job->period;
213
214                 jobs_exec[i] = job->exec_time;
215                 jobs_exec_min[i] = job->min_exec_time;
216                 jobs_exec_max[i] = job->max_exec_time;
217
218                 rte_jobstats_reset(job);
219         }
220
221         flush_exec_cnt = qconf->flush_job.exec_cnt;
222         flush_period = qconf->flush_job.period;
223         flush_exec = qconf->flush_job.exec_time;
224         flush_exec_min = qconf->flush_job.min_exec_time;
225         flush_exec_max = qconf->flush_job.max_exec_time;
226         rte_jobstats_reset(&qconf->flush_job);
227
228         idle_exec_cnt = qconf->idle_job.exec_cnt;
229         idle_exec = qconf->idle_job.exec_time;
230         idle_exec_min = qconf->idle_job.min_exec_time;
231         idle_exec_max = qconf->idle_job.max_exec_time;
232         rte_jobstats_reset(&qconf->idle_job);
233
234         rte_spinlock_unlock(&qconf->lock);
235
236         exec -= idle_exec;
237         busy = exec + management;
238         busy_min = exec_min + management_min;
239         busy_max = exec_max + management_max;
240
241
242         collection_time = rte_get_timer_cycles() - collection_time;
243
244 #define STAT_FMT "\n%-18s %'14.0f %6.1f%% %'10.0f %'10.0f %'10.0f"
245
246         printf("\n----------------"
247                         "\nLCore %3u: statistics (time in ns, collected in %'9.0f)"
248                         "\n%-18s %14s %7s %10s %10s %10s "
249                         "\n%-18s %'14.0f"
250                         "\n%-18s %'14" PRIu64
251                         STAT_FMT /* Exec */
252                         STAT_FMT /* Management */
253                         STAT_FMT /* Busy */
254                         STAT_FMT, /* Idle  */
255                         lcore_id, cycles_to_ns(collection_time),
256                         "Stat type", "total", "%total", "avg", "min", "max",
257                         "Stats duration:", cycles_to_ns(stats_period),
258                         "Loop count:", loop_count,
259                         "Exec time",
260                         cycles_to_ns(exec), exec * 100.0 / stats_period,
261                         cycles_to_ns(loop_count  ? exec / loop_count : 0),
262                         cycles_to_ns(exec_min),
263                         cycles_to_ns(exec_max),
264                         "Management time",
265                         cycles_to_ns(management), management * 100.0 / stats_period,
266                         cycles_to_ns(loop_count  ? management / loop_count : 0),
267                         cycles_to_ns(management_min),
268                         cycles_to_ns(management_max),
269                         "Exec + management",
270                         cycles_to_ns(busy),  busy * 100.0 / stats_period,
271                         cycles_to_ns(loop_count ? busy / loop_count : 0),
272                         cycles_to_ns(busy_min),
273                         cycles_to_ns(busy_max),
274                         "Idle (job)",
275                         cycles_to_ns(idle_exec), idle_exec * 100.0 / stats_period,
276                         cycles_to_ns(idle_exec_cnt ? idle_exec / idle_exec_cnt : 0),
277                         cycles_to_ns(idle_exec_min),
278                         cycles_to_ns(idle_exec_max));
279
280         for (i = 0; i < qconf->n_rx_port; i++) {
281                 job = &qconf->port_fwd_jobs[i];
282                 printf("\n\nJob %" PRIu32 ": %-20s "
283                                 "\n%-18s %'14" PRIu64
284                                 "\n%-18s %'14.0f"
285                                 STAT_FMT,
286                                 i, job->name,
287                                 "Exec count:", jobs_exec_cnt[i],
288                                 "Exec period: ", cycles_to_ns(jobs_period[i]),
289                                 "Exec time",
290                                 cycles_to_ns(jobs_exec[i]), jobs_exec[i] * 100.0 / stats_period,
291                                 cycles_to_ns(jobs_exec_cnt[i] ? jobs_exec[i] / jobs_exec_cnt[i]
292                                                 : 0),
293                                 cycles_to_ns(jobs_exec_min[i]),
294                                 cycles_to_ns(jobs_exec_max[i]));
295         }
296
297         if (qconf->n_rx_port > 0) {
298                 job = &qconf->flush_job;
299                 printf("\n\nJob %" PRIu32 ": %-20s "
300                                 "\n%-18s %'14" PRIu64
301                                 "\n%-18s %'14.0f"
302                                 STAT_FMT,
303                                 i, job->name,
304                                 "Exec count:", flush_exec_cnt,
305                                 "Exec period: ", cycles_to_ns(flush_period),
306                                 "Exec time",
307                                 cycles_to_ns(flush_exec), flush_exec * 100.0 / stats_period,
308                                 cycles_to_ns(flush_exec_cnt ? flush_exec / flush_exec_cnt : 0),
309                                 cycles_to_ns(flush_exec_min),
310                                 cycles_to_ns(flush_exec_max));
311         }
312 }
313
314 /* Print out statistics on packets dropped */
315 static void
316 show_stats_cb(__rte_unused void *param)
317 {
318         uint64_t total_packets_dropped, total_packets_tx, total_packets_rx;
319         unsigned portid, lcore_id;
320
321         total_packets_dropped = 0;
322         total_packets_tx = 0;
323         total_packets_rx = 0;
324
325         const char clr[] = { 27, '[', '2', 'J', '\0' };
326         const char topLeft[] = { 27, '[', '1', ';', '1', 'H', '\0' };
327
328         /* Clear screen and move to top left */
329         printf("%s%s"
330                         "\nPort statistics ===================================",
331                         clr, topLeft);
332
333         for (portid = 0; portid < RTE_MAX_ETHPORTS; portid++) {
334                 /* skip disabled ports */
335                 if ((l2fwd_enabled_port_mask & (1 << portid)) == 0)
336                         continue;
337                 printf("\nStatistics for port %u ------------------------------"
338                                 "\nPackets sent: %24"PRIu64
339                                 "\nPackets received: %20"PRIu64
340                                 "\nPackets dropped: %21"PRIu64,
341                                 portid,
342                                 port_statistics[portid].tx,
343                                 port_statistics[portid].rx,
344                                 port_statistics[portid].dropped);
345
346                 total_packets_dropped += port_statistics[portid].dropped;
347                 total_packets_tx += port_statistics[portid].tx;
348                 total_packets_rx += port_statistics[portid].rx;
349         }
350
351         printf("\nAggregate statistics ==============================="
352                         "\nTotal packets sent: %18"PRIu64
353                         "\nTotal packets received: %14"PRIu64
354                         "\nTotal packets dropped: %15"PRIu64
355                         "\n====================================================",
356                         total_packets_tx,
357                         total_packets_rx,
358                         total_packets_dropped);
359
360         RTE_LCORE_FOREACH(lcore_id) {
361                 if (lcore_queue_conf[lcore_id].n_rx_port > 0)
362                         show_lcore_stats(lcore_id);
363         }
364
365         printf("\n====================================================\n");
366         rte_eal_alarm_set(timer_period * US_PER_S, show_stats_cb, NULL);
367 }
368
369 static void
370 l2fwd_simple_forward(struct rte_mbuf *m, unsigned portid)
371 {
372         struct ether_hdr *eth;
373         void *tmp;
374         int sent;
375         unsigned dst_port;
376         struct rte_eth_dev_tx_buffer *buffer;
377
378         dst_port = l2fwd_dst_ports[portid];
379         eth = rte_pktmbuf_mtod(m, struct ether_hdr *);
380
381         /* 02:00:00:00:00:xx */
382         tmp = &eth->d_addr.addr_bytes[0];
383         *((uint64_t *)tmp) = 0x000000000002 + ((uint64_t)dst_port << 40);
384
385         /* src addr */
386         ether_addr_copy(&l2fwd_ports_eth_addr[dst_port], &eth->s_addr);
387
388         buffer = tx_buffer[dst_port];
389         sent = rte_eth_tx_buffer(dst_port, 0, buffer, m);
390         if (sent)
391                 port_statistics[dst_port].tx += sent;
392 }
393
394 static void
395 l2fwd_job_update_cb(struct rte_jobstats *job, int64_t result)
396 {
397         int64_t err = job->target - result;
398         int64_t histeresis = job->target / 8;
399
400         if (err < -histeresis) {
401                 if (job->min_period + UPDATE_STEP_DOWN < job->period)
402                         job->period -= UPDATE_STEP_DOWN;
403         } else if (err > histeresis) {
404                 if (job->period + UPDATE_STEP_UP < job->max_period)
405                         job->period += UPDATE_STEP_UP;
406         }
407 }
408
409 static void
410 l2fwd_fwd_job(__rte_unused struct rte_timer *timer, void *arg)
411 {
412         struct rte_mbuf *pkts_burst[MAX_PKT_BURST];
413         struct rte_mbuf *m;
414
415         const uint16_t port_idx = (uintptr_t) arg;
416         const unsigned lcore_id = rte_lcore_id();
417         struct lcore_queue_conf *qconf = &lcore_queue_conf[lcore_id];
418         struct rte_jobstats *job = &qconf->port_fwd_jobs[port_idx];
419         const uint16_t portid = qconf->rx_port_list[port_idx];
420
421         uint8_t j;
422         uint16_t total_nb_rx;
423
424         rte_jobstats_start(&qconf->jobs_context, job);
425
426         /* Call rx burst 2 times. This allow rte_jobstats logic to see if this
427          * function must be called more frequently. */
428
429         total_nb_rx = rte_eth_rx_burst(portid, 0, pkts_burst,
430                         MAX_PKT_BURST);
431
432         for (j = 0; j < total_nb_rx; j++) {
433                 m = pkts_burst[j];
434                 rte_prefetch0(rte_pktmbuf_mtod(m, void *));
435                 l2fwd_simple_forward(m, portid);
436         }
437
438         if (total_nb_rx == MAX_PKT_BURST) {
439                 const uint16_t nb_rx = rte_eth_rx_burst(portid, 0, pkts_burst,
440                                 MAX_PKT_BURST);
441
442                 total_nb_rx += nb_rx;
443                 for (j = 0; j < nb_rx; j++) {
444                         m = pkts_burst[j];
445                         rte_prefetch0(rte_pktmbuf_mtod(m, void *));
446                         l2fwd_simple_forward(m, portid);
447                 }
448         }
449
450         port_statistics[portid].rx += total_nb_rx;
451
452         /* Adjust period time in which we are running here. */
453         if (rte_jobstats_finish(job, total_nb_rx) != 0) {
454                 rte_timer_reset(&qconf->rx_timers[port_idx], job->period, PERIODICAL,
455                                 lcore_id, l2fwd_fwd_job, arg);
456         }
457 }
458
459 static void
460 l2fwd_flush_job(__rte_unused struct rte_timer *timer, __rte_unused void *arg)
461 {
462         uint64_t now;
463         unsigned lcore_id;
464         struct lcore_queue_conf *qconf;
465         uint16_t portid;
466         unsigned i;
467         uint32_t sent;
468         struct rte_eth_dev_tx_buffer *buffer;
469
470         lcore_id = rte_lcore_id();
471         qconf = &lcore_queue_conf[lcore_id];
472
473         rte_jobstats_start(&qconf->jobs_context, &qconf->flush_job);
474
475         now = rte_get_timer_cycles();
476         lcore_id = rte_lcore_id();
477         qconf = &lcore_queue_conf[lcore_id];
478
479         for (i = 0; i < qconf->n_rx_port; i++) {
480                 portid = l2fwd_dst_ports[qconf->rx_port_list[i]];
481
482                 if (qconf->next_flush_time[portid] <= now)
483                         continue;
484
485                 buffer = tx_buffer[portid];
486                 sent = rte_eth_tx_buffer_flush(portid, 0, buffer);
487                 if (sent)
488                         port_statistics[portid].tx += sent;
489
490                 qconf->next_flush_time[portid] = rte_get_timer_cycles() + drain_tsc;
491         }
492
493         /* Pass target to indicate that this job is happy of time interwal
494          * in which it was called. */
495         rte_jobstats_finish(&qconf->flush_job, qconf->flush_job.target);
496 }
497
498 /* main processing loop */
499 static void
500 l2fwd_main_loop(void)
501 {
502         unsigned lcore_id;
503         unsigned i, portid;
504         struct lcore_queue_conf *qconf;
505         uint8_t stats_read_pending = 0;
506         uint8_t need_manage;
507
508         lcore_id = rte_lcore_id();
509         qconf = &lcore_queue_conf[lcore_id];
510
511         if (qconf->n_rx_port == 0) {
512                 RTE_LOG(INFO, L2FWD, "lcore %u has nothing to do\n", lcore_id);
513                 return;
514         }
515
516         RTE_LOG(INFO, L2FWD, "entering main loop on lcore %u\n", lcore_id);
517
518         for (i = 0; i < qconf->n_rx_port; i++) {
519
520                 portid = qconf->rx_port_list[i];
521                 RTE_LOG(INFO, L2FWD, " -- lcoreid=%u portid=%u\n", lcore_id,
522                         portid);
523         }
524
525         rte_jobstats_init(&qconf->idle_job, "idle", 0, 0, 0, 0);
526
527         for (;;) {
528                 rte_spinlock_lock(&qconf->lock);
529
530                 do {
531                         rte_jobstats_context_start(&qconf->jobs_context);
532
533                         /* Do the Idle job:
534                          * - Read stats_read_pending flag
535                          * - check if some real job need to be executed
536                          */
537                         rte_jobstats_start(&qconf->jobs_context, &qconf->idle_job);
538
539                         uint64_t repeats = 0;
540
541                         do {
542                                 uint8_t i;
543                                 uint64_t now = rte_get_timer_cycles();
544
545                                 repeats++;
546                                 need_manage = qconf->flush_timer.expire < now;
547                                 /* Check if we was esked to give a stats. */
548                                 stats_read_pending =
549                                                 rte_atomic16_read(&qconf->stats_read_pending);
550                                 need_manage |= stats_read_pending;
551
552                                 for (i = 0; i < qconf->n_rx_port && !need_manage; i++)
553                                         need_manage = qconf->rx_timers[i].expire < now;
554
555                         } while (!need_manage);
556
557                         if (likely(repeats != 1))
558                                 rte_jobstats_finish(&qconf->idle_job, qconf->idle_job.target);
559                         else
560                                 rte_jobstats_abort(&qconf->idle_job);
561
562                         rte_timer_manage();
563                         rte_jobstats_context_finish(&qconf->jobs_context);
564                 } while (likely(stats_read_pending == 0));
565
566                 rte_spinlock_unlock(&qconf->lock);
567                 rte_pause();
568         }
569 }
570
571 static int
572 l2fwd_launch_one_lcore(__attribute__((unused)) void *dummy)
573 {
574         l2fwd_main_loop();
575         return 0;
576 }
577
578 /* display usage */
579 static void
580 l2fwd_usage(const char *prgname)
581 {
582         printf("%s [EAL options] -- -p PORTMASK [-q NQ]\n"
583                "  -p PORTMASK: hexadecimal bitmask of ports to configure\n"
584                "  -q NQ: number of queue (=ports) per lcore (default is 1)\n"
585                    "  -T PERIOD: statistics will be refreshed each PERIOD seconds (0 to disable, 10 default, 86400 maximum)\n"
586                    "  -l set system default locale instead of default (\"C\" locale) for thousands separator in stats.",
587                prgname);
588 }
589
590 static int
591 l2fwd_parse_portmask(const char *portmask)
592 {
593         char *end = NULL;
594         unsigned long pm;
595
596         /* parse hexadecimal string */
597         pm = strtoul(portmask, &end, 16);
598         if ((portmask[0] == '\0') || (end == NULL) || (*end != '\0'))
599                 return -1;
600
601         if (pm == 0)
602                 return -1;
603
604         return pm;
605 }
606
607 static unsigned int
608 l2fwd_parse_nqueue(const char *q_arg)
609 {
610         char *end = NULL;
611         unsigned long n;
612
613         /* parse hexadecimal string */
614         n = strtoul(q_arg, &end, 10);
615         if ((q_arg[0] == '\0') || (end == NULL) || (*end != '\0'))
616                 return 0;
617         if (n == 0)
618                 return 0;
619         if (n >= MAX_RX_QUEUE_PER_LCORE)
620                 return 0;
621
622         return n;
623 }
624
625 static int
626 l2fwd_parse_timer_period(const char *q_arg)
627 {
628         char *end = NULL;
629         int n;
630
631         /* parse number string */
632         n = strtol(q_arg, &end, 10);
633         if ((q_arg[0] == '\0') || (end == NULL) || (*end != '\0'))
634                 return -1;
635         if (n >= MAX_TIMER_PERIOD)
636                 return -1;
637
638         return n;
639 }
640
641 /* Parse the argument given in the command line of the application */
642 static int
643 l2fwd_parse_args(int argc, char **argv)
644 {
645         int opt, ret;
646         char **argvopt;
647         int option_index;
648         char *prgname = argv[0];
649         static struct option lgopts[] = {
650                 {NULL, 0, 0, 0}
651         };
652
653         argvopt = argv;
654
655         while ((opt = getopt_long(argc, argvopt, "p:q:T:l",
656                                   lgopts, &option_index)) != EOF) {
657
658                 switch (opt) {
659                 /* portmask */
660                 case 'p':
661                         l2fwd_enabled_port_mask = l2fwd_parse_portmask(optarg);
662                         if (l2fwd_enabled_port_mask == 0) {
663                                 printf("invalid portmask\n");
664                                 l2fwd_usage(prgname);
665                                 return -1;
666                         }
667                         break;
668
669                 /* nqueue */
670                 case 'q':
671                         l2fwd_rx_queue_per_lcore = l2fwd_parse_nqueue(optarg);
672                         if (l2fwd_rx_queue_per_lcore == 0) {
673                                 printf("invalid queue number\n");
674                                 l2fwd_usage(prgname);
675                                 return -1;
676                         }
677                         break;
678
679                 /* timer period */
680                 case 'T':
681                         timer_period = l2fwd_parse_timer_period(optarg);
682                         if (timer_period < 0) {
683                                 printf("invalid timer period\n");
684                                 l2fwd_usage(prgname);
685                                 return -1;
686                         }
687                         break;
688
689                 /* For thousands separator in printf. */
690                 case 'l':
691                         setlocale(LC_ALL, "");
692                         break;
693
694                 /* long options */
695                 case 0:
696                         l2fwd_usage(prgname);
697                         return -1;
698
699                 default:
700                         l2fwd_usage(prgname);
701                         return -1;
702                 }
703         }
704
705         if (optind >= 0)
706                 argv[optind-1] = prgname;
707
708         ret = optind-1;
709         optind = 1; /* reset getopt lib */
710         return ret;
711 }
712
713 /* Check the link status of all ports in up to 9s, and print them finally */
714 static void
715 check_all_ports_link_status(uint16_t port_num, uint32_t port_mask)
716 {
717 #define CHECK_INTERVAL 100 /* 100ms */
718 #define MAX_CHECK_TIME 90 /* 9s (90 * 100ms) in total */
719         uint16_t portid;
720         uint8_t count, all_ports_up, print_flag = 0;
721         struct rte_eth_link link;
722
723         printf("\nChecking link status");
724         fflush(stdout);
725         for (count = 0; count <= MAX_CHECK_TIME; count++) {
726                 all_ports_up = 1;
727                 for (portid = 0; portid < port_num; portid++) {
728                         if ((port_mask & (1 << portid)) == 0)
729                                 continue;
730                         memset(&link, 0, sizeof(link));
731                         rte_eth_link_get_nowait(portid, &link);
732                         /* print link status if flag set */
733                         if (print_flag == 1) {
734                                 if (link.link_status)
735                                         printf(
736                                         "Port%d Link Up. Speed %u Mbps - %s\n",
737                                                 portid, link.link_speed,
738                                 (link.link_duplex == ETH_LINK_FULL_DUPLEX) ?
739                                         ("full-duplex") : ("half-duplex\n"));
740                                 else
741                                         printf("Port %d Link Down\n", portid);
742                                 continue;
743                         }
744                         /* clear all_ports_up flag if any link down */
745                         if (link.link_status == ETH_LINK_DOWN) {
746                                 all_ports_up = 0;
747                                 break;
748                         }
749                 }
750                 /* after finally printing all link status, get out */
751                 if (print_flag == 1)
752                         break;
753
754                 if (all_ports_up == 0) {
755                         printf(".");
756                         fflush(stdout);
757                         rte_delay_ms(CHECK_INTERVAL);
758                 }
759
760                 /* set the print_flag if all ports up or timeout */
761                 if (all_ports_up == 1 || count == (MAX_CHECK_TIME - 1)) {
762                         print_flag = 1;
763                         printf("done\n");
764                 }
765         }
766 }
767
768 int
769 main(int argc, char **argv)
770 {
771         struct lcore_queue_conf *qconf;
772         struct rte_eth_dev_info dev_info;
773         unsigned lcore_id, rx_lcore_id;
774         unsigned nb_ports_in_mask = 0;
775         int ret;
776         char name[RTE_JOBSTATS_NAMESIZE];
777         uint16_t nb_ports;
778         uint16_t nb_ports_available;
779         uint16_t portid, last_port;
780         uint8_t i;
781
782         /* init EAL */
783         ret = rte_eal_init(argc, argv);
784         if (ret < 0)
785                 rte_exit(EXIT_FAILURE, "Invalid EAL arguments\n");
786         argc -= ret;
787         argv += ret;
788
789         /* parse application arguments (after the EAL ones) */
790         ret = l2fwd_parse_args(argc, argv);
791         if (ret < 0)
792                 rte_exit(EXIT_FAILURE, "Invalid L2FWD arguments\n");
793
794         rte_timer_subsystem_init();
795
796         /* fetch default timer frequency. */
797         hz = rte_get_timer_hz();
798
799         /* create the mbuf pool */
800         l2fwd_pktmbuf_pool =
801                 rte_pktmbuf_pool_create("mbuf_pool", NB_MBUF, 32,
802                         0, RTE_MBUF_DEFAULT_BUF_SIZE, rte_socket_id());
803         if (l2fwd_pktmbuf_pool == NULL)
804                 rte_exit(EXIT_FAILURE, "Cannot init mbuf pool\n");
805
806         nb_ports = rte_eth_dev_count();
807         if (nb_ports == 0)
808                 rte_exit(EXIT_FAILURE, "No Ethernet ports - bye\n");
809
810         /* reset l2fwd_dst_ports */
811         for (portid = 0; portid < RTE_MAX_ETHPORTS; portid++)
812                 l2fwd_dst_ports[portid] = 0;
813         last_port = 0;
814
815         /*
816          * Each logical core is assigned a dedicated TX queue on each port.
817          */
818         for (portid = 0; portid < nb_ports; portid++) {
819                 /* skip ports that are not enabled */
820                 if ((l2fwd_enabled_port_mask & (1 << portid)) == 0)
821                         continue;
822
823                 if (nb_ports_in_mask % 2) {
824                         l2fwd_dst_ports[portid] = last_port;
825                         l2fwd_dst_ports[last_port] = portid;
826                 } else
827                         last_port = portid;
828
829                 nb_ports_in_mask++;
830
831                 rte_eth_dev_info_get(portid, &dev_info);
832         }
833         if (nb_ports_in_mask % 2) {
834                 printf("Notice: odd number of ports in portmask.\n");
835                 l2fwd_dst_ports[last_port] = last_port;
836         }
837
838         rx_lcore_id = 0;
839         qconf = NULL;
840
841         /* Initialize the port/queue configuration of each logical core */
842         for (portid = 0; portid < nb_ports; portid++) {
843                 /* skip ports that are not enabled */
844                 if ((l2fwd_enabled_port_mask & (1 << portid)) == 0)
845                         continue;
846
847                 /* get the lcore_id for this port */
848                 while (rte_lcore_is_enabled(rx_lcore_id) == 0 ||
849                        lcore_queue_conf[rx_lcore_id].n_rx_port ==
850                        l2fwd_rx_queue_per_lcore) {
851                         rx_lcore_id++;
852                         if (rx_lcore_id >= RTE_MAX_LCORE)
853                                 rte_exit(EXIT_FAILURE, "Not enough cores\n");
854                 }
855
856                 if (qconf != &lcore_queue_conf[rx_lcore_id])
857                         /* Assigned a new logical core in the loop above. */
858                         qconf = &lcore_queue_conf[rx_lcore_id];
859
860                 qconf->rx_port_list[qconf->n_rx_port] = portid;
861                 qconf->n_rx_port++;
862                 printf("Lcore %u: RX port %u\n", rx_lcore_id, portid);
863         }
864
865         nb_ports_available = nb_ports;
866
867         /* Initialise each port */
868         for (portid = 0; portid < nb_ports; portid++) {
869                 /* skip ports that are not enabled */
870                 if ((l2fwd_enabled_port_mask & (1 << portid)) == 0) {
871                         printf("Skipping disabled port %u\n", portid);
872                         nb_ports_available--;
873                         continue;
874                 }
875                 /* init port */
876                 printf("Initializing port %u... ", portid);
877                 fflush(stdout);
878                 ret = rte_eth_dev_configure(portid, 1, 1, &port_conf);
879                 if (ret < 0)
880                         rte_exit(EXIT_FAILURE, "Cannot configure device: err=%d, port=%u\n",
881                                   ret, portid);
882
883                 ret = rte_eth_dev_adjust_nb_rx_tx_desc(portid, &nb_rxd,
884                                                        &nb_txd);
885                 if (ret < 0)
886                         rte_exit(EXIT_FAILURE,
887                                  "Cannot adjust number of descriptors: err=%d, port=%u\n",
888                                  ret, portid);
889
890                 rte_eth_macaddr_get(portid, &l2fwd_ports_eth_addr[portid]);
891
892                 /* init one RX queue */
893                 fflush(stdout);
894                 ret = rte_eth_rx_queue_setup(portid, 0, nb_rxd,
895                                              rte_eth_dev_socket_id(portid),
896                                              NULL,
897                                              l2fwd_pktmbuf_pool);
898                 if (ret < 0)
899                         rte_exit(EXIT_FAILURE, "rte_eth_rx_queue_setup:err=%d, port=%u\n",
900                                   ret, portid);
901
902                 /* init one TX queue on each port */
903                 fflush(stdout);
904                 ret = rte_eth_tx_queue_setup(portid, 0, nb_txd,
905                                 rte_eth_dev_socket_id(portid),
906                                 NULL);
907                 if (ret < 0)
908                         rte_exit(EXIT_FAILURE,
909                         "rte_eth_tx_queue_setup:err=%d, port=%u\n",
910                                 ret, portid);
911
912                 /* Initialize TX buffers */
913                 tx_buffer[portid] = rte_zmalloc_socket("tx_buffer",
914                                 RTE_ETH_TX_BUFFER_SIZE(MAX_PKT_BURST), 0,
915                                 rte_eth_dev_socket_id(portid));
916                 if (tx_buffer[portid] == NULL)
917                         rte_exit(EXIT_FAILURE, "Cannot allocate buffer for tx on port %u\n",
918                                         portid);
919
920                 rte_eth_tx_buffer_init(tx_buffer[portid], MAX_PKT_BURST);
921
922                 ret = rte_eth_tx_buffer_set_err_callback(tx_buffer[portid],
923                                 rte_eth_tx_buffer_count_callback,
924                                 &port_statistics[portid].dropped);
925                 if (ret < 0)
926                         rte_exit(EXIT_FAILURE,
927                         "Cannot set error callback for tx buffer on port %u\n",
928                                  portid);
929
930                 /* Start device */
931                 ret = rte_eth_dev_start(portid);
932                 if (ret < 0)
933                         rte_exit(EXIT_FAILURE, "rte_eth_dev_start:err=%d, port=%u\n",
934                                   ret, portid);
935
936                 printf("done:\n");
937
938                 rte_eth_promiscuous_enable(portid);
939
940                 printf("Port %u, MAC address: %02X:%02X:%02X:%02X:%02X:%02X\n\n",
941                                 portid,
942                                 l2fwd_ports_eth_addr[portid].addr_bytes[0],
943                                 l2fwd_ports_eth_addr[portid].addr_bytes[1],
944                                 l2fwd_ports_eth_addr[portid].addr_bytes[2],
945                                 l2fwd_ports_eth_addr[portid].addr_bytes[3],
946                                 l2fwd_ports_eth_addr[portid].addr_bytes[4],
947                                 l2fwd_ports_eth_addr[portid].addr_bytes[5]);
948
949                 /* initialize port stats */
950                 memset(&port_statistics, 0, sizeof(port_statistics));
951         }
952
953         if (!nb_ports_available) {
954                 rte_exit(EXIT_FAILURE,
955                         "All available ports are disabled. Please set portmask.\n");
956         }
957
958         check_all_ports_link_status(nb_ports, l2fwd_enabled_port_mask);
959
960         drain_tsc = (hz + US_PER_S - 1) / US_PER_S * BURST_TX_DRAIN_US;
961
962         RTE_LCORE_FOREACH(lcore_id) {
963                 qconf = &lcore_queue_conf[lcore_id];
964
965                 rte_spinlock_init(&qconf->lock);
966
967                 if (rte_jobstats_context_init(&qconf->jobs_context) != 0)
968                         rte_panic("Jobs stats context for core %u init failed\n", lcore_id);
969
970                 if (qconf->n_rx_port == 0) {
971                         RTE_LOG(INFO, L2FWD,
972                                 "lcore %u: no ports so no jobs stats context initialization\n",
973                                 lcore_id);
974                         continue;
975                 }
976                 /* Add flush job.
977                  * Set fixed period by setting min = max = initial period. Set target to
978                  * zero as it is irrelevant for this job. */
979                 rte_jobstats_init(&qconf->flush_job, "flush", drain_tsc, drain_tsc,
980                                 drain_tsc, 0);
981
982                 rte_timer_init(&qconf->flush_timer);
983                 ret = rte_timer_reset(&qconf->flush_timer, drain_tsc, PERIODICAL,
984                                 lcore_id, &l2fwd_flush_job, NULL);
985
986                 if (ret < 0) {
987                         rte_exit(1, "Failed to reset flush job timer for lcore %u: %s",
988                                         lcore_id, rte_strerror(-ret));
989                 }
990
991                 for (i = 0; i < qconf->n_rx_port; i++) {
992                         struct rte_jobstats *job = &qconf->port_fwd_jobs[i];
993
994                         portid = qconf->rx_port_list[i];
995                         printf("Setting forward job for port %u\n", portid);
996
997                         snprintf(name, RTE_DIM(name), "port %u fwd", portid);
998                         /* Setup forward job.
999                          * Set min, max and initial period. Set target to MAX_PKT_BURST as
1000                          * this is desired optimal RX/TX burst size. */
1001                         rte_jobstats_init(job, name, 0, drain_tsc, 0, MAX_PKT_BURST);
1002                         rte_jobstats_set_update_period_function(job, l2fwd_job_update_cb);
1003
1004                         rte_timer_init(&qconf->rx_timers[i]);
1005                         ret = rte_timer_reset(&qconf->rx_timers[i], 0, PERIODICAL, lcore_id,
1006                                         &l2fwd_fwd_job, (void *)(uintptr_t)i);
1007
1008                         if (ret < 0) {
1009                                 rte_exit(1, "Failed to reset lcore %u port %u job timer: %s",
1010                                                 lcore_id, qconf->rx_port_list[i], rte_strerror(-ret));
1011                         }
1012                 }
1013         }
1014
1015         if (timer_period)
1016                 rte_eal_alarm_set(timer_period * MS_PER_S, show_stats_cb, NULL);
1017         else
1018                 RTE_LOG(INFO, L2FWD, "Stats display disabled\n");
1019
1020         /* launch per-lcore init on every lcore */
1021         rte_eal_mp_remote_launch(l2fwd_launch_one_lcore, NULL, CALL_MASTER);
1022         RTE_LCORE_FOREACH_SLAVE(lcore_id) {
1023                 if (rte_eal_wait_lcore(lcore_id) < 0)
1024                         return -1;
1025         }
1026
1027         return 0;
1028 }