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