netmgr.c 35.2 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/*
 * Copyright (C) Internet Systems Consortium, Inc. ("ISC")
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * See the COPYRIGHT file distributed with this work for additional
 * information regarding copyright ownership.
 */

#include <inttypes.h>
#include <unistd.h>
#include <uv.h>

#include <isc/atomic.h>
#include <isc/buffer.h>
#include <isc/condition.h>
#include <isc/magic.h>
#include <isc/mem.h>
#include <isc/netmgr.h>
#include <isc/print.h>
23
#include <isc/quota.h>
24
25
26
27
28
#include <isc/random.h>
#include <isc/refcount.h>
#include <isc/region.h>
#include <isc/result.h>
#include <isc/sockaddr.h>
29
#include <isc/stats.h>
30
31
32
33
#include <isc/thread.h>
#include <isc/util.h>

#include "netmgr-int.h"
34
#include "uv-compat.h"
35

36
37
38
39
40
41
42
/*%
 * How many isc_nmhandles and isc_nm_uvreqs will we be
 * caching for reuse in a socket.
 */
#define ISC_NM_HANDLES_STACK_SIZE 600
#define ISC_NM_REQS_STACK_SIZE	  600

43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
/*%
 * Shortcut index arrays to get access to statistics counters.
 */

static const isc_statscounter_t udp4statsindex[] = {
	isc_sockstatscounter_udp4open,
	isc_sockstatscounter_udp4openfail,
	isc_sockstatscounter_udp4close,
	isc_sockstatscounter_udp4bindfail,
	isc_sockstatscounter_udp4connectfail,
	isc_sockstatscounter_udp4connect,
	-1,
	-1,
	isc_sockstatscounter_udp4sendfail,
	isc_sockstatscounter_udp4recvfail,
	isc_sockstatscounter_udp4active
};

static const isc_statscounter_t udp6statsindex[] = {
	isc_sockstatscounter_udp6open,
	isc_sockstatscounter_udp6openfail,
	isc_sockstatscounter_udp6close,
	isc_sockstatscounter_udp6bindfail,
	isc_sockstatscounter_udp6connectfail,
	isc_sockstatscounter_udp6connect,
	-1,
	-1,
	isc_sockstatscounter_udp6sendfail,
	isc_sockstatscounter_udp6recvfail,
	isc_sockstatscounter_udp6active
};

static const isc_statscounter_t tcp4statsindex[] = {
76
77
78
79
80
	isc_sockstatscounter_tcp4open,	      isc_sockstatscounter_tcp4openfail,
	isc_sockstatscounter_tcp4close,	      isc_sockstatscounter_tcp4bindfail,
	isc_sockstatscounter_tcp4connectfail, isc_sockstatscounter_tcp4connect,
	isc_sockstatscounter_tcp4acceptfail,  isc_sockstatscounter_tcp4accept,
	isc_sockstatscounter_tcp4sendfail,    isc_sockstatscounter_tcp4recvfail,
81
82
83
84
	isc_sockstatscounter_tcp4active
};

static const isc_statscounter_t tcp6statsindex[] = {
85
86
87
88
89
	isc_sockstatscounter_tcp6open,	      isc_sockstatscounter_tcp6openfail,
	isc_sockstatscounter_tcp6close,	      isc_sockstatscounter_tcp6bindfail,
	isc_sockstatscounter_tcp6connectfail, isc_sockstatscounter_tcp6connect,
	isc_sockstatscounter_tcp6acceptfail,  isc_sockstatscounter_tcp6accept,
	isc_sockstatscounter_tcp6sendfail,    isc_sockstatscounter_tcp6recvfail,
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
	isc_sockstatscounter_tcp6active
};

#if 0
/* XXX: not currently used */
static const isc_statscounter_t unixstatsindex[] = {
	isc_sockstatscounter_unixopen,
	isc_sockstatscounter_unixopenfail,
	isc_sockstatscounter_unixclose,
	isc_sockstatscounter_unixbindfail,
	isc_sockstatscounter_unixconnectfail,
	isc_sockstatscounter_unixconnect,
	isc_sockstatscounter_unixacceptfail,
	isc_sockstatscounter_unixaccept,
	isc_sockstatscounter_unixsendfail,
	isc_sockstatscounter_unixrecvfail,
	isc_sockstatscounter_unixactive
};
108
#endif /* if 0 */
109

110
111
112
113
114
115
116
117
118
/*
 * libuv is not thread safe, but has mechanisms to pass messages
 * between threads. Each socket is owned by a thread. For UDP
 * sockets we have a set of sockets for each interface and we can
 * choose a sibling and send the message directly. For TCP, or if
 * we're calling from a non-networking thread, we need to pass the
 * request using async_cb.
 */

119
static thread_local int isc__nm_tid_v = ISC_NETMGR_TID_UNKNOWN;
120

Ondřej Surý's avatar
Ondřej Surý committed
121
122
123
124
125
126
127
128
129
130
static void
nmsocket_maybe_destroy(isc_nmsocket_t *sock);
static void
nmhandle_free(isc_nmsocket_t *sock, isc_nmhandle_t *handle);
static isc_threadresult_t
nm_thread(isc_threadarg_t worker0);
static void
async_cb(uv_async_t *handle);
static void
process_queue(isc__networker_t *worker, isc_queue_t *queue);
131
132

int
133
isc_nm_tid(void) {
134
135
136
137
	return (isc__nm_tid_v);
}

bool
138
isc__nm_in_netthread(void) {
139
140
141
142
	return (isc__nm_tid_v >= 0);
}

