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