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