isc_nm_t *
Evan Hunt's avatar
Evan Hunt committed
143
isc_nm_start(isc_mem_t *mctx, uint32_t workers) {
144
	isc_nm_t *mgr = NULL;
Evan Hunt's avatar
Evan Hunt committed
145
	char name[32];
146
147

	mgr = isc_mem_get(mctx, sizeof(*mgr));
148
	*mgr = (isc_nm_t){ .nworkers = workers };
149
150
151
152
153
154
155
156
157
158
159

	isc_mem_attach(mctx, &mgr->mctx);
	isc_mutex_init(&mgr->lock);
	isc_condition_init(&mgr->wkstatecond);
	isc_refcount_init(&mgr->references, 1);
	atomic_init(&mgr->workers_running, 0);
	atomic_init(&mgr->workers_paused, 0);
	atomic_init(&mgr->maxudp, 0);
	atomic_init(&mgr->paused, false);
	atomic_init(&mgr->interlocked, false);

160
161
	/*
	 * Default TCP timeout values.
Evan Hunt's avatar
Evan Hunt committed
162
	 * May be updated by isc_nm_tcptimeouts().
163
164
165
166
167
168
	 */
	mgr->init = 30000;
	mgr->idle = 30000;
	mgr->keepalive = 30000;
	mgr->advertised = 30000;

Evan Hunt's avatar
Evan Hunt committed
169
170
171
	isc_mutex_init(&mgr->reqlock);
	isc_mempool_create(mgr->mctx, sizeof(isc__nm_uvreq_t), &mgr->reqpool);
	isc_mempool_setname(mgr->reqpool, "nm_reqpool");
172
	isc_mempool_setfreemax(mgr->reqpool, 4096);
Evan Hunt's avatar
Evan Hunt committed
173
174
175
176
177
178
179
	isc_mempool_associatelock(mgr->reqpool, &mgr->reqlock);
	isc_mempool_setfillcount(mgr->reqpool, 32);

	isc_mutex_init(&mgr->evlock);
	isc_mempool_create(mgr->mctx, sizeof(isc__netievent_storage_t),
			   &mgr->evpool);
	isc_mempool_setname(mgr->evpool, "nm_evpool");
180
	isc_mempool_setfreemax(mgr->evpool, 4096);
Evan Hunt's avatar
Evan Hunt committed
181
182
183
	isc_mempool_associatelock(mgr->evpool, &mgr->evlock);
	isc_mempool_setfillcount(mgr->evpool, 32);

184
185
	mgr->workers = isc_mem_get(mctx, workers * sizeof(isc__networker_t));
	for (size_t i = 0; i < workers; i++) {
Evan Hunt's avatar
Evan Hunt committed
186
		int r;
187
		isc__networker_t *worker = &mgr->workers[i];
188
		*worker = (isc__networker_t){
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
			.mgr = mgr,
			.id = i,
		};

		r = uv_loop_init(&worker->loop);
		RUNTIME_CHECK(r == 0);

		worker->loop.data = &mgr->workers[i];

		r = uv_async_init(&worker->loop, &worker->async, async_cb);
		RUNTIME_CHECK(r == 0);

		isc_mutex_init(&worker->lock);
		isc_condition_init(&worker->cond);

		worker->ievents = isc_queue_new(mgr->mctx, 128);
205
		worker->ievents_prio = isc_queue_new(mgr->mctx, 128);
206
		worker->recvbuf = isc_mem_get(mctx, ISC_NETMGR_RECVBUF_SIZE);
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228

		/*
		 * We need to do this here and not in nm_thread to avoid a
		 * race - we could exit isc_nm_start, launch nm_destroy,
		 * and nm_thread would still not be up.
		 */
		atomic_fetch_add_explicit(&mgr->workers_running, 1,
					  memory_order_relaxed);
		isc_thread_create(nm_thread, &mgr->workers[i], &worker->thread);

		snprintf(name, sizeof(name), "isc-net-%04zu", i);
		isc_thread_setname(worker->thread, name);
	}

	mgr->magic = NM_MAGIC;
	return (mgr);
}

/*
 * Free the resources of the network manager.
 */
static void
Evan Hunt's avatar
Evan Hunt committed
229
nm_destroy(isc_nm_t **mgr0) {
230
231
232
233
	REQUIRE(VALID_NM(*mgr0));
	REQUIRE(!isc__nm_in_netthread());

	isc_nm_t *mgr = *mgr0;
234
	*mgr0 = NULL;
235

236
237
	isc_refcount_destroy(&mgr->references);

238
239
240
241
242
243
244
245
246
247
248
249
	mgr->magic = 0;

	for (size_t i = 0; i < mgr->nworkers; i++) {
		isc__netievent_t *event = NULL;

		LOCK(&mgr->workers[i].lock);
		mgr->workers[i].finished = true;
		UNLOCK(&mgr->workers[i].lock);
		event = isc__nm_get_ievent(mgr, netievent_stop);
		isc__nm_enqueue_ievent(&mgr->workers[i], event);
	}

Mark Andrews's avatar
Mark Andrews committed
250
	LOCK(&mgr->lock);
251
252
253
254
255
256
	while (atomic_load(&mgr->workers_running) > 0) {
		WAIT(&mgr->wkstatecond, &mgr->lock);
	}
	UNLOCK(&mgr->lock);

	for (size_t i = 0; i < mgr->nworkers; i++) {
257
		isc__networker_t *worker = &mgr->workers[i];
Evan Hunt's avatar
Evan Hunt committed
258
		isc__netievent_t *ievent = NULL;
Evan Hunt's avatar
Evan Hunt committed
259
		int r;
Evan Hunt's avatar
Evan Hunt committed
260
261

		/* Empty the async event queues */
262
		while ((ievent = (isc__netievent_t *)isc_queue_dequeue(
Evan Hunt's avatar
Evan Hunt committed
263
264
				worker->ievents)) != NULL)
		{
265
266
			isc_mempool_put(mgr->evpool, ievent);
		}
Evan Hunt's avatar
Evan Hunt committed
267

268
		while ((ievent = (isc__netievent_t *)isc_queue_dequeue(
Evan Hunt's avatar
Evan Hunt committed
269
270
				worker->ievents_prio)) != NULL)
		{
Evan Hunt's avatar
Evan Hunt committed
271
			isc_mempool_put(mgr->evpool, ievent);
272
		}
Evan Hunt's avatar
Evan Hunt committed
273
274

		r = uv_loop_close(&worker->loop);
275
		INSIST(r == 0);
Evan Hunt's avatar
Evan Hunt committed
276

277
278
		isc_queue_destroy(worker->ievents);
		isc_queue_destroy(worker->ievents_prio);
279
280
281
		isc_mutex_destroy(&worker->lock);
		isc_condition_destroy(&worker->cond);

282
283
		isc_mem_put(mgr->mctx, worker->recvbuf,
			    ISC_NETMGR_RECVBUF_SIZE);
284
		isc_thread_join(worker->thread, NULL);
285
286
	}

287
288
289
290
	if (mgr->stats != NULL) {
		isc_stats_detach(&mgr->stats);
	}

291
292
	isc_condition_destroy(&mgr->wkstatecond);
	isc_mutex_destroy(&mgr->lock);
Evan Hunt's avatar
Evan Hunt committed
293
294
295
296
297
298
299

	isc_mempool_destroy(&mgr->evpool);
	isc_mutex_destroy(&mgr->evlock);

	isc_mempool_destroy(&mgr->reqpool);
	isc_mutex_destroy(&mgr->reqlock);

300
301
302
303
304
305
	isc_mem_put(mgr->mctx, mgr->workers,
		    mgr->nworkers * sizeof(isc__networker_t));
	isc_mem_putanddetach(&mgr->mctx, mgr, sizeof(*mgr));
}

