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