f6fa3e803e349bd141e8ca3ffa1b8738681d25da
[samplevnf.git] / VNFs / DPPD-PROX / main.c
1 /*
2 // Copyright (c) 2010-2020 Intel Corporation
3 //
4 // Licensed under the Apache License, Version 2.0 (the "License");
5 // you may not use this file except in compliance with the License.
6 // You may obtain a copy of the License at
7 //
8 //     http://www.apache.org/licenses/LICENSE-2.0
9 //
10 // Unless required by applicable law or agreed to in writing, software
11 // distributed under the License is distributed on an "AS IS" BASIS,
12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 // See the License for the specific language governing permissions and
14 // limitations under the License.
15 */
16
17 #include <string.h>
18 #include <locale.h>
19 #include <unistd.h>
20 #include <signal.h>
21 #include <curses.h>
22
23 #include <rte_cycles.h>
24 #include <rte_atomic.h>
25 #include <rte_table_hash.h>
26 #include <rte_memzone.h>
27 #include <rte_errno.h>
28
29 #include "prox_malloc.h"
30 #include "run.h"
31 #include "main.h"
32 #include "log.h"
33 #include "quit.h"
34 #include "clock.h"
35 #include "defines.h"
36 #include "version.h"
37 #include "prox_args.h"
38 #include "prox_assert.h"
39 #include "prox_cfg.h"
40 #include "prox_shared.h"
41 #include "prox_port_cfg.h"
42 #include "toeplitz.h"
43 #include "hash_utils.h"
44 #include "handle_lb_net.h"
45 #include "prox_cksum.h"
46 #include "thread_nop.h"
47 #include "thread_generic.h"
48 #include "thread_pipeline.h"
49 #include "cqm.h"
50 #include "handle_master.h"
51
52 #if RTE_VERSION < RTE_VERSION_NUM(1,8,0,0)
53 #define RTE_CACHE_LINE_SIZE CACHE_LINE_SIZE
54 #endif
55
56 uint8_t lb_nb_txrings = 0xff;
57 struct rte_ring *ctrl_rings[RTE_MAX_LCORE*MAX_TASKS_PER_CORE];
58
59 static void __attribute__((noreturn)) prox_usage(const char *prgname)
60 {
61         plog_info("\nUsage: %s [-f CONFIG_FILE] [-a|-e] [-m|-s|-i] [-w DEF] [-u] [-t]\n"
62                   "\t-f CONFIG_FILE : configuration file to load, ./prox.cfg by default\n"
63                   "\t-l LOG_FILE : log file name, ./prox.log by default\n"
64                   "\t-p : include PID in log file name if default log file is used\n"
65                   "\t-o DISPLAY: Set display to use, can be 'curses' (default), 'cli' or 'none'\n"
66                   "\t-v verbosity : initial logging verbosity\n"
67                   "\t-a : autostart all cores (by default)\n"
68                   "\t-e : don't autostart\n"
69                   "\t-n : Create NULL devices instead of using PCI devices, useful together with -i\n"
70                   "\t-m : list supported task modes and exit\n"
71                   "\t-s : check configuration file syntax and exit\n"
72                   "\t-i : check initialization sequence and exit\n"
73                   "\t-u : Listen on UDS /tmp/prox.sock\n"
74                   "\t-t : Listen on TCP port 8474\n"
75                   "\t-q : Pass argument to Lua interpreter, useful to define variables\n"
76                   "\t-w : define variable using syntax varname=value\n"
77                   "\t     takes precedence over variables defined in CONFIG_FILE\n"
78                   "\t-k : Log statistics to file \"stats_dump\" in current directory\n"
79                   "\t-d : Run as daemon, the parent process will block until PROX is not initialized\n"
80                   "\t-z : Ignore CPU topology, implies -i\n"
81                   "\t-r : Change initial screen refresh rate. If set to a lower than 0.001 seconds,\n"
82                   "\t     screen refreshing will be disabled\n"
83                   , prgname);
84         exit(EXIT_FAILURE);
85 }
86
87 static void check_mixed_normal_pipeline(void)
88 {
89         struct lcore_cfg *lconf = NULL;
90         uint32_t lcore_id = -1;
91
92         while (prox_core_next(&lcore_id, 0) == 0) {
93                 lconf = &lcore_cfg[lcore_id];
94
95                 int all_thread_nop = 1;
96                 int generic = 0;
97                 int pipeline = 0;
98                 int l3 = 0;
99                 for (uint8_t task_id = 0; task_id < lconf->n_tasks_all; ++task_id) {
100                         struct task_args *targ = &lconf->targs[task_id];
101                         l3 = !strcmp("l3", targ->sub_mode_str);
102                         all_thread_nop = all_thread_nop && !l3 &&
103                                 targ->task_init->thread_x == thread_nop;
104
105                         pipeline = pipeline || targ->task_init->thread_x == thread_pipeline;
106                         generic = generic || targ->task_init->thread_x == thread_generic || l3;
107                 }
108                 PROX_PANIC(generic && pipeline, "Can't run both pipeline and normal thread on same core\n");
109
110                 if (all_thread_nop)
111                         lconf->thread_x = thread_nop;
112                 else {
113                         lconf->thread_x = thread_generic;
114                 }
115         }
116 }
117
118 static void check_zero_rx(void)
119 {
120         struct lcore_cfg *lconf = NULL;
121         struct task_args *targ;
122
123         while (core_targ_next(&lconf, &targ, 0) == 0) {
124                 if (targ->nb_rxports != 0) {
125                         PROX_PANIC(task_init_flag_set(targ->task_init, TASK_FEATURE_NO_RX),
126                            "\tCore %u task %u: rx_ports configured while mode %s does not use it\n", lconf->id, targ->id, targ->task_init->mode_str);
127                 }
128         }
129 }
130
131 static void check_nb_mbuf(void)
132 {
133         struct lcore_cfg *lconf = NULL;
134         struct task_args *targ = NULL;
135         uint8_t port_id;
136         int n_txd = 0, n_rxd = 0;
137
138         while (core_targ_next(&lconf, &targ, 0) == 0) {
139                 for (uint8_t i = 0; i < targ->nb_txports; ++i) {
140                         port_id = targ->tx_port_queue[i].port;
141                         n_txd = prox_port_cfg[port_id].n_txd;
142                 }
143                 for (uint8_t i = 0; i < targ->nb_rxports; ++i) {
144                         port_id = targ->rx_port_queue[i].port;
145                         n_rxd = prox_port_cfg[port_id].n_rxd;
146                 }
147                 if (targ->nb_mbuf <= n_rxd + n_txd + targ->nb_cache_mbuf + MAX_PKT_BURST) {
148                         plog_warn("Core %d, task %d might not have enough mbufs (%d) to support %d txd, %d rxd and %d cache_mbuf\n",
149                                 lconf->id, targ->id, targ->nb_mbuf, n_txd, n_rxd, targ->nb_cache_mbuf);
150                 }
151         }
152 }
153
154 static void check_missing_rx(void)
155 {
156         struct lcore_cfg *lconf = NULL, *rx_lconf = NULL, *tx_lconf = NULL;
157         struct task_args *targ, *rx_targ = NULL, *tx_targ = NULL;
158         uint8_t port_id, rx_port_id, ok, l3, ndp;
159
160         while (core_targ_next(&lconf, &targ, 0) == 0) {
161                 PROX_PANIC((targ->flags & TASK_ARG_RX_RING) && targ->rx_rings[0] == 0 && !targ->tx_opt_ring_task,
162                            "Configuration Error - Core %u task %u Receiving from ring, but nobody xmitting to this ring\n", lconf->id, targ->id);
163                 if (targ->nb_rxports == 0 && targ->nb_rxrings == 0) {
164                         PROX_PANIC(!task_init_flag_set(targ->task_init, TASK_FEATURE_NO_RX),
165                                    "\tCore %u task %u: no rx_ports and no rx_rings configured while required by mode %s\n", lconf->id, targ->id, targ->task_init->mode_str);
166                 }
167         }
168
169         lconf = NULL;
170         while (core_targ_next(&lconf, &targ, 0) == 0) {
171                 l3 = ndp = 0;
172                 if (strcmp(targ->sub_mode_str, "l3") == 0)
173                         l3 = 1;
174                 else if (strcmp(targ->sub_mode_str, "ndp") == 0)
175                         ndp = 1;
176                 else
177                         continue;
178
179                 PROX_PANIC((targ->nb_rxports == 0) && (targ->nb_txports == 0), "L3/NDP task must have a RX or a TX port\n");
180                 // If the L3/NDP sub_mode receives from a port, check that there is at least one core/task
181                 // transmitting to this port in L3/NDP sub_mode
182                 for (uint8_t i = 0; i < targ->nb_rxports; ++i) {
183                         rx_port_id = targ->rx_port_queue[i].port;
184                         ok = 0;
185                         tx_lconf = NULL;
186                         while (core_targ_next(&tx_lconf, &tx_targ, 0) == 0) {
187                                 if ((port_id = tx_targ->tx_port_queue[0].port) == OUT_DISCARD)
188                                         continue;
189                                 if ((rx_port_id == port_id) &&
190                                         ( ((tx_targ->flags & TASK_ARG_L3) && l3) ||
191                                           ((tx_targ->flags & TASK_ARG_NDP) && ndp) ) ) {
192                                         ok = 1;
193                                         break;
194                                 }
195                         }
196                         PROX_PANIC(ok == 0, "RX %s sub mode for port %d on core %d task %d, but no core/task transmitting on that port\n", l3 ? "l3":"ndp", rx_port_id, lconf->id, targ->id);
197                 }
198
199                 // If the L3/NDP sub_mode transmits to a port, check that there is at least one core/task
200                 // receiving from that port in L3/NDP sub_mode.
201                 if ((port_id = targ->tx_port_queue[0].port) == OUT_DISCARD)
202                         continue;
203                 rx_lconf = NULL;
204                 ok = 0;
205                 plog_info("\tCore %d task %d transmitting to port %d in %s submode\n", lconf->id, targ->id, port_id, l3 ? "l3":"ndp");
206                 while (core_targ_next(&rx_lconf, &rx_targ, 0) == 0) {
207                         for (uint8_t i = 0; i < rx_targ->nb_rxports; ++i) {
208                                 rx_port_id = rx_targ->rx_port_queue[i].port;
209                                 if ((rx_port_id == port_id) &&
210                                         ( ((rx_targ->flags & TASK_ARG_L3) && l3) ||
211                                         ((rx_targ->flags & TASK_ARG_NDP) && ndp) ) ){
212                                         ok = 1;
213                                         break;
214                                 }
215                         }
216                         if (ok == 1) {
217                                 plog_info("\tCore %d task %d has found core %d task %d receiving from port %d in %s submode\n", lconf->id, targ->id, rx_lconf->id, rx_targ->id, port_id,
218                                         ((rx_targ->flags & TASK_ARG_L3) && l3) ? "l3":"ndp");
219                                 break;
220                         }
221                 }
222                 PROX_PANIC(ok == 0, "%s sub mode for port %d on core %d task %d, but no core/task receiving on that port\n", l3 ? "l3":"ndp", port_id, lconf->id, targ->id);
223         }
224 }
225
226 static void check_cfg_consistent(void)
227 {
228         check_nb_mbuf();
229         check_missing_rx();
230         check_zero_rx();
231         check_mixed_normal_pipeline();
232 }
233
234 static void plog_all_rings(void)
235 {
236         struct lcore_cfg *lconf = NULL;
237         struct task_args *targ;
238
239         while (core_targ_next(&lconf, &targ, 0) == 0) {
240                 for (uint8_t ring_idx = 0; ring_idx < targ->nb_rxrings; ++ring_idx) {
241                         plog_info("\tCore %u, task %u, rx_ring[%u] %p\n", lconf->id, targ->id, ring_idx, targ->rx_rings[ring_idx]);
242                 }
243         }
244 }
245
246 static int chain_flag_state(struct task_args *targ, uint64_t flag, int is_set)
247 {
248         if (task_init_flag_set(targ->task_init, flag) == is_set)
249                 return 1;
250
251         int ret = 0;
252
253         for (uint32_t i = 0; i < targ->n_prev_tasks; ++i) {
254                 ret = chain_flag_state(targ->prev_tasks[i], flag, is_set);
255                 if (ret)
256                         return 1;
257         }
258         return 0;
259 }
260
261 static int chain_flag_always_set(struct task_args *targ, uint64_t flag)
262 {
263         return (!chain_flag_state(targ, flag, 0));
264 }
265
266 static int chain_flag_never_set(struct task_args *targ, uint64_t flag)
267 {
268         return (!chain_flag_state(targ, flag, 1));
269 }
270
271 static int chain_flag_sometimes_set(struct task_args *targ, uint64_t flag)
272 {
273         return (chain_flag_state(targ, flag, 1));
274 }
275
276 static void configure_if_tx_queues(struct task_args *targ, uint8_t socket)
277 {
278         uint8_t if_port;
279
280         for (uint8_t i = 0; i < targ->nb_txports; ++i) {
281                 if_port = targ->tx_port_queue[i].port;
282
283                 PROX_PANIC(if_port == OUT_DISCARD, "port misconfigured, exiting\n");
284
285                 PROX_PANIC(!prox_port_cfg[if_port].active, "\tPort %u not used, skipping...\n", if_port);
286
287                 int dsocket = prox_port_cfg[if_port].socket;
288                 if (dsocket != -1 && dsocket != socket) {
289                         plog_warn("TX core on socket %d while device on socket %d\n", socket, dsocket);
290                 }
291
292                 if (prox_port_cfg[if_port].tx_ring[0] == '\0') {  // Rings-backed port can use single queue
293                         targ->tx_port_queue[i].queue = prox_port_cfg[if_port].n_txq;
294                         prox_port_cfg[if_port].n_txq++;
295                 } else {
296                         prox_port_cfg[if_port].n_txq = 1;
297                         targ->tx_port_queue[i].queue = 0;
298                 }
299                 /* By default OFFLOAD is enabled, but if the whole
300                    chain has NOOFFLOADS set all the way until the
301                    first task that receives from a port, it will be
302                    disabled for the destination port. */
303 #if RTE_VERSION < RTE_VERSION_NUM(18,8,0,1)
304                 if (chain_flag_always_set(targ, TASK_FEATURE_TXQ_FLAGS_NOOFFLOADS)) {
305                         prox_port_cfg[if_port].tx_conf.txq_flags |= ETH_TXQ_FLAGS_NOOFFLOADS;
306                 }
307 #else
308                 if (chain_flag_always_set(targ, TASK_FEATURE_TXQ_FLAGS_NOOFFLOADS)) {
309                         prox_port_cfg[if_port].requested_tx_offload &= ~(DEV_TX_OFFLOAD_IPV4_CKSUM | DEV_TX_OFFLOAD_UDP_CKSUM);
310                 }
311 #endif
312         }
313 }
314
315 static void configure_if_rx_queues(struct task_args *targ, uint8_t socket)
316 {
317         struct prox_port_cfg *port;
318         for (int i = 0; i < targ->nb_rxports; i++) {
319                 uint8_t if_port = targ->rx_port_queue[i].port;
320
321                 if (if_port == OUT_DISCARD) {
322                         return;
323                 }
324
325                 port = &prox_port_cfg[if_port];
326                 PROX_PANIC(!port->active, "Port %u not used, aborting...\n", if_port);
327
328                 if(port->rx_ring[0] != '\0') {
329                         port->n_rxq = 0;
330                 }
331
332                 // If the mbuf size (of the rx task) is not big enough, we might receive multiple segments
333                 // This is usually the case when setting a big mtu size i.e. enabling jumbo frames.
334                 // If the packets get transmitted, then multi segments will have to be enabled on the TX port
335                 uint16_t max_frame_size = port->mtu + PROX_RTE_ETHER_HDR_LEN + PROX_RTE_ETHER_CRC_LEN + 2 * PROX_VLAN_TAG_SIZE;
336                 if (max_frame_size + sizeof(struct rte_mbuf) + RTE_PKTMBUF_HEADROOM > targ->mbuf_size) {
337                         targ->task_init->flag_features |= TASK_FEATURE_TXQ_FLAGS_MULTSEGS;
338                 }
339                 targ->rx_port_queue[i].queue = port->n_rxq;
340                 port->pool[targ->rx_port_queue[i].queue] = targ->pool;
341                 port->pool_size[targ->rx_port_queue[i].queue] = targ->nb_mbuf - 1;
342                 port->n_rxq++;
343
344                 int dsocket = port->socket;
345                 if (dsocket != -1 && dsocket != socket) {
346                         plog_warn("RX core on socket %d while device on socket %d\n", socket, dsocket);
347                 }
348         }
349 }
350
351 static void configure_if_queues(void)
352 {
353         struct lcore_cfg *lconf = NULL;
354         struct task_args *targ;
355         uint8_t socket;
356
357         while (core_targ_next(&lconf, &targ, 0) == 0) {
358                 socket = rte_lcore_to_socket_id(lconf->id);
359
360                 configure_if_rx_queues(targ, socket);
361                 configure_if_tx_queues(targ, socket);
362         }
363 }
364
365 static void configure_tx_queue_flags(void)
366 {
367         struct lcore_cfg *lconf = NULL;
368         struct task_args *targ;
369         uint8_t socket;
370         uint8_t if_port;
371
372         while (core_targ_next(&lconf, &targ, 0) == 0) {
373                 socket = rte_lcore_to_socket_id(lconf->id);
374                 for (uint8_t i = 0; i < targ->nb_txports; ++i) {
375                         if_port = targ->tx_port_queue[i].port;
376 #if RTE_VERSION < RTE_VERSION_NUM(18,8,0,1)
377                         /* Set the ETH_TXQ_FLAGS_NOREFCOUNT flag if none of
378                         the tasks up to the task transmitting to the port
379                         use refcnt. */
380                         if (chain_flag_never_set(targ, TASK_FEATURE_TXQ_FLAGS_REFCOUNT)) {
381                                 prox_port_cfg[if_port].tx_conf.txq_flags |= ETH_TXQ_FLAGS_NOREFCOUNT;
382                         }
383 #else
384                         /* Set the DEV_TX_OFFLOAD_MBUF_FAST_FREE flag if none of
385                         the tasks up to the task transmitting to the port
386                         use refcnt and per-queue all mbufs comes from the same mempool. */
387                         if (chain_flag_never_set(targ, TASK_FEATURE_TXQ_FLAGS_REFCOUNT)) {
388                                 if (chain_flag_never_set(targ, TASK_FEATURE_TXQ_FLAGS_MULTIPLE_MEMPOOL))
389                                         prox_port_cfg[if_port].requested_tx_offload |= DEV_TX_OFFLOAD_MBUF_FAST_FREE;
390                         }
391 #endif
392                 }
393         }
394 }
395
396 static void configure_multi_segments(void)
397 {
398         struct lcore_cfg *lconf = NULL;
399         struct task_args *targ;
400         uint8_t if_port;
401
402         while (core_targ_next(&lconf, &targ, 0) == 0) {
403                 for (uint8_t i = 0; i < targ->nb_txports; ++i) {
404                         if_port = targ->tx_port_queue[i].port;
405                         // Multi segment is disabled for most tasks. It is only enabled for tasks requiring big packets.
406 #if RTE_VERSION < RTE_VERSION_NUM(18,8,0,1)
407                         // We can only enable "no multi segment" if no such task exists in the chain of tasks.
408                         if (chain_flag_never_set(targ, TASK_FEATURE_TXQ_FLAGS_MULTSEGS)) {
409                                 prox_port_cfg[if_port].tx_conf.txq_flags |= ETH_TXQ_FLAGS_NOMULTSEGS;
410                         }
411 #else
412                         // We enable "multi segment" if at least one task requires it in the chain of tasks.
413                         if (chain_flag_sometimes_set(targ, TASK_FEATURE_TXQ_FLAGS_MULTSEGS)) {
414                                 prox_port_cfg[if_port].requested_tx_offload |= DEV_TX_OFFLOAD_MULTI_SEGS;
415                         }
416 #endif
417                 }
418         }
419 }
420
421 static const char *gen_ring_name(void)
422 {
423         static char retval[] = "XX";
424         static const char* ring_names =
425                 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
426                 "abcdefghijklmnopqrstuvwxyz"
427                 "[\\]^_`!\"#$%&'()*+,-./:;<="
428                 ">?@{|}0123456789";
429         static int idx2 = 0;
430
431         int idx = idx2;
432
433         retval[0] = ring_names[idx % strlen(ring_names)];
434         idx /= strlen(ring_names);
435         retval[1] = idx ? ring_names[(idx - 1) % strlen(ring_names)] : 0;
436
437         idx2++;
438
439         return retval;
440 }
441
442 struct ring_init_stats {
443         uint32_t n_pkt_rings;
444         uint32_t n_ctrl_rings;
445         uint32_t n_opt_rings;
446 };
447
448 static uint32_t ring_init_stats_total(const struct ring_init_stats *ris)
449 {
450         return ris->n_pkt_rings + ris->n_ctrl_rings + ris->n_opt_rings;
451 }
452
453 static uint32_t count_incoming_tasks(uint32_t lcore_worker, uint32_t dest_task)
454 {
455         struct lcore_cfg *lconf = NULL;
456         struct task_args *targ;
457         uint32_t ret = 0;
458         struct core_task ct;
459
460         while (core_targ_next(&lconf, &targ, 0) == 0) {
461                 for (uint8_t idxx = 0; idxx < MAX_PROTOCOLS; ++idxx) {
462                         for (uint8_t ridx = 0; ridx < targ->core_task_set[idxx].n_elems; ++ridx) {
463                                 ct = targ->core_task_set[idxx].core_task[ridx];
464
465                                 if (dest_task == ct.task && lcore_worker == ct.core)
466                                         ret++;
467                         }
468                 }
469         }
470         return ret;
471 }
472
473 static struct rte_ring *get_existing_ring(uint32_t lcore_id, uint32_t task_id)
474 {
475         if (!prox_core_active(lcore_id, 0))
476                 return NULL;
477
478         struct lcore_cfg *lconf = &lcore_cfg[lcore_id];
479
480         if (task_id >= lconf->n_tasks_all)
481                 return NULL;
482
483         if (lconf->targs[task_id].nb_rxrings == 0)
484                 return NULL;
485
486         return lconf->targs[task_id].rx_rings[0];
487 }
488
489 static struct rte_ring *init_ring_between_tasks(struct lcore_cfg *lconf, struct task_args *starg,
490                                     const struct core_task ct, uint8_t ring_idx, int idx,
491                                     struct ring_init_stats *ris)
492 {
493         uint8_t socket;
494         struct rte_ring *ring = NULL;
495         struct lcore_cfg *lworker;
496         struct task_args *dtarg;
497
498         PROX_ASSERT(prox_core_active(ct.core, 0));
499         lworker = &lcore_cfg[ct.core];
500
501         /* socket used is the one that the sending core resides on */
502         socket = rte_lcore_to_socket_id(lconf->id);
503
504         plog_info("\t\tCreating ring on socket %u with size %u\n"
505                   "\t\t\tsource core, task and socket = %u, %u, %u\n"
506                   "\t\t\tdestination core, task and socket = %u, %u, %u\n"
507                   "\t\t\tdestination worker id = %u\n",
508                   socket, starg->ring_size,
509                   lconf->id, starg->id, socket,
510                   ct.core, ct.task, rte_lcore_to_socket_id(ct.core),
511                   ring_idx);
512
513         if (ct.type) {
514                 struct rte_ring **dring = NULL;
515
516                 if (ct.type == CTRL_TYPE_MSG)
517                         dring = &lworker->ctrl_rings_m[ct.task];
518                 else if (ct.type == CTRL_TYPE_PKT) {
519                         dring = &lworker->ctrl_rings_p[ct.task];
520                         starg->flags |= TASK_ARG_CTRL_RINGS_P;
521                 }
522
523                 if (*dring == NULL)
524                         ring = rte_ring_create(gen_ring_name(), starg->ring_size, socket, RING_F_SC_DEQ);
525                 else
526                         ring = *dring;
527                 PROX_PANIC(ring == NULL, "Cannot create ring to connect I/O core %u with worker core %u\n", lconf->id, ct.core);
528
529                 starg->tx_rings[starg->tot_n_txrings_inited] = ring;
530                 starg->tot_n_txrings_inited++;
531                 *dring = ring;
532                 if (lconf->id == prox_cfg.master) {
533                         ctrl_rings[ct.core*MAX_TASKS_PER_CORE + ct.task] = ring;
534                 } else if (ct.core == prox_cfg.master) {
535                         starg->ctrl_plane_ring = ring;
536                 }
537
538                 plog_info("\t\t\tCore %u task %u to -> core %u task %u ctrl_ring %s %p %s\n",
539                           lconf->id, starg->id, ct.core, ct.task, ct.type == CTRL_TYPE_PKT?
540                           "pkt" : "msg", ring, ring->name);
541                 ris->n_ctrl_rings++;
542                 return ring;
543         }
544
545         dtarg = &lworker->targs[ct.task];
546         lworker->targs[ct.task].worker_thread_id = ring_idx;
547         PROX_ASSERT(dtarg->flags & TASK_ARG_RX_RING);
548         PROX_ASSERT(ct.task < lworker->n_tasks_all);
549
550         /* If all the following conditions are met, the ring can be
551            optimized away. */
552         if (!task_is_master(starg) && !task_is_master(dtarg) && starg->lconf->id == dtarg->lconf->id &&
553             starg->nb_txrings == 1 && idx == 0 && dtarg->task &&
554             dtarg->tot_rxrings == 1 && starg->task == dtarg->task - 1) {
555                 plog_info("\t\tOptimizing away ring on core %u from task %u to task %u\n",
556                           dtarg->lconf->id, starg->task, dtarg->task);
557                 /* No need to set up ws_mbuf. */
558                 starg->tx_opt_ring = 1;
559                 /* During init of destination task, the buffer in the
560                    source task will be initialized. */
561                 dtarg->tx_opt_ring_task = starg;
562                 ris->n_opt_rings++;
563                 ++dtarg->nb_rxrings;
564                 return NULL;
565         }
566
567         int ring_created = 1;
568         /* Only create multi-producer rings if configured to do so AND
569            there is only one task sending to the task */
570         if ((prox_cfg.flags & DSF_MP_RINGS && count_incoming_tasks(ct.core, ct.task) > 1)
571                 || (prox_cfg.flags & DSF_ENABLE_BYPASS)) {
572                 ring = get_existing_ring(ct.core, ct.task);
573
574                 if (ring) {
575                         plog_info("\t\tCore %u task %u creatign MP ring %p to core %u task %u\n",
576                                   lconf->id, starg->id, ring, ct.core, ct.task);
577                         ring_created = 0;
578                 }
579                 else {
580                         ring = rte_ring_create(gen_ring_name(), starg->ring_size, socket, RING_F_SC_DEQ);
581                         plog_info("\t\tCore %u task %u using MP ring %p from core %u task %u\n",
582                                   lconf->id, starg->id, ring, ct.core, ct.task);
583                 }
584         }
585         else
586                 ring = rte_ring_create(gen_ring_name(), starg->ring_size, socket, RING_F_SP_ENQ | RING_F_SC_DEQ);
587
588         PROX_PANIC(ring == NULL, "Cannot create ring to connect I/O core %u with worker core %u\n", lconf->id, ct.core);
589
590         starg->tx_rings[starg->tot_n_txrings_inited] = ring;
591         starg->tot_n_txrings_inited++;
592
593         if (ring_created) {
594                 PROX_ASSERT(dtarg->nb_rxrings < MAX_RINGS_PER_TASK);
595                 dtarg->rx_rings[dtarg->nb_rxrings] = ring;
596                 ++dtarg->nb_rxrings;
597                 if (dtarg->nb_rxrings > 1)
598                         dtarg->task_init->flag_features |= TASK_FEATURE_TXQ_FLAGS_MULTIPLE_MEMPOOL;
599         }
600         dtarg->nb_slave_threads = starg->core_task_set[idx].n_elems;
601         dtarg->lb_friend_core = lconf->id;
602         dtarg->lb_friend_task = starg->id;
603         plog_info("\t\tWorker thread %d has core %d, task %d as a lb friend\n", ct.core, lconf->id, starg->id);
604         plog_info("\t\tCore %u task %u tx_ring[%u] -> core %u task %u rx_ring[%u] %p %s %u WT\n",
605                   lconf->id, starg->id, ring_idx, ct.core, ct.task, dtarg->nb_rxrings, ring, ring->name,
606                   dtarg->nb_slave_threads);
607         ++ris->n_pkt_rings;
608         return ring;
609 }
610
611 static void init_rings(void)
612 {
613         struct lcore_cfg *lconf = NULL;
614         struct task_args *starg;
615         struct ring_init_stats ris = {0};
616
617         while (core_targ_next(&lconf, &starg, 1) == 0) {
618                 plog_info("\t*** Initializing rings on core %u, task %u ***\n", lconf->id, starg->id);
619                 for (uint8_t idx = 0; idx < MAX_PROTOCOLS; ++idx) {
620                         for (uint8_t ring_idx = 0; ring_idx < starg->core_task_set[idx].n_elems; ++ring_idx) {
621                                 PROX_ASSERT(ring_idx < MAX_WT_PER_LB);
622                                 PROX_ASSERT(starg->tot_n_txrings_inited < MAX_RINGS_PER_TASK);
623
624                                 struct core_task ct = starg->core_task_set[idx].core_task[ring_idx];
625                                 init_ring_between_tasks(lconf, starg, ct, ring_idx, idx, &ris);
626                         }
627                 }
628         }
629
630         plog_info("\tInitialized %d rings:\n"
631                   "\t\tNumber of packet rings: %u\n"
632                   "\t\tNumber of control rings: %u\n"
633                   "\t\tNumber of optimized rings: %u\n",
634                   ring_init_stats_total(&ris),
635                   ris.n_pkt_rings,
636                   ris.n_ctrl_rings,
637                   ris.n_opt_rings);
638
639         lconf = NULL;
640         struct prox_port_cfg *port;
641         while (core_targ_next(&lconf, &starg, 1) == 0) {
642                 if ((starg->task_init) && (starg->flags & (TASK_ARG_L3|TASK_ARG_NDP))) {
643                         struct core_task ct;
644                         ct.core = prox_cfg.master;
645                         ct.task = 0;
646                         ct.type = CTRL_TYPE_PKT;
647                         struct rte_ring *rx_ring = init_ring_between_tasks(lconf, starg, ct, 0, 0, &ris);
648
649                         ct.core = lconf->id;
650                         ct.task = starg->id;;
651                         struct rte_ring *tx_ring = init_ring_between_tasks(&lcore_cfg[prox_cfg.master], lcore_cfg[prox_cfg.master].targs, ct, 0, 0, &ris);
652                 }
653         }
654 }
655
656 static void shuffle_mempool(struct rte_mempool* mempool, uint32_t nb_mbuf)
657 {
658         struct rte_mbuf** pkts = prox_zmalloc(nb_mbuf * sizeof(*pkts), rte_socket_id());
659         uint64_t got = 0;
660
661         while ((got < nb_mbuf) && (rte_mempool_get_bulk(mempool, (void**)(pkts + got), 1) == 0))
662                 ++got;
663
664         nb_mbuf = got;
665         while (got) {
666                 int idx;
667                 do {
668                         idx = rand() % nb_mbuf;
669                 } while (pkts[idx] == 0);
670
671                 rte_mempool_put_bulk(mempool, (void**)&pkts[idx], 1);
672                 pkts[idx] = 0;
673                 --got;
674         };
675         prox_free(pkts);
676 }
677
678 static void set_mbuf_size(struct task_args *targ)
679 {
680         /* mbuf size can be set
681          *  - from config file (highest priority, overwriting any other config) - should only be used as workaround
682          *  - defaulted to MBUF_SIZE.
683          * Except if set explicitely, ensure that size is big enough for vmxnet3 driver
684          */
685         if (targ->mbuf_size)
686                 return;
687
688         targ->mbuf_size = MBUF_SIZE;
689         struct prox_port_cfg *port;
690         uint16_t max_frame_size = 0, min_buffer_size = 0;
691         int i40e = 0;
692         for (int i = 0; i < targ->nb_rxports; i++) {
693                 uint8_t if_port = targ->rx_port_queue[i].port;
694
695                 if (if_port == OUT_DISCARD) {
696                         continue;
697                 }
698                 port = &prox_port_cfg[if_port];
699                 if (max_frame_size < port->mtu + PROX_RTE_ETHER_HDR_LEN + PROX_RTE_ETHER_CRC_LEN + 2 * PROX_VLAN_TAG_SIZE)
700                         max_frame_size = port->mtu + PROX_RTE_ETHER_HDR_LEN + PROX_RTE_ETHER_CRC_LEN + 2 * PROX_VLAN_TAG_SIZE;
701                 if (min_buffer_size < port->min_rx_bufsize)
702                         min_buffer_size = port->min_rx_bufsize;
703
704                 // Check whether we receive from i40e. This driver have extra mbuf size requirements
705                 if (strcmp(port->short_name, "i40e") == 0)
706                         i40e = 1;
707         }
708         if (i40e) {
709                 // i40e supports a maximum of 5 descriptors chained
710                 uint16_t required_mbuf_size = RTE_ALIGN(max_frame_size / 5, 128) + sizeof(struct rte_mbuf) + RTE_PKTMBUF_HEADROOM;
711                 if (required_mbuf_size > targ->mbuf_size) {
712                         targ->mbuf_size = required_mbuf_size;
713                         plog_info("\t\tSetting mbuf_size to %u to support frame_size %u\n", targ->mbuf_size, max_frame_size);
714                 }
715         }
716         if (min_buffer_size > targ->mbuf_size) {
717                 plog_warn("Mbuf size might be too small. This might result in packet segmentation and memory leak\n");
718         }
719
720 }
721
722 static void setup_mempools_unique_per_socket(void)
723 {
724         uint32_t flags = 0;
725         char name[64];
726         struct lcore_cfg *lconf = NULL;
727         struct task_args *targ;
728
729         struct rte_mempool     *pool[MAX_SOCKETS];
730         uint32_t mbuf_count[MAX_SOCKETS] = {0};
731         uint32_t nb_cache_mbuf[MAX_SOCKETS] = {0};
732         uint32_t mbuf_size[MAX_SOCKETS] = {0};
733
734         while (core_targ_next_early(&lconf, &targ, 0) == 0) {
735                 PROX_PANIC(targ->task_init == NULL, "task_init = NULL, is mode specified for core %d, task %d ?\n", lconf->id, targ->id);
736                 uint8_t socket = rte_lcore_to_socket_id(lconf->id);
737                 PROX_ASSERT(socket < MAX_SOCKETS);
738
739                 set_mbuf_size(targ);
740                 if (targ->rx_port_queue[0].port != OUT_DISCARD) {
741                         struct prox_port_cfg* port_cfg = &prox_port_cfg[targ->rx_port_queue[0].port];
742                         PROX_ASSERT(targ->nb_mbuf != 0);
743                         mbuf_count[socket] += targ->nb_mbuf;
744                         if (nb_cache_mbuf[socket] == 0)
745                                 nb_cache_mbuf[socket] = targ->nb_cache_mbuf;
746                         else {
747                                 PROX_PANIC(nb_cache_mbuf[socket] != targ->nb_cache_mbuf,
748                                            "all mbuf_cache must have the same size if using a unique mempool per socket\n");
749                         }
750                         if (mbuf_size[socket] == 0)
751                                 mbuf_size[socket] = targ->mbuf_size;
752                         else {
753                                 PROX_PANIC(mbuf_size[socket] != targ->mbuf_size,
754                                            "all mbuf_size must have the same size if using a unique mempool per socket\n");
755                         }
756                 }
757         }
758         for (int i = 0 ; i < MAX_SOCKETS; i++) {
759                 if (mbuf_count[i] != 0) {
760                         sprintf(name, "socket_%u_pool", i);
761                         if ((pool[i] = rte_mempool_lookup(name)) == NULL) {
762                                 pool[i] = rte_mempool_create(name,
763                                         mbuf_count[i] - 1, mbuf_size[i],
764                                         nb_cache_mbuf[i],
765                                         sizeof(struct rte_pktmbuf_pool_private),
766                                         rte_pktmbuf_pool_init, NULL,
767                                         prox_pktmbuf_init, NULL,
768                                         i, flags);
769                                 PROX_PANIC(pool[i] == NULL, "\t\tError: cannot create mempool for socket %u\n", i);
770                                 plog_info("\tMempool %p size = %u * %u cache %u, socket %d\n", pool[i],
771                                         mbuf_count[i], mbuf_size[i], nb_cache_mbuf[i], i);
772
773                                 if (prox_cfg.flags & DSF_SHUFFLE) {
774                                         shuffle_mempool(pool[i], mbuf_count[i]);
775                                 }
776                         }
777                 }
778         }
779
780         lconf = NULL;
781         while (core_targ_next_early(&lconf, &targ, 0) == 0) {
782                 uint8_t socket = rte_lcore_to_socket_id(lconf->id);
783
784                 if (targ->rx_port_queue[0].port != OUT_DISCARD) {
785                         /* use this pool for the interface that the core is receiving from */
786                         /* If one core receives from multiple ports, all the ports use the same mempool */
787                         targ->pool = pool[socket];
788                         /* Set the number of mbuf to the number of the unique mempool, so that the used and free work */
789                         targ->nb_mbuf = mbuf_count[socket];
790                         plog_info("\tMempool %p size = %u * %u cache %u, socket %d\n", targ->pool,
791                                   targ->nb_mbuf, mbuf_size[socket], targ->nb_cache_mbuf, socket);
792                 }
793         }
794 }
795
796 static void setup_mempool_for_rx_task(struct lcore_cfg *lconf, struct task_args *targ)
797 {
798         const uint8_t socket = rte_lcore_to_socket_id(lconf->id);
799         struct prox_port_cfg *port_cfg = &prox_port_cfg[targ->rx_port_queue[0].port];
800         const struct rte_memzone *mz;
801         struct rte_mempool *mp = NULL;
802         uint32_t flags = 0;
803         char memzone_name[64];
804         char name[64];
805
806         set_mbuf_size(targ);
807
808         /* allocate memory pool for packets */
809         PROX_ASSERT(targ->nb_mbuf != 0);
810
811         if (targ->pool_name[0] == '\0') {
812                 sprintf(name, "core_%u_task_%u_pool", lconf->id, targ->id);
813         }
814
815         snprintf(memzone_name, sizeof(memzone_name)-1, "MP_%s", targ->pool_name);
816         mz = rte_memzone_lookup(memzone_name);
817
818         if (mz != NULL) {
819                 mp = (struct rte_mempool*)mz->addr;
820
821                 targ->nb_mbuf = mp->size;
822                 targ->pool = mp;
823         }
824
825 #ifdef RTE_LIBRTE_IVSHMEM_FALSE
826         if (mz != NULL && mp != NULL && mp->phys_addr != mz->ioremap_addr) {
827                 /* Init mbufs with ioremap_addr for dma */
828                 mp->phys_addr = mz->ioremap_addr;
829                 mp->elt_pa[0] = mp->phys_addr + (mp->elt_va_start - (uintptr_t)mp);
830
831                 struct prox_pktmbuf_reinit_args init_args;
832                 init_args.mp = mp;
833                 init_args.lconf = lconf;
834
835                 uint32_t elt_sz = mp->elt_size + mp->header_size + mp->trailer_size;
836                 rte_mempool_obj_iter((void*)mp->elt_va_start, mp->size, elt_sz, 1,
837                                      mp->elt_pa, mp->pg_num, mp->pg_shift, prox_pktmbuf_reinit, &init_args);
838         }
839 #endif
840
841         /* Use this pool for the interface that the core is
842            receiving from if one core receives from multiple
843            ports, all the ports use the same mempool */
844         if (targ->pool == NULL) {
845                 plog_info("\tCreating mempool with name '%s' on socket %d\n", name, socket);
846                 targ->pool = rte_mempool_create(name,
847                                                 targ->nb_mbuf - 1, targ->mbuf_size,
848                                                 targ->nb_cache_mbuf,
849                                                 sizeof(struct rte_pktmbuf_pool_private),
850                                                 rte_pktmbuf_pool_init, NULL,
851                                                 prox_pktmbuf_init, lconf,
852                                                 socket, flags);
853         }
854
855         PROX_PANIC(targ->pool == NULL,
856                    "\tError: cannot create mempool for core %u port %u: %s\n", lconf->id, targ->id, rte_strerror(rte_errno));
857
858         plog_info("\tMempool %p size = %u * %u cache %u, socket %d\n", targ->pool,
859                   targ->nb_mbuf, targ->mbuf_size, targ->nb_cache_mbuf, socket);
860         if (prox_cfg.flags & DSF_SHUFFLE) {
861                 shuffle_mempool(targ->pool, targ->nb_mbuf);
862         }
863 }
864
865 static void setup_mempools_multiple_per_socket(void)
866 {
867         struct lcore_cfg *lconf = NULL;
868         struct task_args *targ;
869
870         while (core_targ_next_early(&lconf, &targ, 0) == 0) {
871                 PROX_PANIC(targ->task_init == NULL, "task_init = NULL, is mode specified for core %d, task %d ?\n", lconf->id, targ->id);
872                 if (targ->rx_port_queue[0].port == OUT_DISCARD)
873                         continue;
874                 setup_mempool_for_rx_task(lconf, targ);
875         }
876 }
877
878 static void setup_mempools(void)
879 {
880         if (prox_cfg.flags & UNIQUE_MEMPOOL_PER_SOCKET)
881                 setup_mempools_unique_per_socket();
882         else
883                 setup_mempools_multiple_per_socket();
884 }
885
886 static void set_task_lconf(void)
887 {
888         struct lcore_cfg *lconf;
889         uint32_t lcore_id = -1;
890
891         while(prox_core_next(&lcore_id, 1) == 0) {
892                 lconf = &lcore_cfg[lcore_id];
893                 for (uint8_t task_id = 0; task_id < lconf->n_tasks_all; ++task_id) {
894                         lconf->targs[task_id].lconf = lconf;
895                 }
896         }
897 }
898
899 static void set_dest_threads(void)
900 {
901         struct lcore_cfg *lconf = NULL;
902         struct task_args *targ;
903
904         while (core_targ_next(&lconf, &targ, 0) == 0) {
905                 for (uint8_t idx = 0; idx < MAX_PROTOCOLS; ++idx) {
906                         for (uint8_t ring_idx = 0; ring_idx < targ->core_task_set[idx].n_elems; ++ring_idx) {
907                                 struct core_task ct = targ->core_task_set[idx].core_task[ring_idx];
908
909                                 struct task_args *dest_task = core_targ_get(ct.core, ct.task);
910                                 dest_task->prev_tasks[dest_task->n_prev_tasks++] = targ;
911                         }
912                 }
913         }
914 }
915
916 static void setup_all_task_structs_early_init(void)
917 {
918         struct lcore_cfg *lconf = NULL;
919         struct task_args *targ;
920
921         plog_info("\t*** Calling early init on all tasks ***\n");
922         while (core_targ_next(&lconf, &targ, 0) == 0) {
923                 if (targ->task_init->early_init) {
924                         targ->task_init->early_init(targ);
925                 }
926         }
927 }
928
929 static void setup_all_task_structs(void)
930 {
931         struct lcore_cfg *lconf;
932         uint32_t lcore_id = -1;
933         struct task_base *tmaster = NULL;
934
935         while(prox_core_next(&lcore_id, 1) == 0) {
936                 lconf = &lcore_cfg[lcore_id];
937                 for (uint8_t task_id = 0; task_id < lconf->n_tasks_all; ++task_id) {
938                         if (task_is_master(&lconf->targs[task_id])) {
939                                 plog_info("\tInitializing MASTER struct for core %d task %d\n", lcore_id, task_id);
940                                 lconf->tasks_all[task_id] = init_task_struct(&lconf->targs[task_id]);
941                                 tmaster = lconf->tasks_all[task_id];
942                         }
943                 }
944         }
945         PROX_PANIC(tmaster == NULL, "Can't initialize master task\n");
946         lcore_id = -1;
947
948         while(prox_core_next(&lcore_id, 1) == 0) {
949                 lconf = &lcore_cfg[lcore_id];
950                 plog_info("\tInitializing struct for core %d with %d task\n", lcore_id, lconf->n_tasks_all);
951                 for (uint8_t task_id = 0; task_id < lconf->n_tasks_all; ++task_id) {
952                         if (!task_is_master(&lconf->targs[task_id])) {
953                                 plog_info("\tInitializing struct for core %d task %d\n", lcore_id, task_id);
954                                 lconf->targs[task_id].tmaster = tmaster;
955                                 lconf->tasks_all[task_id] = init_task_struct(&lconf->targs[task_id]);
956                         }
957                 }
958         }
959 }
960
961 static void init_port_activate(void)
962 {
963         struct lcore_cfg *lconf = NULL;
964         struct task_args *targ;
965         uint8_t port_id = 0;
966
967         while (core_targ_next_early(&lconf, &targ, 0) == 0) {
968                 for (int i = 0; i < targ->nb_rxports; i++) {
969                         port_id = targ->rx_port_queue[i].port;
970                         prox_port_cfg[port_id].active = 1;
971                 }
972
973                 for (int i = 0; i < targ->nb_txports; i++) {
974                         port_id = targ->tx_port_queue[i].port;
975                         prox_port_cfg[port_id].active = 1;
976                 }
977         }
978 }
979
980 /* Initialize cores and allocate mempools */
981 static void init_lcores(void)
982 {
983         struct lcore_cfg *lconf = 0;
984         uint32_t lcore_id = -1;
985
986         while(prox_core_next(&lcore_id, 0) == 0) {
987                 uint8_t socket = rte_lcore_to_socket_id(lcore_id);
988                 PROX_PANIC(socket + 1 > MAX_SOCKETS, "Can't configure core %u (on socket %u). MAX_SOCKET is set to %d\n", lcore_id, socket, MAX_SOCKETS);
989         }
990
991         /* need to allocate mempools as the first thing to use the lowest possible address range */
992         plog_info("=== Initializing mempools ===\n");
993         setup_mempools();
994
995         lcore_cfg_alloc_hp();
996
997         set_dest_threads();
998         set_task_lconf();
999
1000         plog_info("=== Initializing port addresses ===\n");
1001         init_port_addr();
1002
1003         plog_info("=== Initializing queue numbers on cores ===\n");
1004         configure_if_queues();
1005
1006         plog_info("=== Initializing rings on cores ===\n");
1007         init_rings();
1008
1009         configure_multi_segments();
1010         configure_tx_queue_flags();
1011
1012         plog_info("=== Checking configuration consistency ===\n");
1013         check_cfg_consistent();
1014
1015         plog_all_rings();
1016 }
1017
1018 static int setup_prox(int argc, char **argv)
1019 {
1020         if (prox_read_config_file() != 0 ||
1021             prox_setup_rte(argv[0]) != 0) {
1022                 return -1;
1023         }
1024
1025         if (prox_cfg.flags & DSF_CHECK_SYNTAX) {
1026                 plog_info("=== Configuration file syntax has been checked ===\n\n");
1027                 exit(EXIT_SUCCESS);
1028         }
1029
1030         init_port_activate();
1031         plog_info("=== Initializing rte devices ===\n");
1032         if (!(prox_cfg.flags & DSF_USE_DUMMY_DEVICES))
1033                 init_rte_ring_dev();
1034         init_rte_dev(prox_cfg.flags & DSF_USE_DUMMY_DEVICES);
1035         plog_info("=== Calibrating TSC overhead ===\n");
1036         clock_init();
1037         plog_info("\tTSC running at %"PRIu64" Hz\n", rte_get_tsc_hz());
1038
1039         init_lcores();
1040         plog_info("=== Initializing ports ===\n");
1041         init_port_all();
1042
1043         setup_all_task_structs_early_init();
1044         plog_info("=== Initializing tasks ===\n");
1045         setup_all_task_structs();
1046
1047         if (prox_cfg.logbuf_size) {
1048                 prox_cfg.logbuf = prox_zmalloc(prox_cfg.logbuf_size, rte_socket_id());
1049                 PROX_PANIC(prox_cfg.logbuf == NULL, "Failed to allocate memory for logbuf with size = %d\n", prox_cfg.logbuf_size);
1050         }
1051
1052         if (prox_cfg.flags & DSF_CHECK_INIT) {
1053                 plog_info("=== Initialization sequence completed ===\n\n");
1054                 exit(EXIT_SUCCESS);
1055         }
1056
1057         /* Current way that works to disable DPDK logging */
1058         FILE *f = fopen("/dev/null", "r");
1059         rte_openlog_stream(f);
1060         plog_info("=== PROX started ===\n");
1061         return 0;
1062 }
1063
1064 static int success = 0;
1065 static void siguser_handler(int signal)
1066 {
1067         if (signal == SIGUSR1)
1068                 success = 1;
1069         else
1070                 success = 0;
1071 }
1072
1073 static void sigabrt_handler(__attribute__((unused)) int signum)
1074 {
1075         /* restore default disposition for SIGABRT and SIGPIPE */
1076         signal(SIGABRT, SIG_DFL);
1077         signal(SIGPIPE, SIG_DFL);
1078
1079         /* ignore further Ctrl-C */
1080         signal(SIGINT, SIG_IGN);
1081
1082         /* more drastic exit on tedious termination signal */
1083         plog_info("Aborting...\n");
1084         if (lcore_cfg != NULL) {
1085                 uint32_t lcore_id;
1086                 pthread_t thread_id, tid0, tid = pthread_self();
1087                 memset(&tid0, 0, sizeof(tid0));
1088
1089                 /* cancel all threads except current one */
1090                 lcore_id = -1;
1091                 while (prox_core_next(&lcore_id, 1) == 0) {
1092                         thread_id = lcore_cfg[lcore_id].thread_id;
1093                         if (pthread_equal(thread_id, tid0))
1094                                 continue;
1095                         if (pthread_equal(thread_id, tid))
1096                                 continue;
1097                         pthread_cancel(thread_id);
1098                 }
1099
1100                 /* wait for cancelled threads to terminate */
1101                 lcore_id = -1;
1102                 while (prox_core_next(&lcore_id, 1) == 0) {
1103                         thread_id = lcore_cfg[lcore_id].thread_id;
1104                         if (pthread_equal(thread_id, tid0))
1105                                 continue;
1106                         if (pthread_equal(thread_id, tid))
1107                                 continue;
1108                         pthread_join(thread_id, NULL);
1109                 }
1110         }
1111
1112         /* close ncurses */
1113         display_end();
1114
1115         /* close ports on termination signal */
1116         close_ports_atexit();
1117
1118         /* terminate now */
1119         abort();
1120 }
1121
1122 static void sigterm_handler(int signum)
1123 {
1124         /* abort on second Ctrl-C */
1125         if (signum == SIGINT)
1126                 signal(SIGINT, sigabrt_handler);
1127
1128         /* gracefully quit on harmless termination signal */
1129         /* ports will subsequently get closed at resulting exit */
1130         quit();
1131 }
1132
1133 static void set_term_env(void)
1134 {
1135         static const char var[] = "TERM";
1136         static char str[] = "TERM=putty";
1137         char *old_value, *new_value;
1138         int max_ver = 0, min_ver = 0, n;
1139
1140         old_value = getenv(var);
1141
1142         const char *ncurses_version = curses_version();
1143         n = sscanf(ncurses_version, "ncurses %d.%d", &max_ver, &min_ver);
1144         if (n != 2) {
1145                 plog_info("\tUnable to extract ncurses version from %s. TERM left unchanged to %s\n", ncurses_version, old_value);
1146                 return;
1147         } else {
1148                 plog_info("\tncurses version = %d.%d (%s)\n", max_ver, min_ver, ncurses_version);
1149         }
1150
1151         if (((max_ver > 6) || ((max_ver == 6) && (min_ver >= 1))) && (strcmp(old_value, "xterm") == 0)) {
1152                 // On recent OSes such as RHEL 8.0, ncurses(6.1)  introduced support
1153                 // for ECMA-48 repeat character control.
1154                 // Some terminal emulators use TERM=xterm but do not support this feature.
1155                 // In this case, printing repeating character such as "22000000 Hz" might
1156                 // display as 220 Hz.
1157                 // Other emulattors, such as tmux, use TERM=screen, and do not exhibit the issue.
1158                 plog_info("\tChanged TERM from %s ", old_value);
1159                 putenv(str);
1160                 new_value = getenv(var);
1161                 plog_info("to %s\n", new_value);
1162         } else {
1163                 plog_info("\tTERM left unchanged to %s\n", old_value);
1164         }
1165 }
1166
1167 int main(int argc, char **argv)
1168 {
1169         /* set en_US locale to print big numbers with ',' */
1170         setlocale(LC_NUMERIC, "en_US.utf-8");
1171
1172         if (prox_parse_args(argc, argv) != 0){
1173                 prox_usage(argv[0]);
1174         }
1175         plog_init(prox_cfg.log_name, prox_cfg.log_name_pid);
1176         plog_info("=== " PROGRAM_NAME " %s ===\n", VERSION_STR());
1177         plog_info("\tUsing DPDK %s\n", rte_version() + sizeof(RTE_VER_PREFIX));
1178         set_term_env();
1179         read_rdt_info();
1180
1181         if (prox_cfg.flags & DSF_LIST_TASK_MODES) {
1182                 /* list supported task modes and exit */
1183                 tasks_list();
1184                 return EXIT_SUCCESS;
1185         }
1186
1187         /* close ports at normal exit */
1188         atexit(close_ports_atexit);
1189         /* gracefully quit on harmless termination signals */
1190         signal(SIGHUP, sigterm_handler);
1191         signal(SIGINT, sigterm_handler);
1192         signal(SIGQUIT, sigterm_handler);
1193         signal(SIGTERM, sigterm_handler);
1194         signal(SIGUSR1, sigterm_handler);
1195         signal(SIGUSR2, sigterm_handler);
1196         /* more drastic exit on tedious termination signals */
1197         signal(SIGABRT, sigabrt_handler);
1198         signal(SIGPIPE, sigabrt_handler);
1199
1200         if (prox_cfg.flags & DSF_DAEMON) {
1201                 signal(SIGUSR1, siguser_handler);
1202                 signal(SIGUSR2, siguser_handler);
1203                 plog_info("=== Running in Daemon mode ===\n");
1204                 plog_info("\tForking child and waiting for setup completion\n");
1205
1206                 pid_t ppid = getpid();
1207                 pid_t pid = fork();
1208                 if (pid < 0) {
1209                         plog_err("Failed to fork process to run in daemon mode\n");
1210                         return EXIT_FAILURE;
1211                 }
1212
1213                 if (pid == 0) {
1214                         fclose(stdin);
1215                         fclose(stdout);
1216                         fclose(stderr);
1217                         if (setsid() < 0) {
1218                                 kill(ppid, SIGUSR2);
1219                                 return EXIT_FAILURE;
1220                         }
1221                         if (setup_prox(argc, argv) != 0) {
1222                                 kill(ppid, SIGUSR2);
1223                                 return EXIT_FAILURE;
1224                         }
1225                         else {
1226                                 kill(ppid, SIGUSR1);
1227                                 run(prox_cfg.flags);
1228                                 return EXIT_SUCCESS;
1229                         }
1230                 }
1231                 else {
1232                         /* Before exiting the parent, wait until the
1233                            child process has finished setting up */
1234                         pause();
1235                         if (prox_cfg.logbuf) {
1236                                 file_print(prox_cfg.logbuf);
1237                         }
1238                         return success? EXIT_SUCCESS : EXIT_FAILURE;
1239                 }
1240         }
1241
1242         if (setup_prox(argc, argv) != 0)
1243                 return EXIT_FAILURE;
1244         run(prox_cfg.flags);
1245
1246         return EXIT_SUCCESS;
1247 }