void
Evan Hunt's avatar
Evan Hunt committed
306
isc_nm_pause(isc_nm_t *mgr) {
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
	REQUIRE(VALID_NM(mgr));
	REQUIRE(!isc__nm_in_netthread());

	atomic_store(&mgr->paused, true);
	isc__nm_acquire_interlocked_force(mgr);

	for (size_t i = 0; i < mgr->nworkers; i++) {
		isc__netievent_t *event = NULL;

		LOCK(&mgr->workers[i].lock);
		mgr->workers[i].paused = true;
		UNLOCK(&mgr->workers[i].lock);

		/*
		 * We have to issue a stop, otherwise the uv_run loop will
		 * run indefinitely!
		 */
		event = isc__nm_get_ievent(mgr, netievent_stop);
		isc__nm_enqueue_ievent(&mgr->workers[i], event);
	}

	LOCK(&mgr->lock);
	while (atomic_load_relaxed(&mgr->workers_paused) !=
Evan Hunt's avatar
Evan Hunt committed
330
331
	       atomic_load_relaxed(&mgr->workers_running))
	{
332
333
334
335
336
337
		WAIT(&mgr->wkstatecond, &mgr->lock);
	}
	UNLOCK(&mgr->lock);
}

void
Evan Hunt's avatar
Evan Hunt committed
338
isc_nm_resume(isc_nm_t *mgr) {
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
	REQUIRE(VALID_NM(mgr));
	REQUIRE(!isc__nm_in_netthread());

	for (size_t i = 0; i < mgr->nworkers; i++) {
		LOCK(&mgr->workers[i].lock);
		mgr->workers[i].paused = false;
		SIGNAL(&mgr->workers[i].cond);
		UNLOCK(&mgr->workers[i].lock);
	}
	isc__nm_drop_interlocked(mgr);

	/*
	 * We're not waiting for all the workers to come back to life;
	 * they eventually will, we don't care.
	 */
}

void
Evan Hunt's avatar
Evan Hunt committed
357
isc_nm_attach(isc_nm_t *mgr, isc_nm_t **dst) {
358
359
360
	REQUIRE(VALID_NM(mgr));
	REQUIRE(dst != NULL && *dst == NULL);

361
	isc_refcount_increment(&mgr->references);
362
363
364
365
366

	*dst = mgr;
}

void
Evan Hunt's avatar
Evan Hunt committed
367
isc_nm_detach(isc_nm_t **mgr0) {
368
369
370
371
372
373
374
375
	isc_nm_t *mgr = NULL;

	REQUIRE(mgr0 != NULL);
	REQUIRE(VALID_NM(*mgr0));

	mgr = *mgr0;
	*mgr0 = NULL;

376
	if (isc_refcount_decrement(&mgr->references) == 1) {
377
378
379
380
		nm_destroy(&mgr);
	}
}

Evan Hunt's avatar
Evan Hunt committed
381
void
Evan Hunt's avatar
Evan Hunt committed
382
isc_nm_closedown(isc_nm_t *mgr) {
Evan Hunt's avatar
Evan Hunt committed
383
384
385
386
387
388
389
390
391
	REQUIRE(VALID_NM(mgr));

	atomic_store(&mgr->closing, true);
	for (size_t i = 0; i < mgr->nworkers; i++) {
		isc__netievent_t *event = NULL;
		event = isc__nm_get_ievent(mgr, netievent_shutdown);
		isc__nm_enqueue_ievent(&mgr->workers[i], event);
	}
}
392
393

void
Evan Hunt's avatar
Evan Hunt committed
394
isc_nm_destroy(isc_nm_t **mgr0) {
395
396
397
398
399
400
401
	isc_nm_t *mgr = NULL;

	REQUIRE(mgr0 != NULL);
	REQUIRE(VALID_NM(*mgr0));

	mgr = *mgr0;

Evan Hunt's avatar
Evan Hunt committed
402
403
404
405
	/*
	 * Close active connections.
	 */
	isc_nm_closedown(mgr);
406

407
	/*
Evan Hunt's avatar
Evan Hunt committed
408
	 * Wait for the manager to be dereferenced elsewhere.
409
410
	 */
	while (isc_refcount_current(&mgr->references) > 1) {
411
412
413
414
415
416
417
418
		/*
		 * Sometimes libuv gets stuck, pausing and unpausing
		 * netmgr goes over all events in async queue for all
		 * the workers, and since it's done only on shutdown it
		 * doesn't cost us anything.
		 */
		isc_nm_pause(mgr);
		isc_nm_resume(mgr);
419
#ifdef WIN32
420
		_sleep(10);
421
#else  /* ifdef WIN32 */
422
		usleep(10000);
423
#endif /* ifdef WIN32 */
424
	}
Evan Hunt's avatar
Evan Hunt committed
425
426
427
428
429

	/*
	 * Detach final reference.
	 */
	isc_nm_detach(mgr0);
430
431
432
}

void
Evan Hunt's avatar
Evan Hunt committed
433
isc_nm_maxudp(isc_nm_t *mgr, uint32_t maxudp) {
434
435
436
437
438
	REQUIRE(VALID_NM(mgr));

	atomic_store(&mgr->maxudp, maxudp);
}

439
440
void
isc_nm_tcp_settimeouts(isc_nm_t *mgr, uint32_t init, uint32_t idle,
Evan Hunt's avatar
Evan Hunt committed
441
		       uint32_t keepalive, uint32_t advertised) {
442
443
444
445
446
447
448
449
450
451
	REQUIRE(VALID_NM(mgr));

	mgr->init = init * 100;
	mgr->idle = idle * 100;
	mgr->keepalive = keepalive * 100;
	mgr->advertised = advertised * 100;
}

void
isc_nm_tcp_gettimeouts(isc_nm_t *mgr, uint32_t *initial, uint32_t *idle,
Evan Hunt's avatar
Evan Hunt committed
452
		       uint32_t *keepalive, uint32_t *advertised) {
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
	REQUIRE(VALID_NM(mgr));

	if (initial != NULL) {
		*initial = mgr->init / 100;
	}

	if (idle != NULL) {
		*idle = mgr->idle / 100;
	}

	if (keepalive != NULL) {
		*keepalive = mgr->keepalive / 100;
	}

	if (advertised != NULL) {
		*advertised = mgr->advertised / 100;
	}
}

472
473
474
475
/*
 * nm_thread is a single worker thread, that runs uv_run event loop
 * until asked to stop.
 */
