primary.c revision 213531
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 213531 2010-10-07 18:20:16Z 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	/* Destroy ggate provider if we created one. */
238	if (res->hr_ggateunit >= 0) {
239		struct g_gate_ctl_destroy ggiod;
240
241		ggiod.gctl_version = G_GATE_VERSION;
242		ggiod.gctl_unit = res->hr_ggateunit;
243		ggiod.gctl_force = 1;
244		if (ioctl(res->hr_ggatefd, G_GATE_CMD_DESTROY, &ggiod) < 0) {
245			pjdlog_errno(LOG_WARNING,
246			    "Unable to destroy hast/%s device",
247			    res->hr_provname);
248		}
249		res->hr_ggateunit = -1;
250	}
251
252	/* Restore errno. */
253	errno = rerrno;
254}
255
256static __dead2 void
257primary_exit(int exitcode, const char *fmt, ...)
258{
259	va_list ap;
260
261	assert(exitcode != EX_OK);
262	va_start(ap, fmt);
263	pjdlogv_errno(LOG_ERR, fmt, ap);
264	va_end(ap);
265	cleanup(gres);
266	exit(exitcode);
267}
268
269static __dead2 void
270primary_exitx(int exitcode, const char *fmt, ...)
271{
272	va_list ap;
273
274	va_start(ap, fmt);
275	pjdlogv(exitcode == EX_OK ? LOG_INFO : LOG_ERR, fmt, ap);
276	va_end(ap);
277	cleanup(gres);
278	exit(exitcode);
279}
280
281static int
282hast_activemap_flush(struct hast_resource *res)
283{
284	const unsigned char *buf;
285	size_t size;
286
287	buf = activemap_bitmap(res->hr_amp, &size);
288	assert(buf != NULL);
289	assert((size % res->hr_local_sectorsize) == 0);
290	if (pwrite(res->hr_localfd, buf, size, METADATA_SIZE) !=
291	    (ssize_t)size) {
292		KEEP_ERRNO(pjdlog_errno(LOG_ERR,
293		    "Unable to flush activemap to disk"));
294		return (-1);
295	}
296	return (0);
297}
298
299static bool
300real_remote(const struct hast_resource *res)
301{
302
303	return (strcmp(res->hr_remoteaddr, "none") != 0);
304}
305
306static void
307init_environment(struct hast_resource *res __unused)
308{
309	struct hio *hio;
310	unsigned int ii, ncomps;
311
312	/*
313	 * In the future it might be per-resource value.
314	 */
315	ncomps = HAST_NCOMPONENTS;
316
317	/*
318	 * Allocate memory needed by lists.
319	 */
320	hio_send_list = malloc(sizeof(hio_send_list[0]) * ncomps);
321	if (hio_send_list == NULL) {
322		primary_exitx(EX_TEMPFAIL,
323		    "Unable to allocate %zu bytes of memory for send lists.",
324		    sizeof(hio_send_list[0]) * ncomps);
325	}
326	hio_send_list_lock = malloc(sizeof(hio_send_list_lock[0]) * ncomps);
327	if (hio_send_list_lock == NULL) {
328		primary_exitx(EX_TEMPFAIL,
329		    "Unable to allocate %zu bytes of memory for send list locks.",
330		    sizeof(hio_send_list_lock[0]) * ncomps);
331	}
332	hio_send_list_cond = malloc(sizeof(hio_send_list_cond[0]) * ncomps);
333	if (hio_send_list_cond == NULL) {
334		primary_exitx(EX_TEMPFAIL,
335		    "Unable to allocate %zu bytes of memory for send list condition variables.",
336		    sizeof(hio_send_list_cond[0]) * ncomps);
337	}
338	hio_recv_list = malloc(sizeof(hio_recv_list[0]) * ncomps);
339	if (hio_recv_list == NULL) {
340		primary_exitx(EX_TEMPFAIL,
341		    "Unable to allocate %zu bytes of memory for recv lists.",
342		    sizeof(hio_recv_list[0]) * ncomps);
343	}
344	hio_recv_list_lock = malloc(sizeof(hio_recv_list_lock[0]) * ncomps);
345	if (hio_recv_list_lock == NULL) {
346		primary_exitx(EX_TEMPFAIL,
347		    "Unable to allocate %zu bytes of memory for recv list locks.",
348		    sizeof(hio_recv_list_lock[0]) * ncomps);
349	}
350	hio_recv_list_cond = malloc(sizeof(hio_recv_list_cond[0]) * ncomps);
351	if (hio_recv_list_cond == NULL) {
352		primary_exitx(EX_TEMPFAIL,
353		    "Unable to allocate %zu bytes of memory for recv list condition variables.",
354		    sizeof(hio_recv_list_cond[0]) * ncomps);
355	}
356	hio_remote_lock = malloc(sizeof(hio_remote_lock[0]) * ncomps);
357	if (hio_remote_lock == NULL) {
358		primary_exitx(EX_TEMPFAIL,
359		    "Unable to allocate %zu bytes of memory for remote connections locks.",
360		    sizeof(hio_remote_lock[0]) * ncomps);
361	}
362
363	/*
364	 * Initialize lists, their locks and theirs condition variables.
365	 */
366	TAILQ_INIT(&hio_free_list);
367	mtx_init(&hio_free_list_lock);
368	cv_init(&hio_free_list_cond);
369	for (ii = 0; ii < HAST_NCOMPONENTS; ii++) {
370		TAILQ_INIT(&hio_send_list[ii]);
371		mtx_init(&hio_send_list_lock[ii]);
372		cv_init(&hio_send_list_cond[ii]);
373		TAILQ_INIT(&hio_recv_list[ii]);
374		mtx_init(&hio_recv_list_lock[ii]);
375		cv_init(&hio_recv_list_cond[ii]);
376		rw_init(&hio_remote_lock[ii]);
377	}
378	TAILQ_INIT(&hio_done_list);
379	mtx_init(&hio_done_list_lock);
380	cv_init(&hio_done_list_cond);
381	mtx_init(&metadata_lock);
382
383	/*
384	 * Allocate requests pool and initialize requests.
385	 */
386	for (ii = 0; ii < HAST_HIO_MAX; ii++) {
387		hio = malloc(sizeof(*hio));
388		if (hio == NULL) {
389			primary_exitx(EX_TEMPFAIL,
390			    "Unable to allocate %zu bytes of memory for hio request.",
391			    sizeof(*hio));
392		}
393		hio->hio_countdown = 0;
394		hio->hio_errors = malloc(sizeof(hio->hio_errors[0]) * ncomps);
395		if (hio->hio_errors == NULL) {
396			primary_exitx(EX_TEMPFAIL,
397			    "Unable allocate %zu bytes of memory for hio errors.",
398			    sizeof(hio->hio_errors[0]) * ncomps);
399		}
400		hio->hio_next = malloc(sizeof(hio->hio_next[0]) * ncomps);
401		if (hio->hio_next == NULL) {
402			primary_exitx(EX_TEMPFAIL,
403			    "Unable allocate %zu bytes of memory for hio_next field.",
404			    sizeof(hio->hio_next[0]) * ncomps);
405		}
406		hio->hio_ggio.gctl_version = G_GATE_VERSION;
407		hio->hio_ggio.gctl_data = malloc(MAXPHYS);
408		if (hio->hio_ggio.gctl_data == NULL) {
409			primary_exitx(EX_TEMPFAIL,
410			    "Unable to allocate %zu bytes of memory for gctl_data.",
411			    MAXPHYS);
412		}
413		hio->hio_ggio.gctl_length = MAXPHYS;
414		hio->hio_ggio.gctl_error = 0;
415		TAILQ_INSERT_HEAD(&hio_free_list, hio, hio_free_next);
416	}
417}
418
419static void
420init_local(struct hast_resource *res)
421{
422	unsigned char *buf;
423	size_t mapsize;
424
425	if (metadata_read(res, true) < 0)
426		exit(EX_NOINPUT);
427	mtx_init(&res->hr_amp_lock);
428	if (activemap_init(&res->hr_amp, res->hr_datasize, res->hr_extentsize,
429	    res->hr_local_sectorsize, res->hr_keepdirty) < 0) {
430		primary_exit(EX_TEMPFAIL, "Unable to create activemap");
431	}
432	mtx_init(&range_lock);
433	cv_init(&range_regular_cond);
434	if (rangelock_init(&range_regular) < 0)
435		primary_exit(EX_TEMPFAIL, "Unable to create regular range lock");
436	cv_init(&range_sync_cond);
437	if (rangelock_init(&range_sync) < 0)
438		primary_exit(EX_TEMPFAIL, "Unable to create sync range lock");
439	mapsize = activemap_ondisk_size(res->hr_amp);
440	buf = calloc(1, mapsize);
441	if (buf == NULL) {
442		primary_exitx(EX_TEMPFAIL,
443		    "Unable to allocate buffer for activemap.");
444	}
445	if (pread(res->hr_localfd, buf, mapsize, METADATA_SIZE) !=
446	    (ssize_t)mapsize) {
447		primary_exit(EX_NOINPUT, "Unable to read activemap");
448	}
449	activemap_copyin(res->hr_amp, buf, mapsize);
450	free(buf);
451	if (res->hr_resuid != 0)
452		return;
453	/*
454	 * We're using provider for the first time, so we have to generate
455	 * resource unique identifier and initialize local and remote counts.
456	 */
457	arc4random_buf(&res->hr_resuid, sizeof(res->hr_resuid));
458	res->hr_primary_localcnt = 1;
459	res->hr_primary_remotecnt = 0;
460	if (metadata_write(res) < 0)
461		exit(EX_NOINPUT);
462}
463
464static bool
465init_remote(struct hast_resource *res, struct proto_conn **inp,
466    struct proto_conn **outp)
467{
468	struct proto_conn *in, *out;
469	struct nv *nvout, *nvin;
470	const unsigned char *token;
471	unsigned char *map;
472	const char *errmsg;
473	int32_t extentsize;
474	int64_t datasize;
475	uint32_t mapsize;
476	size_t size;
477
478	assert((inp == NULL && outp == NULL) || (inp != NULL && outp != NULL));
479	assert(real_remote(res));
480
481	in = out = NULL;
482	errmsg = NULL;
483
484	/* Prepare outgoing connection with remote node. */
485	if (proto_client(res->hr_remoteaddr, &out) < 0) {
486		primary_exit(EX_TEMPFAIL, "Unable to create connection to %s",
487		    res->hr_remoteaddr);
488	}
489	/* Try to connect, but accept failure. */
490	if (proto_connect(out) < 0) {
491		pjdlog_errno(LOG_WARNING, "Unable to connect to %s",
492		    res->hr_remoteaddr);
493		goto close;
494	}
495	/* Error in setting timeout is not critical, but why should it fail? */
496	if (proto_timeout(out, res->hr_timeout) < 0)
497		pjdlog_errno(LOG_WARNING, "Unable to set connection timeout");
498	/*
499	 * First handshake step.
500	 * Setup outgoing connection with remote node.
501	 */
502	nvout = nv_alloc();
503	nv_add_string(nvout, res->hr_name, "resource");
504	if (nv_error(nvout) != 0) {
505		pjdlog_common(LOG_WARNING, 0, nv_error(nvout),
506		    "Unable to allocate header for connection with %s",
507		    res->hr_remoteaddr);
508		nv_free(nvout);
509		goto close;
510	}
511	if (hast_proto_send(res, out, nvout, NULL, 0) < 0) {
512		pjdlog_errno(LOG_WARNING,
513		    "Unable to send handshake header to %s",
514		    res->hr_remoteaddr);
515		nv_free(nvout);
516		goto close;
517	}
518	nv_free(nvout);
519	if (hast_proto_recv_hdr(out, &nvin) < 0) {
520		pjdlog_errno(LOG_WARNING,
521		    "Unable to receive handshake header from %s",
522		    res->hr_remoteaddr);
523		goto close;
524	}
525	errmsg = nv_get_string(nvin, "errmsg");
526	if (errmsg != NULL) {
527		pjdlog_warning("%s", errmsg);
528		nv_free(nvin);
529		goto close;
530	}
531	token = nv_get_uint8_array(nvin, &size, "token");
532	if (token == NULL) {
533		pjdlog_warning("Handshake header from %s has no 'token' field.",
534		    res->hr_remoteaddr);
535		nv_free(nvin);
536		goto close;
537	}
538	if (size != sizeof(res->hr_token)) {
539		pjdlog_warning("Handshake header from %s contains 'token' of wrong size (got %zu, expected %zu).",
540		    res->hr_remoteaddr, size, sizeof(res->hr_token));
541		nv_free(nvin);
542		goto close;
543	}
544	bcopy(token, res->hr_token, sizeof(res->hr_token));
545	nv_free(nvin);
546
547	/*
548	 * Second handshake step.
549	 * Setup incoming connection with remote node.
550	 */
551	if (proto_client(res->hr_remoteaddr, &in) < 0) {
552		pjdlog_errno(LOG_WARNING, "Unable to create connection to %s",
553		    res->hr_remoteaddr);
554	}
555	/* Try to connect, but accept failure. */
556	if (proto_connect(in) < 0) {
557		pjdlog_errno(LOG_WARNING, "Unable to connect to %s",
558		    res->hr_remoteaddr);
559		goto close;
560	}
561	/* Error in setting timeout is not critical, but why should it fail? */
562	if (proto_timeout(in, res->hr_timeout) < 0)
563		pjdlog_errno(LOG_WARNING, "Unable to set connection timeout");
564	nvout = nv_alloc();
565	nv_add_string(nvout, res->hr_name, "resource");
566	nv_add_uint8_array(nvout, res->hr_token, sizeof(res->hr_token),
567	    "token");
568	nv_add_uint64(nvout, res->hr_resuid, "resuid");
569	nv_add_uint64(nvout, res->hr_primary_localcnt, "localcnt");
570	nv_add_uint64(nvout, res->hr_primary_remotecnt, "remotecnt");
571	if (nv_error(nvout) != 0) {
572		pjdlog_common(LOG_WARNING, 0, nv_error(nvout),
573		    "Unable to allocate header for connection with %s",
574		    res->hr_remoteaddr);
575		nv_free(nvout);
576		goto close;
577	}
578	if (hast_proto_send(res, in, nvout, NULL, 0) < 0) {
579		pjdlog_errno(LOG_WARNING,
580		    "Unable to send handshake header to %s",
581		    res->hr_remoteaddr);
582		nv_free(nvout);
583		goto close;
584	}
585	nv_free(nvout);
586	if (hast_proto_recv_hdr(out, &nvin) < 0) {
587		pjdlog_errno(LOG_WARNING,
588		    "Unable to receive handshake header from %s",
589		    res->hr_remoteaddr);
590		goto close;
591	}
592	errmsg = nv_get_string(nvin, "errmsg");
593	if (errmsg != NULL) {
594		pjdlog_warning("%s", errmsg);
595		nv_free(nvin);
596		goto close;
597	}
598	datasize = nv_get_int64(nvin, "datasize");
599	if (datasize != res->hr_datasize) {
600		pjdlog_warning("Data size differs between nodes (local=%jd, remote=%jd).",
601		    (intmax_t)res->hr_datasize, (intmax_t)datasize);
602		nv_free(nvin);
603		goto close;
604	}
605	extentsize = nv_get_int32(nvin, "extentsize");
606	if (extentsize != res->hr_extentsize) {
607		pjdlog_warning("Extent size differs between nodes (local=%zd, remote=%zd).",
608		    (ssize_t)res->hr_extentsize, (ssize_t)extentsize);
609		nv_free(nvin);
610		goto close;
611	}
612	res->hr_secondary_localcnt = nv_get_uint64(nvin, "localcnt");
613	res->hr_secondary_remotecnt = nv_get_uint64(nvin, "remotecnt");
614	res->hr_syncsrc = nv_get_uint8(nvin, "syncsrc");
615	map = NULL;
616	mapsize = nv_get_uint32(nvin, "mapsize");
617	if (mapsize > 0) {
618		map = malloc(mapsize);
619		if (map == NULL) {
620			pjdlog_error("Unable to allocate memory for remote activemap (mapsize=%ju).",
621			    (uintmax_t)mapsize);
622			nv_free(nvin);
623			goto close;
624		}
625		/*
626		 * Remote node have some dirty extents on its own, lets
627		 * download its activemap.
628		 */
629		if (hast_proto_recv_data(res, out, nvin, map,
630		    mapsize) < 0) {
631			pjdlog_errno(LOG_ERR,
632			    "Unable to receive remote activemap");
633			nv_free(nvin);
634			free(map);
635			goto close;
636		}
637		/*
638		 * Merge local and remote bitmaps.
639		 */
640		activemap_merge(res->hr_amp, map, mapsize);
641		free(map);
642		/*
643		 * Now that we merged bitmaps from both nodes, flush it to the
644		 * disk before we start to synchronize.
645		 */
646		(void)hast_activemap_flush(res);
647	}
648	pjdlog_info("Connected to %s.", res->hr_remoteaddr);
649	if (inp != NULL && outp != NULL) {
650		*inp = in;
651		*outp = out;
652	} else {
653		res->hr_remotein = in;
654		res->hr_remoteout = out;
655	}
656	event_send(res, EVENT_CONNECT);
657	return (true);
658close:
659	if (errmsg != NULL && strcmp(errmsg, "Split-brain condition!") == 0)
660		event_send(res, EVENT_SPLITBRAIN);
661	proto_close(out);
662	if (in != NULL)
663		proto_close(in);
664	return (false);
665}
666
667static void
668sync_start(void)
669{
670
671	mtx_lock(&sync_lock);
672	sync_inprogress = true;
673	mtx_unlock(&sync_lock);
674	cv_signal(&sync_cond);
675}
676
677static void
678sync_stop(void)
679{
680
681	mtx_lock(&sync_lock);
682	if (sync_inprogress)
683		sync_inprogress = false;
684	mtx_unlock(&sync_lock);
685}
686
687static void
688init_ggate(struct hast_resource *res)
689{
690	struct g_gate_ctl_create ggiocreate;
691	struct g_gate_ctl_cancel ggiocancel;
692
693	/*
694	 * We communicate with ggate via /dev/ggctl. Open it.
695	 */
696	res->hr_ggatefd = open("/dev/" G_GATE_CTL_NAME, O_RDWR);
697	if (res->hr_ggatefd < 0)
698		primary_exit(EX_OSFILE, "Unable to open /dev/" G_GATE_CTL_NAME);
699	/*
700	 * Create provider before trying to connect, as connection failure
701	 * is not critical, but may take some time.
702	 */
703	ggiocreate.gctl_version = G_GATE_VERSION;
704	ggiocreate.gctl_mediasize = res->hr_datasize;
705	ggiocreate.gctl_sectorsize = res->hr_local_sectorsize;
706	ggiocreate.gctl_flags = 0;
707	ggiocreate.gctl_maxcount = G_GATE_MAX_QUEUE_SIZE;
708	ggiocreate.gctl_timeout = 0;
709	ggiocreate.gctl_unit = G_GATE_NAME_GIVEN;
710	snprintf(ggiocreate.gctl_name, sizeof(ggiocreate.gctl_name), "hast/%s",
711	    res->hr_provname);
712	bzero(ggiocreate.gctl_info, sizeof(ggiocreate.gctl_info));
713	if (ioctl(res->hr_ggatefd, G_GATE_CMD_CREATE, &ggiocreate) == 0) {
714		pjdlog_info("Device hast/%s created.", res->hr_provname);
715		res->hr_ggateunit = ggiocreate.gctl_unit;
716		return;
717	}
718	if (errno != EEXIST) {
719		primary_exit(EX_OSERR, "Unable to create hast/%s device",
720		    res->hr_provname);
721	}
722	pjdlog_debug(1,
723	    "Device hast/%s already exists, we will try to take it over.",
724	    res->hr_provname);
725	/*
726	 * If we received EEXIST, we assume that the process who created the
727	 * provider died and didn't clean up. In that case we will start from
728	 * where he left of.
729	 */
730	ggiocancel.gctl_version = G_GATE_VERSION;
731	ggiocancel.gctl_unit = G_GATE_NAME_GIVEN;
732	snprintf(ggiocancel.gctl_name, sizeof(ggiocancel.gctl_name), "hast/%s",
733	    res->hr_provname);
734	if (ioctl(res->hr_ggatefd, G_GATE_CMD_CANCEL, &ggiocancel) == 0) {
735		pjdlog_info("Device hast/%s recovered.", res->hr_provname);
736		res->hr_ggateunit = ggiocancel.gctl_unit;
737		return;
738	}
739	primary_exit(EX_OSERR, "Unable to take over hast/%s device",
740	    res->hr_provname);
741}
742
743void
744hastd_primary(struct hast_resource *res)
745{
746	pthread_t td;
747	pid_t pid;
748	int error;
749
750	/*
751	 * Create communication channel between parent and child.
752	 */
753	if (proto_client("socketpair://", &res->hr_ctrl) < 0) {
754		KEEP_ERRNO((void)pidfile_remove(pfh));
755		pjdlog_exit(EX_OSERR,
756		    "Unable to create control sockets between parent and child");
757	}
758	/*
759	 * Create communication channel between child and parent.
760	 */
761	if (proto_client("socketpair://", &res->hr_event) < 0) {
762		KEEP_ERRNO((void)pidfile_remove(pfh));
763		pjdlog_exit(EX_OSERR,
764		    "Unable to create event sockets between child and parent");
765	}
766
767	pid = fork();
768	if (pid < 0) {
769		KEEP_ERRNO((void)pidfile_remove(pfh));
770		pjdlog_exit(EX_TEMPFAIL, "Unable to fork");
771	}
772
773	if (pid > 0) {
774		/* This is parent. */
775		/* Declare that we are receiver. */
776		proto_recv(res->hr_event, NULL, 0);
777		res->hr_workerpid = pid;
778		return;
779	}
780
781	gres = res;
782
783	(void)pidfile_close(pfh);
784	hook_fini();
785
786	setproctitle("%s (primary)", res->hr_name);
787
788	/* Declare that we are sender. */
789	proto_send(res->hr_event, NULL, 0);
790
791	init_local(res);
792	init_ggate(res);
793	init_environment(res);
794	/*
795	 * Create the guard thread first, so we can handle signals from the
796	 * very begining.
797	 */
798	error = pthread_create(&td, NULL, guard_thread, res);
799	assert(error == 0);
800	/*
801	 * Create the control thread before sending any event to the parent,
802	 * as we can deadlock when parent sends control request to worker,
803	 * but worker has no control thread started yet, so parent waits.
804	 * In the meantime worker sends an event to the parent, but parent
805	 * is unable to handle the event, because it waits for control
806	 * request response.
807	 */
808	error = pthread_create(&td, NULL, ctrl_thread, res);
809	assert(error == 0);
810	if (real_remote(res) && init_remote(res, NULL, NULL))
811		sync_start();
812	error = pthread_create(&td, NULL, ggate_recv_thread, res);
813	assert(error == 0);
814	error = pthread_create(&td, NULL, local_send_thread, res);
815	assert(error == 0);
816	error = pthread_create(&td, NULL, remote_send_thread, res);
817	assert(error == 0);
818	error = pthread_create(&td, NULL, remote_recv_thread, res);
819	assert(error == 0);
820	error = pthread_create(&td, NULL, ggate_send_thread, res);
821	assert(error == 0);
822	(void)sync_thread(res);
823}
824
825static void
826reqlog(int loglevel, int debuglevel, struct g_gate_ctl_io *ggio, const char *fmt, ...)
827{
828	char msg[1024];
829	va_list ap;
830	int len;
831
832	va_start(ap, fmt);
833	len = vsnprintf(msg, sizeof(msg), fmt, ap);
834	va_end(ap);
835	if ((size_t)len < sizeof(msg)) {
836		switch (ggio->gctl_cmd) {
837		case BIO_READ:
838			(void)snprintf(msg + len, sizeof(msg) - len,
839			    "READ(%ju, %ju).", (uintmax_t)ggio->gctl_offset,
840			    (uintmax_t)ggio->gctl_length);
841			break;
842		case BIO_DELETE:
843			(void)snprintf(msg + len, sizeof(msg) - len,
844			    "DELETE(%ju, %ju).", (uintmax_t)ggio->gctl_offset,
845			    (uintmax_t)ggio->gctl_length);
846			break;
847		case BIO_FLUSH:
848			(void)snprintf(msg + len, sizeof(msg) - len, "FLUSH.");
849			break;
850		case BIO_WRITE:
851			(void)snprintf(msg + len, sizeof(msg) - len,
852			    "WRITE(%ju, %ju).", (uintmax_t)ggio->gctl_offset,
853			    (uintmax_t)ggio->gctl_length);
854			break;
855		default:
856			(void)snprintf(msg + len, sizeof(msg) - len,
857			    "UNKNOWN(%u).", (unsigned int)ggio->gctl_cmd);
858			break;
859		}
860	}
861	pjdlog_common(loglevel, debuglevel, -1, "%s", msg);
862}
863
864static void
865remote_close(struct hast_resource *res, int ncomp)
866{
867
868	rw_wlock(&hio_remote_lock[ncomp]);
869	/*
870	 * A race is possible between dropping rlock and acquiring wlock -
871	 * another thread can close connection in-between.
872	 */
873	if (!ISCONNECTED(res, ncomp)) {
874		assert(res->hr_remotein == NULL);
875		assert(res->hr_remoteout == NULL);
876		rw_unlock(&hio_remote_lock[ncomp]);
877		return;
878	}
879
880	assert(res->hr_remotein != NULL);
881	assert(res->hr_remoteout != NULL);
882
883	pjdlog_debug(2, "Closing incoming connection to %s.",
884	    res->hr_remoteaddr);
885	proto_close(res->hr_remotein);
886	res->hr_remotein = NULL;
887	pjdlog_debug(2, "Closing outgoing connection to %s.",
888	    res->hr_remoteaddr);
889	proto_close(res->hr_remoteout);
890	res->hr_remoteout = NULL;
891
892	rw_unlock(&hio_remote_lock[ncomp]);
893
894	pjdlog_warning("Disconnected from %s.", res->hr_remoteaddr);
895
896	/*
897	 * Stop synchronization if in-progress.
898	 */
899	sync_stop();
900
901	event_send(res, EVENT_DISCONNECT);
902}
903
904/*
905 * Thread receives ggate I/O requests from the kernel and passes them to
906 * appropriate threads:
907 * WRITE - always goes to both local_send and remote_send threads
908 * READ (when the block is up-to-date on local component) -
909 *	only local_send thread
910 * READ (when the block isn't up-to-date on local component) -
911 *	only remote_send thread
912 * DELETE - always goes to both local_send and remote_send threads
913 * FLUSH - always goes to both local_send and remote_send threads
914 */
915static void *
916ggate_recv_thread(void *arg)
917{
918	struct hast_resource *res = arg;
919	struct g_gate_ctl_io *ggio;
920	struct hio *hio;
921	unsigned int ii, ncomp, ncomps;
922	int error;
923
924	ncomps = HAST_NCOMPONENTS;
925
926	for (;;) {
927		pjdlog_debug(2, "ggate_recv: Taking free request.");
928		QUEUE_TAKE2(hio, free);
929		pjdlog_debug(2, "ggate_recv: (%p) Got free request.", hio);
930		ggio = &hio->hio_ggio;
931		ggio->gctl_unit = res->hr_ggateunit;
932		ggio->gctl_length = MAXPHYS;
933		ggio->gctl_error = 0;
934		pjdlog_debug(2,
935		    "ggate_recv: (%p) Waiting for request from the kernel.",
936		    hio);
937		if (ioctl(res->hr_ggatefd, G_GATE_CMD_START, ggio) < 0) {
938			if (sigexit_received)
939				pthread_exit(NULL);
940			primary_exit(EX_OSERR, "G_GATE_CMD_START failed");
941		}
942		error = ggio->gctl_error;
943		switch (error) {
944		case 0:
945			break;
946		case ECANCELED:
947			/* Exit gracefully. */
948			if (!sigexit_received) {
949				pjdlog_debug(2,
950				    "ggate_recv: (%p) Received cancel from the kernel.",
951				    hio);
952				pjdlog_info("Received cancel from the kernel, exiting.");
953			}
954			pthread_exit(NULL);
955		case ENOMEM:
956			/*
957			 * Buffer too small? Impossible, we allocate MAXPHYS
958			 * bytes - request can't be bigger than that.
959			 */
960			/* FALLTHROUGH */
961		case ENXIO:
962		default:
963			primary_exitx(EX_OSERR, "G_GATE_CMD_START failed: %s.",
964			    strerror(error));
965		}
966		for (ii = 0; ii < ncomps; ii++)
967			hio->hio_errors[ii] = EINVAL;
968		reqlog(LOG_DEBUG, 2, ggio,
969		    "ggate_recv: (%p) Request received from the kernel: ",
970		    hio);
971		/*
972		 * Inform all components about new write request.
973		 * For read request prefer local component unless the given
974		 * range is out-of-date, then use remote component.
975		 */
976		switch (ggio->gctl_cmd) {
977		case BIO_READ:
978			pjdlog_debug(2,
979			    "ggate_recv: (%p) Moving request to the send queue.",
980			    hio);
981			refcount_init(&hio->hio_countdown, 1);
982			mtx_lock(&metadata_lock);
983			if (res->hr_syncsrc == HAST_SYNCSRC_UNDEF ||
984			    res->hr_syncsrc == HAST_SYNCSRC_PRIMARY) {
985				/*
986				 * This range is up-to-date on local component,
987				 * so handle request locally.
988				 */
989				 /* Local component is 0 for now. */
990				ncomp = 0;
991			} else /* if (res->hr_syncsrc ==
992			    HAST_SYNCSRC_SECONDARY) */ {
993				assert(res->hr_syncsrc ==
994				    HAST_SYNCSRC_SECONDARY);
995				/*
996				 * This range is out-of-date on local component,
997				 * so send request to the remote node.
998				 */
999				 /* Remote component is 1 for now. */
1000				ncomp = 1;
1001			}
1002			mtx_unlock(&metadata_lock);
1003			QUEUE_INSERT1(hio, send, ncomp);
1004			break;
1005		case BIO_WRITE:
1006			for (;;) {
1007				mtx_lock(&range_lock);
1008				if (rangelock_islocked(range_sync,
1009				    ggio->gctl_offset, ggio->gctl_length)) {
1010					pjdlog_debug(2,
1011					    "regular: Range offset=%jd length=%zu locked.",
1012					    (intmax_t)ggio->gctl_offset,
1013					    (size_t)ggio->gctl_length);
1014					range_regular_wait = true;
1015					cv_wait(&range_regular_cond, &range_lock);
1016					range_regular_wait = false;
1017					mtx_unlock(&range_lock);
1018					continue;
1019				}
1020				if (rangelock_add(range_regular,
1021				    ggio->gctl_offset, ggio->gctl_length) < 0) {
1022					mtx_unlock(&range_lock);
1023					pjdlog_debug(2,
1024					    "regular: Range offset=%jd length=%zu is already locked, waiting.",
1025					    (intmax_t)ggio->gctl_offset,
1026					    (size_t)ggio->gctl_length);
1027					sleep(1);
1028					continue;
1029				}
1030				mtx_unlock(&range_lock);
1031				break;
1032			}
1033			mtx_lock(&res->hr_amp_lock);
1034			if (activemap_write_start(res->hr_amp,
1035			    ggio->gctl_offset, ggio->gctl_length)) {
1036				(void)hast_activemap_flush(res);
1037			}
1038			mtx_unlock(&res->hr_amp_lock);
1039			/* FALLTHROUGH */
1040		case BIO_DELETE:
1041		case BIO_FLUSH:
1042			pjdlog_debug(2,
1043			    "ggate_recv: (%p) Moving request to the send queues.",
1044			    hio);
1045			refcount_init(&hio->hio_countdown, ncomps);
1046			for (ii = 0; ii < ncomps; ii++)
1047				QUEUE_INSERT1(hio, send, ii);
1048			break;
1049		}
1050	}
1051	/* NOTREACHED */
1052	return (NULL);
1053}
1054
1055/*
1056 * Thread reads from or writes to local component.
1057 * If local read fails, it redirects it to remote_send thread.
1058 */
1059static void *
1060local_send_thread(void *arg)
1061{
1062	struct hast_resource *res = arg;
1063	struct g_gate_ctl_io *ggio;
1064	struct hio *hio;
1065	unsigned int ncomp, rncomp;
1066	ssize_t ret;
1067
1068	/* Local component is 0 for now. */
1069	ncomp = 0;
1070	/* Remote component is 1 for now. */
1071	rncomp = 1;
1072
1073	for (;;) {
1074		pjdlog_debug(2, "local_send: Taking request.");
1075		QUEUE_TAKE1(hio, send, ncomp);
1076		pjdlog_debug(2, "local_send: (%p) Got request.", hio);
1077		ggio = &hio->hio_ggio;
1078		switch (ggio->gctl_cmd) {
1079		case BIO_READ:
1080			ret = pread(res->hr_localfd, ggio->gctl_data,
1081			    ggio->gctl_length,
1082			    ggio->gctl_offset + res->hr_localoff);
1083			if (ret == ggio->gctl_length)
1084				hio->hio_errors[ncomp] = 0;
1085			else {
1086				/*
1087				 * If READ failed, try to read from remote node.
1088				 */
1089				QUEUE_INSERT1(hio, send, rncomp);
1090				continue;
1091			}
1092			break;
1093		case BIO_WRITE:
1094			ret = pwrite(res->hr_localfd, ggio->gctl_data,
1095			    ggio->gctl_length,
1096			    ggio->gctl_offset + res->hr_localoff);
1097			if (ret < 0)
1098				hio->hio_errors[ncomp] = errno;
1099			else if (ret != ggio->gctl_length)
1100				hio->hio_errors[ncomp] = EIO;
1101			else
1102				hio->hio_errors[ncomp] = 0;
1103			break;
1104		case BIO_DELETE:
1105			ret = g_delete(res->hr_localfd,
1106			    ggio->gctl_offset + res->hr_localoff,
1107			    ggio->gctl_length);
1108			if (ret < 0)
1109				hio->hio_errors[ncomp] = errno;
1110			else
1111				hio->hio_errors[ncomp] = 0;
1112			break;
1113		case BIO_FLUSH:
1114			ret = g_flush(res->hr_localfd);
1115			if (ret < 0)
1116				hio->hio_errors[ncomp] = errno;
1117			else
1118				hio->hio_errors[ncomp] = 0;
1119			break;
1120		}
1121		if (refcount_release(&hio->hio_countdown)) {
1122			if (ISSYNCREQ(hio)) {
1123				mtx_lock(&sync_lock);
1124				SYNCREQDONE(hio);
1125				mtx_unlock(&sync_lock);
1126				cv_signal(&sync_cond);
1127			} else {
1128				pjdlog_debug(2,
1129				    "local_send: (%p) Moving request to the done queue.",
1130				    hio);
1131				QUEUE_INSERT2(hio, done);
1132			}
1133		}
1134	}
1135	/* NOTREACHED */
1136	return (NULL);
1137}
1138
1139/*
1140 * Thread sends request to secondary node.
1141 */
1142static void *
1143remote_send_thread(void *arg)
1144{
1145	struct hast_resource *res = arg;
1146	struct g_gate_ctl_io *ggio;
1147	struct hio *hio;
1148	struct nv *nv;
1149	unsigned int ncomp;
1150	bool wakeup;
1151	uint64_t offset, length;
1152	uint8_t cmd;
1153	void *data;
1154
1155	/* Remote component is 1 for now. */
1156	ncomp = 1;
1157
1158	for (;;) {
1159		pjdlog_debug(2, "remote_send: Taking request.");
1160		QUEUE_TAKE1(hio, send, ncomp);
1161		pjdlog_debug(2, "remote_send: (%p) Got request.", hio);
1162		ggio = &hio->hio_ggio;
1163		switch (ggio->gctl_cmd) {
1164		case BIO_READ:
1165			cmd = HIO_READ;
1166			data = NULL;
1167			offset = ggio->gctl_offset;
1168			length = ggio->gctl_length;
1169			break;
1170		case BIO_WRITE:
1171			cmd = HIO_WRITE;
1172			data = ggio->gctl_data;
1173			offset = ggio->gctl_offset;
1174			length = ggio->gctl_length;
1175			break;
1176		case BIO_DELETE:
1177			cmd = HIO_DELETE;
1178			data = NULL;
1179			offset = ggio->gctl_offset;
1180			length = ggio->gctl_length;
1181			break;
1182		case BIO_FLUSH:
1183			cmd = HIO_FLUSH;
1184			data = NULL;
1185			offset = 0;
1186			length = 0;
1187			break;
1188		default:
1189			assert(!"invalid condition");
1190			abort();
1191		}
1192		nv = nv_alloc();
1193		nv_add_uint8(nv, cmd, "cmd");
1194		nv_add_uint64(nv, (uint64_t)ggio->gctl_seq, "seq");
1195		nv_add_uint64(nv, offset, "offset");
1196		nv_add_uint64(nv, length, "length");
1197		if (nv_error(nv) != 0) {
1198			hio->hio_errors[ncomp] = nv_error(nv);
1199			pjdlog_debug(2,
1200			    "remote_send: (%p) Unable to prepare header to send.",
1201			    hio);
1202			reqlog(LOG_ERR, 0, ggio,
1203			    "Unable to prepare header to send (%s): ",
1204			    strerror(nv_error(nv)));
1205			/* Move failed request immediately to the done queue. */
1206			goto done_queue;
1207		}
1208		pjdlog_debug(2,
1209		    "remote_send: (%p) Moving request to the recv queue.",
1210		    hio);
1211		/*
1212		 * Protect connection from disappearing.
1213		 */
1214		rw_rlock(&hio_remote_lock[ncomp]);
1215		if (!ISCONNECTED(res, ncomp)) {
1216			rw_unlock(&hio_remote_lock[ncomp]);
1217			hio->hio_errors[ncomp] = ENOTCONN;
1218			goto done_queue;
1219		}
1220		/*
1221		 * Move the request to recv queue before sending it, because
1222		 * in different order we can get reply before we move request
1223		 * to recv queue.
1224		 */
1225		mtx_lock(&hio_recv_list_lock[ncomp]);
1226		wakeup = TAILQ_EMPTY(&hio_recv_list[ncomp]);
1227		TAILQ_INSERT_TAIL(&hio_recv_list[ncomp], hio, hio_next[ncomp]);
1228		mtx_unlock(&hio_recv_list_lock[ncomp]);
1229		if (hast_proto_send(res, res->hr_remoteout, nv, data,
1230		    data != NULL ? length : 0) < 0) {
1231			hio->hio_errors[ncomp] = errno;
1232			rw_unlock(&hio_remote_lock[ncomp]);
1233			pjdlog_debug(2,
1234			    "remote_send: (%p) Unable to send request.", hio);
1235			reqlog(LOG_ERR, 0, ggio,
1236			    "Unable to send request (%s): ",
1237			    strerror(hio->hio_errors[ncomp]));
1238			remote_close(res, ncomp);
1239			/*
1240			 * Take request back from the receive queue and move
1241			 * it immediately to the done queue.
1242			 */
1243			mtx_lock(&hio_recv_list_lock[ncomp]);
1244			TAILQ_REMOVE(&hio_recv_list[ncomp], hio, hio_next[ncomp]);
1245			mtx_unlock(&hio_recv_list_lock[ncomp]);
1246			goto done_queue;
1247		}
1248		rw_unlock(&hio_remote_lock[ncomp]);
1249		nv_free(nv);
1250		if (wakeup)
1251			cv_signal(&hio_recv_list_cond[ncomp]);
1252		continue;
1253done_queue:
1254		nv_free(nv);
1255		if (ISSYNCREQ(hio)) {
1256			if (!refcount_release(&hio->hio_countdown))
1257				continue;
1258			mtx_lock(&sync_lock);
1259			SYNCREQDONE(hio);
1260			mtx_unlock(&sync_lock);
1261			cv_signal(&sync_cond);
1262			continue;
1263		}
1264		if (ggio->gctl_cmd == BIO_WRITE) {
1265			mtx_lock(&res->hr_amp_lock);
1266			if (activemap_need_sync(res->hr_amp, ggio->gctl_offset,
1267			    ggio->gctl_length)) {
1268				(void)hast_activemap_flush(res);
1269			}
1270			mtx_unlock(&res->hr_amp_lock);
1271		}
1272		if (!refcount_release(&hio->hio_countdown))
1273			continue;
1274		pjdlog_debug(2,
1275		    "remote_send: (%p) Moving request to the done queue.",
1276		    hio);
1277		QUEUE_INSERT2(hio, done);
1278	}
1279	/* NOTREACHED */
1280	return (NULL);
1281}
1282
1283/*
1284 * Thread receives answer from secondary node and passes it to ggate_send
1285 * thread.
1286 */
1287static void *
1288remote_recv_thread(void *arg)
1289{
1290	struct hast_resource *res = arg;
1291	struct g_gate_ctl_io *ggio;
1292	struct hio *hio;
1293	struct nv *nv;
1294	unsigned int ncomp;
1295	uint64_t seq;
1296	int error;
1297
1298	/* Remote component is 1 for now. */
1299	ncomp = 1;
1300
1301	for (;;) {
1302		/* Wait until there is anything to receive. */
1303		mtx_lock(&hio_recv_list_lock[ncomp]);
1304		while (TAILQ_EMPTY(&hio_recv_list[ncomp])) {
1305			pjdlog_debug(2, "remote_recv: No requests, waiting.");
1306			cv_wait(&hio_recv_list_cond[ncomp],
1307			    &hio_recv_list_lock[ncomp]);
1308		}
1309		mtx_unlock(&hio_recv_list_lock[ncomp]);
1310		rw_rlock(&hio_remote_lock[ncomp]);
1311		if (!ISCONNECTED(res, ncomp)) {
1312			rw_unlock(&hio_remote_lock[ncomp]);
1313			/*
1314			 * Connection is dead, so move all pending requests to
1315			 * the done queue (one-by-one).
1316			 */
1317			mtx_lock(&hio_recv_list_lock[ncomp]);
1318			hio = TAILQ_FIRST(&hio_recv_list[ncomp]);
1319			assert(hio != NULL);
1320			TAILQ_REMOVE(&hio_recv_list[ncomp], hio,
1321			    hio_next[ncomp]);
1322			mtx_unlock(&hio_recv_list_lock[ncomp]);
1323			goto done_queue;
1324		}
1325		if (hast_proto_recv_hdr(res->hr_remotein, &nv) < 0) {
1326			pjdlog_errno(LOG_ERR,
1327			    "Unable to receive reply header");
1328			rw_unlock(&hio_remote_lock[ncomp]);
1329			remote_close(res, ncomp);
1330			continue;
1331		}
1332		rw_unlock(&hio_remote_lock[ncomp]);
1333		seq = nv_get_uint64(nv, "seq");
1334		if (seq == 0) {
1335			pjdlog_error("Header contains no 'seq' field.");
1336			nv_free(nv);
1337			continue;
1338		}
1339		mtx_lock(&hio_recv_list_lock[ncomp]);
1340		TAILQ_FOREACH(hio, &hio_recv_list[ncomp], hio_next[ncomp]) {
1341			if (hio->hio_ggio.gctl_seq == seq) {
1342				TAILQ_REMOVE(&hio_recv_list[ncomp], hio,
1343				    hio_next[ncomp]);
1344				break;
1345			}
1346		}
1347		mtx_unlock(&hio_recv_list_lock[ncomp]);
1348		if (hio == NULL) {
1349			pjdlog_error("Found no request matching received 'seq' field (%ju).",
1350			    (uintmax_t)seq);
1351			nv_free(nv);
1352			continue;
1353		}
1354		error = nv_get_int16(nv, "error");
1355		if (error != 0) {
1356			/* Request failed on remote side. */
1357			hio->hio_errors[ncomp] = 0;
1358			nv_free(nv);
1359			goto done_queue;
1360		}
1361		ggio = &hio->hio_ggio;
1362		switch (ggio->gctl_cmd) {
1363		case BIO_READ:
1364			rw_rlock(&hio_remote_lock[ncomp]);
1365			if (!ISCONNECTED(res, ncomp)) {
1366				rw_unlock(&hio_remote_lock[ncomp]);
1367				nv_free(nv);
1368				goto done_queue;
1369			}
1370			if (hast_proto_recv_data(res, res->hr_remotein, nv,
1371			    ggio->gctl_data, ggio->gctl_length) < 0) {
1372				hio->hio_errors[ncomp] = errno;
1373				pjdlog_errno(LOG_ERR,
1374				    "Unable to receive reply data");
1375				rw_unlock(&hio_remote_lock[ncomp]);
1376				nv_free(nv);
1377				remote_close(res, ncomp);
1378				goto done_queue;
1379			}
1380			rw_unlock(&hio_remote_lock[ncomp]);
1381			break;
1382		case BIO_WRITE:
1383		case BIO_DELETE:
1384		case BIO_FLUSH:
1385			break;
1386		default:
1387			assert(!"invalid condition");
1388			abort();
1389		}
1390		hio->hio_errors[ncomp] = 0;
1391		nv_free(nv);
1392done_queue:
1393		if (refcount_release(&hio->hio_countdown)) {
1394			if (ISSYNCREQ(hio)) {
1395				mtx_lock(&sync_lock);
1396				SYNCREQDONE(hio);
1397				mtx_unlock(&sync_lock);
1398				cv_signal(&sync_cond);
1399			} else {
1400				pjdlog_debug(2,
1401				    "remote_recv: (%p) Moving request to the done queue.",
1402				    hio);
1403				QUEUE_INSERT2(hio, done);
1404			}
1405		}
1406	}
1407	/* NOTREACHED */
1408	return (NULL);
1409}
1410
1411/*
1412 * Thread sends answer to the kernel.
1413 */
1414static void *
1415ggate_send_thread(void *arg)
1416{
1417	struct hast_resource *res = arg;
1418	struct g_gate_ctl_io *ggio;
1419	struct hio *hio;
1420	unsigned int ii, ncomp, ncomps;
1421
1422	ncomps = HAST_NCOMPONENTS;
1423
1424	for (;;) {
1425		pjdlog_debug(2, "ggate_send: Taking request.");
1426		QUEUE_TAKE2(hio, done);
1427		pjdlog_debug(2, "ggate_send: (%p) Got request.", hio);
1428		ggio = &hio->hio_ggio;
1429		for (ii = 0; ii < ncomps; ii++) {
1430			if (hio->hio_errors[ii] == 0) {
1431				/*
1432				 * One successful request is enough to declare
1433				 * success.
1434				 */
1435				ggio->gctl_error = 0;
1436				break;
1437			}
1438		}
1439		if (ii == ncomps) {
1440			/*
1441			 * None of the requests were successful.
1442			 * Use first error.
1443			 */
1444			ggio->gctl_error = hio->hio_errors[0];
1445		}
1446		if (ggio->gctl_error == 0 && ggio->gctl_cmd == BIO_WRITE) {
1447			mtx_lock(&res->hr_amp_lock);
1448			activemap_write_complete(res->hr_amp,
1449			    ggio->gctl_offset, ggio->gctl_length);
1450			mtx_unlock(&res->hr_amp_lock);
1451		}
1452		if (ggio->gctl_cmd == BIO_WRITE) {
1453			/*
1454			 * Unlock range we locked.
1455			 */
1456			mtx_lock(&range_lock);
1457			rangelock_del(range_regular, ggio->gctl_offset,
1458			    ggio->gctl_length);
1459			if (range_sync_wait)
1460				cv_signal(&range_sync_cond);
1461			mtx_unlock(&range_lock);
1462			/*
1463			 * Bump local count if this is first write after
1464			 * connection failure with remote node.
1465			 */
1466			ncomp = 1;
1467			rw_rlock(&hio_remote_lock[ncomp]);
1468			if (!ISCONNECTED(res, ncomp)) {
1469				mtx_lock(&metadata_lock);
1470				if (res->hr_primary_localcnt ==
1471				    res->hr_secondary_remotecnt) {
1472					res->hr_primary_localcnt++;
1473					pjdlog_debug(1,
1474					    "Increasing localcnt to %ju.",
1475					    (uintmax_t)res->hr_primary_localcnt);
1476					(void)metadata_write(res);
1477				}
1478				mtx_unlock(&metadata_lock);
1479			}
1480			rw_unlock(&hio_remote_lock[ncomp]);
1481		}
1482		if (ioctl(res->hr_ggatefd, G_GATE_CMD_DONE, ggio) < 0)
1483			primary_exit(EX_OSERR, "G_GATE_CMD_DONE failed");
1484		pjdlog_debug(2,
1485		    "ggate_send: (%p) Moving request to the free queue.", hio);
1486		QUEUE_INSERT2(hio, free);
1487	}
1488	/* NOTREACHED */
1489	return (NULL);
1490}
1491
1492/*
1493 * Thread synchronize local and remote components.
1494 */
1495static void *
1496sync_thread(void *arg __unused)
1497{
1498	struct hast_resource *res = arg;
1499	struct hio *hio;
1500	struct g_gate_ctl_io *ggio;
1501	unsigned int ii, ncomp, ncomps;
1502	off_t offset, length, synced;
1503	bool dorewind;
1504	int syncext;
1505
1506	ncomps = HAST_NCOMPONENTS;
1507	dorewind = true;
1508	synced = 0;
1509	offset = -1;
1510
1511	for (;;) {
1512		mtx_lock(&sync_lock);
1513		if (offset >= 0 && !sync_inprogress) {
1514			pjdlog_info("Synchronization interrupted. "
1515			    "%jd bytes synchronized so far.",
1516			    (intmax_t)synced);
1517			event_send(res, EVENT_SYNCINTR);
1518		}
1519		while (!sync_inprogress) {
1520			dorewind = true;
1521			synced = 0;
1522			cv_wait(&sync_cond, &sync_lock);
1523		}
1524		mtx_unlock(&sync_lock);
1525		/*
1526		 * Obtain offset at which we should synchronize.
1527		 * Rewind synchronization if needed.
1528		 */
1529		mtx_lock(&res->hr_amp_lock);
1530		if (dorewind)
1531			activemap_sync_rewind(res->hr_amp);
1532		offset = activemap_sync_offset(res->hr_amp, &length, &syncext);
1533		if (syncext != -1) {
1534			/*
1535			 * We synchronized entire syncext extent, we can mark
1536			 * it as clean now.
1537			 */
1538			if (activemap_extent_complete(res->hr_amp, syncext))
1539				(void)hast_activemap_flush(res);
1540		}
1541		mtx_unlock(&res->hr_amp_lock);
1542		if (dorewind) {
1543			dorewind = false;
1544			if (offset < 0)
1545				pjdlog_info("Nodes are in sync.");
1546			else {
1547				pjdlog_info("Synchronization started. %ju bytes to go.",
1548				    (uintmax_t)(res->hr_extentsize *
1549				    activemap_ndirty(res->hr_amp)));
1550				event_send(res, EVENT_SYNCSTART);
1551			}
1552		}
1553		if (offset < 0) {
1554			sync_stop();
1555			pjdlog_debug(1, "Nothing to synchronize.");
1556			/*
1557			 * Synchronization complete, make both localcnt and
1558			 * remotecnt equal.
1559			 */
1560			ncomp = 1;
1561			rw_rlock(&hio_remote_lock[ncomp]);
1562			if (ISCONNECTED(res, ncomp)) {
1563				if (synced > 0) {
1564					pjdlog_info("Synchronization complete. "
1565					    "%jd bytes synchronized.",
1566					    (intmax_t)synced);
1567					event_send(res, EVENT_SYNCDONE);
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
1954	timeout.tv_nsec = 0;
1955	signo = -1;
1956
1957	for (;;) {
1958		switch (signo) {
1959		case SIGHUP:
1960			config_reload();
1961			break;
1962		case SIGINT:
1963		case SIGTERM:
1964			sigexit_received = true;
1965			primary_exitx(EX_OK,
1966			    "Termination signal received, exiting.");
1967			break;
1968		default:
1969			break;
1970		}
1971
1972		pjdlog_debug(2, "remote_guard: Checking connections.");
1973		now = time(NULL);
1974		if (lastcheck + RETRY_SLEEP <= now) {
1975			for (ii = 0; ii < ncomps; ii++)
1976				guard_one(res, ii);
1977			lastcheck = now;
1978		}
1979		timeout.tv_sec = RETRY_SLEEP;
1980		signo = sigtimedwait(&mask, NULL, &timeout);
1981	}
1982	/* NOTREACHED */
1983	return (NULL);
1984}
1985