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