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