476
static isc_threadresult_t
Evan Hunt's avatar
Evan Hunt committed
477
nm_thread(isc_threadarg_t worker0) {
478
	isc__networker_t *worker = (isc__networker_t *)worker0;
479
480
481
482
483

	isc__nm_tid_v = worker->id;
	isc_thread_setaffinity(isc__nm_tid_v);

	while (true) {
Evan Hunt's avatar
Evan Hunt committed
484
		int r = uv_run(&worker->loop, UV_RUN_DEFAULT);
485
486
487
488
489
490
491
492
493
494
495
		bool pausing = false;

		/*
		 * or there's nothing to do. In the first case - wait
		 * for condition. In the latter - timedwait
		 */
		LOCK(&worker->lock);
		while (worker->paused) {
			LOCK(&worker->mgr->lock);
			if (!pausing) {
				atomic_fetch_add_explicit(
496
497
					&worker->mgr->workers_paused, 1,
					memory_order_acquire);
498
499
500
501
502
503
504
				pausing = true;
			}

			SIGNAL(&worker->mgr->wkstatecond);
			UNLOCK(&worker->mgr->lock);

			WAIT(&worker->cond, &worker->lock);
505
506
507

			/* Process priority events */
			process_queue(worker, worker->ievents_prio);
508
509
510
		}
		if (pausing) {
			uint32_t wp = atomic_fetch_sub_explicit(
511
512
				&worker->mgr->workers_paused, 1,
				memory_order_release);
513
514
515
516
			if (wp == 1) {
				atomic_store(&worker->mgr->paused, false);
			}
		}
517
		bool finished = worker->finished;
518
519
		UNLOCK(&worker->lock);

520
		if (finished) {
521
522
			/*
			 * We need to launch the loop one more time
Evan Hunt's avatar
Evan Hunt committed
523
524
525
526
527
528
529
530
			 * in UV_RUN_NOWAIT mode to make sure that
			 * worker->async is closed, so that we can
			 * close the loop cleanly.  We don't care
			 * about the callback, as in this case we can
			 * be certain that uv_run() will eat the event.
			 *
			 * XXX: We may need to take steps here to ensure
			 * that all netmgr handles are freed.
531
532
533
			 */
			uv_close((uv_handle_t *)&worker->async, NULL);
			uv_run(&worker->loop, UV_RUN_NOWAIT);
534
535
536
537
538
			break;
		}

		if (r == 0) {
			/*
Evan Hunt's avatar
Evan Hunt committed
539
540
541
			 * XXX: uv_run() in UV_RUN_DEFAULT mode returns
			 * zero if there are still active uv_handles.
			 * This shouldn't happen, but if it does, we just
Evan Hunt's avatar
Evan Hunt committed
542
			 * keep checking until they're done. We nap for a
Evan Hunt's avatar
Evan Hunt committed
543
544
545
			 * tenth of a second on each loop so as not to burn
			 * CPU. (We do a conditional wait instead, but it
			 * seems like overkill for this case.)
546
547
548
			 */
#ifdef WIN32
			_sleep(100);
549
#else  /* ifdef WIN32 */
550
			usleep(100000);
551
#endif /* ifdef WIN32 */
552
553
554
555
556
		}

		/*
		 * Empty the async queue.
		 */
557
558
		process_queue(worker, worker->ievents_prio);
		process_queue(worker, worker->ievents);
559
560
561
562
563
564
565
	}

	LOCK(&worker->mgr->lock);
	atomic_fetch_sub_explicit(&worker->mgr->workers_running, 1,
				  memory_order_relaxed);
	SIGNAL(&worker->mgr->wkstatecond);
	UNLOCK(&worker->mgr->lock);
566
567

	return ((isc_threadresult_t)0);
568
569
570
}

/*
Evan Hunt's avatar
Evan Hunt committed
571
572
573
574
 * async_cb is a universal callback for 'async' events sent to event loop.
 * It's the only way to safely pass data to the libuv event loop. We use a
 * single async event and a lockless queue of 'isc__netievent_t' structures
 * passed from other threads.
575
576
 */
static void
Evan Hunt's avatar
Evan Hunt committed
577
async_cb(uv_async_t *handle) {
578
	isc__networker_t *worker = (isc__networker_t *)handle->loop->data;
579
580
581
582
583
	process_queue(worker, worker->ievents_prio);
	process_queue(worker, worker->ievents);
}

static void
Evan Hunt's avatar
Evan Hunt committed
584
process_queue(isc__networker_t *worker, isc_queue_t *queue) {
Evan Hunt's avatar
Evan Hunt committed
585
	isc__netievent_t *ievent = NULL;
586

Evan Hunt's avatar
Evan Hunt committed
587
588
	while ((ievent = (isc__netievent_t *)isc_queue_dequeue(queue)) != NULL)
	{
589
590
		switch (ievent->type) {
		case netievent_stop:
591
			uv_stop(&worker->loop);
Evan Hunt's avatar
Evan Hunt committed
592
			isc_mempool_put(worker->mgr->evpool, ievent);
593
594
595
596
			return;
		case netievent_udplisten:
			isc__nm_async_udplisten(worker, ievent);
			break;
Evan Hunt's avatar
Evan Hunt committed
597
598
		case netievent_udpstop:
			isc__nm_async_udpstop(worker, ievent);
599
600
601
602
603
604
605
606
607
608
			break;
		case netievent_udpsend:
			isc__nm_async_udpsend(worker, ievent);
			break;
		case netievent_tcpconnect:
			isc__nm_async_tcpconnect(worker, ievent);
			break;
		case netievent_tcplisten:
			isc__nm_async_tcplisten(worker, ievent);
			break;
609
610
611
612
613
		case netievent_tcpchildaccept:
			isc__nm_async_tcpchildaccept(worker, ievent);
			break;
		case netievent_tcpaccept:
			isc__nm_async_tcpaccept(worker, ievent);
614
			break;
615
		case netievent_tcpstartread:
616
			isc__nm_async_tcp_startread(worker, ievent);
617
618
			break;
		case netievent_tcppauseread:
619
			isc__nm_async_tcp_pauseread(worker, ievent);
620
621
622
623
			break;
		case netievent_tcpsend:
			isc__nm_async_tcpsend(worker, ievent);
			break;
Evan Hunt's avatar
Evan Hunt committed
624
625
		case netievent_tcpstop:
			isc__nm_async_tcpstop(worker, ievent);
626
627
628
629
			break;
		case netievent_tcpclose:
			isc__nm_async_tcpclose(worker, ievent);
			break;
630
631
632
		case netievent_tcpdnsclose:
			isc__nm_async_tcpdnsclose(worker, ievent);
			break;
Witold Kręcicki's avatar
Witold Kręcicki committed
633
634
635
		case netievent_closecb:
			isc__nm_async_closecb(worker, ievent);
			break;
636
637
638
		case netievent_shutdown:
			isc__nm_async_shutdown(worker, ievent);
			break;
639
640
641
642
		default:
			INSIST(0);
			ISC_UNREACHABLE();
		}
Witold Kręcicki's avatar
Witold Kręcicki committed
643
644

		isc__nm_put_ievent(worker->mgr, ievent);
645
646
647
648
	}
}

void *
Evan Hunt's avatar
Evan Hunt committed
649
isc__nm_get_ievent(isc_nm_t *mgr, isc__netievent_type type) {
Evan Hunt's avatar
Evan Hunt committed
650
	isc__netievent_storage_t *event = isc_mempool_get(mgr->evpool);
651

652
	*event = (isc__netievent_storage_t){ .ni.type = type };
653
654
655
	return (event);
}

