primary.c revision 212034
1/*-
2 * Copyright (c) 2009 The FreeBSD Foundation
3 * Copyright (c) 2010 Pawel Jakub Dawidek <pjd@FreeBSD.org>
4 * All rights reserved.
5 *
6 * This software was developed by Pawel Jakub Dawidek under sponsorship from
7 * the FreeBSD Foundation.
8 *
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
11 * are met:
12 * 1. Redistributions of source code must retain the above copyright
13 *    notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 *    notice, this list of conditions and the following disclaimer in the
16 *    documentation and/or other materials provided with the distribution.
17 *
18 * THIS SOFTWARE IS PROVIDED BY THE AUTHORS AND CONTRIBUTORS ``AS IS'' AND
19 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE
22 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
27 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28 * SUCH DAMAGE.
29 */
30
31#include <sys/cdefs.h>
32__FBSDID("$FreeBSD: head/sbin/hastd/primary.c 212034 2010-08-30 22:28:04Z pjd $");
33
34#include <sys/types.h>
35#include <sys/time.h>
36#include <sys/bio.h>
37#include <sys/disk.h>
38#include <sys/refcount.h>
39#include <sys/stat.h>
40
41#include <geom/gate/g_gate.h>
42
43#include <assert.h>
44#include <err.h>
45#include <errno.h>
46#include <fcntl.h>
47#include <libgeom.h>
48#include <pthread.h>
49#include <signal.h>
50#include <stdint.h>
51#include <stdio.h>
52#include <string.h>
53#include <sysexits.h>
54#include <unistd.h>
55
56#include <activemap.h>
57#include <nv.h>
58#include <rangelock.h>
59
60#include "control.h"
61#include "hast.h"
62#include "hast_proto.h"
63#include "hastd.h"
64#include "hooks.h"
65#include "metadata.h"
66#include "proto.h"
67#include "pjdlog.h"
68#include "subr.h"
69#include "synch.h"
70
71/* The is only one remote component for now. */
72#define	ISREMOTE(no)	((no) == 1)
73
74struct hio {
75	/*
76	 * Number of components we are still waiting for.
77	 * When this field goes to 0, we can send the request back to the
78	 * kernel. Each component has to decrease this counter by one
79	 * even on failure.
80	 */
81	unsigned int		 hio_countdown;
82	/*
83	 * Each component has a place to store its own error.
84	 * Once the request is handled by all components we can decide if the
85	 * request overall is successful or not.
86	 */
87	int			*hio_errors;
88	/*
89	 * Structure used to comunicate with GEOM Gate class.
90	 */
91	struct g_gate_ctl_io	 hio_ggio;
92	TAILQ_ENTRY(hio)	*hio_next;
93};
94#define	hio_free_next	hio_next[0]
95#define	hio_done_next	hio_next[0]
96
97/*
98 * Free list holds unused structures. When free list is empty, we have to wait
99 * until some in-progress requests are freed.
100 */
101static TAILQ_HEAD(, hio) hio_free_list;
102static pthread_mutex_t hio_free_list_lock;
103static pthread_cond_t hio_free_list_cond;
104/*
105 * There is one send list for every component. One requests is placed on all
106 * send lists - each component gets the same request, but each component is
107 * responsible for managing his own send list.
108 */
109static TAILQ_HEAD(, hio) *hio_send_list;
110static pthread_mutex_t *hio_send_list_lock;
111static pthread_cond_t *hio_send_list_cond;
112/*
113 * There is one recv list for every component, although local components don't
114 * use recv lists as local requests are done synchronously.
115 */
116static TAILQ_HEAD(, hio) *hio_recv_list;
117static pthread_mutex_t *hio_recv_list_lock;
118static pthread_cond_t *hio_recv_list_cond;
119/*
120 * Request is placed on done list by the slowest component (the one that
121 * decreased hio_countdown from 1 to 0).
122 */
123static TAILQ_HEAD(, hio) hio_done_list;
124static pthread_mutex_t hio_done_list_lock;
125static pthread_cond_t hio_done_list_cond;
126/*
127 * Structure below are for interaction with sync thread.
128 */
129static bool sync_inprogress;
130static pthread_mutex_t sync_lock;
131static pthread_cond_t sync_cond;
132/*
133 * The lock below allows to synchornize access to remote connections.
134 */
135static pthread_rwlock_t *hio_remote_lock;
136
137/*
138 * Lock to synchronize metadata updates. Also synchronize access to
139 * hr_primary_localcnt and hr_primary_remotecnt fields.
140 */
141static pthread_mutex_t metadata_lock;
142
143/*
144 * Maximum number of outstanding I/O requests.
145 */
146#define	HAST_HIO_MAX	256
147/*
148 * Number of components. At this point there are only two components: local
149 * and remote, but in the future it might be possible to use multiple local
150 * and remote components.
151 */
152#define	HAST_NCOMPONENTS	2
153/*
154 * Number of seconds to sleep between reconnect retries or keepalive packets.
155 */
156#define	RETRY_SLEEP		10
157
158#define	ISCONNECTED(res, no)	\
159	((res)->hr_remotein != NULL && (res)->hr_remoteout != NULL)
160
161#define	QUEUE_INSERT1(hio, name, ncomp)	do {				\
162	bool _wakeup;							\
163									\
164	mtx_lock(&hio_##name##_list_lock[(ncomp)]);			\
165	_wakeup = TAILQ_EMPTY(&hio_##name##_list[(ncomp)]);		\
166	TAILQ_INSERT_TAIL(&hio_##name##_list[(ncomp)], (hio),		\
167	    hio_next[(ncomp)]);						\
168	mtx_unlock(&hio_##name##_list_lock[ncomp]);			\
169	if (_wakeup)							\
170		cv_signal(&hio_##name##_list_cond[(ncomp)]);		\
171} while (0)
172#define	QUEUE_INSERT2(hio, name)	do {				\
173	bool _wakeup;							\
174									\
175	mtx_lock(&hio_##name##_list_lock);				\
176	_wakeup = TAILQ_EMPTY(&hio_##name##_list);			\
177	TAILQ_INSERT_TAIL(&hio_##name##_list, (hio), hio_##name##_next);\
178	mtx_unlock(&hio_##name##_list_lock);				\
179	if (_wakeup)							\
180		cv_signal(&hio_##name##_list_cond);			\
181} while (0)
182#define	QUEUE_TAKE1(hio, name, ncomp)	do {				\
183	mtx_lock(&hio_##name##_list_lock[(ncomp)]);			\
184	while (((hio) = TAILQ_FIRST(&hio_##name##_list[(ncomp)])) == NULL) { \
185		cv_wait(&hio_##name##_list_cond[(ncomp)],		\
186		    &hio_##name##_list_lock[(ncomp)]);			\
187	}								\
188	TAILQ_REMOVE(&hio_##name##_list[(ncomp)], (hio),		\
189	    hio_next[(ncomp)]);						\
190	mtx_unlock(&hio_##name##_list_lock[(ncomp)]);			\
191} while (0)
192#define	QUEUE_TAKE2(hio, name)	do {					\
193	mtx_lock(&hio_##name##_list_lock);				\
194	while (((hio) = TAILQ_FIRST(&hio_##name##_list)) == NULL) {	\
195		cv_wait(&hio_##name##_list_cond,			\
196		    &hio_##name##_list_lock);				\
197	}								\
198	TAILQ_REMOVE(&hio_##name##_list, (hio), hio_##name##_next);	\
199	mtx_unlock(&hio_##name##_list_lock);				\
200} while (0)
201
202#define	SYNCREQ(hio)		do {					\
203	(hio)->hio_ggio.gctl_unit = -1;					\
204	(hio)->hio_ggio.gctl_seq = 1;					\
205} while (0)
206#define	ISSYNCREQ(hio)		((hio)->hio_ggio.gctl_unit == -1)
207#define	SYNCREQDONE(hio)	do { (hio)->hio_ggio.gctl_unit = -2; } while (0)
208#define	ISSYNCREQDONE(hio)	((hio)->hio_ggio.gctl_unit == -2)
209
210static struct hast_resource *gres;
211
212static pthread_mutex_t range_lock;
213static struct rangelocks *range_regular;
214static bool range_regular_wait;
215static pthread_cond_t range_regular_cond;
216static struct rangelocks *range_sync;
217static bool range_sync_wait;
218static pthread_cond_t range_sync_cond;
219
220static void *ggate_recv_thread(void *arg);
221static void *local_send_thread(void *arg);
222static void *remote_send_thread(void *arg);
223static void *remote_recv_thread(void *arg);
224static void *ggate_send_thread(void *arg);
225static void *sync_thread(void *arg);
226static void *guard_thread(void *arg);
227
228static void
229dummy_sighandler(int sig __unused)
230{
231	/* Nothing to do. */
232}
233
234static void
235cleanup(struct hast_resource *res)
236{
237	int rerrno;
238
239	/* Remember errno. */
240	rerrno = errno;
241
242	/*
243	 * Close descriptor to /dev/hast/<name>
244	 * to work-around race in the kernel.
245	 */
246	close(res->hr_localfd);
247
248	/* Destroy ggate provider if we created one. */
249	if (res->hr_ggateunit >= 0) {
250		struct g_gate_ctl_destroy ggiod;
251
252		ggiod.gctl_version = G_GATE_VERSION;
253		ggiod.gctl_unit = res->hr_ggateunit;
254		ggiod.gctl_force = 1;
255		if (ioctl(res->hr_ggatefd, G_GATE_CMD_DESTROY, &ggiod) < 0) {
256			pjdlog_warning("Unable to destroy hast/%s device",
257			    res->hr_provname);
258		}
259		res->hr_ggateunit = -1;
260	}
261
262	/* Restore errno. */
263	errno = rerrno;
264}
265
266static void
267primary_exit(int exitcode, const char *fmt, ...)
268{
269	va_list ap;
270
271	assert(exitcode != EX_OK);
272	va_start(ap, fmt);
273	pjdlogv_errno(LOG_ERR, fmt, ap);
274	va_end(ap);
275	cleanup(gres);
276	exit(exitcode);
277}
278
279static void
280primary_exitx(int exitcode, const char *fmt, ...)
281{
282	va_list ap;
283
284	va_start(ap, fmt);
285	pjdlogv(exitcode == EX_OK ? LOG_INFO : LOG_ERR, fmt, ap);
286	va_end(ap);
287	cleanup(gres);
288	exit(exitcode);
289}
290
291static int
292hast_activemap_flush(struct hast_resource *res)
293{
294	const unsigned char *buf;
295	size_t size;
296
297	buf = activemap_bitmap(res->hr_amp, &size);
298	assert(buf != NULL);
299	assert((size % res->hr_local_sectorsize) == 0);
300	if (pwrite(res->hr_localfd, buf, size, METADATA_SIZE) !=
301	    (ssize_t)size) {
302		KEEP_ERRNO(pjdlog_errno(LOG_ERR,
303		    "Unable to flush activemap to disk"));
304		return (-1);
305	}
306	return (0);
307}
308
309static bool
310real_remote(const struct hast_resource *res)
311{
312
313	return (strcmp(res->hr_remoteaddr, "none") != 0);
314}
315
316static void
317init_environment(struct hast_resource *res __unused)
318{
319	struct hio *hio;
320	unsigned int ii, ncomps;
321	sigset_t mask;
322
323	/*
324	 * In the future it might be per-resource value.
325	 */
326	ncomps = HAST_NCOMPONENTS;
327
328	/*
329	 * Allocate memory needed by lists.
330	 */
331	hio_send_list = malloc(sizeof(hio_send_list[0]) * ncomps);
332	if (hio_send_list == NULL) {
333		primary_exitx(EX_TEMPFAIL,
334		    "Unable to allocate %zu bytes of memory for send lists.",
335		    sizeof(hio_send_list[0]) * ncomps);
336	}
337	hio_send_list_lock = malloc(sizeof(hio_send_list_lock[0]) * ncomps);
338	if (hio_send_list_lock == NULL) {
339		primary_exitx(EX_TEMPFAIL,
340		    "Unable to allocate %zu bytes of memory for send list locks.",
341		    sizeof(hio_send_list_lock[0]) * ncomps);
342	}
343	hio_send_list_cond = malloc(sizeof(hio_send_list_cond[0]) * ncomps);
344	if (hio_send_list_cond == NULL) {
345		primary_exitx(EX_TEMPFAIL,
346		    "Unable to allocate %zu bytes of memory for send list condition variables.",
347		    sizeof(hio_send_list_cond[0]) * ncomps);
348	}
349	hio_recv_list = malloc(sizeof(hio_recv_list[0]) * ncomps);
350	if (hio_recv_list == NULL) {
351		primary_exitx(EX_TEMPFAIL,
352		    "Unable to allocate %zu bytes of memory for recv lists.",
353		    sizeof(hio_recv_list[0]) * ncomps);
354	}
355	hio_recv_list_lock = malloc(sizeof(hio_recv_list_lock[0]) * ncomps);
356	if (hio_recv_list_lock == NULL) {
357		primary_exitx(EX_TEMPFAIL,
358		    "Unable to allocate %zu bytes of memory for recv list locks.",
359		    sizeof(hio_recv_list_lock[0]) * ncomps);
360	}
361	hio_recv_list_cond = malloc(sizeof(hio_recv_list_cond[0]) * ncomps);
362	if (hio_recv_list_cond == NULL) {
363		primary_exitx(EX_TEMPFAIL,
364		    "Unable to allocate %zu bytes of memory for recv list condition variables.",
365		    sizeof(hio_recv_list_cond[0]) * ncomps);
366	}
367	hio_remote_lock = malloc(sizeof(hio_remote_lock[0]) * ncomps);
368	if (hio_remote_lock == NULL) {
369		primary_exitx(EX_TEMPFAIL,
370		    "Unable to allocate %zu bytes of memory for remote connections locks.",
371		    sizeof(hio_remote_lock[0]) * ncomps);
372	}
373
374	/*
375	 * Initialize lists, their locks and theirs condition variables.
376	 */
377	TAILQ_INIT(&hio_free_list);
378	mtx_init(&hio_free_list_lock);
379	cv_init(&hio_free_list_cond);
380	for (ii = 0; ii < HAST_NCOMPONENTS; ii++) {
381		TAILQ_INIT(&hio_send_list[ii]);
382		mtx_init(&hio_send_list_lock[ii]);
383		cv_init(&hio_send_list_cond[ii]);
384		TAILQ_INIT(&hio_recv_list[ii]);
385		mtx_init(&hio_recv_list_lock[ii]);
386		cv_init(&hio_recv_list_cond[ii]);
387		rw_init(&hio_remote_lock[ii]);
388	}
389	TAILQ_INIT(&hio_done_list);
390	mtx_init(&hio_done_list_lock);
391	cv_init(&hio_done_list_cond);
392	mtx_init(&metadata_lock);
393
394	/*
395	 * Allocate requests pool and initialize requests.
396	 */
397	for (ii = 0; ii < HAST_HIO_MAX; ii++) {
398		hio = malloc(sizeof(*hio));
399		if (hio == NULL) {
400			primary_exitx(EX_TEMPFAIL,
401			    "Unable to allocate %zu bytes of memory for hio request.",
402			    sizeof(*hio));
403		}
404		hio->hio_countdown = 0;
405		hio->hio_errors = malloc(sizeof(hio->hio_errors[0]) * ncomps);
406		if (hio->hio_errors == NULL) {
407			primary_exitx(EX_TEMPFAIL,
408			    "Unable allocate %zu bytes of memory for hio errors.",
409			    sizeof(hio->hio_errors[0]) * ncomps);
410		}
411		hio->hio_next = malloc(sizeof(hio->hio_next[0]) * ncomps);
412		if (hio->hio_next == NULL) {
413			primary_exitx(EX_TEMPFAIL,
414			    "Unable allocate %zu bytes of memory for hio_next field.",
415			    sizeof(hio->hio_next[0]) * ncomps);
416		}
417		hio->hio_ggio.gctl_version = G_GATE_VERSION;
418		hio->hio_ggio.gctl_data = malloc(MAXPHYS);
419		if (hio->hio_ggio.gctl_data == NULL) {
420			primary_exitx(EX_TEMPFAIL,
421			    "Unable to allocate %zu bytes of memory for gctl_data.",
422			    MAXPHYS);
423		}
424		hio->hio_ggio.gctl_length = MAXPHYS;
425		hio->hio_ggio.gctl_error = 0;
426		TAILQ_INSERT_HEAD(&hio_free_list, hio, hio_free_next);
427	}
428
429	/*
430	 * Turn on signals handling.
431	 */
432	/* Because SIGCHLD is ignored by default, setup dummy handler for it. */
433	PJDLOG_VERIFY(signal(SIGCHLD, dummy_sighandler) != SIG_ERR);
434	PJDLOG_VERIFY(sigfillset(&mask) == 0);
435	PJDLOG_VERIFY(sigprocmask(SIG_SETMASK, &mask, NULL) == 0);
436}
437
438static void
439init_local(struct hast_resource *res)
440{
441	unsigned char *buf;
442	size_t mapsize;
443
444	if (metadata_read(res, true) < 0)
445		exit(EX_NOINPUT);
446	mtx_init(&res->hr_amp_lock);
447	if (activemap_init(&res->hr_amp, res->hr_datasize, res->hr_extentsize,
448	    res->hr_local_sectorsize, res->hr_keepdirty) < 0) {
449		primary_exit(EX_TEMPFAIL, "Unable to create activemap");
450	}
451	mtx_init(&range_lock);
452	cv_init(&range_regular_cond);
453	if (rangelock_init(&range_regular) < 0)
454		primary_exit(EX_TEMPFAIL, "Unable to create regular range lock");
455	cv_init(&range_sync_cond);
456	if (rangelock_init(&range_sync) < 0)
457		primary_exit(EX_TEMPFAIL, "Unable to create sync range lock");
458	mapsize = activemap_ondisk_size(res->hr_amp);
459	buf = calloc(1, mapsize);
460	if (buf == NULL) {
461		primary_exitx(EX_TEMPFAIL,
462		    "Unable to allocate buffer for activemap.");
463	}
464	if (pread(res->hr_localfd, buf, mapsize, METADATA_SIZE) !=
465	    (ssize_t)mapsize) {
466		primary_exit(EX_NOINPUT, "Unable to read activemap");
467	}
468	activemap_copyin(res->hr_amp, buf, mapsize);
469	free(buf);
470	if (res->hr_resuid != 0)
471		return;
472	/*
473	 * We're using provider for the first time, so we have to generate
474	 * resource unique identifier and initialize local and remote counts.
475	 */
476	arc4random_buf(&res->hr_resuid, sizeof(res->hr_resuid));
477	res->hr_primary_localcnt = 1;
478	res->hr_primary_remotecnt = 0;
479	if (metadata_write(res) < 0)
480		exit(EX_NOINPUT);
481}
482
483static bool
484init_remote(struct hast_resource *res, struct proto_conn **inp,
485    struct proto_conn **outp)
486{
487	struct proto_conn *in, *out;
488	struct nv *nvout, *nvin;
489	const unsigned char *token;
490	unsigned char *map;
491	const char *errmsg;
492	int32_t extentsize;
493	int64_t datasize;
494	uint32_t mapsize;
495	size_t size;
496
497	assert((inp == NULL && outp == NULL) || (inp != NULL && outp != NULL));
498	assert(real_remote(res));
499
500	in = out = NULL;
501	errmsg = NULL;
502
503	/* Prepare outgoing connection with remote node. */
504	if (proto_client(res->hr_remoteaddr, &out) < 0) {
505		primary_exit(EX_TEMPFAIL, "Unable to create connection to %s",
506		    res->hr_remoteaddr);
507	}
508	/* Try to connect, but accept failure. */
509	if (proto_connect(out) < 0) {
510		pjdlog_errno(LOG_WARNING, "Unable to connect to %s",
511		    res->hr_remoteaddr);
512		goto close;
513	}
514	/* Error in setting timeout is not critical, but why should it fail? */
515	if (proto_timeout(out, res->hr_timeout) < 0)
516		pjdlog_errno(LOG_WARNING, "Unable to set connection timeout");
517	/*
518	 * First handshake step.
519	 * Setup outgoing connection with remote node.
520	 */
521	nvout = nv_alloc();
522	nv_add_string(nvout, res->hr_name, "resource");
523	if (nv_error(nvout) != 0) {
524		pjdlog_common(LOG_WARNING, 0, nv_error(nvout),
525		    "Unable to allocate header for connection with %s",
526		    res->hr_remoteaddr);
527		nv_free(nvout);
528		goto close;
529	}
530	if (hast_proto_send(res, out, nvout, NULL, 0) < 0) {
531		pjdlog_errno(LOG_WARNING,
532		    "Unable to send handshake header to %s",
533		    res->hr_remoteaddr);
534		nv_free(nvout);
535		goto close;
536	}
537	nv_free(nvout);
538	if (hast_proto_recv_hdr(out, &nvin) < 0) {
539		pjdlog_errno(LOG_WARNING,
540		    "Unable to receive handshake header from %s",
541		    res->hr_remoteaddr);
542		goto close;
543	}
544	errmsg = nv_get_string(nvin, "errmsg");
545	if (errmsg != NULL) {
546		pjdlog_warning("%s", errmsg);
547		nv_free(nvin);
548		goto close;
549	}
550	token = nv_get_uint8_array(nvin, &size, "token");
551	if (token == NULL) {
552		pjdlog_warning("Handshake header from %s has no 'token' field.",
553		    res->hr_remoteaddr);
554		nv_free(nvin);
555		goto close;
556	}
557	if (size != sizeof(res->hr_token)) {
558		pjdlog_warning("Handshake header from %s contains 'token' of wrong size (got %zu, expected %zu).",
559		    res->hr_remoteaddr, size, sizeof(res->hr_token));
560		nv_free(nvin);
561		goto close;
562	}
563	bcopy(token, res->hr_token, sizeof(res->hr_token));
564	nv_free(nvin);
565
566	/*
567	 * Second handshake step.
568	 * Setup incoming connection with remote node.
569	 */
570	if (proto_client(res->hr_remoteaddr, &in) < 0) {
571		pjdlog_errno(LOG_WARNING, "Unable to create connection to %s",
572		    res->hr_remoteaddr);
573	}
574	/* Try to connect, but accept failure. */
575	if (proto_connect(in) < 0) {
576		pjdlog_errno(LOG_WARNING, "Unable to connect to %s",
577		    res->hr_remoteaddr);
578		goto close;
579	}
580	/* Error in setting timeout is not critical, but why should it fail? */
581	if (proto_timeout(in, res->hr_timeout) < 0)
582		pjdlog_errno(LOG_WARNING, "Unable to set connection timeout");
583	nvout = nv_alloc();
584	nv_add_string(nvout, res->hr_name, "resource");
585	nv_add_uint8_array(nvout, res->hr_token, sizeof(res->hr_token),
586	    "token");
587	nv_add_uint64(nvout, res->hr_resuid, "resuid");
588	nv_add_uint64(nvout, res->hr_primary_localcnt, "localcnt");
589	nv_add_uint64(nvout, res->hr_primary_remotecnt, "remotecnt");
590	if (nv_error(nvout) != 0) {
591		pjdlog_common(LOG_WARNING, 0, nv_error(nvout),
592		    "Unable to allocate header for connection with %s",
593		    res->hr_remoteaddr);
594		nv_free(nvout);
595		goto close;
596	}
597	if (hast_proto_send(res, in, nvout, NULL, 0) < 0) {
598		pjdlog_errno(LOG_WARNING,
599		    "Unable to send handshake header to %s",
600		    res->hr_remoteaddr);
601		nv_free(nvout);
602		goto close;
603	}
604	nv_free(nvout);
605	if (hast_proto_recv_hdr(out, &nvin) < 0) {
606		pjdlog_errno(LOG_WARNING,
607		    "Unable to receive handshake header from %s",
608		    res->hr_remoteaddr);
609		goto close;
610	}
611	errmsg = nv_get_string(nvin, "errmsg");
612	if (errmsg != NULL) {
613		pjdlog_warning("%s", errmsg);
614		nv_free(nvin);
615		goto close;
616	}
617	datasize = nv_get_int64(nvin, "datasize");
618	if (datasize != res->hr_datasize) {
619		pjdlog_warning("Data size differs between nodes (local=%jd, remote=%jd).",
620		    (intmax_t)res->hr_datasize, (intmax_t)datasize);
621		nv_free(nvin);
622		goto close;
623	}
624	extentsize = nv_get_int32(nvin, "extentsize");
625	if (extentsize != res->hr_extentsize) {
626		pjdlog_warning("Extent size differs between nodes (local=%zd, remote=%zd).",
627		    (ssize_t)res->hr_extentsize, (ssize_t)extentsize);
628		nv_free(nvin);
629		goto close;
630	}
631	res->hr_secondary_localcnt = nv_get_uint64(nvin, "localcnt");
632	res->hr_secondary_remotecnt = nv_get_uint64(nvin, "remotecnt");
633	res->hr_syncsrc = nv_get_uint8(nvin, "syncsrc");
634	map = NULL;
635	mapsize = nv_get_uint32(nvin, "mapsize");
636	if (mapsize > 0) {
637		map = malloc(mapsize);
638		if (map == NULL) {
639			pjdlog_error("Unable to allocate memory for remote activemap (mapsize=%ju).",
640			    (uintmax_t)mapsize);
641			nv_free(nvin);
642			goto close;
643		}
644		/*
645		 * Remote node have some dirty extents on its own, lets
646		 * download its activemap.
647		 */
648		if (hast_proto_recv_data(res, out, nvin, map,
649		    mapsize) < 0) {
650			pjdlog_errno(LOG_ERR,
651			    "Unable to receive remote activemap");
652			nv_free(nvin);
653			free(map);
654			goto close;
655		}
656		/*
657		 * Merge local and remote bitmaps.
658		 */
659		activemap_merge(res->hr_amp, map, mapsize);
660		free(map);
661		/*
662		 * Now that we merged bitmaps from both nodes, flush it to the
663		 * disk before we start to synchronize.
664		 */
665		(void)hast_activemap_flush(res);
666	}
667	pjdlog_info("Connected to %s.", res->hr_remoteaddr);
668	if (inp != NULL && outp != NULL) {
669		*inp = in;
670		*outp = out;
671	} else {
672		res->hr_remotein = in;
673		res->hr_remoteout = out;
674	}
675	hook_exec(res->hr_exec, "connect", res->hr_name, NULL);
676	return (true);
677close:
678	if (errmsg != NULL && strcmp(errmsg, "Split-brain condition!") == 0)
679		hook_exec(res->hr_exec, "split-brain", res->hr_name, NULL);
680	proto_close(out);
681	if (in != NULL)
682		proto_close(in);
683	return (false);
684}
685
686static void
687sync_start(void)
688{
689
690	mtx_lock(&sync_lock);
691	sync_inprogress = true;
692	mtx_unlock(&sync_lock);
693	cv_signal(&sync_cond);
694}
695
696static void
697sync_stop(void)
698{
699
700	mtx_lock(&sync_lock);
701	if (sync_inprogress)
702		sync_inprogress = false;
703	mtx_unlock(&sync_lock);
704}
705
706static void
707init_ggate(struct hast_resource *res)
708{
709	struct g_gate_ctl_create ggiocreate;
710	struct g_gate_ctl_cancel ggiocancel;
711
712	/*
713	 * We communicate with ggate via /dev/ggctl. Open it.
714	 */
715	res->hr_ggatefd = open("/dev/" G_GATE_CTL_NAME, O_RDWR);
716	if (res->hr_ggatefd < 0)
717		primary_exit(EX_OSFILE, "Unable to open /dev/" G_GATE_CTL_NAME);
718	/*
719	 * Create provider before trying to connect, as connection failure
720	 * is not critical, but may take some time.
721	 */
722	ggiocreate.gctl_version = G_GATE_VERSION;
723	ggiocreate.gctl_mediasize = res->hr_datasize;
724	ggiocreate.gctl_sectorsize = res->hr_local_sectorsize;
725	ggiocreate.gctl_flags = 0;
726	ggiocreate.gctl_maxcount = G_GATE_MAX_QUEUE_SIZE;
727	ggiocreate.gctl_timeout = 0;
728	ggiocreate.gctl_unit = G_GATE_NAME_GIVEN;
729	snprintf(ggiocreate.gctl_name, sizeof(ggiocreate.gctl_name), "hast/%s",
730	    res->hr_provname);
731	bzero(ggiocreate.gctl_info, sizeof(ggiocreate.gctl_info));
732	if (ioctl(res->hr_ggatefd, G_GATE_CMD_CREATE, &ggiocreate) == 0) {
733		pjdlog_info("Device hast/%s created.", res->hr_provname);
734		res->hr_ggateunit = ggiocreate.gctl_unit;
735		return;
736	}
737	if (errno != EEXIST) {
738		primary_exit(EX_OSERR, "Unable to create hast/%s device",
739		    res->hr_provname);
740	}
741	pjdlog_debug(1,
742	    "Device hast/%s already exists, we will try to take it over.",
743	    res->hr_provname);
744	/*
745	 * If we received EEXIST, we assume that the process who created the
746	 * provider died and didn't clean up. In that case we will start from
747	 * where he left of.
748	 */
749	ggiocancel.gctl_version = G_GATE_VERSION;
750	ggiocancel.gctl_unit = G_GATE_NAME_GIVEN;
751	snprintf(ggiocancel.gctl_name, sizeof(ggiocancel.gctl_name), "hast/%s",
752	    res->hr_provname);
753	if (ioctl(res->hr_ggatefd, G_GATE_CMD_CANCEL, &ggiocancel) == 0) {
754		pjdlog_info("Device hast/%s recovered.", res->hr_provname);
755		res->hr_ggateunit = ggiocancel.gctl_unit;
756		return;
757	}
758	primary_exit(EX_OSERR, "Unable to take over hast/%s device",
759	    res->hr_provname);
760}
761
762void
763hastd_primary(struct hast_resource *res)
764{
765	pthread_t td;
766	pid_t pid;
767	int error;
768
769	/*
770	 * Create communication channel between parent and child.
771	 */
772	if (proto_client("socketpair://", &res->hr_ctrl) < 0) {
773		KEEP_ERRNO((void)pidfile_remove(pfh));
774		pjdlog_exit(EX_OSERR,
775		    "Unable to create control sockets between parent and child");
776	}
777
778	pid = fork();
779	if (pid < 0) {
780		KEEP_ERRNO((void)pidfile_remove(pfh));
781		pjdlog_exit(EX_TEMPFAIL, "Unable to fork");
782	}
783
784	if (pid > 0) {
785		/* This is parent. */
786		res->hr_workerpid = pid;
787		return;
788	}
789
790	gres = res;
791
792	(void)pidfile_close(pfh);
793	hook_fini();
794
795	setproctitle("%s (primary)", res->hr_name);
796
797	signal(SIGHUP, SIG_DFL);
798	signal(SIGCHLD, SIG_DFL);
799
800	hook_init();
801	init_local(res);
802	if (real_remote(res) && init_remote(res, NULL, NULL))
803		sync_start();
804	init_ggate(res);
805	init_environment(res);
806	error = pthread_create(&td, NULL, ggate_recv_thread, res);
807	assert(error == 0);
808	error = pthread_create(&td, NULL, local_send_thread, res);
809	assert(error == 0);
810	error = pthread_create(&td, NULL, remote_send_thread, res);
811	assert(error == 0);
812	error = pthread_create(&td, NULL, remote_recv_thread, res);
813	assert(error == 0);
814	error = pthread_create(&td, NULL, ggate_send_thread, res);
815	assert(error == 0);
816	error = pthread_create(&td, NULL, sync_thread, res);
817	assert(error == 0);
818	error = pthread_create(&td, NULL, ctrl_thread, res);
819	assert(error == 0);
820	(void)guard_thread(res);
821}
822
823static void
824reqlog(int loglevel, int debuglevel, struct g_gate_ctl_io *ggio, const char *fmt, ...)
825{
826	char msg[1024];
827	va_list ap;
828	int len;
829
830	va_start(ap, fmt);
831	len = vsnprintf(msg, sizeof(msg), fmt, ap);
832	va_end(ap);
833	if ((size_t)len < sizeof(msg)) {
834		switch (ggio->gctl_cmd) {
835		case BIO_READ:
836			(void)snprintf(msg + len, sizeof(msg) - len,
837			    "READ(%ju, %ju).", (uintmax_t)ggio->gctl_offset,
838			    (uintmax_t)ggio->gctl_length);
839			break;
840		case BIO_DELETE:
841			(void)snprintf(msg + len, sizeof(msg) - len,
842			    "DELETE(%ju, %ju).", (uintmax_t)ggio->gctl_offset,
843			    (uintmax_t)ggio->gctl_length);
844			break;
845		case BIO_FLUSH:
846			(void)snprintf(msg + len, sizeof(msg) - len, "FLUSH.");
847			break;
848		case BIO_WRITE:
849			(void)snprintf(msg + len, sizeof(msg) - len,
850			    "WRITE(%ju, %ju).", (uintmax_t)ggio->gctl_offset,
851			    (uintmax_t)ggio->gctl_length);
852			break;
853		default:
854			(void)snprintf(msg + len, sizeof(msg) - len,
855			    "UNKNOWN(%u).", (unsigned int)ggio->gctl_cmd);
856			break;
857		}
858	}
859	pjdlog_common(loglevel, debuglevel, -1, "%s", msg);
860}
861
862static void
863remote_close(struct hast_resource *res, int ncomp)
864{
865
866	rw_wlock(&hio_remote_lock[ncomp]);
867	/*
868	 * A race is possible between dropping rlock and acquiring wlock -
869	 * another thread can close connection in-between.
870	 */
871	if (!ISCONNECTED(res, ncomp)) {
872		assert(res->hr_remotein == NULL);
873		assert(res->hr_remoteout == NULL);
874		rw_unlock(&hio_remote_lock[ncomp]);
875		return;
876	}
877
878	assert(res->hr_remotein != NULL);
879	assert(res->hr_remoteout != NULL);
880
881	pjdlog_debug(2, "Closing incoming connection to %s.",
882	    res->hr_remoteaddr);
883	proto_close(res->hr_remotein);
884	res->hr_remotein = NULL;
885	pjdlog_debug(2, "Closing outgoing connection to %s.",
886	    res->hr_remoteaddr);
887	proto_close(res->hr_remoteout);
888	res->hr_remoteout = NULL;
889
890	rw_unlock(&hio_remote_lock[ncomp]);
891
892	pjdlog_warning("Disconnected from %s.", res->hr_remoteaddr);
893
894	/*
895	 * Stop synchronization if in-progress.
896	 */
897	sync_stop();
898
899	hook_exec(res->hr_exec, "disconnect", res->hr_name, NULL);
900}
901
902/*
903 * Thread receives ggate I/O requests from the kernel and passes them to
904 * appropriate threads:
905 * WRITE - always goes to both local_send and remote_send threads
906 * READ (when the block is up-to-date on local component) -
907 *	only local_send thread
908 * READ (when the block isn't up-to-date on local component) -
909 *	only remote_send thread
910 * DELETE - always goes to both local_send and remote_send threads
911 * FLUSH - always goes to both local_send and remote_send threads
912 */
913static void *
914ggate_recv_thread(void *arg)
915{
916	struct hast_resource *res = arg;
917	struct g_gate_ctl_io *ggio;
918	struct hio *hio;
919	unsigned int ii, ncomp, ncomps;
920	int error;
921
922	ncomps = HAST_NCOMPONENTS;
923
924	for (;;) {
925		pjdlog_debug(2, "ggate_recv: Taking free request.");
926		QUEUE_TAKE2(hio, free);
927		pjdlog_debug(2, "ggate_recv: (%p) Got free request.", hio);
928		ggio = &hio->hio_ggio;
929		ggio->gctl_unit = res->hr_ggateunit;
930		ggio->gctl_length = MAXPHYS;
931		ggio->gctl_error = 0;
932		pjdlog_debug(2,
933		    "ggate_recv: (%p) Waiting for request from the kernel.",
934		    hio);
935		if (ioctl(res->hr_ggatefd, G_GATE_CMD_START, ggio) < 0) {
936			if (sigexit_received)
937				pthread_exit(NULL);
938			primary_exit(EX_OSERR, "G_GATE_CMD_START failed");
939		}
940		error = ggio->gctl_error;
941		switch (error) {
942		case 0:
943			break;
944		case ECANCELED:
945			/* Exit gracefully. */
946			if (!sigexit_received) {
947				pjdlog_debug(2,
948				    "ggate_recv: (%p) Received cancel from the kernel.",
949				    hio);
950				pjdlog_info("Received cancel from the kernel, exiting.");
951			}
952			pthread_exit(NULL);
953		case ENOMEM:
954			/*
955			 * Buffer too small? Impossible, we allocate MAXPHYS
956			 * bytes - request can't be bigger than that.
957			 */
958			/* FALLTHROUGH */
959		case ENXIO:
960		default:
961			primary_exitx(EX_OSERR, "G_GATE_CMD_START failed: %s.",
962			    strerror(error));
963		}
964		for (ii = 0; ii < ncomps; ii++)
965			hio->hio_errors[ii] = EINVAL;
966		reqlog(LOG_DEBUG, 2, ggio,
967		    "ggate_recv: (%p) Request received from the kernel: ",
968		    hio);
969		/*
970		 * Inform all components about new write request.
971		 * For read request prefer local component unless the given
972		 * range is out-of-date, then use remote component.
973		 */
974		switch (ggio->gctl_cmd) {
975		case BIO_READ:
976			pjdlog_debug(2,
977			    "ggate_recv: (%p) Moving request to the send queue.",
978			    hio);
979			refcount_init(&hio->hio_countdown, 1);
980			mtx_lock(&metadata_lock);
981			if (res->hr_syncsrc == HAST_SYNCSRC_UNDEF ||
982			    res->hr_syncsrc == HAST_SYNCSRC_PRIMARY) {
983				/*
984				 * This range is up-to-date on local component,
985				 * so handle request locally.
986				 */
987				 /* Local component is 0 for now. */
988				ncomp = 0;
989			} else /* if (res->hr_syncsrc ==
990			    HAST_SYNCSRC_SECONDARY) */ {
991				assert(res->hr_syncsrc ==
992				    HAST_SYNCSRC_SECONDARY);
993				/*
994				 * This range is out-of-date on local component,
995				 * so send request to the remote node.
996				 */
997				 /* Remote component is 1 for now. */
998				ncomp = 1;
999			}
1000			mtx_unlock(&metadata_lock);
1001			QUEUE_INSERT1(hio, send, ncomp);
1002			break;
1003		case BIO_WRITE:
1004			for (;;) {
1005				mtx_lock(&range_lock);
1006				if (rangelock_islocked(range_sync,
1007				    ggio->gctl_offset, ggio->gctl_length)) {
1008					pjdlog_debug(2,
1009					    "regular: Range offset=%jd length=%zu locked.",
1010					    (intmax_t)ggio->gctl_offset,
1011					    (size_t)ggio->gctl_length);
1012					range_regular_wait = true;
1013					cv_wait(&range_regular_cond, &range_lock);
1014					range_regular_wait = false;
1015					mtx_unlock(&range_lock);
1016					continue;
1017				}
1018				if (rangelock_add(range_regular,
1019				    ggio->gctl_offset, ggio->gctl_length) < 0) {
1020					mtx_unlock(&range_lock);
1021					pjdlog_debug(2,
1022					    "regular: Range offset=%jd length=%zu is already locked, waiting.",
1023					    (intmax_t)ggio->gctl_offset,
1024					    (size_t)ggio->gctl_length);
1025					sleep(1);
1026					continue;
1027				}
1028				mtx_unlock(&range_lock);
1029				break;
1030			}
1031			mtx_lock(&res->hr_amp_lock);
1032			if (activemap_write_start(res->hr_amp,
1033			    ggio->gctl_offset, ggio->gctl_length)) {
1034				(void)hast_activemap_flush(res);
1035			}
1036			mtx_unlock(&res->hr_amp_lock);
1037			/* FALLTHROUGH */
1038		case BIO_DELETE:
1039		case BIO_FLUSH:
1040			pjdlog_debug(2,
1041			    "ggate_recv: (%p) Moving request to the send queues.",
1042			    hio);
1043			refcount_init(&hio->hio_countdown, ncomps);
1044			for (ii = 0; ii < ncomps; ii++)
1045				QUEUE_INSERT1(hio, send, ii);
1046			break;
1047		}
1048	}
1049	/* NOTREACHED */
1050	return (NULL);
1051}
1052
1053/*
1054 * Thread reads from or writes to local component.
1055 * If local read fails, it redirects it to remote_send thread.
1056 */
1057static void *
1058local_send_thread(void *arg)
1059{
1060	struct hast_resource *res = arg;
1061	struct g_gate_ctl_io *ggio;
1062	struct hio *hio;
1063	unsigned int ncomp, rncomp;
1064	ssize_t ret;
1065
1066	/* Local component is 0 for now. */
1067	ncomp = 0;
1068	/* Remote component is 1 for now. */
1069	rncomp = 1;
1070
1071	for (;;) {
1072		pjdlog_debug(2, "local_send: Taking request.");
1073		QUEUE_TAKE1(hio, send, ncomp);
1074		pjdlog_debug(2, "local_send: (%p) Got request.", hio);
1075		ggio = &hio->hio_ggio;
1076		switch (ggio->gctl_cmd) {
1077		case BIO_READ:
1078			ret = pread(res->hr_localfd, ggio->gctl_data,
1079			    ggio->gctl_length,
1080			    ggio->gctl_offset + res->hr_localoff);
1081			if (ret == ggio->gctl_length)
1082				hio->hio_errors[ncomp] = 0;
1083			else {
1084				/*
1085				 * If READ failed, try to read from remote node.
1086				 */
1087				QUEUE_INSERT1(hio, send, rncomp);
1088				continue;
1089			}
1090			break;
1091		case BIO_WRITE:
1092			ret = pwrite(res->hr_localfd, ggio->gctl_data,
1093			    ggio->gctl_length,
1094			    ggio->gctl_offset + res->hr_localoff);
1095			if (ret < 0)
1096				hio->hio_errors[ncomp] = errno;
1097			else if (ret != ggio->gctl_length)
1098				hio->hio_errors[ncomp] = EIO;
1099			else
1100				hio->hio_errors[ncomp] = 0;
1101			break;
1102		case BIO_DELETE:
1103			ret = g_delete(res->hr_localfd,
1104			    ggio->gctl_offset + res->hr_localoff,
1105			    ggio->gctl_length);
1106			if (ret < 0)
1107				hio->hio_errors[ncomp] = errno;
1108			else
1109				hio->hio_errors[ncomp] = 0;
1110			break;
1111		case BIO_FLUSH:
1112			ret = g_flush(res->hr_localfd);
1113			if (ret < 0)
1114				hio->hio_errors[ncomp] = errno;
1115			else
1116				hio->hio_errors[ncomp] = 0;
1117			break;
1118		}
1119		if (refcount_release(&hio->hio_countdown)) {
1120			if (ISSYNCREQ(hio)) {
1121				mtx_lock(&sync_lock);
1122				SYNCREQDONE(hio);
1123				mtx_unlock(&sync_lock);
1124				cv_signal(&sync_cond);
1125			} else {
1126				pjdlog_debug(2,
1127				    "local_send: (%p) Moving request to the done queue.",
1128				    hio);
1129				QUEUE_INSERT2(hio, done);
1130			}
1131		}
1132	}
1133	/* NOTREACHED */
1134	return (NULL);
1135}
1136
1137/*
1138 * Thread sends request to secondary node.
1139 */
1140static void *
1141remote_send_thread(void *arg)
1142{
1143	struct hast_resource *res = arg;
1144	struct g_gate_ctl_io *ggio;
1145	struct hio *hio;
1146	struct nv *nv;
1147	unsigned int ncomp;
1148	bool wakeup;
1149	uint64_t offset, length;
1150	uint8_t cmd;
1151	void *data;
1152
1153	/* Remote component is 1 for now. */
1154	ncomp = 1;
1155
1156	for (;;) {
1157		pjdlog_debug(2, "remote_send: Taking request.");
1158		QUEUE_TAKE1(hio, send, ncomp);
1159		pjdlog_debug(2, "remote_send: (%p) Got request.", hio);
1160		ggio = &hio->hio_ggio;
1161		switch (ggio->gctl_cmd) {
1162		case BIO_READ:
1163			cmd = HIO_READ;
1164			data = NULL;
1165			offset = ggio->gctl_offset;
1166			length = ggio->gctl_length;
1167			break;
1168		case BIO_WRITE:
1169			cmd = HIO_WRITE;
1170			data = ggio->gctl_data;
1171			offset = ggio->gctl_offset;
1172			length = ggio->gctl_length;
1173			break;
1174		case BIO_DELETE:
1175			cmd = HIO_DELETE;
1176			data = NULL;
1177			offset = ggio->gctl_offset;
1178			length = ggio->gctl_length;
1179			break;
1180		case BIO_FLUSH:
1181			cmd = HIO_FLUSH;
1182			data = NULL;
1183			offset = 0;
1184			length = 0;
1185			break;
1186		default:
1187			assert(!"invalid condition");
1188			abort();
1189		}
1190		nv = nv_alloc();
1191		nv_add_uint8(nv, cmd, "cmd");
1192		nv_add_uint64(nv, (uint64_t)ggio->gctl_seq, "seq");
1193		nv_add_uint64(nv, offset, "offset");
1194		nv_add_uint64(nv, length, "length");
1195		if (nv_error(nv) != 0) {
1196			hio->hio_errors[ncomp] = nv_error(nv);
1197			pjdlog_debug(2,
1198			    "remote_send: (%p) Unable to prepare header to send.",
1199			    hio);
1200			reqlog(LOG_ERR, 0, ggio,
1201			    "Unable to prepare header to send (%s): ",
1202			    strerror(nv_error(nv)));
1203			/* Move failed request immediately to the done queue. */
1204			goto done_queue;
1205		}
1206		pjdlog_debug(2,
1207		    "remote_send: (%p) Moving request to the recv queue.",
1208		    hio);
1209		/*
1210		 * Protect connection from disappearing.
1211		 */
1212		rw_rlock(&hio_remote_lock[ncomp]);
1213		if (!ISCONNECTED(res, ncomp)) {
1214			rw_unlock(&hio_remote_lock[ncomp]);
1215			hio->hio_errors[ncomp] = ENOTCONN;
1216			goto done_queue;
1217		}
1218		/*
1219		 * Move the request to recv queue before sending it, because
1220		 * in different order we can get reply before we move request
1221		 * to recv queue.
1222		 */
1223		mtx_lock(&hio_recv_list_lock[ncomp]);
1224		wakeup = TAILQ_EMPTY(&hio_recv_list[ncomp]);
1225		TAILQ_INSERT_TAIL(&hio_recv_list[ncomp], hio, hio_next[ncomp]);
1226		mtx_unlock(&hio_recv_list_lock[ncomp]);
1227		if (hast_proto_send(res, res->hr_remoteout, nv, data,
1228		    data != NULL ? length : 0) < 0) {
1229			hio->hio_errors[ncomp] = errno;
1230			rw_unlock(&hio_remote_lock[ncomp]);
1231			pjdlog_debug(2,
1232			    "remote_send: (%p) Unable to send request.", hio);
1233			reqlog(LOG_ERR, 0, ggio,
1234			    "Unable to send request (%s): ",
1235			    strerror(hio->hio_errors[ncomp]));
1236			remote_close(res, ncomp);
1237			/*
1238			 * Take request back from the receive queue and move
1239			 * it immediately to the done queue.
1240			 */
1241			mtx_lock(&hio_recv_list_lock[ncomp]);
1242			TAILQ_REMOVE(&hio_recv_list[ncomp], hio, hio_next[ncomp]);
1243			mtx_unlock(&hio_recv_list_lock[ncomp]);
1244			goto done_queue;
1245		}
1246		rw_unlock(&hio_remote_lock[ncomp]);
1247		nv_free(nv);
1248		if (wakeup)
1249			cv_signal(&hio_recv_list_cond[ncomp]);
1250		continue;
1251done_queue:
1252		nv_free(nv);
1253		if (ISSYNCREQ(hio)) {
1254			if (!refcount_release(&hio->hio_countdown))
1255				continue;
1256			mtx_lock(&sync_lock);
1257			SYNCREQDONE(hio);
1258			mtx_unlock(&sync_lock);
1259			cv_signal(&sync_cond);
1260			continue;
1261		}
1262		if (ggio->gctl_cmd == BIO_WRITE) {
1263			mtx_lock(&res->hr_amp_lock);
1264			if (activemap_need_sync(res->hr_amp, ggio->gctl_offset,
1265			    ggio->gctl_length)) {
1266				(void)hast_activemap_flush(res);
1267			}
1268			mtx_unlock(&res->hr_amp_lock);
1269		}
1270		if (!refcount_release(&hio->hio_countdown))
1271			continue;
1272		pjdlog_debug(2,
1273		    "remote_send: (%p) Moving request to the done queue.",
1274		    hio);
1275		QUEUE_INSERT2(hio, done);
1276	}
1277	/* NOTREACHED */
1278	return (NULL);
1279}
1280
1281/*
1282 * Thread receives answer from secondary node and passes it to ggate_send
1283 * thread.
1284 */
1285static void *
1286remote_recv_thread(void *arg)
1287{
1288	struct hast_resource *res = arg;
1289	struct g_gate_ctl_io *ggio;
1290	struct hio *hio;
1291	struct nv *nv;
1292	unsigned int ncomp;
1293	uint64_t seq;
1294	int error;
1295
1296	/* Remote component is 1 for now. */
1297	ncomp = 1;
1298
1299	for (;;) {
1300		/* Wait until there is anything to receive. */
1301		mtx_lock(&hio_recv_list_lock[ncomp]);
1302		while (TAILQ_EMPTY(&hio_recv_list[ncomp])) {
1303			pjdlog_debug(2, "remote_recv: No requests, waiting.");
1304			cv_wait(&hio_recv_list_cond[ncomp],
1305			    &hio_recv_list_lock[ncomp]);
1306		}
1307		mtx_unlock(&hio_recv_list_lock[ncomp]);
1308		rw_rlock(&hio_remote_lock[ncomp]);
1309		if (!ISCONNECTED(res, ncomp)) {
1310			rw_unlock(&hio_remote_lock[ncomp]);
1311			/*
1312			 * Connection is dead, so move all pending requests to
1313			 * the done queue (one-by-one).
1314			 */
1315			mtx_lock(&hio_recv_list_lock[ncomp]);
1316			hio = TAILQ_FIRST(&hio_recv_list[ncomp]);
1317			assert(hio != NULL);
1318			TAILQ_REMOVE(&hio_recv_list[ncomp], hio,
1319			    hio_next[ncomp]);
1320			mtx_unlock(&hio_recv_list_lock[ncomp]);
1321			goto done_queue;
1322		}
1323		if (hast_proto_recv_hdr(res->hr_remotein, &nv) < 0) {
1324			pjdlog_errno(LOG_ERR,
1325			    "Unable to receive reply header");
1326			rw_unlock(&hio_remote_lock[ncomp]);
1327			remote_close(res, ncomp);
1328			continue;
1329		}
1330		rw_unlock(&hio_remote_lock[ncomp]);
1331		seq = nv_get_uint64(nv, "seq");
1332		if (seq == 0) {
1333			pjdlog_error("Header contains no 'seq' field.");
1334			nv_free(nv);
1335			continue;
1336		}
1337		mtx_lock(&hio_recv_list_lock[ncomp]);
1338		TAILQ_FOREACH(hio, &hio_recv_list[ncomp], hio_next[ncomp]) {
1339			if (hio->hio_ggio.gctl_seq == seq) {
1340				TAILQ_REMOVE(&hio_recv_list[ncomp], hio,
1341				    hio_next[ncomp]);
1342				break;
1343			}
1344		}
1345		mtx_unlock(&hio_recv_list_lock[ncomp]);
1346		if (hio == NULL) {
1347			pjdlog_error("Found no request matching received 'seq' field (%ju).",
1348			    (uintmax_t)seq);
1349			nv_free(nv);
1350			continue;
1351		}
1352		error = nv_get_int16(nv, "error");
1353		if (error != 0) {
1354			/* Request failed on remote side. */
1355			hio->hio_errors[ncomp] = 0;
1356			nv_free(nv);
1357			goto done_queue;
1358		}
1359		ggio = &hio->hio_ggio;
1360		switch (ggio->gctl_cmd) {
1361		case BIO_READ:
1362			rw_rlock(&hio_remote_lock[ncomp]);
1363			if (!ISCONNECTED(res, ncomp)) {
1364				rw_unlock(&hio_remote_lock[ncomp]);
1365				nv_free(nv);
1366				goto done_queue;
1367			}
1368			if (hast_proto_recv_data(res, res->hr_remotein, nv,
1369			    ggio->gctl_data, ggio->gctl_length) < 0) {
1370				hio->hio_errors[ncomp] = errno;
1371				pjdlog_errno(LOG_ERR,
1372				    "Unable to receive reply data");
1373				rw_unlock(&hio_remote_lock[ncomp]);
1374				nv_free(nv);
1375				remote_close(res, ncomp);
1376				goto done_queue;
1377			}
1378			rw_unlock(&hio_remote_lock[ncomp]);
1379			break;
1380		case BIO_WRITE:
1381		case BIO_DELETE:
1382		case BIO_FLUSH:
1383			break;
1384		default:
1385			assert(!"invalid condition");
1386			abort();
1387		}
1388		hio->hio_errors[ncomp] = 0;
1389		nv_free(nv);
1390done_queue:
1391		if (refcount_release(&hio->hio_countdown)) {
1392			if (ISSYNCREQ(hio)) {
1393				mtx_lock(&sync_lock);
1394				SYNCREQDONE(hio);
1395				mtx_unlock(&sync_lock);
1396				cv_signal(&sync_cond);
1397			} else {
1398				pjdlog_debug(2,
1399				    "remote_recv: (%p) Moving request to the done queue.",
1400				    hio);
1401				QUEUE_INSERT2(hio, done);
1402			}
1403		}
1404	}
1405	/* NOTREACHED */
1406	return (NULL);
1407}
1408
1409/*
1410 * Thread sends answer to the kernel.
1411 */
1412static void *
1413ggate_send_thread(void *arg)
1414{
1415	struct hast_resource *res = arg;
1416	struct g_gate_ctl_io *ggio;
1417	struct hio *hio;
1418	unsigned int ii, ncomp, ncomps;
1419
1420	ncomps = HAST_NCOMPONENTS;
1421
1422	for (;;) {
1423		pjdlog_debug(2, "ggate_send: Taking request.");
1424		QUEUE_TAKE2(hio, done);
1425		pjdlog_debug(2, "ggate_send: (%p) Got request.", hio);
1426		ggio = &hio->hio_ggio;
1427		for (ii = 0; ii < ncomps; ii++) {
1428			if (hio->hio_errors[ii] == 0) {
1429				/*
1430				 * One successful request is enough to declare
1431				 * success.
1432				 */
1433				ggio->gctl_error = 0;
1434				break;
1435			}
1436		}
1437		if (ii == ncomps) {
1438			/*
1439			 * None of the requests were successful.
1440			 * Use first error.
1441			 */
1442			ggio->gctl_error = hio->hio_errors[0];
1443		}
1444		if (ggio->gctl_error == 0 && ggio->gctl_cmd == BIO_WRITE) {
1445			mtx_lock(&res->hr_amp_lock);
1446			activemap_write_complete(res->hr_amp,
1447			    ggio->gctl_offset, ggio->gctl_length);
1448			mtx_unlock(&res->hr_amp_lock);
1449		}
1450		if (ggio->gctl_cmd == BIO_WRITE) {
1451			/*
1452			 * Unlock range we locked.
1453			 */
1454			mtx_lock(&range_lock);
1455			rangelock_del(range_regular, ggio->gctl_offset,
1456			    ggio->gctl_length);
1457			if (range_sync_wait)
1458				cv_signal(&range_sync_cond);
1459			mtx_unlock(&range_lock);
1460			/*
1461			 * Bump local count if this is first write after
1462			 * connection failure with remote node.
1463			 */
1464			ncomp = 1;
1465			rw_rlock(&hio_remote_lock[ncomp]);
1466			if (!ISCONNECTED(res, ncomp)) {
1467				mtx_lock(&metadata_lock);
1468				if (res->hr_primary_localcnt ==
1469				    res->hr_secondary_remotecnt) {
1470					res->hr_primary_localcnt++;
1471					pjdlog_debug(1,
1472					    "Increasing localcnt to %ju.",
1473					    (uintmax_t)res->hr_primary_localcnt);
1474					(void)metadata_write(res);
1475				}
1476				mtx_unlock(&metadata_lock);
1477			}
1478			rw_unlock(&hio_remote_lock[ncomp]);
1479		}
1480		if (ioctl(res->hr_ggatefd, G_GATE_CMD_DONE, ggio) < 0)
1481			primary_exit(EX_OSERR, "G_GATE_CMD_DONE failed");
1482		pjdlog_debug(2,
1483		    "ggate_send: (%p) Moving request to the free queue.", hio);
1484		QUEUE_INSERT2(hio, free);
1485	}
1486	/* NOTREACHED */
1487	return (NULL);
1488}
1489
1490/*
1491 * Thread synchronize local and remote components.
1492 */
1493static void *
1494sync_thread(void *arg __unused)
1495{
1496	struct hast_resource *res = arg;
1497	struct hio *hio;
1498	struct g_gate_ctl_io *ggio;
1499	unsigned int ii, ncomp, ncomps;
1500	off_t offset, length, synced;
1501	bool dorewind;
1502	int syncext;
1503
1504	ncomps = HAST_NCOMPONENTS;
1505	dorewind = true;
1506	synced = 0;
1507	offset = -1;
1508
1509	for (;;) {
1510		mtx_lock(&sync_lock);
1511		if (offset >= 0 && !sync_inprogress) {
1512			pjdlog_info("Synchronization interrupted. "
1513			    "%jd bytes synchronized so far.",
1514			    (intmax_t)synced);
1515			hook_exec(res->hr_exec, "syncintr", res->hr_name, NULL);
1516		}
1517		while (!sync_inprogress) {
1518			dorewind = true;
1519			synced = 0;
1520			cv_wait(&sync_cond, &sync_lock);
1521		}
1522		mtx_unlock(&sync_lock);
1523		/*
1524		 * Obtain offset at which we should synchronize.
1525		 * Rewind synchronization if needed.
1526		 */
1527		mtx_lock(&res->hr_amp_lock);
1528		if (dorewind)
1529			activemap_sync_rewind(res->hr_amp);
1530		offset = activemap_sync_offset(res->hr_amp, &length, &syncext);
1531		if (syncext != -1) {
1532			/*
1533			 * We synchronized entire syncext extent, we can mark
1534			 * it as clean now.
1535			 */
1536			if (activemap_extent_complete(res->hr_amp, syncext))
1537				(void)hast_activemap_flush(res);
1538		}
1539		mtx_unlock(&res->hr_amp_lock);
1540		if (dorewind) {
1541			dorewind = false;
1542			if (offset < 0)
1543				pjdlog_info("Nodes are in sync.");
1544			else {
1545				pjdlog_info("Synchronization started. %ju bytes to go.",
1546				    (uintmax_t)(res->hr_extentsize *
1547				    activemap_ndirty(res->hr_amp)));
1548				hook_exec(res->hr_exec, "syncstart",
1549				    res->hr_name, NULL);
1550			}
1551		}
1552		if (offset < 0) {
1553			sync_stop();
1554			pjdlog_debug(1, "Nothing to synchronize.");
1555			/*
1556			 * Synchronization complete, make both localcnt and
1557			 * remotecnt equal.
1558			 */
1559			ncomp = 1;
1560			rw_rlock(&hio_remote_lock[ncomp]);
1561			if (ISCONNECTED(res, ncomp)) {
1562				if (synced > 0) {
1563					pjdlog_info("Synchronization complete. "
1564					    "%jd bytes synchronized.",
1565					    (intmax_t)synced);
1566					hook_exec(res->hr_exec, "syncdone",
1567					    res->hr_name, NULL);
1568				}
1569				mtx_lock(&metadata_lock);
1570				res->hr_syncsrc = HAST_SYNCSRC_UNDEF;
1571				res->hr_primary_localcnt =
1572				    res->hr_secondary_localcnt;
1573				res->hr_primary_remotecnt =
1574				    res->hr_secondary_remotecnt;
1575				pjdlog_debug(1,
1576				    "Setting localcnt to %ju and remotecnt to %ju.",
1577				    (uintmax_t)res->hr_primary_localcnt,
1578				    (uintmax_t)res->hr_secondary_localcnt);
1579				(void)metadata_write(res);
1580				mtx_unlock(&metadata_lock);
1581			}
1582			rw_unlock(&hio_remote_lock[ncomp]);
1583			continue;
1584		}
1585		pjdlog_debug(2, "sync: Taking free request.");
1586		QUEUE_TAKE2(hio, free);
1587		pjdlog_debug(2, "sync: (%p) Got free request.", hio);
1588		/*
1589		 * Lock the range we are going to synchronize. We don't want
1590		 * race where someone writes between our read and write.
1591		 */
1592		for (;;) {
1593			mtx_lock(&range_lock);
1594			if (rangelock_islocked(range_regular, offset, length)) {
1595				pjdlog_debug(2,
1596				    "sync: Range offset=%jd length=%jd locked.",
1597				    (intmax_t)offset, (intmax_t)length);
1598				range_sync_wait = true;
1599				cv_wait(&range_sync_cond, &range_lock);
1600				range_sync_wait = false;
1601				mtx_unlock(&range_lock);
1602				continue;
1603			}
1604			if (rangelock_add(range_sync, offset, length) < 0) {
1605				mtx_unlock(&range_lock);
1606				pjdlog_debug(2,
1607				    "sync: Range offset=%jd length=%jd is already locked, waiting.",
1608				    (intmax_t)offset, (intmax_t)length);
1609				sleep(1);
1610				continue;
1611			}
1612			mtx_unlock(&range_lock);
1613			break;
1614		}
1615		/*
1616		 * First read the data from synchronization source.
1617		 */
1618		SYNCREQ(hio);
1619		ggio = &hio->hio_ggio;
1620		ggio->gctl_cmd = BIO_READ;
1621		ggio->gctl_offset = offset;
1622		ggio->gctl_length = length;
1623		ggio->gctl_error = 0;
1624		for (ii = 0; ii < ncomps; ii++)
1625			hio->hio_errors[ii] = EINVAL;
1626		reqlog(LOG_DEBUG, 2, ggio, "sync: (%p) Sending sync request: ",
1627		    hio);
1628		pjdlog_debug(2, "sync: (%p) Moving request to the send queue.",
1629		    hio);
1630		mtx_lock(&metadata_lock);
1631		if (res->hr_syncsrc == HAST_SYNCSRC_PRIMARY) {
1632			/*
1633			 * This range is up-to-date on local component,
1634			 * so handle request locally.
1635			 */
1636			 /* Local component is 0 for now. */
1637			ncomp = 0;
1638		} else /* if (res->hr_syncsrc == HAST_SYNCSRC_SECONDARY) */ {
1639			assert(res->hr_syncsrc == HAST_SYNCSRC_SECONDARY);
1640			/*
1641			 * This range is out-of-date on local component,
1642			 * so send request to the remote node.
1643			 */
1644			 /* Remote component is 1 for now. */
1645			ncomp = 1;
1646		}
1647		mtx_unlock(&metadata_lock);
1648		refcount_init(&hio->hio_countdown, 1);
1649		QUEUE_INSERT1(hio, send, ncomp);
1650
1651		/*
1652		 * Let's wait for READ to finish.
1653		 */
1654		mtx_lock(&sync_lock);
1655		while (!ISSYNCREQDONE(hio))
1656			cv_wait(&sync_cond, &sync_lock);
1657		mtx_unlock(&sync_lock);
1658
1659		if (hio->hio_errors[ncomp] != 0) {
1660			pjdlog_error("Unable to read synchronization data: %s.",
1661			    strerror(hio->hio_errors[ncomp]));
1662			goto free_queue;
1663		}
1664
1665		/*
1666		 * We read the data from synchronization source, now write it
1667		 * to synchronization target.
1668		 */
1669		SYNCREQ(hio);
1670		ggio->gctl_cmd = BIO_WRITE;
1671		for (ii = 0; ii < ncomps; ii++)
1672			hio->hio_errors[ii] = EINVAL;
1673		reqlog(LOG_DEBUG, 2, ggio, "sync: (%p) Sending sync request: ",
1674		    hio);
1675		pjdlog_debug(2, "sync: (%p) Moving request to the send queue.",
1676		    hio);
1677		mtx_lock(&metadata_lock);
1678		if (res->hr_syncsrc == HAST_SYNCSRC_PRIMARY) {
1679			/*
1680			 * This range is up-to-date on local component,
1681			 * so we update remote component.
1682			 */
1683			 /* Remote component is 1 for now. */
1684			ncomp = 1;
1685		} else /* if (res->hr_syncsrc == HAST_SYNCSRC_SECONDARY) */ {
1686			assert(res->hr_syncsrc == HAST_SYNCSRC_SECONDARY);
1687			/*
1688			 * This range is out-of-date on local component,
1689			 * so we update it.
1690			 */
1691			 /* Local component is 0 for now. */
1692			ncomp = 0;
1693		}
1694		mtx_unlock(&metadata_lock);
1695
1696		pjdlog_debug(2, "sync: (%p) Moving request to the send queues.",
1697		    hio);
1698		refcount_init(&hio->hio_countdown, 1);
1699		QUEUE_INSERT1(hio, send, ncomp);
1700
1701		/*
1702		 * Let's wait for WRITE to finish.
1703		 */
1704		mtx_lock(&sync_lock);
1705		while (!ISSYNCREQDONE(hio))
1706			cv_wait(&sync_cond, &sync_lock);
1707		mtx_unlock(&sync_lock);
1708
1709		if (hio->hio_errors[ncomp] != 0) {
1710			pjdlog_error("Unable to write synchronization data: %s.",
1711			    strerror(hio->hio_errors[ncomp]));
1712			goto free_queue;
1713		}
1714
1715		synced += length;
1716free_queue:
1717		mtx_lock(&range_lock);
1718		rangelock_del(range_sync, offset, length);
1719		if (range_regular_wait)
1720			cv_signal(&range_regular_cond);
1721		mtx_unlock(&range_lock);
1722		pjdlog_debug(2, "sync: (%p) Moving request to the free queue.",
1723		    hio);
1724		QUEUE_INSERT2(hio, free);
1725	}
1726	/* NOTREACHED */
1727	return (NULL);
1728}
1729
1730static void
1731config_reload(void)
1732{
1733	struct hastd_config *newcfg;
1734	struct hast_resource *res;
1735	unsigned int ii, ncomps;
1736	int modified;
1737
1738	pjdlog_info("Reloading configuration...");
1739
1740	ncomps = HAST_NCOMPONENTS;
1741
1742	newcfg = yy_config_parse(cfgpath, false);
1743	if (newcfg == NULL)
1744		goto failed;
1745
1746	TAILQ_FOREACH(res, &newcfg->hc_resources, hr_next) {
1747		if (strcmp(res->hr_name, gres->hr_name) == 0)
1748			break;
1749	}
1750	/*
1751	 * If resource was removed from the configuration file, resource
1752	 * name, provider name or path to local component was modified we
1753	 * shouldn't be here. This means that someone modified configuration
1754	 * file and send SIGHUP to us instead of main hastd process.
1755	 * Log advice and ignore the signal.
1756	 */
1757	if (res == NULL || strcmp(gres->hr_name, res->hr_name) != 0 ||
1758	    strcmp(gres->hr_provname, res->hr_provname) != 0 ||
1759	    strcmp(gres->hr_localpath, res->hr_localpath) != 0) {
1760		pjdlog_warning("To reload configuration send SIGHUP to the main hastd process (pid %u).",
1761		    (unsigned int)getppid());
1762		goto failed;
1763	}
1764
1765#define MODIFIED_REMOTEADDR	0x1
1766#define MODIFIED_REPLICATION	0x2
1767#define MODIFIED_TIMEOUT	0x4
1768#define MODIFIED_EXEC		0x8
1769	modified = 0;
1770	if (strcmp(gres->hr_remoteaddr, res->hr_remoteaddr) != 0) {
1771		/*
1772		 * Don't copy res->hr_remoteaddr to gres just yet.
1773		 * We want remote_close() to log disconnect from the old
1774		 * addresses, not from the new ones.
1775		 */
1776		modified |= MODIFIED_REMOTEADDR;
1777	}
1778	if (gres->hr_replication != res->hr_replication) {
1779		gres->hr_replication = res->hr_replication;
1780		modified |= MODIFIED_REPLICATION;
1781	}
1782	if (gres->hr_timeout != res->hr_timeout) {
1783		gres->hr_timeout = res->hr_timeout;
1784		modified |= MODIFIED_TIMEOUT;
1785	}
1786	if (strcmp(gres->hr_exec, res->hr_exec) != 0) {
1787		strlcpy(gres->hr_exec, res->hr_exec, sizeof(gres->hr_exec));
1788		modified |= MODIFIED_EXEC;
1789	}
1790	/*
1791	 * If only timeout was modified we only need to change it without
1792	 * reconnecting.
1793	 */
1794	if (modified == MODIFIED_TIMEOUT) {
1795		for (ii = 0; ii < ncomps; ii++) {
1796			if (!ISREMOTE(ii))
1797				continue;
1798			rw_rlock(&hio_remote_lock[ii]);
1799			if (!ISCONNECTED(gres, ii)) {
1800				rw_unlock(&hio_remote_lock[ii]);
1801				continue;
1802			}
1803			rw_unlock(&hio_remote_lock[ii]);
1804			if (proto_timeout(gres->hr_remotein,
1805			    gres->hr_timeout) < 0) {
1806				pjdlog_errno(LOG_WARNING,
1807				    "Unable to set connection timeout");
1808			}
1809			if (proto_timeout(gres->hr_remoteout,
1810			    gres->hr_timeout) < 0) {
1811				pjdlog_errno(LOG_WARNING,
1812				    "Unable to set connection timeout");
1813			}
1814		}
1815	} else if ((modified &
1816	    (MODIFIED_REMOTEADDR | MODIFIED_REPLICATION)) != 0) {
1817		for (ii = 0; ii < ncomps; ii++) {
1818			if (!ISREMOTE(ii))
1819				continue;
1820			remote_close(gres, ii);
1821		}
1822		if (modified & MODIFIED_REMOTEADDR) {
1823			strlcpy(gres->hr_remoteaddr, res->hr_remoteaddr,
1824			    sizeof(gres->hr_remoteaddr));
1825		}
1826	}
1827#undef	MODIFIED_REMOTEADDR
1828#undef	MODIFIED_REPLICATION
1829#undef	MODIFIED_TIMEOUT
1830#undef	MODIFIED_EXEC
1831
1832	pjdlog_info("Configuration reloaded successfully.");
1833	return;
1834failed:
1835	if (newcfg != NULL) {
1836		if (newcfg->hc_controlconn != NULL)
1837			proto_close(newcfg->hc_controlconn);
1838		if (newcfg->hc_listenconn != NULL)
1839			proto_close(newcfg->hc_listenconn);
1840		yy_config_free(newcfg);
1841	}
1842	pjdlog_warning("Configuration not reloaded.");
1843}
1844
1845static void
1846keepalive_send(struct hast_resource *res, unsigned int ncomp)
1847{
1848	struct nv *nv;
1849
1850	nv = nv_alloc();
1851	nv_add_uint8(nv, HIO_KEEPALIVE, "cmd");
1852	if (nv_error(nv) != 0) {
1853		nv_free(nv);
1854		pjdlog_debug(1,
1855		    "keepalive_send: Unable to prepare header to send.");
1856		return;
1857	}
1858	if (hast_proto_send(res, res->hr_remoteout, nv, NULL, 0) < 0) {
1859		pjdlog_common(LOG_DEBUG, 1, errno,
1860		    "keepalive_send: Unable to send request");
1861		nv_free(nv);
1862		rw_unlock(&hio_remote_lock[ncomp]);
1863		remote_close(res, ncomp);
1864		rw_rlock(&hio_remote_lock[ncomp]);
1865		return;
1866	}
1867	nv_free(nv);
1868	pjdlog_debug(2, "keepalive_send: Request sent.");
1869}
1870
1871static void
1872guard_one(struct hast_resource *res, unsigned int ncomp)
1873{
1874	struct proto_conn *in, *out;
1875
1876	if (!ISREMOTE(ncomp))
1877		return;
1878
1879	rw_rlock(&hio_remote_lock[ncomp]);
1880
1881	if (!real_remote(res)) {
1882		rw_unlock(&hio_remote_lock[ncomp]);
1883		return;
1884	}
1885
1886	if (ISCONNECTED(res, ncomp)) {
1887		assert(res->hr_remotein != NULL);
1888		assert(res->hr_remoteout != NULL);
1889		keepalive_send(res, ncomp);
1890	}
1891
1892	if (ISCONNECTED(res, ncomp)) {
1893		assert(res->hr_remotein != NULL);
1894		assert(res->hr_remoteout != NULL);
1895		rw_unlock(&hio_remote_lock[ncomp]);
1896		pjdlog_debug(2, "remote_guard: Connection to %s is ok.",
1897		    res->hr_remoteaddr);
1898		return;
1899	}
1900
1901	assert(res->hr_remotein == NULL);
1902	assert(res->hr_remoteout == NULL);
1903	/*
1904	 * Upgrade the lock. It doesn't have to be atomic as no other thread
1905	 * can change connection status from disconnected to connected.
1906	 */
1907	rw_unlock(&hio_remote_lock[ncomp]);
1908	pjdlog_debug(2, "remote_guard: Reconnecting to %s.",
1909	    res->hr_remoteaddr);
1910	in = out = NULL;
1911	if (init_remote(res, &in, &out)) {
1912		rw_wlock(&hio_remote_lock[ncomp]);
1913		assert(res->hr_remotein == NULL);
1914		assert(res->hr_remoteout == NULL);
1915		assert(in != NULL && out != NULL);
1916		res->hr_remotein = in;
1917		res->hr_remoteout = out;
1918		rw_unlock(&hio_remote_lock[ncomp]);
1919		pjdlog_info("Successfully reconnected to %s.",
1920		    res->hr_remoteaddr);
1921		sync_start();
1922	} else {
1923		/* Both connections should be NULL. */
1924		assert(res->hr_remotein == NULL);
1925		assert(res->hr_remoteout == NULL);
1926		assert(in == NULL && out == NULL);
1927		pjdlog_debug(2, "remote_guard: Reconnect to %s failed.",
1928		    res->hr_remoteaddr);
1929	}
1930}
1931
1932/*
1933 * Thread guards remote connections and reconnects when needed, handles
1934 * signals, etc.
1935 */
1936static void *
1937guard_thread(void *arg)
1938{
1939	struct hast_resource *res = arg;
1940	unsigned int ii, ncomps;
1941	struct timespec timeout;
1942	time_t lastcheck, now;
1943	sigset_t mask;
1944	int signo;
1945
1946	ncomps = HAST_NCOMPONENTS;
1947	lastcheck = time(NULL);
1948
1949	PJDLOG_VERIFY(sigemptyset(&mask) == 0);
1950	PJDLOG_VERIFY(sigaddset(&mask, SIGHUP) == 0);
1951	PJDLOG_VERIFY(sigaddset(&mask, SIGINT) == 0);
1952	PJDLOG_VERIFY(sigaddset(&mask, SIGTERM) == 0);
1953	PJDLOG_VERIFY(sigaddset(&mask, SIGCHLD) == 0);
1954
1955	timeout.tv_nsec = 0;
1956	signo = -1;
1957
1958	for (;;) {
1959		switch (signo) {
1960		case SIGHUP:
1961			config_reload();
1962			break;
1963		case SIGINT:
1964		case SIGTERM:
1965			sigexit_received = true;
1966			primary_exitx(EX_OK,
1967			    "Termination signal received, exiting.");
1968			break;
1969		default:
1970			break;
1971		}
1972		hook_check(signo == SIGCHLD);
1973
1974		pjdlog_debug(2, "remote_guard: Checking connections.");
1975		now = time(NULL);
1976		if (lastcheck + RETRY_SLEEP <= now) {
1977			for (ii = 0; ii < ncomps; ii++)
1978				guard_one(res, ii);
1979			lastcheck = now;
1980		}
1981		timeout.tv_sec = RETRY_SLEEP;
1982		signo = sigtimedwait(&mask, NULL, &timeout);
1983	}
1984	/* NOTREACHED */
1985	return (NULL);
1986}
1987