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