Witold Kręcicki's avatar
Witold Kręcicki committed
656
void
Evan Hunt's avatar
Evan Hunt committed
657
isc__nm_put_ievent(isc_nm_t *mgr, void *ievent) {
Evan Hunt's avatar
Evan Hunt committed
658
	isc_mempool_put(mgr->evpool, ievent);
Witold Kręcicki's avatar
Witold Kręcicki committed
659
660
}

661
void
Evan Hunt's avatar
Evan Hunt committed
662
isc__nm_enqueue_ievent(isc__networker_t *worker, isc__netievent_t *event) {
663
664
665
666
667
668
669
670
671
672
673
674
	if (event->type > netievent_prio) {
		/*
		 * We need to make sure this signal will be delivered and
		 * the queue will be processed.
		 */
		LOCK(&worker->lock);
		isc_queue_enqueue(worker->ievents_prio, (uintptr_t)event);
		SIGNAL(&worker->cond);
		UNLOCK(&worker->lock);
	} else {
		isc_queue_enqueue(worker->ievents, (uintptr_t)event);
	}
675
676
677
	uv_async_send(&worker->async);
}

678
bool
Evan Hunt's avatar
Evan Hunt committed
679
isc__nmsocket_active(isc_nmsocket_t *sock) {
680
681
682
683
684
685
686
687
688
	REQUIRE(VALID_NMSOCK(sock));
	if (sock->parent != NULL) {
		return (atomic_load(&sock->parent->active));
	}

	return (atomic_load(&sock->active));
}

void
689
isc__nmsocket_attach(isc_nmsocket_t *sock, isc_nmsocket_t **target) {
690
691
692
693
694
	REQUIRE(VALID_NMSOCK(sock));
	REQUIRE(target != NULL && *target == NULL);

	if (sock->parent != NULL) {
		INSIST(sock->parent->parent == NULL); /* sanity check */
695
		isc_refcount_increment0(&sock->parent->references);
696
	} else {
697
		isc_refcount_increment0(&sock->references);
698
699
700
701
702
703
704
705
706
	}

	*target = sock;
}

/*
 * Free all resources inside a socket (including its children if any).
 */
static void
Evan Hunt's avatar
Evan Hunt committed
707
708
nmsocket_cleanup(isc_nmsocket_t *sock, bool dofree) {
	isc_nmhandle_t *handle = NULL;
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
	isc__nm_uvreq_t *uvreq = NULL;

	REQUIRE(VALID_NMSOCK(sock));
	REQUIRE(!isc__nmsocket_active(sock));

	atomic_store(&sock->destroying, true);

	if (sock->parent == NULL && sock->children != NULL) {
		/*
		 * We shouldn't be here unless there are no active handles,
		 * so we can clean up and free the children.
		 */
		for (int i = 0; i < sock->nchildren; i++) {
			if (!atomic_load(&sock->children[i].destroying)) {
				nmsocket_cleanup(&sock->children[i], false);
			}
		}

		/*
		 * This was a parent socket; free the children.
		 */
		isc_mem_put(sock->mgr->mctx, sock->children,
			    sock->nchildren * sizeof(*sock));
		sock->children = NULL;
		sock->nchildren = 0;
	}
735
	if (sock->statsindex != NULL) {
736
		isc__nm_decstats(sock->mgr, sock->statsindex[STATID_ACTIVE]);
737
	}
738

739
740
741
742
743
744
745
746
747
	sock->tcphandle = NULL;

	if (sock->outerhandle != NULL) {
		isc_nmhandle_unref(sock->outerhandle);
		sock->outerhandle = NULL;
	}

	if (sock->outer != NULL) {
		isc__nmsocket_detach(&sock->outer);
748
749
750
751
752
753
754
	}

	while ((handle = isc_astack_pop(sock->inactivehandles)) != NULL) {
		nmhandle_free(sock, handle);
	}

	if (sock->buf != NULL) {
755
		isc_mem_free(sock->mgr->mctx, sock->buf);
756
757
758
759
760
761
	}

	if (sock->quota != NULL) {
		isc_quota_detach(&sock->quota);
	}

762
763
	sock->pquota = NULL;

Witold Kręcicki's avatar
Witold Kręcicki committed
764
765
	if (sock->timer_initialized) {
		sock->timer_initialized = false;
766
		/* We might be in timer callback */
767
		if (!uv_is_closing((uv_handle_t *)&sock->timer)) {
768
769
770
			uv_timer_stop(&sock->timer);
			uv_close((uv_handle_t *)&sock->timer, NULL);
		}
Witold Kręcicki's avatar
Witold Kręcicki committed
771
772
	}

773
774
775
	isc_astack_destroy(sock->inactivehandles);

	while ((uvreq = isc_astack_pop(sock->inactivereqs)) != NULL) {
Evan Hunt's avatar
Evan Hunt committed
776
		isc_mempool_put(sock->mgr->reqpool, uvreq);
777
778
779
	}

	isc_astack_destroy(sock->inactivereqs);
780
	sock->magic = 0;
781
782
783

	isc_mem_free(sock->mgr->mctx, sock->ah_frees);
	isc_mem_free(sock->mgr->mctx, sock->ah_handles);
784
785
	isc_mutex_destroy(&sock->lock);
	isc_condition_destroy(&sock->cond);
786
787
788
789
790
791
792
793
794
795
796

	if (dofree) {
		isc_nm_t *mgr = sock->mgr;
		isc_mem_put(mgr->mctx, sock, sizeof(*sock));
		isc_nm_detach(&mgr);
	} else {
		isc_nm_detach(&sock->mgr);
	}
}

static void
Evan Hunt's avatar
Evan Hunt committed
797
798
nmsocket_maybe_destroy(isc_nmsocket_t *sock) {
	int active_handles;
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
	bool destroy = false;

	if (sock->parent != NULL) {
		/*
		 * This is a child socket and cannot be destroyed except
		 * as a side effect of destroying the parent, so let's go
		 * see if the parent is ready to be destroyed.
		 */
		nmsocket_maybe_destroy(sock->parent);
		return;
	}

	/*
	 * This is a parent socket (or a standalone). See whether the
	 * children have active handles before deciding whether to
	 * accept destruction.
	 */
	LOCK(&sock->lock);
817
	if (atomic_load(&sock->active) || atomic_load(&sock->destroying) ||
Evan Hunt's avatar
Evan Hunt committed
818
819
	    !atomic_load(&sock->closed) || atomic_load(&sock->references) != 0)
	{
820
821
822
823
824
		UNLOCK(&sock->lock);
		return;
	}

	active_handles = atomic_load(&sock->ah);
825
826
827
	if (sock->children != NULL) {
		for (int i = 0; i < sock->nchildren; i++) {
			LOCK(&sock->children[i].lock);
Witold Kręcicki's avatar
Witold Kręcicki committed
828
			active_handles += atomic_load(&sock->children[i].ah);
829
830
831
832
			UNLOCK(&sock->children[i].lock);
		}
	}

Evan Hunt's avatar
Evan Hunt committed
833
	if (active_handles == 0 || sock->tcphandle != NULL) {
834
835
836
837
838
839
840
841
842
843
		destroy = true;
	}
	UNLOCK(&sock->lock);

	if (destroy) {
		nmsocket_cleanup(sock, true);
	}
}

