xref: /mOS-networking-stack/core/src/core.c (revision 91df013f)
1 #define _GNU_SOURCE
2 #include <sched.h>
3 #include <unistd.h>
4 #include <sys/time.h>
5 #include <semaphore.h>
6 #include <sys/mman.h>
7 #include <signal.h>
8 #include <assert.h>
9 #include <string.h>
10 
11 #include "cpu.h"
12 #include "eth_in.h"
13 #include "fhash.h"
14 #include "tcp_send_buffer.h"
15 #include "tcp_ring_buffer.h"
16 #include "socket.h"
17 #include "eth_out.h"
18 #include "tcp.h"
19 #include "tcp_in.h"
20 #include "tcp_out.h"
21 #include "mtcp_api.h"
22 #include "eventpoll.h"
23 #include "logger.h"
24 #include "config.h"
25 #include "arp.h"
26 #include "ip_out.h"
27 #include "timer.h"
28 #include "debug.h"
29 #include "event_callback.h"
30 #include "tcp_rb.h"
31 #include "tcp_stream.h"
32 #include "io_module.h"
33 
34 #ifdef ENABLE_DPDK
35 /* for launching rte thread */
36 #include <rte_launch.h>
37 #include <rte_lcore.h>
38 #endif /* !ENABLE_DPDK */
39 #define PS_CHUNK_SIZE 64
40 #define RX_THRESH (PS_CHUNK_SIZE * 0.8)
41 
42 #define ROUND_STAT FALSE
43 #define TIME_STAT FALSE
44 #define EVENT_STAT FALSE
45 #define TESTING FALSE
46 
47 #define LOG_FILE_NAME "log"
48 #define MAX_FILE_NAME 1024
49 
50 #define MAX(a, b) ((a)>(b)?(a):(b))
51 #define MIN(a, b) ((a)<(b)?(a):(b))
52 
53 #define PER_STREAM_SLICE 0.1		// in ms
54 #define PER_STREAM_TCHECK 1			// in ms
55 #define PS_SELECT_TIMEOUT 100		// in us
56 
57 #define GBPS(bytes) (bytes * 8.0 / (1000 * 1000 * 1000))
58 
59 /*----------------------------------------------------------------------------*/
60 /* handlers for threads */
61 struct mtcp_thread_context *g_pctx[MAX_CPUS] = {0};
62 struct log_thread_context *g_logctx[MAX_CPUS] = {0};
63 /*----------------------------------------------------------------------------*/
64 static pthread_t g_thread[MAX_CPUS] = {0};
65 static pthread_t log_thread[MAX_CPUS] = {0};
66 /*----------------------------------------------------------------------------*/
67 static sem_t g_init_sem[MAX_CPUS];
68 static sem_t g_done_sem[MAX_CPUS];
69 static int running[MAX_CPUS] = {0};
70 /*----------------------------------------------------------------------------*/
71 mtcp_sighandler_t app_signal_handler;
72 static int sigint_cnt[MAX_CPUS] = {0};
73 static struct timespec sigint_ts[MAX_CPUS];
74 /*----------------------------------------------------------------------------*/
75 #ifdef NETSTAT
76 #if NETSTAT_TOTAL
77 static int printer = -1;
78 #if ROUND_STAT
79 #endif /* ROUND_STAT */
80 #endif /* NETSTAT_TOTAL */
81 #endif /* NETSTAT */
82 /*----------------------------------------------------------------------------*/
83 void
84 HandleSignal(int signal)
85 {
86 	int i = 0;
87 
88 	if (signal == SIGINT) {
89 #ifdef DARWIN
90 		int core = 0;
91 #else
92 		int core = sched_getcpu();
93 #endif
94 		struct timespec cur_ts;
95 
96 		clock_gettime(CLOCK_REALTIME, &cur_ts);
97 
98 		if (sigint_cnt[core] > 0 && cur_ts.tv_sec == sigint_ts[core].tv_sec) {
99 			for (i = 0; i < g_config.mos->num_cores; i++) {
100 				if (running[i]) {
101 					exit(0);
102 					g_pctx[i]->exit = TRUE;
103 				}
104 			}
105 		} else {
106 			for (i = 0; i < g_config.mos->num_cores; i++) {
107 				if (g_pctx[i])
108 					g_pctx[i]->interrupt = TRUE;
109 			}
110 			if (!app_signal_handler) {
111 				for (i = 0; i < g_config.mos->num_cores; i++) {
112 					if (running[i]) {
113 						exit(0);
114 						g_pctx[i]->exit = TRUE;
115 					}
116 				}
117 			}
118 		}
119 		sigint_cnt[core]++;
120 		clock_gettime(CLOCK_REALTIME, &sigint_ts[core]);
121 	}
122 
123 	if (signal != SIGUSR1) {
124 		if (app_signal_handler) {
125 			app_signal_handler(signal);
126 		}
127 	}
128 }
129 /*----------------------------------------------------------------------------*/
130 static int
131 AttachDevice(struct mtcp_thread_context* ctx)
132 {
133 	int working = -1;
134 	mtcp_manager_t mtcp = ctx->mtcp_manager;
135 
136 	if (mtcp->iom->link_devices)
137 		working = mtcp->iom->link_devices(ctx);
138 	else
139 		return 0;
140 
141 	return working;
142 }
143 /*----------------------------------------------------------------------------*/
144 #ifdef TIMESTAT
145 static inline void
146 InitStatCounter(struct stat_counter *counter)
147 {
148 	counter->cnt = 0;
149 	counter->sum = 0;
150 	counter->max = 0;
151 	counter->min = 0;
152 }
153 /*----------------------------------------------------------------------------*/
154 static inline void
155 UpdateStatCounter(struct stat_counter *counter, int64_t value)
156 {
157 	counter->cnt++;
158 	counter->sum += value;
159 	if (value > counter->max)
160 		counter->max = value;
161 	if (counter->min == 0 || value < counter->min)
162 		counter->min = value;
163 }
164 /*----------------------------------------------------------------------------*/
165 static inline uint64_t
166 GetAverageStat(struct stat_counter *counter)
167 {
168 	return counter->cnt ? (counter->sum / counter->cnt) : 0;
169 }
170 /*----------------------------------------------------------------------------*/
171 static inline int64_t
172 TimeDiffUs(struct timeval *t2, struct timeval *t1)
173 {
174 	return (t2->tv_sec - t1->tv_sec) * 1000000 +
175 			(int64_t)(t2->tv_usec - t1->tv_usec);
176 }
177 /*----------------------------------------------------------------------------*/
178 #endif
179 #ifdef NETSTAT
180 static inline void
181 PrintThreadNetworkStats(mtcp_manager_t mtcp, struct net_stat *ns)
182 {
183 	int i;
184 
185 	for (i = 0; i < g_config.mos->netdev_table->num; i++) {
186 		ns->rx_packets[i] = mtcp->nstat.rx_packets[i] - mtcp->p_nstat.rx_packets[i];
187 		ns->rx_errors[i] = mtcp->nstat.rx_errors[i] - mtcp->p_nstat.rx_errors[i];
188 		ns->rx_bytes[i] = mtcp->nstat.rx_bytes[i] - mtcp->p_nstat.rx_bytes[i];
189 		ns->tx_packets[i] = mtcp->nstat.tx_packets[i] - mtcp->p_nstat.tx_packets[i];
190 		ns->tx_drops[i] = mtcp->nstat.tx_drops[i] - mtcp->p_nstat.tx_drops[i];
191 		ns->tx_bytes[i] = mtcp->nstat.tx_bytes[i] - mtcp->p_nstat.tx_bytes[i];
192 #if NETSTAT_PERTHREAD
193 		if (g_config.mos->netdev_table->ent[i]->stat_print) {
194 			fprintf(stderr, "[CPU%2d] %s flows: %6u, "
195 					"RX: %7llu(pps) (err: %5llu), %5.2lf(Gbps), "
196 					"TX: %7llu(pps), %5.2lf(Gbps)\n",
197 					mtcp->ctx->cpu,
198 					g_config.mos->netdev_table->ent[i]->dev_name,
199 					(unsigned)mtcp->flow_cnt,
200 					(long long unsigned)ns->rx_packets[i],
201 					(long long unsigned)ns->rx_errors[i],
202 					GBPS(ns->rx_bytes[i]),
203 					(long long unsigned)ns->tx_packets[i],
204 					GBPS(ns->tx_bytes[i]));
205 		}
206 #endif
207 	}
208 	mtcp->p_nstat = mtcp->nstat;
209 
210 }
211 /*----------------------------------------------------------------------------*/
212 #if ROUND_STAT
213 static inline void
214 PrintThreadRoundStats(mtcp_manager_t mtcp, struct run_stat *rs)
215 {
216 #define ROUND_DIV (1000)
217 	rs->rounds = mtcp->runstat.rounds - mtcp->p_runstat.rounds;
218 	rs->rounds_rx = mtcp->runstat.rounds_rx - mtcp->p_runstat.rounds_rx;
219 	rs->rounds_rx_try = mtcp->runstat.rounds_rx_try - mtcp->p_runstat.rounds_rx_try;
220 	rs->rounds_tx = mtcp->runstat.rounds_tx - mtcp->p_runstat.rounds_tx;
221 	rs->rounds_tx_try = mtcp->runstat.rounds_tx_try - mtcp->p_runstat.rounds_tx_try;
222 	rs->rounds_select = mtcp->runstat.rounds_select - mtcp->p_runstat.rounds_select;
223 	rs->rounds_select_rx = mtcp->runstat.rounds_select_rx - mtcp->p_runstat.rounds_select_rx;
224 	rs->rounds_select_tx = mtcp->runstat.rounds_select_tx - mtcp->p_runstat.rounds_select_tx;
225 	rs->rounds_select_intr = mtcp->runstat.rounds_select_intr - mtcp->p_runstat.rounds_select_intr;
226 	rs->rounds_twcheck = mtcp->runstat.rounds_twcheck - mtcp->p_runstat.rounds_twcheck;
227 	mtcp->p_runstat = mtcp->runstat;
228 #if NETSTAT_PERTHREAD
229 	fprintf(stderr, "[CPU%2d] Rounds: %4lluK, "
230 			"rx: %3lluK (try: %4lluK), tx: %3lluK (try: %4lluK), "
231 			"ps_select: %4llu (rx: %4llu, tx: %4llu, intr: %3llu)\n",
232 			mtcp->ctx->cpu, rs->rounds / ROUND_DIV,
233 			rs->rounds_rx / ROUND_DIV, rs->rounds_rx_try / ROUND_DIV,
234 			rs->rounds_tx / ROUND_DIV, rs->rounds_tx_try / ROUND_DIV,
235 			rs->rounds_select,
236 			rs->rounds_select_rx, rs->rounds_select_tx, rs->rounds_select_intr);
237 #endif
238 }
239 #endif /* ROUND_STAT */
240 /*----------------------------------------------------------------------------*/
241 #if TIME_STAT
242 static inline void
243 PrintThreadRoundTime(mtcp_manager_t mtcp)
244 {
245 	fprintf(stderr, "[CPU%2d] Time: (avg, max) "
246 			"round: (%4luus, %4luus), processing: (%4luus, %4luus), "
247 			"tcheck: (%4luus, %4luus), epoll: (%4luus, %4luus), "
248 			"handle: (%4luus, %4luus), xmit: (%4luus, %4luus), "
249 			"select: (%4luus, %4luus)\n", mtcp->ctx->cpu,
250 			GetAverageStat(&mtcp->rtstat.round), mtcp->rtstat.round.max,
251 			GetAverageStat(&mtcp->rtstat.processing), mtcp->rtstat.processing.max,
252 			GetAverageStat(&mtcp->rtstat.tcheck), mtcp->rtstat.tcheck.max,
253 			GetAverageStat(&mtcp->rtstat.epoll), mtcp->rtstat.epoll.max,
254 			GetAverageStat(&mtcp->rtstat.handle), mtcp->rtstat.handle.max,
255 			GetAverageStat(&mtcp->rtstat.xmit), mtcp->rtstat.xmit.max,
256 			GetAverageStat(&mtcp->rtstat.select), mtcp->rtstat.select.max);
257 
258 	InitStatCounter(&mtcp->rtstat.round);
259 	InitStatCounter(&mtcp->rtstat.processing);
260 	InitStatCounter(&mtcp->rtstat.tcheck);
261 	InitStatCounter(&mtcp->rtstat.epoll);
262 	InitStatCounter(&mtcp->rtstat.handle);
263 	InitStatCounter(&mtcp->rtstat.xmit);
264 	InitStatCounter(&mtcp->rtstat.select);
265 }
266 #endif
267 #endif /* NETSTAT */
268 /*----------------------------------------------------------------------------*/
269 #if EVENT_STAT
270 static inline void
271 PrintEventStat(int core, struct mtcp_epoll_stat *stat)
272 {
273 	fprintf(stderr, "[CPU%2d] calls: %lu, waits: %lu, wakes: %lu, "
274 			"issued: %lu, registered: %lu, invalidated: %lu, handled: %lu\n",
275 			core, stat->calls, stat->waits, stat->wakes,
276 			stat->issued, stat->registered, stat->invalidated, stat->handled);
277 	memset(stat, 0, sizeof(struct mtcp_epoll_stat));
278 }
279 #endif /* EVENT_STAT */
280 /*----------------------------------------------------------------------------*/
281 #ifdef NETSTAT
282 static inline void
283 PrintNetworkStats(mtcp_manager_t mtcp, uint32_t cur_ts)
284 {
285 #define TIMEOUT 1
286 	int i;
287 	struct net_stat ns;
288 	bool stat_print = false;
289 #if ROUND_STAT
290 	struct run_stat rs;
291 #endif /* ROUND_STAT */
292 #ifdef NETSTAT_TOTAL
293 	static double peak_total_rx_gbps = 0;
294 	static double peak_total_tx_gbps = 0;
295 	static double avg_total_rx_gbps = 0;
296 	static double avg_total_tx_gbps = 0;
297 
298 	double total_rx_gbps = 0, total_tx_gbps = 0;
299 	int j;
300 	uint32_t gflow_cnt = 0;
301 	struct net_stat g_nstat;
302 #if ROUND_STAT
303 	struct run_stat g_runstat;
304 #endif /* ROUND_STAT */
305 #endif /* NETSTAT_TOTAL */
306 
307 	if (TS_TO_MSEC(cur_ts - mtcp->p_nstat_ts) < SEC_TO_MSEC(TIMEOUT)) {
308 		return;
309 	}
310 
311 	mtcp->p_nstat_ts = cur_ts;
312 	gflow_cnt = 0;
313 	memset(&g_nstat, 0, sizeof(struct net_stat));
314 	for (i = 0; i < g_config.mos->num_cores; i++) {
315 		if (running[i]) {
316 			PrintThreadNetworkStats(g_mtcp[i], &ns);
317 #if NETSTAT_TOTAL
318 			gflow_cnt += g_mtcp[i]->flow_cnt;
319 			for (j = 0; j < g_config.mos->netdev_table->num; j++) {
320 				g_nstat.rx_packets[j] += ns.rx_packets[j];
321 				g_nstat.rx_errors[j] += ns.rx_errors[j];
322 				g_nstat.rx_bytes[j] += ns.rx_bytes[j];
323 				g_nstat.tx_packets[j] += ns.tx_packets[j];
324 				g_nstat.tx_drops[j] += ns.tx_drops[j];
325 				g_nstat.tx_bytes[j] += ns.tx_bytes[j];
326 			}
327 #endif
328 		}
329 	}
330 #if NETSTAT_TOTAL
331 	for (i = 0; i < g_config.mos->netdev_table->num; i++) {
332 		if (g_config.mos->netdev_table->ent[i]->stat_print) {
333 			fprintf(stderr, "[ ALL ] %s, "
334 			"RX: %7llu(pps) (err: %5llu), %5.2lf(Gbps), "
335 			"TX: %7llu(pps), %5.2lf(Gbps)\n",
336 				g_config.mos->netdev_table->ent[i]->dev_name,
337 				(long long unsigned)g_nstat.rx_packets[i],
338 				(long long unsigned)g_nstat.rx_errors[i],
339 				GBPS(g_nstat.rx_bytes[i]),
340 				(long long unsigned)g_nstat.tx_packets[i],
341 				GBPS(g_nstat.tx_bytes[i]));
342 			total_rx_gbps += GBPS(g_nstat.rx_bytes[i]);
343 			total_tx_gbps += GBPS(g_nstat.tx_bytes[i]);
344 			stat_print = true;
345 		}
346 	}
347 	if (stat_print) {
348 		fprintf(stderr, "[ ALL ] flows: %6u\n", gflow_cnt);
349 		if (avg_total_rx_gbps == 0)
350 			avg_total_rx_gbps = total_rx_gbps;
351 		else
352 			avg_total_rx_gbps = avg_total_rx_gbps * 0.6 + total_rx_gbps * 0.4;
353 
354 		if (avg_total_tx_gbps == 0)
355 			avg_total_tx_gbps = total_tx_gbps;
356 		else
357 			avg_total_tx_gbps = avg_total_tx_gbps * 0.6 + total_tx_gbps * 0.4;
358 
359 		if (peak_total_rx_gbps < total_rx_gbps)
360 			peak_total_rx_gbps = total_rx_gbps;
361 		if (peak_total_tx_gbps < total_tx_gbps)
362 			peak_total_tx_gbps = total_tx_gbps;
363 
364 		fprintf(stderr, "[ PEAK ] RX: %5.2lf(Gbps), TX: %5.2lf(Gbps)\n"
365 						"[ RECENT AVG ] RX: %5.2lf(Gbps), TX: %5.2lf(Gbps)\n",
366 				peak_total_rx_gbps, peak_total_tx_gbps,
367 				avg_total_rx_gbps, avg_total_tx_gbps);
368 	}
369 #endif
370 
371 #if ROUND_STAT
372 	memset(&g_runstat, 0, sizeof(struct run_stat));
373 	for (i = 0; i < g_config.mos->num_cores; i++) {
374 		if (running[i]) {
375 			PrintThreadRoundStats(g_mtcp[i], &rs);
376 #if DBGMSG
377 			g_runstat.rounds += rs.rounds;
378 			g_runstat.rounds_rx += rs.rounds_rx;
379 			g_runstat.rounds_rx_try += rs.rounds_rx_try;
380 			g_runstat.rounds_tx += rs.rounds_tx;
381 			g_runstat.rounds_tx_try += rs.rounds_tx_try;
382 			g_runstat.rounds_select += rs.rounds_select;
383 			g_runstat.rounds_select_rx += rs.rounds_select_rx;
384 			g_runstat.rounds_select_tx += rs.rounds_select_tx;
385 #endif
386 		}
387 	}
388 
389 	TRACE_DBG("[ ALL ] Rounds: %4ldK, "
390 		  "rx: %3ldK (try: %4ldK), tx: %3ldK (try: %4ldK), "
391 		  "ps_select: %4ld (rx: %4ld, tx: %4ld)\n",
392 		  g_runstat.rounds / 1000, g_runstat.rounds_rx / 1000,
393 		  g_runstat.rounds_rx_try / 1000, g_runstat.rounds_tx / 1000,
394 		  g_runstat.rounds_tx_try / 1000, g_runstat.rounds_select,
395 		  g_runstat.rounds_select_rx, g_runstat.rounds_select_tx);
396 #endif /* ROUND_STAT */
397 
398 #if TIME_STAT
399 	for (i = 0; i < g_config.mos->num_cores; i++) {
400 		if (running[i]) {
401 			PrintThreadRoundTime(g_mtcp[i]);
402 		}
403 	}
404 #endif
405 
406 #if EVENT_STAT
407 	for (i = 0; i < g_config.mos->num_cores; i++) {
408 		if (running[i] && g_mtcp[i]->ep) {
409 			PrintEventStat(i, &g_mtcp[i]->ep->stat);
410 		}
411 	}
412 #endif
413 
414 	fflush(stderr);
415 }
416 #endif /* NETSTAT */
417 /*----------------------------------------------------------------------------*/
418 static inline void
419 FlushMonitorReadEvents(mtcp_manager_t mtcp)
420 {
421 	struct event_queue *mtcpq;
422 	struct tcp_stream *cur_stream;
423 	struct mon_listener *walk;
424 
425 	/* check if monitor sockets should be passed data */
426 	TAILQ_FOREACH(walk, &mtcp->monitors, link) {
427 		if (walk->socket->socktype != MOS_SOCK_MONITOR_STREAM ||
428 			!(mtcpq = walk->eq))
429 			continue;
430 
431 		while (mtcpq->num_events > 0) {
432 			cur_stream =
433 				(struct tcp_stream *)mtcpq->events[mtcpq->start++].ev.data.ptr;
434 			/* only read events */
435 			if (cur_stream != NULL &&
436 					(cur_stream->socket->events | MOS_EPOLLIN)) {
437 				if (cur_stream->rcvvar != NULL &&
438 						cur_stream->rcvvar->rcvbuf != NULL) {
439 					/* no need to pass pkt context */
440 					struct socket_map *walk;
441 					SOCKQ_FOREACH_START(walk, &cur_stream->msocks) {
442 						HandleCallback(mtcp, MOS_NULL, walk,
443 							       cur_stream->side, NULL,
444 							       MOS_ON_CONN_NEW_DATA);
445 					} SOCKQ_FOREACH_END;
446 				}
447 				/* reset the actions now */
448 				cur_stream->actions = 0;
449 			}
450 			if (mtcpq->start >= mtcpq->size)
451 				mtcpq->start = 0;
452 			mtcpq->num_events--;
453 		}
454 	}
455 }
456 /*----------------------------------------------------------------------------*/
457 static inline void
458 FlushBufferedReadEvents(mtcp_manager_t mtcp)
459 {
460 	int i;
461 	int offset;
462 	struct event_queue *mtcpq;
463 	struct tcp_stream *cur_stream;
464 
465 	if (mtcp->ep == NULL) {
466 		TRACE_EPOLL("No epoll socket has been registered yet!\n");
467 		return;
468 	} else {
469 		/* case when mtcpq exists */
470 		mtcpq = mtcp->ep->mtcp_queue;
471 		offset = mtcpq->start;
472 	}
473 
474 	/* we will use queued-up epoll read-in events
475 	 * to trigger buffered read monitor events */
476 	for (i = 0; i < mtcpq->num_events; i++) {
477 		cur_stream = mtcp->smap[mtcpq->events[offset++].sockid].stream;
478 		/* only read events */
479 		/* Raise new data callback event */
480 		if (cur_stream != NULL &&
481 				(cur_stream->socket->events | MOS_EPOLLIN)) {
482 			if (cur_stream->rcvvar != NULL &&
483 					cur_stream->rcvvar->rcvbuf != NULL) {
484 				/* no need to pass pkt context */
485 				struct socket_map *walk;
486 				SOCKQ_FOREACH_START(walk, &cur_stream->msocks) {
487 					HandleCallback(mtcp, MOS_NULL, walk, cur_stream->side,
488 							NULL, MOS_ON_CONN_NEW_DATA);
489 				} SOCKQ_FOREACH_END;
490 			}
491 		}
492 		if (offset >= mtcpq->size)
493 			offset = 0;
494 	}
495 }
496 /*----------------------------------------------------------------------------*/
497 static inline void
498 FlushEpollEvents(mtcp_manager_t mtcp, uint32_t cur_ts)
499 {
500 	struct mtcp_epoll *ep = mtcp->ep;
501 	struct event_queue *usrq = ep->usr_queue;
502 	struct event_queue *mtcpq = ep->mtcp_queue;
503 
504 	pthread_mutex_lock(&ep->epoll_lock);
505 	if (ep->mtcp_queue->num_events > 0) {
506 		/* while mtcp_queue have events */
507 		/* and usr_queue is not full */
508 		while (mtcpq->num_events > 0 && usrq->num_events < usrq->size) {
509 			/* copy the event from mtcp_queue to usr_queue */
510 			usrq->events[usrq->end++] = mtcpq->events[mtcpq->start++];
511 
512 			if (usrq->end >= usrq->size)
513 				usrq->end = 0;
514 			usrq->num_events++;
515 
516 			if (mtcpq->start >= mtcpq->size)
517 				mtcpq->start = 0;
518 			mtcpq->num_events--;
519 		}
520 	}
521 
522 	/* if there are pending events, wake up user */
523 	if (ep->waiting && (ep->usr_queue->num_events > 0 ||
524 				ep->usr_shadow_queue->num_events > 0)) {
525 		STAT_COUNT(mtcp->runstat.rounds_epoll);
526 		TRACE_EPOLL("Broadcasting events. num: %d, cur_ts: %u, prev_ts: %u\n",
527 				ep->usr_queue->num_events, cur_ts, mtcp->ts_last_event);
528 		mtcp->ts_last_event = cur_ts;
529 		ep->stat.wakes++;
530 		pthread_cond_signal(&ep->epoll_cond);
531 	}
532 	pthread_mutex_unlock(&ep->epoll_lock);
533 }
534 /*----------------------------------------------------------------------------*/
535 static inline void
536 HandleApplicationCalls(mtcp_manager_t mtcp, uint32_t cur_ts)
537 {
538 	tcp_stream *stream;
539 	int cnt, max_cnt;
540 	int handled, delayed;
541 	int control, send, ack;
542 
543 	/* connect handling */
544 	while ((stream = StreamDequeue(mtcp->connectq))) {
545 		if (stream->state != TCP_ST_SYN_SENT) {
546 			TRACE_INFO("Got a connection request from app with state: %s",
547 				   TCPStateToString(stream));
548 			exit(EXIT_FAILURE);
549 		} else {
550 			stream->cb_events |= MOS_ON_CONN_START |
551 				MOS_ON_TCP_STATE_CHANGE;
552 			/* if monitor is on... */
553 			if (stream->pair_stream != NULL)
554 				stream->pair_stream->cb_events |=
555 					MOS_ON_CONN_START;
556 		}
557 		AddtoControlList(mtcp, stream, cur_ts);
558 	}
559 
560 	/* send queue handling */
561 	while ((stream = StreamDequeue(mtcp->sendq))) {
562 		stream->sndvar->on_sendq = FALSE;
563 		AddtoSendList(mtcp, stream);
564 	}
565 
566 	/* ack queue handling */
567 	while ((stream = StreamDequeue(mtcp->ackq))) {
568 		stream->sndvar->on_ackq = FALSE;
569 		EnqueueACK(mtcp, stream, cur_ts, ACK_OPT_AGGREGATE);
570 	}
571 
572 	/* close handling */
573 	handled = delayed = 0;
574 	control = send = ack = 0;
575 	while ((stream = StreamDequeue(mtcp->closeq))) {
576 		struct tcp_send_vars *sndvar = stream->sndvar;
577 		sndvar->on_closeq = FALSE;
578 
579 		if (sndvar->sndbuf) {
580 			sndvar->fss = sndvar->sndbuf->head_seq + sndvar->sndbuf->len;
581 		} else {
582 			sndvar->fss = stream->snd_nxt;
583 		}
584 
585 		if (g_config.mos->tcp_timeout > 0)
586 			RemoveFromTimeoutList(mtcp, stream);
587 
588 		if (stream->have_reset) {
589 			handled++;
590 			if (stream->state != TCP_ST_CLOSED_RSVD) {
591 				stream->close_reason = TCP_RESET;
592 				stream->state = TCP_ST_CLOSED_RSVD;
593 				stream->cb_events |= MOS_ON_TCP_STATE_CHANGE;
594 				TRACE_STATE("Stream %d: TCP_ST_CLOSED_RSVD\n", stream->id);
595 				DestroyTCPStream(mtcp, stream);
596 			} else {
597 				TRACE_ERROR("Stream already closed.\n");
598 			}
599 
600 		} else if (sndvar->on_control_list) {
601 			sndvar->on_closeq_int = TRUE;
602 			StreamInternalEnqueue(mtcp->closeq_int, stream);
603 			delayed++;
604 			if (sndvar->on_control_list)
605 				control++;
606 			if (sndvar->on_send_list)
607 				send++;
608 			if (sndvar->on_ack_list)
609 				ack++;
610 
611 		} else if (sndvar->on_send_list || sndvar->on_ack_list) {
612 			handled++;
613 			if (stream->state == TCP_ST_ESTABLISHED) {
614 				stream->state = TCP_ST_FIN_WAIT_1;
615 				stream->cb_events |= MOS_ON_TCP_STATE_CHANGE;
616 				TRACE_STATE("Stream %d: TCP_ST_FIN_WAIT_1\n", stream->id);
617 
618 			} else if (stream->state == TCP_ST_CLOSE_WAIT) {
619 				stream->state = TCP_ST_LAST_ACK;
620 				stream->cb_events |= MOS_ON_TCP_STATE_CHANGE;
621 				TRACE_STATE("Stream %d: TCP_ST_LAST_ACK\n", stream->id);
622 			}
623 			stream->control_list_waiting = TRUE;
624 
625 		} else if (stream->state != TCP_ST_CLOSED_RSVD) {
626 			handled++;
627 			if (stream->state == TCP_ST_ESTABLISHED) {
628 				stream->state = TCP_ST_FIN_WAIT_1;
629 				stream->cb_events |= MOS_ON_TCP_STATE_CHANGE;
630 				TRACE_STATE("Stream %d: TCP_ST_FIN_WAIT_1\n", stream->id);
631 
632 			} else if (stream->state == TCP_ST_CLOSE_WAIT) {
633 				stream->state = TCP_ST_LAST_ACK;
634 				stream->cb_events |= MOS_ON_TCP_STATE_CHANGE;
635 				TRACE_STATE("Stream %d: TCP_ST_LAST_ACK\n", stream->id);
636 			}
637 			//sndvar->rto = TCP_FIN_RTO;
638 			//UpdateRetransmissionTimer(mtcp, stream, mtcp->cur_ts);
639 			AddtoControlList(mtcp, stream, cur_ts);
640 		} else {
641 			TRACE_ERROR("Already closed connection!\n");
642 		}
643 	}
644 	TRACE_ROUND("Handling close connections. cnt: %d\n", cnt);
645 
646 	cnt = 0;
647 	max_cnt = mtcp->closeq_int->count;
648 	while (cnt++ < max_cnt) {
649 		stream = StreamInternalDequeue(mtcp->closeq_int);
650 
651 		if (stream->sndvar->on_control_list) {
652 			StreamInternalEnqueue(mtcp->closeq_int, stream);
653 
654 		} else if (stream->state != TCP_ST_CLOSED_RSVD) {
655 			handled++;
656 			stream->sndvar->on_closeq_int = FALSE;
657 			if (stream->state == TCP_ST_ESTABLISHED) {
658 				stream->state = TCP_ST_FIN_WAIT_1;
659 				stream->cb_events |= MOS_ON_TCP_STATE_CHANGE;
660 				TRACE_STATE("Stream %d: TCP_ST_FIN_WAIT_1\n", stream->id);
661 
662 			} else if (stream->state == TCP_ST_CLOSE_WAIT) {
663 				stream->state = TCP_ST_LAST_ACK;
664 				stream->cb_events |= MOS_ON_TCP_STATE_CHANGE;
665 				TRACE_STATE("Stream %d: TCP_ST_LAST_ACK\n", stream->id);
666 			}
667 			AddtoControlList(mtcp, stream, cur_ts);
668 		} else {
669 			stream->sndvar->on_closeq_int = FALSE;
670 			TRACE_ERROR("Already closed connection!\n");
671 		}
672 	}
673 
674 	/* reset handling */
675 	while ((stream = StreamDequeue(mtcp->resetq))) {
676 		stream->sndvar->on_resetq = FALSE;
677 
678 		if (g_config.mos->tcp_timeout > 0)
679 			RemoveFromTimeoutList(mtcp, stream);
680 
681 		if (stream->have_reset) {
682 			if (stream->state != TCP_ST_CLOSED_RSVD) {
683 				stream->close_reason = TCP_RESET;
684 				stream->state = TCP_ST_CLOSED_RSVD;
685 				stream->cb_events |= MOS_ON_TCP_STATE_CHANGE;
686 				TRACE_STATE("Stream %d: TCP_ST_CLOSED_RSVD\n", stream->id);
687 				DestroyTCPStream(mtcp, stream);
688 			} else {
689 				TRACE_ERROR("Stream already closed.\n");
690 			}
691 
692 		} else if (stream->sndvar->on_control_list ||
693 				stream->sndvar->on_send_list || stream->sndvar->on_ack_list) {
694 			/* wait until all the queues are flushed */
695 			stream->sndvar->on_resetq_int = TRUE;
696 			StreamInternalEnqueue(mtcp->resetq_int, stream);
697 
698 		} else {
699 			if (stream->state != TCP_ST_CLOSED_RSVD) {
700 				stream->close_reason = TCP_ACTIVE_CLOSE;
701 				stream->state = TCP_ST_CLOSED_RSVD;
702 				stream->cb_events |= MOS_ON_TCP_STATE_CHANGE;
703 				TRACE_STATE("Stream %d: TCP_ST_CLOSED_RSVD\n", stream->id);
704 				AddtoControlList(mtcp, stream, cur_ts);
705 			} else {
706 				TRACE_ERROR("Stream already closed.\n");
707 			}
708 		}
709 	}
710 	TRACE_ROUND("Handling reset connections. cnt: %d\n", cnt);
711 
712 	cnt = 0;
713 	max_cnt = mtcp->resetq_int->count;
714 	while (cnt++ < max_cnt) {
715 		stream = StreamInternalDequeue(mtcp->resetq_int);
716 
717 		if (stream->sndvar->on_control_list ||
718 				stream->sndvar->on_send_list || stream->sndvar->on_ack_list) {
719 			/* wait until all the queues are flushed */
720 			StreamInternalEnqueue(mtcp->resetq_int, stream);
721 
722 		} else {
723 			stream->sndvar->on_resetq_int = FALSE;
724 
725 			if (stream->state != TCP_ST_CLOSED_RSVD) {
726 				stream->close_reason = TCP_ACTIVE_CLOSE;
727 				stream->state = TCP_ST_CLOSED_RSVD;
728 				stream->cb_events |= MOS_ON_TCP_STATE_CHANGE;
729 				TRACE_STATE("Stream %d: TCP_ST_CLOSED_RSVD\n", stream->id);
730 				AddtoControlList(mtcp, stream, cur_ts);
731 			} else {
732 				TRACE_ERROR("Stream already closed.\n");
733 			}
734 		}
735 	}
736 
737 	/* destroy streams in destroyq */
738 	while ((stream = StreamDequeue(mtcp->destroyq))) {
739 		DestroyTCPStream(mtcp, stream);
740 	}
741 
742 	mtcp->wakeup_flag = FALSE;
743 }
744 /*----------------------------------------------------------------------------*/
745 static inline void
746 WritePacketsToChunks(mtcp_manager_t mtcp, uint32_t cur_ts)
747 {
748 	int thresh = g_config.mos->max_concurrency;
749 	int i;
750 
751 	/* Set the threshold to g_config.mos->max_concurrency to send ACK immediately */
752 	/* Otherwise, set to appropriate value (e.g. thresh) */
753 	assert(mtcp->g_sender != NULL);
754 	if (mtcp->g_sender->control_list_cnt)
755 		WriteTCPControlList(mtcp, mtcp->g_sender, cur_ts, thresh);
756 	if (mtcp->g_sender->ack_list_cnt)
757 		WriteTCPACKList(mtcp, mtcp->g_sender, cur_ts, thresh);
758 	if (mtcp->g_sender->send_list_cnt)
759 		WriteTCPDataList(mtcp, mtcp->g_sender, cur_ts, thresh);
760 
761 	for (i = 0; i < g_config.mos->netdev_table->num; i++) {
762 		assert(mtcp->n_sender[i] != NULL);
763 		if (mtcp->n_sender[i]->control_list_cnt)
764 			WriteTCPControlList(mtcp, mtcp->n_sender[i], cur_ts, thresh);
765 		if (mtcp->n_sender[i]->ack_list_cnt)
766 			WriteTCPACKList(mtcp, mtcp->n_sender[i], cur_ts, thresh);
767 		if (mtcp->n_sender[i]->send_list_cnt)
768 			WriteTCPDataList(mtcp, mtcp->n_sender[i], cur_ts, thresh);
769 	}
770 }
771 /*----------------------------------------------------------------------------*/
772 #if TESTING
773 static int
774 DestroyRemainingFlows(mtcp_manager_t mtcp)
775 {
776 	struct hashtable *ht = mtcp->tcp_flow_table;
777 	tcp_stream *walk;
778 	int cnt, i;
779 
780 	cnt = 0;
781 
782 	thread_printf(mtcp, mtcp->log_fp,
783 			"CPU %d: Flushing remaining flows.\n", mtcp->ctx->cpu);
784 
785 	for (i = 0; i < NUM_BINS; i++) {
786 		TAILQ_FOREACH(walk, &ht->ht_table[i], rcvvar->he_link) {
787 			thread_printf(mtcp, mtcp->log_fp,
788 					"CPU %d: Destroying stream %d\n", mtcp->ctx->cpu, walk->id);
789 #ifdef DUMP_STREAM
790 			DumpStream(mtcp, walk);
791 #endif
792 			DestroyTCPStream(mtcp, walk);
793 			cnt++;
794 		}
795 	}
796 
797 	return cnt;
798 }
799 #endif
800 /*----------------------------------------------------------------------------*/
801 static void
802 InterruptApplication(mtcp_manager_t mtcp)
803 {
804 	/* interrupt if the mtcp_epoll_wait() is waiting */
805 	if (mtcp->ep) {
806 		pthread_mutex_lock(&mtcp->ep->epoll_lock);
807 		if (mtcp->ep->waiting) {
808 			pthread_cond_signal(&mtcp->ep->epoll_cond);
809 		}
810 		pthread_mutex_unlock(&mtcp->ep->epoll_lock);
811 	}
812 	/* interrupt if the accept() is waiting */
813 	if (mtcp->listener) {
814 		if (mtcp->listener->socket) {
815 			pthread_mutex_lock(&mtcp->listener->accept_lock);
816 			if (!(mtcp->listener->socket->opts & MTCP_NONBLOCK)) {
817 				pthread_cond_signal(&mtcp->listener->accept_cond);
818 			}
819 			pthread_mutex_unlock(&mtcp->listener->accept_lock);
820 		}
821 	}
822 }
823 /*----------------------------------------------------------------------------*/
824 void
825 RunPassiveLoop(mtcp_manager_t mtcp)
826 {
827 	sem_wait(&g_done_sem[mtcp->ctx->cpu]);
828 	sem_destroy(&g_done_sem[mtcp->ctx->cpu]);
829 	return;
830 }
831 /*----------------------------------------------------------------------------*/
832 static void
833 RunMainLoop(struct mtcp_thread_context *ctx)
834 {
835 	mtcp_manager_t mtcp = ctx->mtcp_manager;
836 	int i;
837 	int recv_cnt;
838 	int rx_inf, tx_inf;
839 	struct timeval cur_ts = {0};
840 	uint32_t ts, ts_prev;
841 
842 #if TIME_STAT
843 	struct timeval prev_ts, processing_ts, tcheck_ts,
844 				   epoll_ts, handle_ts, xmit_ts, select_ts;
845 #endif
846 	int thresh;
847 
848 	gettimeofday(&cur_ts, NULL);
849 
850 	TRACE_DBG("CPU %d: mtcp thread running.\n", ctx->cpu);
851 
852 #if TIME_STAT
853 	prev_ts = cur_ts;
854 	InitStatCounter(&mtcp->rtstat.round);
855 	InitStatCounter(&mtcp->rtstat.processing);
856 	InitStatCounter(&mtcp->rtstat.tcheck);
857 	InitStatCounter(&mtcp->rtstat.epoll);
858 	InitStatCounter(&mtcp->rtstat.handle);
859 	InitStatCounter(&mtcp->rtstat.xmit);
860 	InitStatCounter(&mtcp->rtstat.select);
861 #endif
862 
863 	ts = ts_prev = 0;
864 	while ((!ctx->done || mtcp->flow_cnt) && !ctx->exit) {
865 
866 		STAT_COUNT(mtcp->runstat.rounds);
867 		recv_cnt = 0;
868 		gettimeofday(&cur_ts, NULL);
869 #if TIME_STAT
870 		/* measure the inter-round delay */
871 		UpdateStatCounter(&mtcp->rtstat.round, TimeDiffUs(&cur_ts, &prev_ts));
872 		prev_ts = cur_ts;
873 #endif
874 
875 		ts = TIMEVAL_TO_TS(&cur_ts);
876 		mtcp->cur_ts = ts;
877 
878 		for (rx_inf = 0; rx_inf < g_config.mos->netdev_table->num; rx_inf++) {
879 
880 			recv_cnt = mtcp->iom->recv_pkts(ctx, rx_inf);
881 			STAT_COUNT(mtcp->runstat.rounds_rx_try);
882 
883 			for (i = 0; i < recv_cnt; i++) {
884 				uint16_t len;
885 				uint8_t *pktbuf;
886 				pktbuf = mtcp->iom->get_rptr(mtcp->ctx, rx_inf, i, &len);
887 				ProcessPacket(mtcp, rx_inf, i, ts, pktbuf, len);
888 			}
889 
890 #ifdef ENABLE_DPDKR
891 			mtcp->iom->send_pkts(ctx, rx_inf);
892 			continue;
893 #endif
894 		}
895 		STAT_COUNT(mtcp->runstat.rounds_rx);
896 
897 #if TIME_STAT
898 		gettimeofday(&processing_ts, NULL);
899 		UpdateStatCounter(&mtcp->rtstat.processing,
900 				TimeDiffUs(&processing_ts, &cur_ts));
901 #endif /* TIME_STAT */
902 
903 		/* Handle user defined timeout */
904 		struct timer *walk, *tmp;
905 		for (walk = TAILQ_FIRST(&mtcp->timer_list); walk != NULL; walk = tmp) {
906 			tmp = TAILQ_NEXT(walk, timer_link);
907 			if (TIMEVAL_LT(&cur_ts, &walk->exp))
908 				break;
909 
910 			struct mtcp_context mctx = {.cpu = ctx->cpu};
911 			walk->cb(&mctx, walk->id, 0, 0 /* FIXME */, NULL);
912 			DelTimer(mtcp, walk);
913 		}
914 
915 		/* interaction with application */
916 		if (mtcp->flow_cnt > 0) {
917 
918 			/* check retransmission timeout and timewait expire */
919 #if 0
920 			thresh = (int)mtcp->flow_cnt / (TS_TO_USEC(PER_STREAM_TCHECK));
921 			assert(thresh >= 0);
922 			if (thresh == 0)
923 				thresh = 1;
924 			if (recv_cnt > 0 && thresh > recv_cnt)
925 				thresh = recv_cnt;
926 #else
927 			thresh = g_config.mos->max_concurrency;
928 #endif
929 
930 			/* Eunyoung, you may fix this later
931 			 * if there is no rcv packet, we will send as much as possible
932 			 */
933 			if (thresh == -1)
934 				thresh = g_config.mos->max_concurrency;
935 
936 			CheckRtmTimeout(mtcp, ts, thresh);
937 			CheckTimewaitExpire(mtcp, ts, thresh);
938 
939 			if (g_config.mos->tcp_timeout > 0 && ts != ts_prev) {
940 				CheckConnectionTimeout(mtcp, ts, thresh);
941 			}
942 
943 #if TIME_STAT
944 		}
945 		gettimeofday(&tcheck_ts, NULL);
946 		UpdateStatCounter(&mtcp->rtstat.tcheck,
947 				TimeDiffUs(&tcheck_ts, &processing_ts));
948 
949 		if (mtcp->flow_cnt > 0) {
950 #endif /* TIME_STAT */
951 
952 		}
953 
954 		/*
955 		 * before flushing epoll events, call monitor events for
956 		 * all registered `read` events
957 		 */
958 		if (mtcp->num_msp > 0)
959 			/* call this when only a standalone monitor is running */
960 			FlushMonitorReadEvents(mtcp);
961 
962 		/* if epoll is in use, flush all the queued events */
963 		if (mtcp->ep) {
964 			FlushBufferedReadEvents(mtcp);
965 			FlushEpollEvents(mtcp, ts);
966 		}
967 #if TIME_STAT
968 		gettimeofday(&epoll_ts, NULL);
969 		UpdateStatCounter(&mtcp->rtstat.epoll,
970 				TimeDiffUs(&epoll_ts, &tcheck_ts));
971 #endif /* TIME_STAT */
972 
973 		if (end_app_exists && mtcp->flow_cnt > 0) {
974 			/* handle stream queues  */
975 			HandleApplicationCalls(mtcp, ts);
976 		}
977 
978 #ifdef ENABLE_DPDKR
979 		continue;
980 #endif
981 
982 #if TIME_STAT
983 		gettimeofday(&handle_ts, NULL);
984 		UpdateStatCounter(&mtcp->rtstat.handle,
985 				TimeDiffUs(&handle_ts, &epoll_ts));
986 #endif /* TIME_STAT */
987 
988 		WritePacketsToChunks(mtcp, ts);
989 
990 		/* send packets from write buffer */
991 		/* Send until tx is available */
992 		int num_dev = g_config.mos->netdev_table->num;
993 		if (likely(mtcp->iom->send_pkts != NULL))
994 			for (tx_inf = 0; tx_inf < num_dev; tx_inf++) {
995 				mtcp->iom->send_pkts(ctx, tx_inf);
996 			}
997 
998 #if TIME_STAT
999 		gettimeofday(&xmit_ts, NULL);
1000 		UpdateStatCounter(&mtcp->rtstat.xmit,
1001 				TimeDiffUs(&xmit_ts, &handle_ts));
1002 #endif /* TIME_STAT */
1003 
1004 		if (ts != ts_prev) {
1005 			ts_prev = ts;
1006 #ifdef NETSTAT
1007 			if (ctx->cpu == printer) {
1008 #ifdef RUN_ARP
1009 				ARPTimer(mtcp, ts);
1010 #endif
1011 #ifdef NETSTAT
1012 				PrintNetworkStats(mtcp, ts);
1013 #endif
1014 			}
1015 #endif /* NETSTAT */
1016 		}
1017 
1018 		if (mtcp->iom->select)
1019 			mtcp->iom->select(ctx);
1020 
1021 		if (ctx->interrupt) {
1022 			InterruptApplication(mtcp);
1023 		}
1024 	}
1025 
1026 #if TESTING
1027 	DestroyRemainingFlows(mtcp);
1028 #endif
1029 
1030 	TRACE_DBG("MTCP thread %d out of main loop.\n", ctx->cpu);
1031 	/* flush logs */
1032 	flush_log_data(mtcp);
1033 	TRACE_DBG("MTCP thread %d flushed logs.\n", ctx->cpu);
1034 	InterruptApplication(mtcp);
1035 	TRACE_INFO("MTCP thread %d finished.\n", ctx->cpu);
1036 }
1037 /*----------------------------------------------------------------------------*/
1038 struct mtcp_sender *
1039 CreateMTCPSender(int ifidx)
1040 {
1041 	struct mtcp_sender *sender;
1042 
1043 	sender = (struct mtcp_sender *)calloc(1, sizeof(struct mtcp_sender));
1044 	if (!sender) {
1045 		return NULL;
1046 	}
1047 
1048 	sender->ifidx = ifidx;
1049 
1050 	TAILQ_INIT(&sender->control_list);
1051 	TAILQ_INIT(&sender->send_list);
1052 	TAILQ_INIT(&sender->ack_list);
1053 
1054 	sender->control_list_cnt = 0;
1055 	sender->send_list_cnt = 0;
1056 	sender->ack_list_cnt = 0;
1057 
1058 	return sender;
1059 }
1060 /*----------------------------------------------------------------------------*/
1061 void
1062 DestroyMTCPSender(struct mtcp_sender *sender)
1063 {
1064 	free(sender);
1065 }
1066 /*----------------------------------------------------------------------------*/
1067 static mtcp_manager_t
1068 InitializeMTCPManager(struct mtcp_thread_context* ctx)
1069 {
1070 	mtcp_manager_t mtcp;
1071 	char log_name[MAX_FILE_NAME];
1072 	int i;
1073 
1074 	posix_seq_srand((unsigned)pthread_self());
1075 
1076 	mtcp = (mtcp_manager_t)calloc(1, sizeof(struct mtcp_manager));
1077 	if (!mtcp) {
1078 		perror("malloc");
1079 		CTRACE_ERROR("Failed to allocate mtcp_manager.\n");
1080 		return NULL;
1081 	}
1082 	g_mtcp[ctx->cpu] = mtcp;
1083 
1084 	mtcp->tcp_flow_table = CreateHashtable();
1085 	if (!mtcp->tcp_flow_table) {
1086 		CTRACE_ERROR("Falied to allocate tcp flow table.\n");
1087 		return NULL;
1088 	}
1089 
1090 #ifdef HUGEPAGE
1091 #define	IS_HUGEPAGE 1
1092 #else
1093 #define	IS_HUGEPAGE 0
1094 #endif
1095 	if (mon_app_exists) {
1096 		/* initialize event callback */
1097 #ifdef NEWEV
1098 		InitEvent(mtcp);
1099 #else
1100 		InitEvent(mtcp, NUM_EV_TABLE);
1101 #endif
1102 	}
1103 
1104 	if (!(mtcp->bufseg_pool = MPCreate(sizeof(tcpbufseg_t),
1105 			sizeof(tcpbufseg_t) * g_config.mos->max_concurrency *
1106 			((g_config.mos->rmem_size - 1) / UNITBUFSIZE + 1), 0))) {
1107 		TRACE_ERROR("Failed to allocate ev_table pool\n");
1108 		exit(0);
1109 	}
1110 	if (!(mtcp->sockent_pool = MPCreate(sizeof(struct sockent),
1111 			sizeof(struct sockent) * g_config.mos->max_concurrency * 3, 0))) {
1112 		TRACE_ERROR("Failed to allocate ev_table pool\n");
1113 		exit(0);
1114 	}
1115 #ifdef USE_TIMER_POOL
1116 	if (!(mtcp->timer_pool = MPCreate(sizeof(struct timer),
1117 					  sizeof(struct timer) * g_config.mos->max_concurrency * 10, 0))) {
1118 		TRACE_ERROR("Failed to allocate ev_table pool\n");
1119 		exit(0);
1120 	}
1121 #endif
1122 	mtcp->flow_pool = MPCreate(sizeof(tcp_stream),
1123 								sizeof(tcp_stream) * g_config.mos->max_concurrency, IS_HUGEPAGE);
1124 	if (!mtcp->flow_pool) {
1125 		CTRACE_ERROR("Failed to allocate tcp flow pool.\n");
1126 		return NULL;
1127 	}
1128 	mtcp->rv_pool = MPCreate(sizeof(struct tcp_recv_vars),
1129 			sizeof(struct tcp_recv_vars) * g_config.mos->max_concurrency, IS_HUGEPAGE);
1130 	if (!mtcp->rv_pool) {
1131 		CTRACE_ERROR("Failed to allocate tcp recv variable pool.\n");
1132 		return NULL;
1133 	}
1134 	mtcp->sv_pool = MPCreate(sizeof(struct tcp_send_vars),
1135 			sizeof(struct tcp_send_vars) * g_config.mos->max_concurrency, IS_HUGEPAGE);
1136 	if (!mtcp->sv_pool) {
1137 		CTRACE_ERROR("Failed to allocate tcp send variable pool.\n");
1138 		return NULL;
1139 	}
1140 
1141 	mtcp->rbm_snd = SBManagerCreate(g_config.mos->wmem_size, g_config.mos->no_ring_buffers,
1142 					g_config.mos->max_concurrency);
1143 	if (!mtcp->rbm_snd) {
1144 		CTRACE_ERROR("Failed to create send ring buffer.\n");
1145 		return NULL;
1146 	}
1147 
1148 	mtcp->smap = (socket_map_t)calloc(g_config.mos->max_concurrency, sizeof(struct socket_map));
1149 	if (!mtcp->smap) {
1150 		perror("calloc");
1151 		CTRACE_ERROR("Failed to allocate memory for stream map.\n");
1152 		return NULL;
1153 	}
1154 
1155 	if (mon_app_exists) {
1156 		mtcp->msmap = (socket_map_t)calloc(g_config.mos->max_concurrency, sizeof(struct socket_map));
1157 		if (!mtcp->msmap) {
1158 			perror("calloc");
1159 			CTRACE_ERROR("Failed to allocate memory for monitor stream map.\n");
1160 			return NULL;
1161 		}
1162 
1163 		for (i = 0; i < g_config.mos->max_concurrency; i++) {
1164 			mtcp->msmap[i].monitor_stream = calloc(1, sizeof(struct mon_stream));
1165 			if (!mtcp->msmap[i].monitor_stream) {
1166 				perror("calloc");
1167 				CTRACE_ERROR("Failed to allocate memory for monitr stream map\n");
1168 				return NULL;
1169 			}
1170 		}
1171 	}
1172 
1173 	TAILQ_INIT(&mtcp->timer_list);
1174 	TAILQ_INIT(&mtcp->monitors);
1175 
1176 	TAILQ_INIT(&mtcp->free_smap);
1177 	for (i = 0; i < g_config.mos->max_concurrency; i++) {
1178 		mtcp->smap[i].id = i;
1179 		mtcp->smap[i].socktype = MOS_SOCK_UNUSED;
1180 		memset(&mtcp->smap[i].saddr, 0, sizeof(struct sockaddr_in));
1181 		mtcp->smap[i].stream = NULL;
1182 		TAILQ_INSERT_TAIL(&mtcp->free_smap, &mtcp->smap[i], link);
1183 	}
1184 
1185 	if (mon_app_exists) {
1186 		TAILQ_INIT(&mtcp->free_msmap);
1187 		for (i = 0; i < g_config.mos->max_concurrency; i++) {
1188 			mtcp->msmap[i].id = i;
1189 			mtcp->msmap[i].socktype = MOS_SOCK_UNUSED;
1190 			memset(&mtcp->msmap[i].saddr, 0, sizeof(struct sockaddr_in));
1191 			TAILQ_INSERT_TAIL(&mtcp->free_msmap, &mtcp->msmap[i], link);
1192 		}
1193 	}
1194 
1195 	mtcp->ctx = ctx;
1196 	mtcp->ep = NULL;
1197 
1198 	snprintf(log_name, MAX_FILE_NAME, "%s/"LOG_FILE_NAME"_%d",
1199 			g_config.mos->mos_log, ctx->cpu);
1200 	mtcp->log_fp = fopen(log_name, "w+");
1201 	if (!mtcp->log_fp) {
1202 		perror("fopen");
1203 		CTRACE_ERROR("Failed to create file for logging. (%s)\n", log_name);
1204 		return NULL;
1205 	}
1206 	mtcp->sp_fd = g_logctx[ctx->cpu]->pair_sp_fd;
1207 	mtcp->logger = g_logctx[ctx->cpu];
1208 
1209 	mtcp->connectq = CreateStreamQueue(BACKLOG_SIZE);
1210 	if (!mtcp->connectq) {
1211 		CTRACE_ERROR("Failed to create connect queue.\n");
1212 		return NULL;
1213 	}
1214 	mtcp->sendq = CreateStreamQueue(g_config.mos->max_concurrency);
1215 	if (!mtcp->sendq) {
1216 		CTRACE_ERROR("Failed to create send queue.\n");
1217 		return NULL;
1218 	}
1219 	mtcp->ackq = CreateStreamQueue(g_config.mos->max_concurrency);
1220 	if (!mtcp->ackq) {
1221 		CTRACE_ERROR("Failed to create ack queue.\n");
1222 		return NULL;
1223 	}
1224 	mtcp->closeq = CreateStreamQueue(g_config.mos->max_concurrency);
1225 	if (!mtcp->closeq) {
1226 		CTRACE_ERROR("Failed to create close queue.\n");
1227 		return NULL;
1228 	}
1229 	mtcp->closeq_int = CreateInternalStreamQueue(g_config.mos->max_concurrency);
1230 	if (!mtcp->closeq_int) {
1231 		CTRACE_ERROR("Failed to create close queue.\n");
1232 		return NULL;
1233 	}
1234 	mtcp->resetq = CreateStreamQueue(g_config.mos->max_concurrency);
1235 	if (!mtcp->resetq) {
1236 		CTRACE_ERROR("Failed to create reset queue.\n");
1237 		return NULL;
1238 	}
1239 	mtcp->resetq_int = CreateInternalStreamQueue(g_config.mos->max_concurrency);
1240 	if (!mtcp->resetq_int) {
1241 		CTRACE_ERROR("Failed to create reset queue.\n");
1242 		return NULL;
1243 	}
1244 	mtcp->destroyq = CreateStreamQueue(g_config.mos->max_concurrency);
1245 	if (!mtcp->destroyq) {
1246 		CTRACE_ERROR("Failed to create destroy queue.\n");
1247 		return NULL;
1248 	}
1249 
1250 	mtcp->g_sender = CreateMTCPSender(-1);
1251 	if (!mtcp->g_sender) {
1252 		CTRACE_ERROR("Failed to create global sender structure.\n");
1253 		return NULL;
1254 	}
1255 	for (i = 0; i < g_config.mos->netdev_table->num; i++) {
1256 		mtcp->n_sender[i] = CreateMTCPSender(i);
1257 		if (!mtcp->n_sender[i]) {
1258 			CTRACE_ERROR("Failed to create per-nic sender structure.\n");
1259 			return NULL;
1260 		}
1261 	}
1262 
1263 	mtcp->rto_store = InitRTOHashstore();
1264 	TAILQ_INIT(&mtcp->timewait_list);
1265 	TAILQ_INIT(&mtcp->timeout_list);
1266 
1267 	return mtcp;
1268 }
1269 /*----------------------------------------------------------------------------*/
1270 static void *
1271 MTCPRunThread(void *arg)
1272 {
1273 	mctx_t mctx = (mctx_t)arg;
1274 	int cpu = mctx->cpu;
1275 	int working;
1276 	struct mtcp_manager *mtcp;
1277 	struct mtcp_thread_context *ctx;
1278 
1279 	/* affinitize the thread to this core first */
1280 	mtcp_core_affinitize(cpu);
1281 
1282 	/* memory alloc after core affinitization would use local memory
1283 	   most time */
1284 	ctx = calloc(1, sizeof(*ctx));
1285 	if (!ctx) {
1286 		perror("calloc");
1287 		TRACE_ERROR("Failed to calloc mtcp context.\n");
1288 		exit(-1);
1289 	}
1290 	ctx->thread = pthread_self();
1291 	ctx->cpu = cpu;
1292 	mtcp = ctx->mtcp_manager = InitializeMTCPManager(ctx);
1293 	if (!mtcp) {
1294 		TRACE_ERROR("Failed to initialize mtcp manager.\n");
1295 		exit(-1);
1296 	}
1297 
1298 	/* assign mtcp context's underlying I/O module */
1299 	mtcp->iom = current_iomodule_func;
1300 
1301 	/* I/O initializing */
1302 	if (mtcp->iom->init_handle)
1303 		mtcp->iom->init_handle(ctx);
1304 
1305 	if (pthread_mutex_init(&ctx->flow_pool_lock, NULL)) {
1306 		perror("pthread_mutex_init of ctx->flow_pool_lock\n");
1307 		exit(-1);
1308 	}
1309 
1310 	if (pthread_mutex_init(&ctx->socket_pool_lock, NULL)) {
1311 		perror("pthread_mutex_init of ctx->socket_pool_lock\n");
1312 		exit(-1);
1313 	}
1314 
1315 	SQ_LOCK_INIT(&ctx->connect_lock, "ctx->connect_lock", exit(-1));
1316 	SQ_LOCK_INIT(&ctx->close_lock, "ctx->close_lock", exit(-1));
1317 	SQ_LOCK_INIT(&ctx->reset_lock, "ctx->reset_lock", exit(-1));
1318 	SQ_LOCK_INIT(&ctx->sendq_lock, "ctx->sendq_lock", exit(-1));
1319 	SQ_LOCK_INIT(&ctx->ackq_lock, "ctx->ackq_lock", exit(-1));
1320 	SQ_LOCK_INIT(&ctx->destroyq_lock, "ctx->destroyq_lock", exit(-1));
1321 
1322 	/* remember this context pointer for signal processing */
1323 	g_pctx[cpu] = ctx;
1324 	mlockall(MCL_CURRENT);
1325 
1326 	// attach (nic device, queue)
1327 	working = AttachDevice(ctx);
1328 	if (working != 0) {
1329 		sem_post(&g_init_sem[ctx->cpu]);
1330 		TRACE_DBG("MTCP thread %d finished. Not attached any device\n", ctx->cpu);
1331 		pthread_exit(NULL);
1332 	}
1333 
1334 	TRACE_DBG("CPU %d: initialization finished.\n", cpu);
1335 	sem_post(&g_init_sem[ctx->cpu]);
1336 
1337 	/* start the main loop */
1338 	RunMainLoop(ctx);
1339 
1340 	TRACE_DBG("MTCP thread %d finished.\n", ctx->cpu);
1341 
1342 	/* signaling mTCP thread is done */
1343 	sem_post(&g_done_sem[mctx->cpu]);
1344 
1345 	//pthread_exit(NULL);
1346 	return 0;
1347 }
1348 /*----------------------------------------------------------------------------*/
1349 #ifdef ENABLE_DPDK
1350 static int MTCPDPDKRunThread(void *arg)
1351 {
1352 	MTCPRunThread(arg);
1353 	return 0;
1354 }
1355 #endif /* !ENABLE_DPDK */
1356 /*----------------------------------------------------------------------------*/
1357 mctx_t
1358 mtcp_create_context(int cpu)
1359 {
1360 	mctx_t mctx;
1361 	int ret;
1362 
1363 	if (cpu >=  g_config.mos->num_cores) {
1364 		TRACE_ERROR("Failed initialize new mtcp context. "
1365 					"Requested cpu id %d exceed the number of cores %d configured to use.\n",
1366 					cpu, g_config.mos->num_cores);
1367 		return NULL;
1368 	}
1369 
1370         /* check if mtcp_create_context() was already initialized */
1371         if (g_logctx[cpu] != NULL) {
1372                 TRACE_ERROR("%s was already initialized before!\n",
1373                             __FUNCTION__);
1374                 return NULL;
1375         }
1376 
1377 	ret = sem_init(&g_init_sem[cpu], 0, 0);
1378 	if (ret) {
1379 		TRACE_ERROR("Failed initialize init_sem.\n");
1380 		return NULL;
1381 	}
1382 
1383 	ret = sem_init(&g_done_sem[cpu], 0, 0);
1384 	if (ret) {
1385 		TRACE_ERROR("Failed initialize done_sem.\n");
1386 		return NULL;
1387 	}
1388 
1389 	mctx = (mctx_t)calloc(1, sizeof(struct mtcp_context));
1390 	if (!mctx) {
1391 		TRACE_ERROR("Failed to allocate memory for mtcp_context.\n");
1392 		return NULL;
1393 	}
1394 	mctx->cpu = cpu;
1395 	g_ctx[cpu] = mctx;
1396 
1397 	/* initialize logger */
1398 	g_logctx[cpu] = (struct log_thread_context *)
1399 			calloc(1, sizeof(struct log_thread_context));
1400 	if (!g_logctx[cpu]) {
1401 		perror("malloc");
1402 		TRACE_ERROR("Failed to allocate memory for log thread context.\n");
1403 		return NULL;
1404 	}
1405 	InitLogThreadContext(g_logctx[cpu], cpu);
1406 	if (pthread_create(&log_thread[cpu],
1407 			   NULL, ThreadLogMain, (void *)g_logctx[cpu])) {
1408 		perror("pthread_create");
1409 		TRACE_ERROR("Failed to create log thread\n");
1410 		return NULL;
1411 	}
1412 
1413 #ifdef ENABLE_DPDK
1414 	/* Wake up mTCP threads (wake up I/O threads) */
1415 	if (current_iomodule_func == &dpdk_module_func) {
1416 		int master;
1417 		master = rte_get_master_lcore();
1418 		if (master == cpu) {
1419 			lcore_config[master].ret = 0;
1420 			lcore_config[master].state = FINISHED;
1421 			if (pthread_create(&g_thread[cpu],
1422 					   NULL, MTCPRunThread, (void *)mctx) != 0) {
1423 				TRACE_ERROR("pthread_create of mtcp thread failed!\n");
1424 				return NULL;
1425 			}
1426 		} else
1427 			rte_eal_remote_launch(MTCPDPDKRunThread, mctx, cpu);
1428 	} else
1429 #endif /* !ENABLE_DPDK */
1430 		{
1431 			if (pthread_create(&g_thread[cpu],
1432 					   NULL, MTCPRunThread, (void *)mctx) != 0) {
1433 				TRACE_ERROR("pthread_create of mtcp thread failed!\n");
1434 				return NULL;
1435 			}
1436 		}
1437 
1438 	sem_wait(&g_init_sem[cpu]);
1439 	sem_destroy(&g_init_sem[cpu]);
1440 
1441 	running[cpu] = TRUE;
1442 
1443 #ifdef NETSTAT
1444 #if NETSTAT_TOTAL
1445 	if (printer < 0) {
1446 		printer = cpu;
1447 		TRACE_INFO("CPU %d is in charge of printing stats.\n", printer);
1448 	}
1449 #endif
1450 #endif
1451 
1452 	return mctx;
1453 }
1454 /*----------------------------------------------------------------------------*/
1455 /**
1456  * TODO: It currently always returns 0. Add appropriate error return values
1457  */
1458 int
1459 mtcp_destroy_context(mctx_t mctx)
1460 {
1461 	struct mtcp_thread_context *ctx = g_pctx[mctx->cpu];
1462 	struct mtcp_manager *mtcp = ctx->mtcp_manager;
1463 	struct log_thread_context *log_ctx = mtcp->logger;
1464 	int ret, i;
1465 
1466 	TRACE_DBG("CPU %d: mtcp_destroy_context()\n", mctx->cpu);
1467 
1468 	/* close all stream sockets that are still open */
1469 	if (!ctx->exit) {
1470 		for (i = 0; i < g_config.mos->max_concurrency; i++) {
1471 			if (mtcp->smap[i].socktype == MOS_SOCK_STREAM) {
1472 				TRACE_DBG("Closing remaining socket %d (%s)\n",
1473 						i, TCPStateToString(mtcp->smap[i].stream));
1474 #ifdef DUMP_STREAM
1475 				DumpStream(mtcp, mtcp->smap[i].stream);
1476 #endif
1477 				mtcp_close(mctx, i);
1478 			}
1479 		}
1480 	}
1481 
1482 	ctx->done = 1;
1483 
1484 	//pthread_kill(g_thread[mctx->cpu], SIGINT);
1485 #ifdef ENABLE_DPDK
1486 	ctx->exit = 1;
1487 	/* XXX - dpdk logic changes */
1488 	if (current_iomodule_func == &dpdk_module_func) {
1489 		int master = rte_get_master_lcore();
1490 		if (master == mctx->cpu)
1491 			pthread_join(g_thread[mctx->cpu], NULL);
1492 		else
1493 			rte_eal_wait_lcore(mctx->cpu);
1494 	} else
1495 #endif /* !ENABLE_DPDK */
1496 		{
1497 			pthread_join(g_thread[mctx->cpu], NULL);
1498 		}
1499 
1500 	TRACE_INFO("MTCP thread %d joined.\n", mctx->cpu);
1501 	running[mctx->cpu] = FALSE;
1502 
1503 #ifdef NETSTAT
1504 #if NETSTAT_TOTAL
1505 	if (printer == mctx->cpu) {
1506 		for (i = 0; i < num_cpus; i++) {
1507 			if (i != mctx->cpu && running[i]) {
1508 				printer = i;
1509 				break;
1510 			}
1511 		}
1512 	}
1513 #endif
1514 #endif
1515 
1516 	log_ctx->done = 1;
1517 	ret = write(log_ctx->pair_sp_fd, "F", 1);
1518 	if (ret != 1)
1519 		TRACE_ERROR("CPU %d: Fail to signal socket pair\n", mctx->cpu);
1520 
1521 	pthread_join(log_thread[ctx->cpu], NULL);
1522 	fclose(mtcp->log_fp);
1523 	TRACE_LOG("Log thread %d joined.\n", mctx->cpu);
1524 
1525 	if (mtcp->connectq) {
1526 		DestroyStreamQueue(mtcp->connectq);
1527 		mtcp->connectq = NULL;
1528 	}
1529 	if (mtcp->sendq) {
1530 		DestroyStreamQueue(mtcp->sendq);
1531 		mtcp->sendq = NULL;
1532 	}
1533 	if (mtcp->ackq) {
1534 		DestroyStreamQueue(mtcp->ackq);
1535 		mtcp->ackq = NULL;
1536 	}
1537 	if (mtcp->closeq) {
1538 		DestroyStreamQueue(mtcp->closeq);
1539 		mtcp->closeq = NULL;
1540 	}
1541 	if (mtcp->closeq_int) {
1542 		DestroyInternalStreamQueue(mtcp->closeq_int);
1543 		mtcp->closeq_int = NULL;
1544 	}
1545 	if (mtcp->resetq) {
1546 		DestroyStreamQueue(mtcp->resetq);
1547 		mtcp->resetq = NULL;
1548 	}
1549 	if (mtcp->resetq_int) {
1550 		DestroyInternalStreamQueue(mtcp->resetq_int);
1551 		mtcp->resetq_int = NULL;
1552 	}
1553 	if (mtcp->destroyq) {
1554 		DestroyStreamQueue(mtcp->destroyq);
1555 		mtcp->destroyq = NULL;
1556 	}
1557 
1558 	DestroyMTCPSender(mtcp->g_sender);
1559 	for (i = 0; i < g_config.mos->netdev_table->num; i++) {
1560 		DestroyMTCPSender(mtcp->n_sender[i]);
1561 	}
1562 
1563 	MPDestroy(mtcp->rv_pool);
1564 	MPDestroy(mtcp->sv_pool);
1565 	MPDestroy(mtcp->flow_pool);
1566 
1567 	if (mtcp->ap) {
1568 		DestroyAddressPool(mtcp->ap);
1569 	}
1570 
1571 	SQ_LOCK_DESTROY(&ctx->connect_lock);
1572 	SQ_LOCK_DESTROY(&ctx->close_lock);
1573 	SQ_LOCK_DESTROY(&ctx->reset_lock);
1574 	SQ_LOCK_DESTROY(&ctx->sendq_lock);
1575 	SQ_LOCK_DESTROY(&ctx->ackq_lock);
1576 	SQ_LOCK_DESTROY(&ctx->destroyq_lock);
1577 
1578 	//TRACE_INFO("MTCP thread %d destroyed.\n", mctx->cpu);
1579 	if (mtcp->iom->destroy_handle)
1580 		mtcp->iom->destroy_handle(ctx);
1581 	free(ctx);
1582 	free(mctx);
1583 
1584 	return 0;
1585 }
1586 /*----------------------------------------------------------------------------*/
1587 mtcp_sighandler_t
1588 mtcp_register_signal(int signum, mtcp_sighandler_t handler)
1589 {
1590 	mtcp_sighandler_t prev;
1591 
1592 	if (signum == SIGINT) {
1593 		prev = app_signal_handler;
1594 		app_signal_handler = handler;
1595 	} else {
1596 		if ((prev = signal(signum, handler)) == SIG_ERR) {
1597 			perror("signal");
1598 			return SIG_ERR;
1599 		}
1600 	}
1601 
1602 	return prev;
1603 }
1604 /*----------------------------------------------------------------------------*/
1605 int
1606 mtcp_getconf(struct mtcp_conf *conf)
1607 {
1608 	int i, j;
1609 
1610 	if (!conf)
1611 		return -1;
1612 
1613 	conf->num_cores = g_config.mos->num_cores;
1614 	conf->max_concurrency = g_config.mos->max_concurrency;
1615 	conf->cpu_mask = g_config.mos->cpu_mask;
1616 
1617 	conf->rcvbuf_size = g_config.mos->rmem_size;
1618 	conf->sndbuf_size = g_config.mos->wmem_size;
1619 
1620 	conf->tcp_timewait = g_config.mos->tcp_tw_interval;
1621 	conf->tcp_timeout = g_config.mos->tcp_timeout;
1622 
1623 	i = 0;
1624 	struct conf_block *bwalk;
1625 	TAILQ_FOREACH(bwalk, &g_config.app_blkh, link) {
1626 		struct app_conf *app_conf = (struct app_conf *)bwalk->conf;
1627 		for (j = 0; j < app_conf->app_argc; j++)
1628 			conf->app_argv[i][j] = app_conf->app_argv[j];
1629 		conf->app_argc[i] = app_conf->app_argc;
1630 		conf->app_cpu_mask[i] = app_conf->cpu_mask;
1631 		i++;
1632 	}
1633 	conf->num_app = i;
1634 
1635 	return 0;
1636 }
1637 /*----------------------------------------------------------------------------*/
1638 int
1639 mtcp_setconf(const struct mtcp_conf *conf)
1640 {
1641 	if (!conf)
1642 		return -1;
1643 
1644 	g_config.mos->num_cores = conf->num_cores;
1645 	g_config.mos->max_concurrency = conf->max_concurrency;
1646 
1647 	g_config.mos->rmem_size = conf->rcvbuf_size;
1648 	g_config.mos->wmem_size = conf->sndbuf_size;
1649 
1650 	g_config.mos->tcp_tw_interval = conf->tcp_timewait;
1651 	g_config.mos->tcp_timeout = conf->tcp_timeout;
1652 
1653 	TRACE_CONFIG("Configuration updated by mtcp_setconf().\n");
1654 	//PrintConfiguration();
1655 
1656 	return 0;
1657 }
1658 /*----------------------------------------------------------------------------*/
1659 int
1660 mtcp_init(const char *config_file)
1661 {
1662 	int i;
1663 	int ret;
1664 
1665 	if (geteuid()) {
1666 		TRACE_CONFIG("[CAUTION] Run as root if mlock is necessary.\n");
1667 #if defined(ENABLE_DPDK) || defined(ENABLE_DPDKR) || defined(ENABLE_NETMAP)
1668 		TRACE_CONFIG("[CAUTION] Run the app as root!\n");
1669 		exit(EXIT_FAILURE);
1670 #endif
1671 	}
1672 
1673 	/* getting cpu and NIC */
1674 	num_cpus = GetNumCPUs();
1675 	assert(num_cpus >= 1);
1676 	for (i = 0; i < num_cpus; i++) {
1677 		g_mtcp[i] = NULL;
1678 		running[i] = FALSE;
1679 		sigint_cnt[i] = 0;
1680 	}
1681 
1682 	ret = LoadConfigurationUpperHalf(config_file);
1683 	if (ret) {
1684 		TRACE_CONFIG("Error occured while loading configuration.\n");
1685 		return -1;
1686 	}
1687 
1688 #if defined(ENABLE_PSIO)
1689 	current_iomodule_func = &ps_module_func;
1690 #elif defined(ENABLE_DPDK)
1691 	current_iomodule_func = &dpdk_module_func;
1692 #elif defined(ENABLE_PCAP)
1693 	current_iomodule_func = &pcap_module_func;
1694 #elif defined(ENABLE_DPDKR)
1695 	current_iomodule_func = &dpdkr_module_func;
1696 #elif defined(ENABLE_NETMAP)
1697 	current_iomodule_func = &netmap_module_func;
1698 #endif
1699 
1700 	if (current_iomodule_func->load_module_upper_half)
1701 		current_iomodule_func->load_module_upper_half();
1702 
1703 	LoadConfigurationLowerHalf();
1704 
1705 	//PrintConfiguration();
1706 
1707 	for (i = 0; i < g_config.mos->netdev_table->num; i++) {
1708 		ap[i] = CreateAddressPool(g_config.mos->netdev_table->ent[i]->ip_addr, 1);
1709 		if (!ap[i]) {
1710 			TRACE_CONFIG("Error occured while create address pool[%d]\n",
1711 				     i);
1712 			return -1;
1713 		}
1714         }
1715 
1716 	//PrintInterfaceInfo();
1717 	//PrintRoutingTable();
1718 	//PrintARPTable();
1719 	InitARPTable();
1720 
1721 	if (signal(SIGUSR1, HandleSignal) == SIG_ERR) {
1722 		perror("signal, SIGUSR1");
1723 		return -1;
1724 	}
1725 	if (signal(SIGINT, HandleSignal) == SIG_ERR) {
1726 		perror("signal, SIGINT");
1727 		return -1;
1728 	}
1729 	app_signal_handler = NULL;
1730 
1731 	printf("load_module(): %p\n", current_iomodule_func);
1732 	/* load system-wide io module specs */
1733 	if (current_iomodule_func->load_module_lower_half)
1734 		current_iomodule_func->load_module_lower_half();
1735 
1736 	GlobInitEvent();
1737 
1738 	PrintConf(&g_config);
1739 
1740 	return 0;
1741 }
1742 /*----------------------------------------------------------------------------*/
1743 int
1744 mtcp_destroy()
1745 {
1746 	int i;
1747 
1748 	/* wait until all threads are closed */
1749 	for (i = 0; i < num_cpus; i++) {
1750 		if (running[i]) {
1751 			if (pthread_join(g_thread[i], NULL) != 0)
1752 				return -1;
1753 		}
1754 	}
1755 
1756 	for (i = 0; i < g_config.mos->netdev_table->num; i++)
1757 		DestroyAddressPool(ap[i]);
1758 
1759 	TRACE_INFO("All MTCP threads are joined.\n");
1760 
1761 	return 0;
1762 }
1763 /*----------------------------------------------------------------------------*/
1764