primary.c revision 219721
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 219721 2011-03-17 21:02:14Z trociny $");
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 comunicate with GEOM Gate class.
90	 */
91	struct g_gate_ctl_io	 hio_ggio;
92	TAILQ_ENTRY(hio)	*hio_next;
93};
94#define	hio_free_next	hio_next[0]
95#define	hio_done_next	hio_next[0]
96
97/*
98 * Free list holds unused structures. When free list is empty, we have to wait
99 * until some in-progress requests are freed.
100 */
101static TAILQ_HEAD(, hio) hio_free_list;
102static pthread_mutex_t hio_free_list_lock;
103static pthread_cond_t hio_free_list_cond;
104/*
105 * There is one send list for every component. One requests is placed on all
106 * send lists - each component gets the same request, but each component is
107 * responsible for managing his own send list.
108 */
109static TAILQ_HEAD(, hio) *hio_send_list;
110static pthread_mutex_t *hio_send_list_lock;
111static pthread_cond_t *hio_send_list_cond;
112/*
113 * There is one recv list for every component, although local components don't
114 * use recv lists as local requests are done synchronously.
115 */
116static TAILQ_HEAD(, hio) *hio_recv_list;
117static pthread_mutex_t *hio_recv_list_lock;
118static pthread_cond_t *hio_recv_list_cond;
119/*
120 * Request is placed on done list by the slowest component (the one that
121 * decreased hio_countdown from 1 to 0).
122 */
123static TAILQ_HEAD(, hio) hio_done_list;
124static pthread_mutex_t hio_done_list_lock;
125static pthread_cond_t hio_done_list_cond;
126/*
127 * Structure below are for interaction with sync thread.
128 */
129static bool sync_inprogress;
130static pthread_mutex_t sync_lock;
131static pthread_cond_t sync_cond;
132/*
133 * The lock below allows to synchornize access to remote connections.
134 */
135static pthread_rwlock_t *hio_remote_lock;
136
137/*
138 * Lock to synchronize metadata updates. Also synchronize access to
139 * hr_primary_localcnt and hr_primary_remotecnt fields.
140 */
141static pthread_mutex_t metadata_lock;
142
143/*
144 * Maximum number of outstanding I/O requests.
145 */
146#define	HAST_HIO_MAX	256
147/*
148 * Number of components. At this point there are only two components: local
149 * and remote, but in the future it might be possible to use multiple local
150 * and remote components.
151 */
152#define	HAST_NCOMPONENTS	2
153
154#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 = 1;
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, HAST_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	map = NULL;
671	mapsize = nv_get_uint32(nvin, "mapsize");
672	if (mapsize > 0) {
673		map = malloc(mapsize);
674		if (map == NULL) {
675			pjdlog_error("Unable to allocate memory for remote activemap (mapsize=%ju).",
676			    (uintmax_t)mapsize);
677			nv_free(nvin);
678			goto close;
679		}
680		/*
681		 * Remote node have some dirty extents on its own, lets
682		 * download its activemap.
683		 */
684		if (hast_proto_recv_data(res, out, nvin, map,
685		    mapsize) < 0) {
686			pjdlog_errno(LOG_ERR,
687			    "Unable to receive remote activemap");
688			nv_free(nvin);
689			free(map);
690			goto close;
691		}
692		/*
693		 * Merge local and remote bitmaps.
694		 */
695		activemap_merge(res->hr_amp, map, mapsize);
696		free(map);
697		/*
698		 * Now that we merged bitmaps from both nodes, flush it to the
699		 * disk before we start to synchronize.
700		 */
701		(void)hast_activemap_flush(res);
702	}
703	nv_free(nvin);
704	pjdlog_info("Connected to %s.", res->hr_remoteaddr);
705	if (inp != NULL && outp != NULL) {
706		*inp = in;
707		*outp = out;
708	} else {
709		res->hr_remotein = in;
710		res->hr_remoteout = out;
711	}
712	event_send(res, EVENT_CONNECT);
713	return (true);
714close:
715	if (errmsg != NULL && strcmp(errmsg, "Split-brain condition!") == 0)
716		event_send(res, EVENT_SPLITBRAIN);
717	proto_close(out);
718	if (in != NULL)
719		proto_close(in);
720	return (false);
721}
722
723static void
724sync_start(void)
725{
726
727	mtx_lock(&sync_lock);
728	sync_inprogress = true;
729	mtx_unlock(&sync_lock);
730	cv_signal(&sync_cond);
731}
732
733static void
734sync_stop(void)
735{
736
737	mtx_lock(&sync_lock);
738	if (sync_inprogress)
739		sync_inprogress = false;
740	mtx_unlock(&sync_lock);
741}
742
743static void
744init_ggate(struct hast_resource *res)
745{
746	struct g_gate_ctl_create ggiocreate;
747	struct g_gate_ctl_cancel ggiocancel;
748
749	/*
750	 * We communicate with ggate via /dev/ggctl. Open it.
751	 */
752	res->hr_ggatefd = open("/dev/" G_GATE_CTL_NAME, O_RDWR);
753	if (res->hr_ggatefd < 0)
754		primary_exit(EX_OSFILE, "Unable to open /dev/" G_GATE_CTL_NAME);
755	/*
756	 * Create provider before trying to connect, as connection failure
757	 * is not critical, but may take some time.
758	 */
759	bzero(&ggiocreate, sizeof(ggiocreate));
760	ggiocreate.gctl_version = G_GATE_VERSION;
761	ggiocreate.gctl_mediasize = res->hr_datasize;
762	ggiocreate.gctl_sectorsize = res->hr_local_sectorsize;
763	ggiocreate.gctl_flags = 0;
764	ggiocreate.gctl_maxcount = G_GATE_MAX_QUEUE_SIZE;
765	ggiocreate.gctl_timeout = 0;
766	ggiocreate.gctl_unit = G_GATE_NAME_GIVEN;
767	snprintf(ggiocreate.gctl_name, sizeof(ggiocreate.gctl_name), "hast/%s",
768	    res->hr_provname);
769	if (ioctl(res->hr_ggatefd, G_GATE_CMD_CREATE, &ggiocreate) == 0) {
770		pjdlog_info("Device hast/%s created.", res->hr_provname);
771		res->hr_ggateunit = ggiocreate.gctl_unit;
772		return;
773	}
774	if (errno != EEXIST) {
775		primary_exit(EX_OSERR, "Unable to create hast/%s device",
776		    res->hr_provname);
777	}
778	pjdlog_debug(1,
779	    "Device hast/%s already exists, we will try to take it over.",
780	    res->hr_provname);
781	/*
782	 * If we received EEXIST, we assume that the process who created the
783	 * provider died and didn't clean up. In that case we will start from
784	 * where he left of.
785	 */
786	bzero(&ggiocancel, sizeof(ggiocancel));
787	ggiocancel.gctl_version = G_GATE_VERSION;
788	ggiocancel.gctl_unit = G_GATE_NAME_GIVEN;
789	snprintf(ggiocancel.gctl_name, sizeof(ggiocancel.gctl_name), "hast/%s",
790	    res->hr_provname);
791	if (ioctl(res->hr_ggatefd, G_GATE_CMD_CANCEL, &ggiocancel) == 0) {
792		pjdlog_info("Device hast/%s recovered.", res->hr_provname);
793		res->hr_ggateunit = ggiocancel.gctl_unit;
794		return;
795	}
796	primary_exit(EX_OSERR, "Unable to take over hast/%s device",
797	    res->hr_provname);
798}
799
800void
801hastd_primary(struct hast_resource *res)
802{
803	pthread_t td;
804	pid_t pid;
805	int error, mode, debuglevel;
806
807	/*
808	 * Create communication channel for sending control commands from
809	 * parent to child.
810	 */
811	if (proto_client("socketpair://", &res->hr_ctrl) < 0) {
812		/* TODO: There's no need for this to be fatal error. */
813		KEEP_ERRNO((void)pidfile_remove(pfh));
814		pjdlog_exit(EX_OSERR,
815		    "Unable to create control sockets between parent and child");
816	}
817	/*
818	 * Create communication channel for sending events from child to parent.
819	 */
820	if (proto_client("socketpair://", &res->hr_event) < 0) {
821		/* TODO: There's no need for this to be fatal error. */
822		KEEP_ERRNO((void)pidfile_remove(pfh));
823		pjdlog_exit(EX_OSERR,
824		    "Unable to create event sockets between child and parent");
825	}
826	/*
827	 * Create communication channel for sending connection requests from
828	 * child to parent.
829	 */
830	if (proto_client("socketpair://", &res->hr_conn) < 0) {
831		/* TODO: There's no need for this to be fatal error. */
832		KEEP_ERRNO((void)pidfile_remove(pfh));
833		pjdlog_exit(EX_OSERR,
834		    "Unable to create connection sockets between child and parent");
835	}
836
837	pid = fork();
838	if (pid < 0) {
839		/* TODO: There's no need for this to be fatal error. */
840		KEEP_ERRNO((void)pidfile_remove(pfh));
841		pjdlog_exit(EX_TEMPFAIL, "Unable to fork");
842	}
843
844	if (pid > 0) {
845		/* This is parent. */
846		/* Declare that we are receiver. */
847		proto_recv(res->hr_event, NULL, 0);
848		proto_recv(res->hr_conn, NULL, 0);
849		/* Declare that we are sender. */
850		proto_send(res->hr_ctrl, NULL, 0);
851		res->hr_workerpid = pid;
852		return;
853	}
854
855	gres = res;
856	mode = pjdlog_mode_get();
857	debuglevel = pjdlog_debug_get();
858
859	/* Declare that we are sender. */
860	proto_send(res->hr_event, NULL, 0);
861	proto_send(res->hr_conn, NULL, 0);
862	/* Declare that we are receiver. */
863	proto_recv(res->hr_ctrl, NULL, 0);
864	descriptors_cleanup(res);
865
866	descriptors_assert(res, mode);
867
868	pjdlog_init(mode);
869	pjdlog_debug_set(debuglevel);
870	pjdlog_prefix_set("[%s] (%s) ", res->hr_name, role2str(res->hr_role));
871	setproctitle("%s (primary)", res->hr_name);
872
873	init_local(res);
874	init_ggate(res);
875	init_environment(res);
876
877	if (drop_privs() != 0) {
878		cleanup(res);
879		exit(EX_CONFIG);
880	}
881	pjdlog_info("Privileges successfully dropped.");
882
883	/*
884	 * Create the guard thread first, so we can handle signals from the
885	 * very begining.
886	 */
887	error = pthread_create(&td, NULL, guard_thread, res);
888	PJDLOG_ASSERT(error == 0);
889	/*
890	 * Create the control thread before sending any event to the parent,
891	 * as we can deadlock when parent sends control request to worker,
892	 * but worker has no control thread started yet, so parent waits.
893	 * In the meantime worker sends an event to the parent, but parent
894	 * is unable to handle the event, because it waits for control
895	 * request response.
896	 */
897	error = pthread_create(&td, NULL, ctrl_thread, res);
898	PJDLOG_ASSERT(error == 0);
899	if (real_remote(res) && init_remote(res, NULL, NULL))
900		sync_start();
901	error = pthread_create(&td, NULL, ggate_recv_thread, res);
902	PJDLOG_ASSERT(error == 0);
903	error = pthread_create(&td, NULL, local_send_thread, res);
904	PJDLOG_ASSERT(error == 0);
905	error = pthread_create(&td, NULL, remote_send_thread, res);
906	PJDLOG_ASSERT(error == 0);
907	error = pthread_create(&td, NULL, remote_recv_thread, res);
908	PJDLOG_ASSERT(error == 0);
909	error = pthread_create(&td, NULL, ggate_send_thread, res);
910	PJDLOG_ASSERT(error == 0);
911	(void)sync_thread(res);
912}
913
914static void
915reqlog(int loglevel, int debuglevel, struct g_gate_ctl_io *ggio, const char *fmt, ...)
916{
917	char msg[1024];
918	va_list ap;
919	int len;
920
921	va_start(ap, fmt);
922	len = vsnprintf(msg, sizeof(msg), fmt, ap);
923	va_end(ap);
924	if ((size_t)len < sizeof(msg)) {
925		switch (ggio->gctl_cmd) {
926		case BIO_READ:
927			(void)snprintf(msg + len, sizeof(msg) - len,
928			    "READ(%ju, %ju).", (uintmax_t)ggio->gctl_offset,
929			    (uintmax_t)ggio->gctl_length);
930			break;
931		case BIO_DELETE:
932			(void)snprintf(msg + len, sizeof(msg) - len,
933			    "DELETE(%ju, %ju).", (uintmax_t)ggio->gctl_offset,
934			    (uintmax_t)ggio->gctl_length);
935			break;
936		case BIO_FLUSH:
937			(void)snprintf(msg + len, sizeof(msg) - len, "FLUSH.");
938			break;
939		case BIO_WRITE:
940			(void)snprintf(msg + len, sizeof(msg) - len,
941			    "WRITE(%ju, %ju).", (uintmax_t)ggio->gctl_offset,
942			    (uintmax_t)ggio->gctl_length);
943			break;
944		default:
945			(void)snprintf(msg + len, sizeof(msg) - len,
946			    "UNKNOWN(%u).", (unsigned int)ggio->gctl_cmd);
947			break;
948		}
949	}
950	pjdlog_common(loglevel, debuglevel, -1, "%s", msg);
951}
952
953static void
954remote_close(struct hast_resource *res, int ncomp)
955{
956
957	rw_wlock(&hio_remote_lock[ncomp]);
958	/*
959	 * A race is possible between dropping rlock and acquiring wlock -
960	 * another thread can close connection in-between.
961	 */
962	if (!ISCONNECTED(res, ncomp)) {
963		PJDLOG_ASSERT(res->hr_remotein == NULL);
964		PJDLOG_ASSERT(res->hr_remoteout == NULL);
965		rw_unlock(&hio_remote_lock[ncomp]);
966		return;
967	}
968
969	PJDLOG_ASSERT(res->hr_remotein != NULL);
970	PJDLOG_ASSERT(res->hr_remoteout != NULL);
971
972	pjdlog_debug(2, "Closing incoming connection to %s.",
973	    res->hr_remoteaddr);
974	proto_close(res->hr_remotein);
975	res->hr_remotein = NULL;
976	pjdlog_debug(2, "Closing outgoing connection to %s.",
977	    res->hr_remoteaddr);
978	proto_close(res->hr_remoteout);
979	res->hr_remoteout = NULL;
980
981	rw_unlock(&hio_remote_lock[ncomp]);
982
983	pjdlog_warning("Disconnected from %s.", res->hr_remoteaddr);
984
985	/*
986	 * Stop synchronization if in-progress.
987	 */
988	sync_stop();
989
990	event_send(res, EVENT_DISCONNECT);
991}
992
993/*
994 * Thread receives ggate I/O requests from the kernel and passes them to
995 * appropriate threads:
996 * WRITE - always goes to both local_send and remote_send threads
997 * READ (when the block is up-to-date on local component) -
998 *	only local_send thread
999 * READ (when the block isn't up-to-date on local component) -
1000 *	only remote_send thread
1001 * DELETE - always goes to both local_send and remote_send threads
1002 * FLUSH - always goes to both local_send and remote_send threads
1003 */
1004static void *
1005ggate_recv_thread(void *arg)
1006{
1007	struct hast_resource *res = arg;
1008	struct g_gate_ctl_io *ggio;
1009	struct hio *hio;
1010	unsigned int ii, ncomp, ncomps;
1011	int error;
1012
1013	ncomps = HAST_NCOMPONENTS;
1014
1015	for (;;) {
1016		pjdlog_debug(2, "ggate_recv: Taking free request.");
1017		QUEUE_TAKE2(hio, free);
1018		pjdlog_debug(2, "ggate_recv: (%p) Got free request.", hio);
1019		ggio = &hio->hio_ggio;
1020		ggio->gctl_unit = res->hr_ggateunit;
1021		ggio->gctl_length = MAXPHYS;
1022		ggio->gctl_error = 0;
1023		pjdlog_debug(2,
1024		    "ggate_recv: (%p) Waiting for request from the kernel.",
1025		    hio);
1026		if (ioctl(res->hr_ggatefd, G_GATE_CMD_START, ggio) < 0) {
1027			if (sigexit_received)
1028				pthread_exit(NULL);
1029			primary_exit(EX_OSERR, "G_GATE_CMD_START failed");
1030		}
1031		error = ggio->gctl_error;
1032		switch (error) {
1033		case 0:
1034			break;
1035		case ECANCELED:
1036			/* Exit gracefully. */
1037			if (!sigexit_received) {
1038				pjdlog_debug(2,
1039				    "ggate_recv: (%p) Received cancel from the kernel.",
1040				    hio);
1041				pjdlog_info("Received cancel from the kernel, exiting.");
1042			}
1043			pthread_exit(NULL);
1044		case ENOMEM:
1045			/*
1046			 * Buffer too small? Impossible, we allocate MAXPHYS
1047			 * bytes - request can't be bigger than that.
1048			 */
1049			/* FALLTHROUGH */
1050		case ENXIO:
1051		default:
1052			primary_exitx(EX_OSERR, "G_GATE_CMD_START failed: %s.",
1053			    strerror(error));
1054		}
1055		for (ii = 0; ii < ncomps; ii++)
1056			hio->hio_errors[ii] = EINVAL;
1057		reqlog(LOG_DEBUG, 2, ggio,
1058		    "ggate_recv: (%p) Request received from the kernel: ",
1059		    hio);
1060		/*
1061		 * Inform all components about new write request.
1062		 * For read request prefer local component unless the given
1063		 * range is out-of-date, then use remote component.
1064		 */
1065		switch (ggio->gctl_cmd) {
1066		case BIO_READ:
1067			pjdlog_debug(2,
1068			    "ggate_recv: (%p) Moving request to the send queue.",
1069			    hio);
1070			refcount_init(&hio->hio_countdown, 1);
1071			mtx_lock(&metadata_lock);
1072			if (res->hr_syncsrc == HAST_SYNCSRC_UNDEF ||
1073			    res->hr_syncsrc == HAST_SYNCSRC_PRIMARY) {
1074				/*
1075				 * This range is up-to-date on local component,
1076				 * so handle request locally.
1077				 */
1078				 /* Local component is 0 for now. */
1079				ncomp = 0;
1080			} else /* if (res->hr_syncsrc ==
1081			    HAST_SYNCSRC_SECONDARY) */ {
1082				PJDLOG_ASSERT(res->hr_syncsrc ==
1083				    HAST_SYNCSRC_SECONDARY);
1084				/*
1085				 * This range is out-of-date on local component,
1086				 * so send request to the remote node.
1087				 */
1088				 /* Remote component is 1 for now. */
1089				ncomp = 1;
1090			}
1091			mtx_unlock(&metadata_lock);
1092			QUEUE_INSERT1(hio, send, ncomp);
1093			break;
1094		case BIO_WRITE:
1095			if (res->hr_resuid == 0) {
1096				/* This is first write, initialize resuid. */
1097				(void)init_resuid(res);
1098			}
1099			for (;;) {
1100				mtx_lock(&range_lock);
1101				if (rangelock_islocked(range_sync,
1102				    ggio->gctl_offset, ggio->gctl_length)) {
1103					pjdlog_debug(2,
1104					    "regular: Range offset=%jd length=%zu locked.",
1105					    (intmax_t)ggio->gctl_offset,
1106					    (size_t)ggio->gctl_length);
1107					range_regular_wait = true;
1108					cv_wait(&range_regular_cond, &range_lock);
1109					range_regular_wait = false;
1110					mtx_unlock(&range_lock);
1111					continue;
1112				}
1113				if (rangelock_add(range_regular,
1114				    ggio->gctl_offset, ggio->gctl_length) < 0) {
1115					mtx_unlock(&range_lock);
1116					pjdlog_debug(2,
1117					    "regular: Range offset=%jd length=%zu is already locked, waiting.",
1118					    (intmax_t)ggio->gctl_offset,
1119					    (size_t)ggio->gctl_length);
1120					sleep(1);
1121					continue;
1122				}
1123				mtx_unlock(&range_lock);
1124				break;
1125			}
1126			mtx_lock(&res->hr_amp_lock);
1127			if (activemap_write_start(res->hr_amp,
1128			    ggio->gctl_offset, ggio->gctl_length)) {
1129				(void)hast_activemap_flush(res);
1130			}
1131			mtx_unlock(&res->hr_amp_lock);
1132			/* FALLTHROUGH */
1133		case BIO_DELETE:
1134		case BIO_FLUSH:
1135			pjdlog_debug(2,
1136			    "ggate_recv: (%p) Moving request to the send queues.",
1137			    hio);
1138			refcount_init(&hio->hio_countdown, ncomps);
1139			for (ii = 0; ii < ncomps; ii++)
1140				QUEUE_INSERT1(hio, send, ii);
1141			break;
1142		}
1143	}
1144	/* NOTREACHED */
1145	return (NULL);
1146}
1147
1148/*
1149 * Thread reads from or writes to local component.
1150 * If local read fails, it redirects it to remote_send thread.
1151 */
1152static void *
1153local_send_thread(void *arg)
1154{
1155	struct hast_resource *res = arg;
1156	struct g_gate_ctl_io *ggio;
1157	struct hio *hio;
1158	unsigned int ncomp, rncomp;
1159	ssize_t ret;
1160
1161	/* Local component is 0 for now. */
1162	ncomp = 0;
1163	/* Remote component is 1 for now. */
1164	rncomp = 1;
1165
1166	for (;;) {
1167		pjdlog_debug(2, "local_send: Taking request.");
1168		QUEUE_TAKE1(hio, send, ncomp, 0);
1169		pjdlog_debug(2, "local_send: (%p) Got request.", hio);
1170		ggio = &hio->hio_ggio;
1171		switch (ggio->gctl_cmd) {
1172		case BIO_READ:
1173			ret = pread(res->hr_localfd, ggio->gctl_data,
1174			    ggio->gctl_length,
1175			    ggio->gctl_offset + res->hr_localoff);
1176			if (ret == ggio->gctl_length)
1177				hio->hio_errors[ncomp] = 0;
1178			else {
1179				/*
1180				 * If READ failed, try to read from remote node.
1181				 */
1182				if (ret < 0) {
1183					reqlog(LOG_WARNING, 0, ggio,
1184					    "Local request failed (%s), trying remote node. ",
1185					    strerror(errno));
1186				} else if (ret != ggio->gctl_length) {
1187					reqlog(LOG_WARNING, 0, ggio,
1188					    "Local request failed (%zd != %jd), trying remote node. ",
1189					    ret, (intmax_t)ggio->gctl_length);
1190				}
1191				QUEUE_INSERT1(hio, send, rncomp);
1192				continue;
1193			}
1194			break;
1195		case BIO_WRITE:
1196			ret = pwrite(res->hr_localfd, ggio->gctl_data,
1197			    ggio->gctl_length,
1198			    ggio->gctl_offset + res->hr_localoff);
1199			if (ret < 0) {
1200				hio->hio_errors[ncomp] = errno;
1201				reqlog(LOG_WARNING, 0, ggio,
1202				    "Local request failed (%s): ",
1203				    strerror(errno));
1204			} else if (ret != ggio->gctl_length) {
1205				hio->hio_errors[ncomp] = EIO;
1206				reqlog(LOG_WARNING, 0, ggio,
1207				    "Local request failed (%zd != %jd): ",
1208				    ret, (intmax_t)ggio->gctl_length);
1209			} else {
1210				hio->hio_errors[ncomp] = 0;
1211			}
1212			break;
1213		case BIO_DELETE:
1214			ret = g_delete(res->hr_localfd,
1215			    ggio->gctl_offset + res->hr_localoff,
1216			    ggio->gctl_length);
1217			if (ret < 0) {
1218				hio->hio_errors[ncomp] = errno;
1219				reqlog(LOG_WARNING, 0, ggio,
1220				    "Local request failed (%s): ",
1221				    strerror(errno));
1222			} else {
1223				hio->hio_errors[ncomp] = 0;
1224			}
1225			break;
1226		case BIO_FLUSH:
1227			ret = g_flush(res->hr_localfd);
1228			if (ret < 0) {
1229				hio->hio_errors[ncomp] = errno;
1230				reqlog(LOG_WARNING, 0, ggio,
1231				    "Local request failed (%s): ",
1232				    strerror(errno));
1233			} else {
1234				hio->hio_errors[ncomp] = 0;
1235			}
1236			break;
1237		}
1238		if (refcount_release(&hio->hio_countdown)) {
1239			if (ISSYNCREQ(hio)) {
1240				mtx_lock(&sync_lock);
1241				SYNCREQDONE(hio);
1242				mtx_unlock(&sync_lock);
1243				cv_signal(&sync_cond);
1244			} else {
1245				pjdlog_debug(2,
1246				    "local_send: (%p) Moving request to the done queue.",
1247				    hio);
1248				QUEUE_INSERT2(hio, done);
1249			}
1250		}
1251	}
1252	/* NOTREACHED */
1253	return (NULL);
1254}
1255
1256static void
1257keepalive_send(struct hast_resource *res, unsigned int ncomp)
1258{
1259	struct nv *nv;
1260
1261	rw_rlock(&hio_remote_lock[ncomp]);
1262
1263	if (!ISCONNECTED(res, ncomp)) {
1264		rw_unlock(&hio_remote_lock[ncomp]);
1265		return;
1266	}
1267
1268	PJDLOG_ASSERT(res->hr_remotein != NULL);
1269	PJDLOG_ASSERT(res->hr_remoteout != NULL);
1270
1271	nv = nv_alloc();
1272	nv_add_uint8(nv, HIO_KEEPALIVE, "cmd");
1273	if (nv_error(nv) != 0) {
1274		rw_unlock(&hio_remote_lock[ncomp]);
1275		nv_free(nv);
1276		pjdlog_debug(1,
1277		    "keepalive_send: Unable to prepare header to send.");
1278		return;
1279	}
1280	if (hast_proto_send(res, res->hr_remoteout, nv, NULL, 0) < 0) {
1281		rw_unlock(&hio_remote_lock[ncomp]);
1282		pjdlog_common(LOG_DEBUG, 1, errno,
1283		    "keepalive_send: Unable to send request");
1284		nv_free(nv);
1285		remote_close(res, ncomp);
1286		return;
1287	}
1288
1289	rw_unlock(&hio_remote_lock[ncomp]);
1290	nv_free(nv);
1291	pjdlog_debug(2, "keepalive_send: Request sent.");
1292}
1293
1294/*
1295 * Thread sends request to secondary node.
1296 */
1297static void *
1298remote_send_thread(void *arg)
1299{
1300	struct hast_resource *res = arg;
1301	struct g_gate_ctl_io *ggio;
1302	time_t lastcheck, now;
1303	struct hio *hio;
1304	struct nv *nv;
1305	unsigned int ncomp;
1306	bool wakeup;
1307	uint64_t offset, length;
1308	uint8_t cmd;
1309	void *data;
1310
1311	/* Remote component is 1 for now. */
1312	ncomp = 1;
1313	lastcheck = time(NULL);
1314
1315	for (;;) {
1316		pjdlog_debug(2, "remote_send: Taking request.");
1317		QUEUE_TAKE1(hio, send, ncomp, HAST_KEEPALIVE);
1318		if (hio == NULL) {
1319			now = time(NULL);
1320			if (lastcheck + HAST_KEEPALIVE <= now) {
1321				keepalive_send(res, ncomp);
1322				lastcheck = now;
1323			}
1324			continue;
1325		}
1326		pjdlog_debug(2, "remote_send: (%p) Got request.", hio);
1327		ggio = &hio->hio_ggio;
1328		switch (ggio->gctl_cmd) {
1329		case BIO_READ:
1330			cmd = HIO_READ;
1331			data = NULL;
1332			offset = ggio->gctl_offset;
1333			length = ggio->gctl_length;
1334			break;
1335		case BIO_WRITE:
1336			cmd = HIO_WRITE;
1337			data = ggio->gctl_data;
1338			offset = ggio->gctl_offset;
1339			length = ggio->gctl_length;
1340			break;
1341		case BIO_DELETE:
1342			cmd = HIO_DELETE;
1343			data = NULL;
1344			offset = ggio->gctl_offset;
1345			length = ggio->gctl_length;
1346			break;
1347		case BIO_FLUSH:
1348			cmd = HIO_FLUSH;
1349			data = NULL;
1350			offset = 0;
1351			length = 0;
1352			break;
1353		default:
1354			PJDLOG_ASSERT(!"invalid condition");
1355			abort();
1356		}
1357		nv = nv_alloc();
1358		nv_add_uint8(nv, cmd, "cmd");
1359		nv_add_uint64(nv, (uint64_t)ggio->gctl_seq, "seq");
1360		nv_add_uint64(nv, offset, "offset");
1361		nv_add_uint64(nv, length, "length");
1362		if (nv_error(nv) != 0) {
1363			hio->hio_errors[ncomp] = nv_error(nv);
1364			pjdlog_debug(2,
1365			    "remote_send: (%p) Unable to prepare header to send.",
1366			    hio);
1367			reqlog(LOG_ERR, 0, ggio,
1368			    "Unable to prepare header to send (%s): ",
1369			    strerror(nv_error(nv)));
1370			/* Move failed request immediately to the done queue. */
1371			goto done_queue;
1372		}
1373		pjdlog_debug(2,
1374		    "remote_send: (%p) Moving request to the recv queue.",
1375		    hio);
1376		/*
1377		 * Protect connection from disappearing.
1378		 */
1379		rw_rlock(&hio_remote_lock[ncomp]);
1380		if (!ISCONNECTED(res, ncomp)) {
1381			rw_unlock(&hio_remote_lock[ncomp]);
1382			hio->hio_errors[ncomp] = ENOTCONN;
1383			goto done_queue;
1384		}
1385		/*
1386		 * Move the request to recv queue before sending it, because
1387		 * in different order we can get reply before we move request
1388		 * to recv queue.
1389		 */
1390		mtx_lock(&hio_recv_list_lock[ncomp]);
1391		wakeup = TAILQ_EMPTY(&hio_recv_list[ncomp]);
1392		TAILQ_INSERT_TAIL(&hio_recv_list[ncomp], hio, hio_next[ncomp]);
1393		mtx_unlock(&hio_recv_list_lock[ncomp]);
1394		if (hast_proto_send(res, res->hr_remoteout, nv, data,
1395		    data != NULL ? length : 0) < 0) {
1396			hio->hio_errors[ncomp] = errno;
1397			rw_unlock(&hio_remote_lock[ncomp]);
1398			pjdlog_debug(2,
1399			    "remote_send: (%p) Unable to send request.", hio);
1400			reqlog(LOG_ERR, 0, ggio,
1401			    "Unable to send request (%s): ",
1402			    strerror(hio->hio_errors[ncomp]));
1403			remote_close(res, ncomp);
1404			/*
1405			 * Take request back from the receive queue and move
1406			 * it immediately to the done queue.
1407			 */
1408			mtx_lock(&hio_recv_list_lock[ncomp]);
1409			TAILQ_REMOVE(&hio_recv_list[ncomp], hio, hio_next[ncomp]);
1410			mtx_unlock(&hio_recv_list_lock[ncomp]);
1411			goto done_queue;
1412		}
1413		rw_unlock(&hio_remote_lock[ncomp]);
1414		nv_free(nv);
1415		if (wakeup)
1416			cv_signal(&hio_recv_list_cond[ncomp]);
1417		continue;
1418done_queue:
1419		nv_free(nv);
1420		if (ISSYNCREQ(hio)) {
1421			if (!refcount_release(&hio->hio_countdown))
1422				continue;
1423			mtx_lock(&sync_lock);
1424			SYNCREQDONE(hio);
1425			mtx_unlock(&sync_lock);
1426			cv_signal(&sync_cond);
1427			continue;
1428		}
1429		if (ggio->gctl_cmd == BIO_WRITE) {
1430			mtx_lock(&res->hr_amp_lock);
1431			if (activemap_need_sync(res->hr_amp, ggio->gctl_offset,
1432			    ggio->gctl_length)) {
1433				(void)hast_activemap_flush(res);
1434			}
1435			mtx_unlock(&res->hr_amp_lock);
1436		}
1437		if (!refcount_release(&hio->hio_countdown))
1438			continue;
1439		pjdlog_debug(2,
1440		    "remote_send: (%p) Moving request to the done queue.",
1441		    hio);
1442		QUEUE_INSERT2(hio, done);
1443	}
1444	/* NOTREACHED */
1445	return (NULL);
1446}
1447
1448/*
1449 * Thread receives answer from secondary node and passes it to ggate_send
1450 * thread.
1451 */
1452static void *
1453remote_recv_thread(void *arg)
1454{
1455	struct hast_resource *res = arg;
1456	struct g_gate_ctl_io *ggio;
1457	struct hio *hio;
1458	struct nv *nv;
1459	unsigned int ncomp;
1460	uint64_t seq;
1461	int error;
1462
1463	/* Remote component is 1 for now. */
1464	ncomp = 1;
1465
1466	for (;;) {
1467		/* Wait until there is anything to receive. */
1468		mtx_lock(&hio_recv_list_lock[ncomp]);
1469		while (TAILQ_EMPTY(&hio_recv_list[ncomp])) {
1470			pjdlog_debug(2, "remote_recv: No requests, waiting.");
1471			cv_wait(&hio_recv_list_cond[ncomp],
1472			    &hio_recv_list_lock[ncomp]);
1473		}
1474		mtx_unlock(&hio_recv_list_lock[ncomp]);
1475		rw_rlock(&hio_remote_lock[ncomp]);
1476		if (!ISCONNECTED(res, ncomp)) {
1477			rw_unlock(&hio_remote_lock[ncomp]);
1478			/*
1479			 * Connection is dead, so move all pending requests to
1480			 * the done queue (one-by-one).
1481			 */
1482			mtx_lock(&hio_recv_list_lock[ncomp]);
1483			hio = TAILQ_FIRST(&hio_recv_list[ncomp]);
1484			PJDLOG_ASSERT(hio != NULL);
1485			TAILQ_REMOVE(&hio_recv_list[ncomp], hio,
1486			    hio_next[ncomp]);
1487			mtx_unlock(&hio_recv_list_lock[ncomp]);
1488			goto done_queue;
1489		}
1490		if (hast_proto_recv_hdr(res->hr_remotein, &nv) < 0) {
1491			pjdlog_errno(LOG_ERR,
1492			    "Unable to receive reply header");
1493			rw_unlock(&hio_remote_lock[ncomp]);
1494			remote_close(res, ncomp);
1495			continue;
1496		}
1497		rw_unlock(&hio_remote_lock[ncomp]);
1498		seq = nv_get_uint64(nv, "seq");
1499		if (seq == 0) {
1500			pjdlog_error("Header contains no 'seq' field.");
1501			nv_free(nv);
1502			continue;
1503		}
1504		mtx_lock(&hio_recv_list_lock[ncomp]);
1505		TAILQ_FOREACH(hio, &hio_recv_list[ncomp], hio_next[ncomp]) {
1506			if (hio->hio_ggio.gctl_seq == seq) {
1507				TAILQ_REMOVE(&hio_recv_list[ncomp], hio,
1508				    hio_next[ncomp]);
1509				break;
1510			}
1511		}
1512		mtx_unlock(&hio_recv_list_lock[ncomp]);
1513		if (hio == NULL) {
1514			pjdlog_error("Found no request matching received 'seq' field (%ju).",
1515			    (uintmax_t)seq);
1516			nv_free(nv);
1517			continue;
1518		}
1519		error = nv_get_int16(nv, "error");
1520		if (error != 0) {
1521			/* Request failed on remote side. */
1522			hio->hio_errors[ncomp] = error;
1523			reqlog(LOG_WARNING, 0, &hio->hio_ggio,
1524			    "Remote request failed (%s): ", strerror(error));
1525			nv_free(nv);
1526			goto done_queue;
1527		}
1528		ggio = &hio->hio_ggio;
1529		switch (ggio->gctl_cmd) {
1530		case BIO_READ:
1531			rw_rlock(&hio_remote_lock[ncomp]);
1532			if (!ISCONNECTED(res, ncomp)) {
1533				rw_unlock(&hio_remote_lock[ncomp]);
1534				nv_free(nv);
1535				goto done_queue;
1536			}
1537			if (hast_proto_recv_data(res, res->hr_remotein, nv,
1538			    ggio->gctl_data, ggio->gctl_length) < 0) {
1539				hio->hio_errors[ncomp] = errno;
1540				pjdlog_errno(LOG_ERR,
1541				    "Unable to receive reply data");
1542				rw_unlock(&hio_remote_lock[ncomp]);
1543				nv_free(nv);
1544				remote_close(res, ncomp);
1545				goto done_queue;
1546			}
1547			rw_unlock(&hio_remote_lock[ncomp]);
1548			break;
1549		case BIO_WRITE:
1550		case BIO_DELETE:
1551		case BIO_FLUSH:
1552			break;
1553		default:
1554			PJDLOG_ASSERT(!"invalid condition");
1555			abort();
1556		}
1557		hio->hio_errors[ncomp] = 0;
1558		nv_free(nv);
1559done_queue:
1560		if (refcount_release(&hio->hio_countdown)) {
1561			if (ISSYNCREQ(hio)) {
1562				mtx_lock(&sync_lock);
1563				SYNCREQDONE(hio);
1564				mtx_unlock(&sync_lock);
1565				cv_signal(&sync_cond);
1566			} else {
1567				pjdlog_debug(2,
1568				    "remote_recv: (%p) Moving request to the done queue.",
1569				    hio);
1570				QUEUE_INSERT2(hio, done);
1571			}
1572		}
1573	}
1574	/* NOTREACHED */
1575	return (NULL);
1576}
1577
1578/*
1579 * Thread sends answer to the kernel.
1580 */
1581static void *
1582ggate_send_thread(void *arg)
1583{
1584	struct hast_resource *res = arg;
1585	struct g_gate_ctl_io *ggio;
1586	struct hio *hio;
1587	unsigned int ii, ncomp, ncomps;
1588
1589	ncomps = HAST_NCOMPONENTS;
1590
1591	for (;;) {
1592		pjdlog_debug(2, "ggate_send: Taking request.");
1593		QUEUE_TAKE2(hio, done);
1594		pjdlog_debug(2, "ggate_send: (%p) Got request.", hio);
1595		ggio = &hio->hio_ggio;
1596		for (ii = 0; ii < ncomps; ii++) {
1597			if (hio->hio_errors[ii] == 0) {
1598				/*
1599				 * One successful request is enough to declare
1600				 * success.
1601				 */
1602				ggio->gctl_error = 0;
1603				break;
1604			}
1605		}
1606		if (ii == ncomps) {
1607			/*
1608			 * None of the requests were successful.
1609			 * Use first error.
1610			 */
1611			ggio->gctl_error = hio->hio_errors[0];
1612		}
1613		if (ggio->gctl_error == 0 && ggio->gctl_cmd == BIO_WRITE) {
1614			mtx_lock(&res->hr_amp_lock);
1615			activemap_write_complete(res->hr_amp,
1616			    ggio->gctl_offset, ggio->gctl_length);
1617			mtx_unlock(&res->hr_amp_lock);
1618		}
1619		if (ggio->gctl_cmd == BIO_WRITE) {
1620			/*
1621			 * Unlock range we locked.
1622			 */
1623			mtx_lock(&range_lock);
1624			rangelock_del(range_regular, ggio->gctl_offset,
1625			    ggio->gctl_length);
1626			if (range_sync_wait)
1627				cv_signal(&range_sync_cond);
1628			mtx_unlock(&range_lock);
1629			/*
1630			 * Bump local count if this is first write after
1631			 * connection failure with remote node.
1632			 */
1633			ncomp = 1;
1634			rw_rlock(&hio_remote_lock[ncomp]);
1635			if (!ISCONNECTED(res, ncomp)) {
1636				mtx_lock(&metadata_lock);
1637				if (res->hr_primary_localcnt ==
1638				    res->hr_secondary_remotecnt) {
1639					res->hr_primary_localcnt++;
1640					pjdlog_debug(1,
1641					    "Increasing localcnt to %ju.",
1642					    (uintmax_t)res->hr_primary_localcnt);
1643					(void)metadata_write(res);
1644				}
1645				mtx_unlock(&metadata_lock);
1646			}
1647			rw_unlock(&hio_remote_lock[ncomp]);
1648		}
1649		if (ioctl(res->hr_ggatefd, G_GATE_CMD_DONE, ggio) < 0)
1650			primary_exit(EX_OSERR, "G_GATE_CMD_DONE failed");
1651		pjdlog_debug(2,
1652		    "ggate_send: (%p) Moving request to the free queue.", hio);
1653		QUEUE_INSERT2(hio, free);
1654	}
1655	/* NOTREACHED */
1656	return (NULL);
1657}
1658
1659/*
1660 * Thread synchronize local and remote components.
1661 */
1662static void *
1663sync_thread(void *arg __unused)
1664{
1665	struct hast_resource *res = arg;
1666	struct hio *hio;
1667	struct g_gate_ctl_io *ggio;
1668	struct timeval tstart, tend, tdiff;
1669	unsigned int ii, ncomp, ncomps;
1670	off_t offset, length, synced;
1671	bool dorewind;
1672	int syncext;
1673
1674	ncomps = HAST_NCOMPONENTS;
1675	dorewind = true;
1676	synced = 0;
1677	offset = -1;
1678
1679	for (;;) {
1680		mtx_lock(&sync_lock);
1681		if (offset >= 0 && !sync_inprogress) {
1682			gettimeofday(&tend, NULL);
1683			timersub(&tend, &tstart, &tdiff);
1684			pjdlog_info("Synchronization interrupted after %#.0T. "
1685			    "%NB synchronized so far.", &tdiff,
1686			    (intmax_t)synced);
1687			event_send(res, EVENT_SYNCINTR);
1688		}
1689		while (!sync_inprogress) {
1690			dorewind = true;
1691			synced = 0;
1692			cv_wait(&sync_cond, &sync_lock);
1693		}
1694		mtx_unlock(&sync_lock);
1695		/*
1696		 * Obtain offset at which we should synchronize.
1697		 * Rewind synchronization if needed.
1698		 */
1699		mtx_lock(&res->hr_amp_lock);
1700		if (dorewind)
1701			activemap_sync_rewind(res->hr_amp);
1702		offset = activemap_sync_offset(res->hr_amp, &length, &syncext);
1703		if (syncext != -1) {
1704			/*
1705			 * We synchronized entire syncext extent, we can mark
1706			 * it as clean now.
1707			 */
1708			if (activemap_extent_complete(res->hr_amp, syncext))
1709				(void)hast_activemap_flush(res);
1710		}
1711		mtx_unlock(&res->hr_amp_lock);
1712		if (dorewind) {
1713			dorewind = false;
1714			if (offset < 0)
1715				pjdlog_info("Nodes are in sync.");
1716			else {
1717				pjdlog_info("Synchronization started. %NB to go.",
1718				    (intmax_t)(res->hr_extentsize *
1719				    activemap_ndirty(res->hr_amp)));
1720				event_send(res, EVENT_SYNCSTART);
1721				gettimeofday(&tstart, NULL);
1722			}
1723		}
1724		if (offset < 0) {
1725			sync_stop();
1726			pjdlog_debug(1, "Nothing to synchronize.");
1727			/*
1728			 * Synchronization complete, make both localcnt and
1729			 * remotecnt equal.
1730			 */
1731			ncomp = 1;
1732			rw_rlock(&hio_remote_lock[ncomp]);
1733			if (ISCONNECTED(res, ncomp)) {
1734				if (synced > 0) {
1735					int64_t bps;
1736
1737					gettimeofday(&tend, NULL);
1738					timersub(&tend, &tstart, &tdiff);
1739					bps = (int64_t)((double)synced /
1740					    ((double)tdiff.tv_sec +
1741					    (double)tdiff.tv_usec / 1000000));
1742					pjdlog_info("Synchronization complete. "
1743					    "%NB synchronized in %#.0lT (%NB/sec).",
1744					    (intmax_t)synced, &tdiff,
1745					    (intmax_t)bps);
1746					event_send(res, EVENT_SYNCDONE);
1747				}
1748				mtx_lock(&metadata_lock);
1749				res->hr_syncsrc = HAST_SYNCSRC_UNDEF;
1750				res->hr_primary_localcnt =
1751				    res->hr_secondary_localcnt;
1752				res->hr_primary_remotecnt =
1753				    res->hr_secondary_remotecnt;
1754				pjdlog_debug(1,
1755				    "Setting localcnt to %ju and remotecnt to %ju.",
1756				    (uintmax_t)res->hr_primary_localcnt,
1757				    (uintmax_t)res->hr_secondary_localcnt);
1758				(void)metadata_write(res);
1759				mtx_unlock(&metadata_lock);
1760			}
1761			rw_unlock(&hio_remote_lock[ncomp]);
1762			continue;
1763		}
1764		pjdlog_debug(2, "sync: Taking free request.");
1765		QUEUE_TAKE2(hio, free);
1766		pjdlog_debug(2, "sync: (%p) Got free request.", hio);
1767		/*
1768		 * Lock the range we are going to synchronize. We don't want
1769		 * race where someone writes between our read and write.
1770		 */
1771		for (;;) {
1772			mtx_lock(&range_lock);
1773			if (rangelock_islocked(range_regular, offset, length)) {
1774				pjdlog_debug(2,
1775				    "sync: Range offset=%jd length=%jd locked.",
1776				    (intmax_t)offset, (intmax_t)length);
1777				range_sync_wait = true;
1778				cv_wait(&range_sync_cond, &range_lock);
1779				range_sync_wait = false;
1780				mtx_unlock(&range_lock);
1781				continue;
1782			}
1783			if (rangelock_add(range_sync, offset, length) < 0) {
1784				mtx_unlock(&range_lock);
1785				pjdlog_debug(2,
1786				    "sync: Range offset=%jd length=%jd is already locked, waiting.",
1787				    (intmax_t)offset, (intmax_t)length);
1788				sleep(1);
1789				continue;
1790			}
1791			mtx_unlock(&range_lock);
1792			break;
1793		}
1794		/*
1795		 * First read the data from synchronization source.
1796		 */
1797		SYNCREQ(hio);
1798		ggio = &hio->hio_ggio;
1799		ggio->gctl_cmd = BIO_READ;
1800		ggio->gctl_offset = offset;
1801		ggio->gctl_length = length;
1802		ggio->gctl_error = 0;
1803		for (ii = 0; ii < ncomps; ii++)
1804			hio->hio_errors[ii] = EINVAL;
1805		reqlog(LOG_DEBUG, 2, ggio, "sync: (%p) Sending sync request: ",
1806		    hio);
1807		pjdlog_debug(2, "sync: (%p) Moving request to the send queue.",
1808		    hio);
1809		mtx_lock(&metadata_lock);
1810		if (res->hr_syncsrc == HAST_SYNCSRC_PRIMARY) {
1811			/*
1812			 * This range is up-to-date on local component,
1813			 * so handle request locally.
1814			 */
1815			 /* Local component is 0 for now. */
1816			ncomp = 0;
1817		} else /* if (res->hr_syncsrc == HAST_SYNCSRC_SECONDARY) */ {
1818			PJDLOG_ASSERT(res->hr_syncsrc == HAST_SYNCSRC_SECONDARY);
1819			/*
1820			 * This range is out-of-date on local component,
1821			 * so send request to the remote node.
1822			 */
1823			 /* Remote component is 1 for now. */
1824			ncomp = 1;
1825		}
1826		mtx_unlock(&metadata_lock);
1827		refcount_init(&hio->hio_countdown, 1);
1828		QUEUE_INSERT1(hio, send, ncomp);
1829
1830		/*
1831		 * Let's wait for READ to finish.
1832		 */
1833		mtx_lock(&sync_lock);
1834		while (!ISSYNCREQDONE(hio))
1835			cv_wait(&sync_cond, &sync_lock);
1836		mtx_unlock(&sync_lock);
1837
1838		if (hio->hio_errors[ncomp] != 0) {
1839			pjdlog_error("Unable to read synchronization data: %s.",
1840			    strerror(hio->hio_errors[ncomp]));
1841			goto free_queue;
1842		}
1843
1844		/*
1845		 * We read the data from synchronization source, now write it
1846		 * to synchronization target.
1847		 */
1848		SYNCREQ(hio);
1849		ggio->gctl_cmd = BIO_WRITE;
1850		for (ii = 0; ii < ncomps; ii++)
1851			hio->hio_errors[ii] = EINVAL;
1852		reqlog(LOG_DEBUG, 2, ggio, "sync: (%p) Sending sync request: ",
1853		    hio);
1854		pjdlog_debug(2, "sync: (%p) Moving request to the send queue.",
1855		    hio);
1856		mtx_lock(&metadata_lock);
1857		if (res->hr_syncsrc == HAST_SYNCSRC_PRIMARY) {
1858			/*
1859			 * This range is up-to-date on local component,
1860			 * so we update remote component.
1861			 */
1862			 /* Remote component is 1 for now. */
1863			ncomp = 1;
1864		} else /* if (res->hr_syncsrc == HAST_SYNCSRC_SECONDARY) */ {
1865			PJDLOG_ASSERT(res->hr_syncsrc == HAST_SYNCSRC_SECONDARY);
1866			/*
1867			 * This range is out-of-date on local component,
1868			 * so we update it.
1869			 */
1870			 /* Local component is 0 for now. */
1871			ncomp = 0;
1872		}
1873		mtx_unlock(&metadata_lock);
1874
1875		pjdlog_debug(2, "sync: (%p) Moving request to the send queues.",
1876		    hio);
1877		refcount_init(&hio->hio_countdown, 1);
1878		QUEUE_INSERT1(hio, send, ncomp);
1879
1880		/*
1881		 * Let's wait for WRITE to finish.
1882		 */
1883		mtx_lock(&sync_lock);
1884		while (!ISSYNCREQDONE(hio))
1885			cv_wait(&sync_cond, &sync_lock);
1886		mtx_unlock(&sync_lock);
1887
1888		if (hio->hio_errors[ncomp] != 0) {
1889			pjdlog_error("Unable to write synchronization data: %s.",
1890			    strerror(hio->hio_errors[ncomp]));
1891			goto free_queue;
1892		}
1893
1894		synced += length;
1895free_queue:
1896		mtx_lock(&range_lock);
1897		rangelock_del(range_sync, offset, length);
1898		if (range_regular_wait)
1899			cv_signal(&range_regular_cond);
1900		mtx_unlock(&range_lock);
1901		pjdlog_debug(2, "sync: (%p) Moving request to the free queue.",
1902		    hio);
1903		QUEUE_INSERT2(hio, free);
1904	}
1905	/* NOTREACHED */
1906	return (NULL);
1907}
1908
1909void
1910primary_config_reload(struct hast_resource *res, struct nv *nv)
1911{
1912	unsigned int ii, ncomps;
1913	int modified, vint;
1914	const char *vstr;
1915
1916	pjdlog_info("Reloading configuration...");
1917
1918	PJDLOG_ASSERT(res->hr_role == HAST_ROLE_PRIMARY);
1919	PJDLOG_ASSERT(gres == res);
1920	nv_assert(nv, "remoteaddr");
1921	nv_assert(nv, "replication");
1922	nv_assert(nv, "checksum");
1923	nv_assert(nv, "compression");
1924	nv_assert(nv, "timeout");
1925	nv_assert(nv, "exec");
1926
1927	ncomps = HAST_NCOMPONENTS;
1928
1929#define MODIFIED_REMOTEADDR	0x01
1930#define MODIFIED_REPLICATION	0x02
1931#define MODIFIED_CHECKSUM	0x04
1932#define MODIFIED_COMPRESSION	0x08
1933#define MODIFIED_TIMEOUT	0x10
1934#define MODIFIED_EXEC		0x20
1935	modified = 0;
1936
1937	vstr = nv_get_string(nv, "remoteaddr");
1938	if (strcmp(gres->hr_remoteaddr, vstr) != 0) {
1939		/*
1940		 * Don't copy res->hr_remoteaddr to gres just yet.
1941		 * We want remote_close() to log disconnect from the old
1942		 * addresses, not from the new ones.
1943		 */
1944		modified |= MODIFIED_REMOTEADDR;
1945	}
1946	vint = nv_get_int32(nv, "replication");
1947	if (gres->hr_replication != vint) {
1948		gres->hr_replication = vint;
1949		modified |= MODIFIED_REPLICATION;
1950	}
1951	vint = nv_get_int32(nv, "checksum");
1952	if (gres->hr_checksum != vint) {
1953		gres->hr_checksum = vint;
1954		modified |= MODIFIED_CHECKSUM;
1955	}
1956	vint = nv_get_int32(nv, "compression");
1957	if (gres->hr_compression != vint) {
1958		gres->hr_compression = vint;
1959		modified |= MODIFIED_COMPRESSION;
1960	}
1961	vint = nv_get_int32(nv, "timeout");
1962	if (gres->hr_timeout != vint) {
1963		gres->hr_timeout = vint;
1964		modified |= MODIFIED_TIMEOUT;
1965	}
1966	vstr = nv_get_string(nv, "exec");
1967	if (strcmp(gres->hr_exec, vstr) != 0) {
1968		strlcpy(gres->hr_exec, vstr, sizeof(gres->hr_exec));
1969		modified |= MODIFIED_EXEC;
1970	}
1971
1972	/*
1973	 * Change timeout for connected sockets.
1974	 * Don't bother if we need to reconnect.
1975	 */
1976	if ((modified & MODIFIED_TIMEOUT) != 0 &&
1977	    (modified & (MODIFIED_REMOTEADDR | MODIFIED_REPLICATION)) == 0) {
1978		for (ii = 0; ii < ncomps; ii++) {
1979			if (!ISREMOTE(ii))
1980				continue;
1981			rw_rlock(&hio_remote_lock[ii]);
1982			if (!ISCONNECTED(gres, ii)) {
1983				rw_unlock(&hio_remote_lock[ii]);
1984				continue;
1985			}
1986			rw_unlock(&hio_remote_lock[ii]);
1987			if (proto_timeout(gres->hr_remotein,
1988			    gres->hr_timeout) < 0) {
1989				pjdlog_errno(LOG_WARNING,
1990				    "Unable to set connection timeout");
1991			}
1992			if (proto_timeout(gres->hr_remoteout,
1993			    gres->hr_timeout) < 0) {
1994				pjdlog_errno(LOG_WARNING,
1995				    "Unable to set connection timeout");
1996			}
1997		}
1998	}
1999	if ((modified & (MODIFIED_REMOTEADDR | MODIFIED_REPLICATION)) != 0) {
2000		for (ii = 0; ii < ncomps; ii++) {
2001			if (!ISREMOTE(ii))
2002				continue;
2003			remote_close(gres, ii);
2004		}
2005		if (modified & MODIFIED_REMOTEADDR) {
2006			vstr = nv_get_string(nv, "remoteaddr");
2007			strlcpy(gres->hr_remoteaddr, vstr,
2008			    sizeof(gres->hr_remoteaddr));
2009		}
2010	}
2011#undef	MODIFIED_REMOTEADDR
2012#undef	MODIFIED_REPLICATION
2013#undef	MODIFIED_CHECKSUM
2014#undef	MODIFIED_COMPRESSION
2015#undef	MODIFIED_TIMEOUT
2016#undef	MODIFIED_EXEC
2017
2018	pjdlog_info("Configuration reloaded successfully.");
2019}
2020
2021static void
2022guard_one(struct hast_resource *res, unsigned int ncomp)
2023{
2024	struct proto_conn *in, *out;
2025
2026	if (!ISREMOTE(ncomp))
2027		return;
2028
2029	rw_rlock(&hio_remote_lock[ncomp]);
2030
2031	if (!real_remote(res)) {
2032		rw_unlock(&hio_remote_lock[ncomp]);
2033		return;
2034	}
2035
2036	if (ISCONNECTED(res, ncomp)) {
2037		PJDLOG_ASSERT(res->hr_remotein != NULL);
2038		PJDLOG_ASSERT(res->hr_remoteout != NULL);
2039		rw_unlock(&hio_remote_lock[ncomp]);
2040		pjdlog_debug(2, "remote_guard: Connection to %s is ok.",
2041		    res->hr_remoteaddr);
2042		return;
2043	}
2044
2045	PJDLOG_ASSERT(res->hr_remotein == NULL);
2046	PJDLOG_ASSERT(res->hr_remoteout == NULL);
2047	/*
2048	 * Upgrade the lock. It doesn't have to be atomic as no other thread
2049	 * can change connection status from disconnected to connected.
2050	 */
2051	rw_unlock(&hio_remote_lock[ncomp]);
2052	pjdlog_debug(2, "remote_guard: Reconnecting to %s.",
2053	    res->hr_remoteaddr);
2054	in = out = NULL;
2055	if (init_remote(res, &in, &out)) {
2056		rw_wlock(&hio_remote_lock[ncomp]);
2057		PJDLOG_ASSERT(res->hr_remotein == NULL);
2058		PJDLOG_ASSERT(res->hr_remoteout == NULL);
2059		PJDLOG_ASSERT(in != NULL && out != NULL);
2060		res->hr_remotein = in;
2061		res->hr_remoteout = out;
2062		rw_unlock(&hio_remote_lock[ncomp]);
2063		pjdlog_info("Successfully reconnected to %s.",
2064		    res->hr_remoteaddr);
2065		sync_start();
2066	} else {
2067		/* Both connections should be NULL. */
2068		PJDLOG_ASSERT(res->hr_remotein == NULL);
2069		PJDLOG_ASSERT(res->hr_remoteout == NULL);
2070		PJDLOG_ASSERT(in == NULL && out == NULL);
2071		pjdlog_debug(2, "remote_guard: Reconnect to %s failed.",
2072		    res->hr_remoteaddr);
2073	}
2074}
2075
2076/*
2077 * Thread guards remote connections and reconnects when needed, handles
2078 * signals, etc.
2079 */
2080static void *
2081guard_thread(void *arg)
2082{
2083	struct hast_resource *res = arg;
2084	unsigned int ii, ncomps;
2085	struct timespec timeout;
2086	time_t lastcheck, now;
2087	sigset_t mask;
2088	int signo;
2089
2090	ncomps = HAST_NCOMPONENTS;
2091	lastcheck = time(NULL);
2092
2093	PJDLOG_VERIFY(sigemptyset(&mask) == 0);
2094	PJDLOG_VERIFY(sigaddset(&mask, SIGINT) == 0);
2095	PJDLOG_VERIFY(sigaddset(&mask, SIGTERM) == 0);
2096
2097	timeout.tv_sec = HAST_KEEPALIVE;
2098	timeout.tv_nsec = 0;
2099	signo = -1;
2100
2101	for (;;) {
2102		switch (signo) {
2103		case SIGINT:
2104		case SIGTERM:
2105			sigexit_received = true;
2106			primary_exitx(EX_OK,
2107			    "Termination signal received, exiting.");
2108			break;
2109		default:
2110			break;
2111		}
2112
2113		pjdlog_debug(2, "remote_guard: Checking connections.");
2114		now = time(NULL);
2115		if (lastcheck + HAST_KEEPALIVE <= now) {
2116			for (ii = 0; ii < ncomps; ii++)
2117				guard_one(res, ii);
2118			lastcheck = now;
2119		}
2120		signo = sigtimedwait(&mask, NULL, &timeout);
2121	}
2122	/* NOTREACHED */
2123	return (NULL);
2124}
2125