void
Evan Hunt's avatar
Evan Hunt committed
844
isc__nmsocket_prep_destroy(isc_nmsocket_t *sock) {
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
	REQUIRE(sock->parent == NULL);

	/*
	 * The final external reference to the socket is gone. We can try
	 * destroying the socket, but we have to wait for all the inflight
	 * handles to finish first.
	 */
	atomic_store(&sock->active, false);

	/*
	 * If the socket has children, they'll need to be marked inactive
	 * so they can be cleaned up too.
	 */
	if (sock->children != NULL) {
		for (int i = 0; i < sock->nchildren; i++) {
			atomic_store(&sock->children[i].active, false);
		}
	}

	/*
	 * If we're here then we already stopped listening; otherwise
	 * we'd have a hanging reference from the listening process.
	 *
	 * If it's a regular socket we may need to close it.
	 */
	if (!atomic_load(&sock->closed)) {
		switch (sock->type) {
		case isc_nm_tcpsocket:
			isc__nm_tcp_close(sock);
			break;
		case isc_nm_tcpdnssocket:
			isc__nm_tcpdns_close(sock);
			break;
		default:
			break;
		}
	}

	nmsocket_maybe_destroy(sock);
}

void
887
isc__nmsocket_detach(isc_nmsocket_t **sockp) {
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
	REQUIRE(sockp != NULL && *sockp != NULL);
	REQUIRE(VALID_NMSOCK(*sockp));

	isc_nmsocket_t *sock = *sockp, *rsock = NULL;
	*sockp = NULL;

	/*
	 * If the socket is a part of a set (a child socket) we are
	 * counting references for the whole set at the parent.
	 */
	if (sock->parent != NULL) {
		rsock = sock->parent;
		INSIST(rsock->parent == NULL); /* Sanity check */
	} else {
		rsock = sock;
	}

905
	if (isc_refcount_decrement(&rsock->references) == 1) {
906
907
908
909
		isc__nmsocket_prep_destroy(rsock);
	}
}

910
911
912
913
914
915
916
917
918
919
920
void
isc_nmsocket_close(isc_nmsocket_t **sockp) {
	REQUIRE(sockp != NULL);
	REQUIRE(VALID_NMSOCK(*sockp));
	REQUIRE((*sockp)->type == isc_nm_udplistener ||
		(*sockp)->type == isc_nm_tcplistener ||
		(*sockp)->type == isc_nm_tcpdnslistener);

	isc__nmsocket_detach(sockp);
}

921
void
922
isc__nmsocket_init(isc_nmsocket_t *sock, isc_nm_t *mgr, isc_nmsocket_type type,
Evan Hunt's avatar
Evan Hunt committed
923
		   isc_nmiface_t *iface) {
924
925
926
927
	uint16_t family;

	REQUIRE(sock != NULL);
	REQUIRE(mgr != NULL);
928
	REQUIRE(iface != NULL);
929
930
931

	family = iface->addr.type.sa.sa_family;

932
933
934
935
936
937
938
939
	*sock = (isc_nmsocket_t){ .type = type,
				  .iface = iface,
				  .fd = -1,
				  .ah_size = 32,
				  .inactivehandles = isc_astack_new(
					  mgr->mctx, ISC_NM_HANDLES_STACK_SIZE),
				  .inactivereqs = isc_astack_new(
					  mgr->mctx, ISC_NM_REQS_STACK_SIZE) };
940

941
942
943
	isc_nm_attach(mgr, &sock->mgr);
	sock->uv_handle.handle.data = sock;

Evan Hunt's avatar
Evan Hunt committed
944
945
	sock->ah_frees = isc_mem_allocate(mgr->mctx,
					  sock->ah_size * sizeof(size_t));
946
947
	sock->ah_handles = isc_mem_allocate(
		mgr->mctx, sock->ah_size * sizeof(isc_nmhandle_t *));
948
	ISC_LINK_INIT(&sock->quotacb, link);
949
950
951
952
953
	for (size_t i = 0; i < 32; i++) {
		sock->ah_frees[i] = i;
		sock->ah_handles[i] = NULL;
	}

954
955
956
957
958
959
960
961
	switch (type) {
	case isc_nm_udpsocket:
	case isc_nm_udplistener:
		if (family == AF_INET) {
			sock->statsindex = udp4statsindex;
		} else {
			sock->statsindex = udp6statsindex;
		}
962
		isc__nm_incstats(sock->mgr, sock->statsindex[STATID_ACTIVE]);
963
964
965
966
967
968
969
970
		break;
	case isc_nm_tcpsocket:
	case isc_nm_tcplistener:
		if (family == AF_INET) {
			sock->statsindex = tcp4statsindex;
		} else {
			sock->statsindex = tcp6statsindex;
		}
971
		isc__nm_incstats(sock->mgr, sock->statsindex[STATID_ACTIVE]);
Mark Andrews's avatar
Mark Andrews committed
972
		break;
973
974
975
976
	default:
		break;
	}

977
978
979
	isc_mutex_init(&sock->lock);
	isc_condition_init(&sock->cond);
	isc_refcount_init(&sock->references, 1);
980

981
	atomic_init(&sock->active, true);
982
983
984
985
	atomic_init(&sock->sequential, false);
	atomic_init(&sock->overlimit, false);
	atomic_init(&sock->processing, false);
	atomic_init(&sock->readpaused, false);
986
987
988
989
990

	sock->magic = NMSOCK_MAGIC;
}

void
Evan Hunt's avatar
Evan Hunt committed
991
992
isc__nm_alloc_cb(uv_handle_t *handle, size_t size, uv_buf_t *buf) {
	isc_nmsocket_t *sock = uv_handle_get_data(handle);
993
994
995
996
	isc__networker_t *worker = NULL;

	REQUIRE(VALID_NMSOCK(sock));
	REQUIRE(isc__nm_in_netthread());
997
	REQUIRE(size <= ISC_NETMGR_RECVBUF_SIZE);
998
999

	worker = &sock->mgr->workers[sock->tid];
Evan Hunt's avatar
Evan Hunt committed
1000
	INSIST(!worker->recvbuf_inuse);
1001

Evan Hunt's avatar
Evan Hunt committed
1002
1003
	buf->base = worker->recvbuf;
	worker->recvbuf_inuse = true;
1004
	buf->len = ISC_NETMGR_RECVBUF_SIZE;
1005
1006
1007
}

void
Evan Hunt's avatar
Evan Hunt committed
1008
isc__nm_free_uvbuf(isc_nmsocket_t *sock, const uv_buf_t *buf) {
1009
1010
1011
	isc__networker_t *worker = NULL;

	REQUIRE(VALID_NMSOCK(sock));
1012
1013
1014
1015
	if (buf->base == NULL) {
		/* Empty buffer: might happen in case of error. */
		return;
	}
1016
1017
	worker = &sock->mgr->workers[sock->tid];

Evan Hunt's avatar
Evan Hunt committed
1018
	REQUIRE(worker->recvbuf_inuse);
1019
1020
1021
	if (buf->base > worker->recvbuf &&
	    buf->base <= worker->recvbuf + ISC_NETMGR_RECVBUF_SIZE)
	{
1022
		/* Can happen in case of out-of-order recvmmsg in libuv1.36 */
1023
1024
		return;
	}
Evan Hunt's avatar
Evan Hunt committed
1025
1026
	REQUIRE(buf->base == worker->recvbuf);
	worker->recvbuf_inuse = false;
1027
1028
1029
}

static isc_nmhandle_t *
Evan Hunt's avatar
Evan Hunt committed
1030
alloc_handle(isc_nmsocket_t *sock) {
1031
1032
1033
1034
	isc_nmhandle_t *handle =
		isc_mem_get(sock->mgr->mctx,
			    sizeof(isc_nmhandle_t) + sock->extrahandlesize);

1035
	*handle = (isc_nmhandle_t){ .magic = NMHANDLE_MAGIC };
1036
1037
1038
1039
1040
1041
1042
	isc_refcount_init(&handle->references, 1);

	return (handle);
}

isc_nmhandle_t *
isc__nmhandle_get(isc_nmsocket_t *sock, isc_sockaddr_t *peer,
Evan Hunt's avatar
Evan Hunt committed
1043
		  isc_sockaddr_t *local) {
1044
	isc_nmhandle_t *handle = NULL;
Evan Hunt's avatar
Evan Hunt committed
1045
1046
	size_t handlenum;
	int pos;
1047
1048
1049
1050
1051
1052
1053
1054
1055

	REQUIRE(VALID_NMSOCK(sock));

	handle = isc_astack_pop(sock->inactivehandles);

	if (handle == NULL) {
		handle = alloc_handle(sock);
	} else {
		INSIST(VALID_NMHANDLE(handle));
1056
		isc_refcount_increment0(&handle->references);
1057
1058
	}

1059
1060
	isc__nmsocket_attach(sock, &handle->sock);

1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
	if (peer != NULL) {
		memcpy(&handle->peer, peer, sizeof(isc_sockaddr_t));
	} else {
		memcpy(&handle->peer, &sock->peer, sizeof(isc_sockaddr_t));
	}

	if (local != NULL) {
		memcpy(&handle->local, local, sizeof(isc_sockaddr_t));
	} else if (sock->iface != NULL) {
		memcpy(&handle->local, &sock->iface->addr,
		       sizeof(isc_sockaddr_t));
	} else {
		INSIST(0);
		ISC_UNREACHABLE();
	}

	LOCK(&sock->lock);
	/* We need to add this handle to the list of active handles */
1079
	if ((size_t)atomic_load(&sock->ah) == sock->ah_size) {
1080
1081
		sock->ah_frees =
			isc_mem_reallocate(sock->mgr->mctx, sock->ah_frees,
1082
1083
1084
1085
					   sock->ah_size * 2 * sizeof(size_t));
		sock->ah_handles = isc_mem_reallocate(
			sock->mgr->mctx, sock->ah_handles,
			sock->ah_size * 2 * sizeof(isc_nmhandle_t *));
1086
1087
1088
1089
1090
1091
1092
1093
1094

		for (size_t i = sock->ah_size; i < sock->ah_size * 2; i++) {
			sock->ah_frees[i] = i;
			sock->ah_handles[i] = NULL;
		}

		sock->ah_size *= 2;
	}

Witold Kręcicki's avatar
Witold Kręcicki committed
1095
1096
1097
	handlenum = atomic_fetch_add(&sock->ah, 1);
	pos = sock->ah_frees[handlenum];

1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
	INSIST(sock->ah_handles[pos] == NULL);
	sock->ah_handles[pos] = handle;
	handle->ah_pos = pos;
	UNLOCK(&sock->lock);

	if (sock->type == isc_nm_tcpsocket) {
		INSIST(sock->tcphandle == NULL);
		sock->tcphandle = handle;
	}

	return (handle);
}

void
Evan Hunt's avatar
Evan Hunt committed
1112
isc_nmhandle_ref(isc_nmhandle_t *handle) {
1113
1114
	REQUIRE(VALID_NMHANDLE(handle));

1115
	isc_refcount_increment(&handle->references);
1116
1117
1118
}

bool
Evan Hunt's avatar
Evan Hunt committed
1119
isc_nmhandle_is_stream(isc_nmhandle_t *handle) {
1120
1121
1122
	REQUIRE(VALID_NMHANDLE(handle));

	return (handle->sock->type == isc_nm_tcpsocket ||
1123
		handle->sock->type == isc_nm_tcpdnssocket);
1124
1125
1126
}

static void
Evan Hunt's avatar
Evan Hunt committed
1127
nmhandle_free(isc_nmsocket_t *sock, isc_nmhandle_t *handle) {
1128
1129
	size_t extra = sock->extrahandlesize;

1130
1131
	isc_refcount_destroy(&handle->references);

1132
	if (handle->dofree != NULL) {
1133
1134
1135
		handle->dofree(handle->opaque);
	}

1136
	*handle = (isc_nmhandle_t){ .magic = 0 };
Witold Kręcicki's avatar
Witold Kręcicki committed
1137

1138
1139
1140
	isc_mem_put(sock->mgr->mctx, handle, sizeof(isc_nmhandle_t) + extra);
}

1141
static void
Evan Hunt's avatar
Evan Hunt committed
1142
nmhandle_deactivate(isc_nmsocket_t *sock, isc_nmhandle_t *handle) {
Evan Hunt's avatar
Evan Hunt committed
1143
1144
1145
	size_t handlenum;
	bool reuse = false;

1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
	/*
	 * We do all of this under lock to avoid races with socket
	 * destruction.  We have to do this now, because at this point the
	 * socket is either unused or still attached to event->sock.
	 */
	LOCK(&sock->lock);

	INSIST(sock->ah_handles[handle->ah_pos] == handle);
	INSIST(sock->ah_size > handle->ah_pos);
	INSIST(atomic_load(&sock->ah) > 0);

	sock->ah_handles[handle->ah_pos] = NULL;
Evan Hunt's avatar
Evan Hunt committed
1158
	handlenum = atomic_fetch_sub(&sock->ah, 1) - 1;
1159
1160
1161
	sock->ah_frees[handlenum] = handle->ah_pos;
	handle->ah_pos = 0;
	if (atomic_load(&sock->active)) {
1162
		reuse = isc_astack_trypush(sock->inactivehandles, handle);
1163
1164
1165
1166
1167
1168
1169
	}
	if (!reuse) {
		nmhandle_free(sock, handle);
	}
	UNLOCK(&sock->lock);
}

1170
void
Evan Hunt's avatar
Evan Hunt committed
1171
isc_nmhandle_unref(isc_nmhandle_t *handle) {
1172
	isc_nmsocket_t *sock = NULL;
1173
1174
1175

	REQUIRE(VALID_NMHANDLE(handle));

1176
	if (isc_refcount_decrement(&handle->references) > 1) {
Witold Kręcicki's avatar
Witold Kręcicki committed
1177
1178
		return;
	}
1179
1180
	/* We need an acquire memory barrier here */
	(void)isc_refcount_current(&handle->references);
1181

Witold Kręcicki's avatar
Witold Kręcicki committed
1182
1183
	sock = handle->sock;
	handle->sock = NULL;
1184

Witold Kręcicki's avatar
Witold Kręcicki committed
1185
1186
1187
	if (handle->doreset != NULL) {
		handle->doreset(handle->opaque);
	}
1188

1189
1190
1191
1192
	nmhandle_deactivate(sock, handle);

	/*
	 * The handle is gone now. If the socket has a callback configured
1193
	 * for that (e.g., to perform cleanup after request processing),
1194
	 * call it now, or schedule it to run asynchronously.
1195
1196
1197
1198
1199
	 */
	if (sock->closehandle_cb != NULL) {
		if (sock->tid == isc_nm_tid()) {
			sock->closehandle_cb(sock);
		} else {
1200
1201
			isc__netievent_closecb_t *event = isc__nm_get_ievent(
				sock->mgr, netievent_closecb);
1202
1203
1204
1205
			/*
			 * The socket will be finally detached by the closecb
			 * event handler.
			 */
1206
			isc__nmsocket_attach(sock, &event->sock);
1207
			isc__nm_enqueue_ievent(&sock->mgr->workers[sock->tid],
1208
					       (isc__netievent_t *)event);
1209
1210
1211
		}
	}

1212
	isc__nmsocket_detach(&sock);
1213
1214
1215
}

void *
Evan Hunt's avatar
Evan Hunt committed
1216
isc_nmhandle_getdata(isc_nmhandle_t *handle) {
1217
1218
1219
1220
1221
1222
1223
	REQUIRE(VALID_NMHANDLE(handle));

	return (handle->opaque);
}

void
isc_nmhandle_setdata(isc_nmhandle_t *handle, void *arg,
Evan Hunt's avatar
Evan Hunt committed
1224
		     isc_nm_opaquecb_t doreset, isc_nm_opaquecb_t dofree) {
1225
1226
1227
1228
1229
1230
1231
1232
	REQUIRE(VALID_NMHANDLE(handle));

	handle->opaque = arg;
	handle->doreset = doreset;
	handle->dofree = dofree;
}

void *
Evan Hunt's avatar
Evan Hunt committed
1233
isc_nmhandle_getextra(isc_nmhandle_t *handle) {
1234
1235
1236
1237
1238
1239
	REQUIRE(VALID_NMHANDLE(handle));

	return (handle->extra);
}

isc_sockaddr_t
Evan Hunt's avatar
Evan Hunt committed
1240
isc_nmhandle_peeraddr(isc_nmhandle_t *handle) {
1241
1242
1243
1244
1245
1246
	REQUIRE(VALID_NMHANDLE(handle));

	return (handle->peer);
}

isc_sockaddr_t
Evan Hunt's avatar
Evan Hunt committed
1247
isc_nmhandle_localaddr(isc_nmhandle_t *handle) {
1248
1249
1250
1251
1252
	REQUIRE(VALID_NMHANDLE(handle));

	return (handle->local);
}

1253
isc_nm_t *
Evan Hunt's avatar
Evan Hunt committed
1254
isc_nmhandle_netmgr(isc_nmhandle_t *handle) {
1255
1256
1257
1258
1259
1260
	REQUIRE(VALID_NMHANDLE(handle));
	REQUIRE(VALID_NMSOCK(handle->sock));

	return (handle->sock->mgr);
}

1261
isc__nm_uvreq_t *
Evan Hunt's avatar
Evan Hunt committed
1262
isc__nm_uvreq_get(isc_nm_t *mgr, isc_nmsocket_t *sock) {
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
	isc__nm_uvreq_t *req = NULL;

	REQUIRE(VALID_NM(mgr));
	REQUIRE(VALID_NMSOCK(sock));

	if (sock != NULL && atomic_load(&sock->active)) {
		/* Try to reuse one */
		req = isc_astack_pop(sock->inactivereqs);
	}

	if (req == NULL) {
Evan Hunt's avatar
Evan Hunt committed
1274
		req = isc_mempool_get(mgr->reqpool);
1275
1276
	}

1277
	*req = (isc__nm_uvreq_t){ .magic = 0 };
1278
	req->uv_req.req.data = req;
1279
	isc__nmsocket_attach(sock, &req->sock);
1280
1281
1282
1283
1284
1285
	req->magic = UVREQ_MAGIC;

	return (req);
}

void
Evan Hunt's avatar
Evan Hunt committed
1286
isc__nm_uvreq_put(isc__nm_uvreq_t **req0, isc_nmsocket_t *sock) {
1287
	isc__nm_uvreq_t *req = NULL;
Evan Hunt's avatar
Evan Hunt committed
1288
	isc_nmhandle_t *handle = NULL;
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307

	REQUIRE(req0 != NULL);
	REQUIRE(VALID_UVREQ(*req0));

	req = *req0;
	*req0 = NULL;

	INSIST(sock == req->sock);

	req->magic = 0;

	/*
	 * We need to save this first to make sure that handle,
	 * sock, and the netmgr won't all disappear.
	 */
	handle = req->handle;
	req->handle = NULL;

	if (!atomic_load(&sock->active) ||
1308
	    !isc_astack_trypush(sock->inactivereqs, req)) {
Evan Hunt's avatar
Evan Hunt committed
1309
		isc_mempool_put(sock->mgr->reqpool, req);
1310
1311
1312
1313
1314
1315
	}

	if (handle != NULL) {
		isc_nmhandle_unref(handle);
	}

1316
	isc__nmsocket_detach(&sock);
1317
1318
1319
}

isc_result_t
1320
isc_nm_send(isc_nmhandle_t *handle, isc_region_t *region, isc_nm_cb_t cb,
Evan Hunt's avatar
Evan Hunt committed
1321
	    void *cbarg) {
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
	REQUIRE(VALID_NMHANDLE(handle));

	switch (handle->sock->type) {
	case isc_nm_udpsocket:
	case isc_nm_udplistener:
		return (isc__nm_udp_send(handle, region, cb, cbarg