primary.c revision 214284
1204076Spjd/*-
2204076Spjd * Copyright (c) 2009 The FreeBSD Foundation
3210886Spjd * Copyright (c) 2010 Pawel Jakub Dawidek <pjd@FreeBSD.org>
4204076Spjd * All rights reserved.
5204076Spjd *
6204076Spjd * This software was developed by Pawel Jakub Dawidek under sponsorship from
7204076Spjd * the FreeBSD Foundation.
8204076Spjd *
9204076Spjd * Redistribution and use in source and binary forms, with or without
10204076Spjd * modification, are permitted provided that the following conditions
11204076Spjd * are met:
12204076Spjd * 1. Redistributions of source code must retain the above copyright
13204076Spjd *    notice, this list of conditions and the following disclaimer.
14204076Spjd * 2. Redistributions in binary form must reproduce the above copyright
15204076Spjd *    notice, this list of conditions and the following disclaimer in the
16204076Spjd *    documentation and/or other materials provided with the distribution.
17204076Spjd *
18204076Spjd * THIS SOFTWARE IS PROVIDED BY THE AUTHORS AND CONTRIBUTORS ``AS IS'' AND
19204076Spjd * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20204076Spjd * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21204076Spjd * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE
22204076Spjd * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23204076Spjd * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24204076Spjd * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25204076Spjd * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26204076Spjd * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
27204076Spjd * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28204076Spjd * SUCH DAMAGE.
29204076Spjd */
30204076Spjd
31204076Spjd#include <sys/cdefs.h>
32204076Spjd__FBSDID("$FreeBSD: head/sbin/hastd/primary.c 214284 2010-10-24 17:28:25Z pjd $");
33204076Spjd
34204076Spjd#include <sys/types.h>
35204076Spjd#include <sys/time.h>
36204076Spjd#include <sys/bio.h>
37204076Spjd#include <sys/disk.h>
38204076Spjd#include <sys/refcount.h>
39204076Spjd#include <sys/stat.h>
40204076Spjd
41204076Spjd#include <geom/gate/g_gate.h>
42204076Spjd
43204076Spjd#include <assert.h>
44204076Spjd#include <err.h>
45204076Spjd#include <errno.h>
46204076Spjd#include <fcntl.h>
47204076Spjd#include <libgeom.h>
48204076Spjd#include <pthread.h>
49211982Spjd#include <signal.h>
50204076Spjd#include <stdint.h>
51204076Spjd#include <stdio.h>
52204076Spjd#include <string.h>
53204076Spjd#include <sysexits.h>
54204076Spjd#include <unistd.h>
55204076Spjd
56204076Spjd#include <activemap.h>
57204076Spjd#include <nv.h>
58204076Spjd#include <rangelock.h>
59204076Spjd
60204076Spjd#include "control.h"
61212038Spjd#include "event.h"
62204076Spjd#include "hast.h"
63204076Spjd#include "hast_proto.h"
64204076Spjd#include "hastd.h"
65211886Spjd#include "hooks.h"
66204076Spjd#include "metadata.h"
67204076Spjd#include "proto.h"
68204076Spjd#include "pjdlog.h"
69204076Spjd#include "subr.h"
70204076Spjd#include "synch.h"
71204076Spjd
72210886Spjd/* The is only one remote component for now. */
73210886Spjd#define	ISREMOTE(no)	((no) == 1)
74210886Spjd
75204076Spjdstruct hio {
76204076Spjd	/*
77204076Spjd	 * Number of components we are still waiting for.
78204076Spjd	 * When this field goes to 0, we can send the request back to the
79204076Spjd	 * kernel. Each component has to decrease this counter by one
80204076Spjd	 * even on failure.
81204076Spjd	 */
82204076Spjd	unsigned int		 hio_countdown;
83204076Spjd	/*
84204076Spjd	 * Each component has a place to store its own error.
85204076Spjd	 * Once the request is handled by all components we can decide if the
86204076Spjd	 * request overall is successful or not.
87204076Spjd	 */
88204076Spjd	int			*hio_errors;
89204076Spjd	/*
90204076Spjd	 * Structure used to comunicate with GEOM Gate class.
91204076Spjd	 */
92204076Spjd	struct g_gate_ctl_io	 hio_ggio;
93204076Spjd	TAILQ_ENTRY(hio)	*hio_next;
94204076Spjd};
95204076Spjd#define	hio_free_next	hio_next[0]
96204076Spjd#define	hio_done_next	hio_next[0]
97204076Spjd
98204076Spjd/*
99204076Spjd * Free list holds unused structures. When free list is empty, we have to wait
100204076Spjd * until some in-progress requests are freed.
101204076Spjd */
102204076Spjdstatic TAILQ_HEAD(, hio) hio_free_list;
103204076Spjdstatic pthread_mutex_t hio_free_list_lock;
104204076Spjdstatic pthread_cond_t hio_free_list_cond;
105204076Spjd/*
106204076Spjd * There is one send list for every component. One requests is placed on all
107204076Spjd * send lists - each component gets the same request, but each component is
108204076Spjd * responsible for managing his own send list.
109204076Spjd */
110204076Spjdstatic TAILQ_HEAD(, hio) *hio_send_list;
111204076Spjdstatic pthread_mutex_t *hio_send_list_lock;
112204076Spjdstatic pthread_cond_t *hio_send_list_cond;
113204076Spjd/*
114204076Spjd * There is one recv list for every component, although local components don't
115204076Spjd * use recv lists as local requests are done synchronously.
116204076Spjd */
117204076Spjdstatic TAILQ_HEAD(, hio) *hio_recv_list;
118204076Spjdstatic pthread_mutex_t *hio_recv_list_lock;
119204076Spjdstatic pthread_cond_t *hio_recv_list_cond;
120204076Spjd/*
121204076Spjd * Request is placed on done list by the slowest component (the one that
122204076Spjd * decreased hio_countdown from 1 to 0).
123204076Spjd */
124204076Spjdstatic TAILQ_HEAD(, hio) hio_done_list;
125204076Spjdstatic pthread_mutex_t hio_done_list_lock;
126204076Spjdstatic pthread_cond_t hio_done_list_cond;
127204076Spjd/*
128204076Spjd * Structure below are for interaction with sync thread.
129204076Spjd */
130204076Spjdstatic bool sync_inprogress;
131204076Spjdstatic pthread_mutex_t sync_lock;
132204076Spjdstatic pthread_cond_t sync_cond;
133204076Spjd/*
134204076Spjd * The lock below allows to synchornize access to remote connections.
135204076Spjd */
136204076Spjdstatic pthread_rwlock_t *hio_remote_lock;
137204076Spjd
138204076Spjd/*
139204076Spjd * Lock to synchronize metadata updates. Also synchronize access to
140204076Spjd * hr_primary_localcnt and hr_primary_remotecnt fields.
141204076Spjd */
142204076Spjdstatic pthread_mutex_t metadata_lock;
143204076Spjd
144204076Spjd/*
145204076Spjd * Maximum number of outstanding I/O requests.
146204076Spjd */
147204076Spjd#define	HAST_HIO_MAX	256
148204076Spjd/*
149204076Spjd * Number of components. At this point there are only two components: local
150204076Spjd * and remote, but in the future it might be possible to use multiple local
151204076Spjd * and remote components.
152204076Spjd */
153204076Spjd#define	HAST_NCOMPONENTS	2
154204076Spjd/*
155211982Spjd * Number of seconds to sleep between reconnect retries or keepalive packets.
156204076Spjd */
157211982Spjd#define	RETRY_SLEEP		10
158204076Spjd
159204076Spjd#define	ISCONNECTED(res, no)	\
160204076Spjd	((res)->hr_remotein != NULL && (res)->hr_remoteout != NULL)
161204076Spjd
162204076Spjd#define	QUEUE_INSERT1(hio, name, ncomp)	do {				\
163204076Spjd	bool _wakeup;							\
164204076Spjd									\
165204076Spjd	mtx_lock(&hio_##name##_list_lock[(ncomp)]);			\
166204076Spjd	_wakeup = TAILQ_EMPTY(&hio_##name##_list[(ncomp)]);		\
167204076Spjd	TAILQ_INSERT_TAIL(&hio_##name##_list[(ncomp)], (hio),		\
168204076Spjd	    hio_next[(ncomp)]);						\
169204076Spjd	mtx_unlock(&hio_##name##_list_lock[ncomp]);			\
170204076Spjd	if (_wakeup)							\
171204076Spjd		cv_signal(&hio_##name##_list_cond[(ncomp)]);		\
172204076Spjd} while (0)
173204076Spjd#define	QUEUE_INSERT2(hio, name)	do {				\
174204076Spjd	bool _wakeup;							\
175204076Spjd									\
176204076Spjd	mtx_lock(&hio_##name##_list_lock);				\
177204076Spjd	_wakeup = TAILQ_EMPTY(&hio_##name##_list);			\
178204076Spjd	TAILQ_INSERT_TAIL(&hio_##name##_list, (hio), hio_##name##_next);\
179204076Spjd	mtx_unlock(&hio_##name##_list_lock);				\
180204076Spjd	if (_wakeup)							\
181204076Spjd		cv_signal(&hio_##name##_list_cond);			\
182204076Spjd} while (0)
183204076Spjd#define	QUEUE_TAKE1(hio, name, ncomp)	do {				\
184204076Spjd	mtx_lock(&hio_##name##_list_lock[(ncomp)]);			\
185204076Spjd	while (((hio) = TAILQ_FIRST(&hio_##name##_list[(ncomp)])) == NULL) { \
186204076Spjd		cv_wait(&hio_##name##_list_cond[(ncomp)],		\
187204076Spjd		    &hio_##name##_list_lock[(ncomp)]);			\
188204076Spjd	}								\
189204076Spjd	TAILQ_REMOVE(&hio_##name##_list[(ncomp)], (hio),		\
190204076Spjd	    hio_next[(ncomp)]);						\
191204076Spjd	mtx_unlock(&hio_##name##_list_lock[(ncomp)]);			\
192204076Spjd} while (0)
193204076Spjd#define	QUEUE_TAKE2(hio, name)	do {					\
194204076Spjd	mtx_lock(&hio_##name##_list_lock);				\
195204076Spjd	while (((hio) = TAILQ_FIRST(&hio_##name##_list)) == NULL) {	\
196204076Spjd		cv_wait(&hio_##name##_list_cond,			\
197204076Spjd		    &hio_##name##_list_lock);				\
198204076Spjd	}								\
199204076Spjd	TAILQ_REMOVE(&hio_##name##_list, (hio), hio_##name##_next);	\
200204076Spjd	mtx_unlock(&hio_##name##_list_lock);				\
201204076Spjd} while (0)
202204076Spjd
203209183Spjd#define	SYNCREQ(hio)		do {					\
204209183Spjd	(hio)->hio_ggio.gctl_unit = -1;					\
205209183Spjd	(hio)->hio_ggio.gctl_seq = 1;					\
206209183Spjd} while (0)
207204076Spjd#define	ISSYNCREQ(hio)		((hio)->hio_ggio.gctl_unit == -1)
208204076Spjd#define	SYNCREQDONE(hio)	do { (hio)->hio_ggio.gctl_unit = -2; } while (0)
209204076Spjd#define	ISSYNCREQDONE(hio)	((hio)->hio_ggio.gctl_unit == -2)
210204076Spjd
211204076Spjdstatic struct hast_resource *gres;
212204076Spjd
213204076Spjdstatic pthread_mutex_t range_lock;
214204076Spjdstatic struct rangelocks *range_regular;
215204076Spjdstatic bool range_regular_wait;
216204076Spjdstatic pthread_cond_t range_regular_cond;
217204076Spjdstatic struct rangelocks *range_sync;
218204076Spjdstatic bool range_sync_wait;
219204076Spjdstatic pthread_cond_t range_sync_cond;
220204076Spjd
221204076Spjdstatic void *ggate_recv_thread(void *arg);
222204076Spjdstatic void *local_send_thread(void *arg);
223204076Spjdstatic void *remote_send_thread(void *arg);
224204076Spjdstatic void *remote_recv_thread(void *arg);
225204076Spjdstatic void *ggate_send_thread(void *arg);
226204076Spjdstatic void *sync_thread(void *arg);
227204076Spjdstatic void *guard_thread(void *arg);
228204076Spjd
229211982Spjdstatic void
230204076Spjdcleanup(struct hast_resource *res)
231204076Spjd{
232204076Spjd	int rerrno;
233204076Spjd
234204076Spjd	/* Remember errno. */
235204076Spjd	rerrno = errno;
236204076Spjd
237204076Spjd	/* Destroy ggate provider if we created one. */
238204076Spjd	if (res->hr_ggateunit >= 0) {
239204076Spjd		struct g_gate_ctl_destroy ggiod;
240204076Spjd
241213533Spjd		bzero(&ggiod, sizeof(ggiod));
242204076Spjd		ggiod.gctl_version = G_GATE_VERSION;
243204076Spjd		ggiod.gctl_unit = res->hr_ggateunit;
244204076Spjd		ggiod.gctl_force = 1;
245204076Spjd		if (ioctl(res->hr_ggatefd, G_GATE_CMD_DESTROY, &ggiod) < 0) {
246213531Spjd			pjdlog_errno(LOG_WARNING,
247213531Spjd			    "Unable to destroy hast/%s device",
248204076Spjd			    res->hr_provname);
249204076Spjd		}
250204076Spjd		res->hr_ggateunit = -1;
251204076Spjd	}
252204076Spjd
253204076Spjd	/* Restore errno. */
254204076Spjd	errno = rerrno;
255204076Spjd}
256204076Spjd
257212899Spjdstatic __dead2 void
258204076Spjdprimary_exit(int exitcode, const char *fmt, ...)
259204076Spjd{
260204076Spjd	va_list ap;
261204076Spjd
262204076Spjd	assert(exitcode != EX_OK);
263204076Spjd	va_start(ap, fmt);
264204076Spjd	pjdlogv_errno(LOG_ERR, fmt, ap);
265204076Spjd	va_end(ap);
266204076Spjd	cleanup(gres);
267204076Spjd	exit(exitcode);
268204076Spjd}
269204076Spjd
270212899Spjdstatic __dead2 void
271204076Spjdprimary_exitx(int exitcode, const char *fmt, ...)
272204076Spjd{
273204076Spjd	va_list ap;
274204076Spjd
275204076Spjd	va_start(ap, fmt);
276204076Spjd	pjdlogv(exitcode == EX_OK ? LOG_INFO : LOG_ERR, fmt, ap);
277204076Spjd	va_end(ap);
278204076Spjd	cleanup(gres);
279204076Spjd	exit(exitcode);
280204076Spjd}
281204076Spjd
282204076Spjdstatic int
283204076Spjdhast_activemap_flush(struct hast_resource *res)
284204076Spjd{
285204076Spjd	const unsigned char *buf;
286204076Spjd	size_t size;
287204076Spjd
288204076Spjd	buf = activemap_bitmap(res->hr_amp, &size);
289204076Spjd	assert(buf != NULL);
290204076Spjd	assert((size % res->hr_local_sectorsize) == 0);
291204076Spjd	if (pwrite(res->hr_localfd, buf, size, METADATA_SIZE) !=
292204076Spjd	    (ssize_t)size) {
293204076Spjd		KEEP_ERRNO(pjdlog_errno(LOG_ERR,
294204076Spjd		    "Unable to flush activemap to disk"));
295204076Spjd		return (-1);
296204076Spjd	}
297204076Spjd	return (0);
298204076Spjd}
299204076Spjd
300210881Spjdstatic bool
301210881Spjdreal_remote(const struct hast_resource *res)
302210881Spjd{
303210881Spjd
304210881Spjd	return (strcmp(res->hr_remoteaddr, "none") != 0);
305210881Spjd}
306210881Spjd
307204076Spjdstatic void
308204076Spjdinit_environment(struct hast_resource *res __unused)
309204076Spjd{
310204076Spjd	struct hio *hio;
311204076Spjd	unsigned int ii, ncomps;
312204076Spjd
313204076Spjd	/*
314204076Spjd	 * In the future it might be per-resource value.
315204076Spjd	 */
316204076Spjd	ncomps = HAST_NCOMPONENTS;
317204076Spjd
318204076Spjd	/*
319204076Spjd	 * Allocate memory needed by lists.
320204076Spjd	 */
321204076Spjd	hio_send_list = malloc(sizeof(hio_send_list[0]) * ncomps);
322204076Spjd	if (hio_send_list == NULL) {
323204076Spjd		primary_exitx(EX_TEMPFAIL,
324204076Spjd		    "Unable to allocate %zu bytes of memory for send lists.",
325204076Spjd		    sizeof(hio_send_list[0]) * ncomps);
326204076Spjd	}
327204076Spjd	hio_send_list_lock = malloc(sizeof(hio_send_list_lock[0]) * ncomps);
328204076Spjd	if (hio_send_list_lock == NULL) {
329204076Spjd		primary_exitx(EX_TEMPFAIL,
330204076Spjd		    "Unable to allocate %zu bytes of memory for send list locks.",
331204076Spjd		    sizeof(hio_send_list_lock[0]) * ncomps);
332204076Spjd	}
333204076Spjd	hio_send_list_cond = malloc(sizeof(hio_send_list_cond[0]) * ncomps);
334204076Spjd	if (hio_send_list_cond == NULL) {
335204076Spjd		primary_exitx(EX_TEMPFAIL,
336204076Spjd		    "Unable to allocate %zu bytes of memory for send list condition variables.",
337204076Spjd		    sizeof(hio_send_list_cond[0]) * ncomps);
338204076Spjd	}
339204076Spjd	hio_recv_list = malloc(sizeof(hio_recv_list[0]) * ncomps);
340204076Spjd	if (hio_recv_list == NULL) {
341204076Spjd		primary_exitx(EX_TEMPFAIL,
342204076Spjd		    "Unable to allocate %zu bytes of memory for recv lists.",
343204076Spjd		    sizeof(hio_recv_list[0]) * ncomps);
344204076Spjd	}
345204076Spjd	hio_recv_list_lock = malloc(sizeof(hio_recv_list_lock[0]) * ncomps);
346204076Spjd	if (hio_recv_list_lock == NULL) {
347204076Spjd		primary_exitx(EX_TEMPFAIL,
348204076Spjd		    "Unable to allocate %zu bytes of memory for recv list locks.",
349204076Spjd		    sizeof(hio_recv_list_lock[0]) * ncomps);
350204076Spjd	}
351204076Spjd	hio_recv_list_cond = malloc(sizeof(hio_recv_list_cond[0]) * ncomps);
352204076Spjd	if (hio_recv_list_cond == NULL) {
353204076Spjd		primary_exitx(EX_TEMPFAIL,
354204076Spjd		    "Unable to allocate %zu bytes of memory for recv list condition variables.",
355204076Spjd		    sizeof(hio_recv_list_cond[0]) * ncomps);
356204076Spjd	}
357204076Spjd	hio_remote_lock = malloc(sizeof(hio_remote_lock[0]) * ncomps);
358204076Spjd	if (hio_remote_lock == NULL) {
359204076Spjd		primary_exitx(EX_TEMPFAIL,
360204076Spjd		    "Unable to allocate %zu bytes of memory for remote connections locks.",
361204076Spjd		    sizeof(hio_remote_lock[0]) * ncomps);
362204076Spjd	}
363204076Spjd
364204076Spjd	/*
365204076Spjd	 * Initialize lists, their locks and theirs condition variables.
366204076Spjd	 */
367204076Spjd	TAILQ_INIT(&hio_free_list);
368204076Spjd	mtx_init(&hio_free_list_lock);
369204076Spjd	cv_init(&hio_free_list_cond);
370204076Spjd	for (ii = 0; ii < HAST_NCOMPONENTS; ii++) {
371204076Spjd		TAILQ_INIT(&hio_send_list[ii]);
372204076Spjd		mtx_init(&hio_send_list_lock[ii]);
373204076Spjd		cv_init(&hio_send_list_cond[ii]);
374204076Spjd		TAILQ_INIT(&hio_recv_list[ii]);
375204076Spjd		mtx_init(&hio_recv_list_lock[ii]);
376204076Spjd		cv_init(&hio_recv_list_cond[ii]);
377204076Spjd		rw_init(&hio_remote_lock[ii]);
378204076Spjd	}
379204076Spjd	TAILQ_INIT(&hio_done_list);
380204076Spjd	mtx_init(&hio_done_list_lock);
381204076Spjd	cv_init(&hio_done_list_cond);
382204076Spjd	mtx_init(&metadata_lock);
383204076Spjd
384204076Spjd	/*
385204076Spjd	 * Allocate requests pool and initialize requests.
386204076Spjd	 */
387204076Spjd	for (ii = 0; ii < HAST_HIO_MAX; ii++) {
388204076Spjd		hio = malloc(sizeof(*hio));
389204076Spjd		if (hio == NULL) {
390204076Spjd			primary_exitx(EX_TEMPFAIL,
391204076Spjd			    "Unable to allocate %zu bytes of memory for hio request.",
392204076Spjd			    sizeof(*hio));
393204076Spjd		}
394204076Spjd		hio->hio_countdown = 0;
395204076Spjd		hio->hio_errors = malloc(sizeof(hio->hio_errors[0]) * ncomps);
396204076Spjd		if (hio->hio_errors == NULL) {
397204076Spjd			primary_exitx(EX_TEMPFAIL,
398204076Spjd			    "Unable allocate %zu bytes of memory for hio errors.",
399204076Spjd			    sizeof(hio->hio_errors[0]) * ncomps);
400204076Spjd		}
401204076Spjd		hio->hio_next = malloc(sizeof(hio->hio_next[0]) * ncomps);
402204076Spjd		if (hio->hio_next == NULL) {
403204076Spjd			primary_exitx(EX_TEMPFAIL,
404204076Spjd			    "Unable allocate %zu bytes of memory for hio_next field.",
405204076Spjd			    sizeof(hio->hio_next[0]) * ncomps);
406204076Spjd		}
407204076Spjd		hio->hio_ggio.gctl_version = G_GATE_VERSION;
408204076Spjd		hio->hio_ggio.gctl_data = malloc(MAXPHYS);
409204076Spjd		if (hio->hio_ggio.gctl_data == NULL) {
410204076Spjd			primary_exitx(EX_TEMPFAIL,
411204076Spjd			    "Unable to allocate %zu bytes of memory for gctl_data.",
412204076Spjd			    MAXPHYS);
413204076Spjd		}
414204076Spjd		hio->hio_ggio.gctl_length = MAXPHYS;
415204076Spjd		hio->hio_ggio.gctl_error = 0;
416204076Spjd		TAILQ_INSERT_HEAD(&hio_free_list, hio, hio_free_next);
417204076Spjd	}
418204076Spjd}
419204076Spjd
420214284Spjdstatic bool
421214284Spjdinit_resuid(struct hast_resource *res)
422214284Spjd{
423214284Spjd
424214284Spjd	mtx_lock(&metadata_lock);
425214284Spjd	if (res->hr_resuid != 0) {
426214284Spjd		mtx_unlock(&metadata_lock);
427214284Spjd		return (false);
428214284Spjd	} else {
429214284Spjd		/* Initialize unique resource identifier. */
430214284Spjd		arc4random_buf(&res->hr_resuid, sizeof(res->hr_resuid));
431214284Spjd		mtx_unlock(&metadata_lock);
432214284Spjd		if (metadata_write(res) < 0)
433214284Spjd			exit(EX_NOINPUT);
434214284Spjd		return (true);
435214284Spjd	}
436214284Spjd}
437214284Spjd
438204076Spjdstatic void
439204076Spjdinit_local(struct hast_resource *res)
440204076Spjd{
441204076Spjd	unsigned char *buf;
442204076Spjd	size_t mapsize;
443204076Spjd
444204076Spjd	if (metadata_read(res, true) < 0)
445204076Spjd		exit(EX_NOINPUT);
446204076Spjd	mtx_init(&res->hr_amp_lock);
447204076Spjd	if (activemap_init(&res->hr_amp, res->hr_datasize, res->hr_extentsize,
448204076Spjd	    res->hr_local_sectorsize, res->hr_keepdirty) < 0) {
449204076Spjd		primary_exit(EX_TEMPFAIL, "Unable to create activemap");
450204076Spjd	}
451204076Spjd	mtx_init(&range_lock);
452204076Spjd	cv_init(&range_regular_cond);
453204076Spjd	if (rangelock_init(&range_regular) < 0)
454204076Spjd		primary_exit(EX_TEMPFAIL, "Unable to create regular range lock");
455204076Spjd	cv_init(&range_sync_cond);
456204076Spjd	if (rangelock_init(&range_sync) < 0)
457204076Spjd		primary_exit(EX_TEMPFAIL, "Unable to create sync range lock");
458204076Spjd	mapsize = activemap_ondisk_size(res->hr_amp);
459204076Spjd	buf = calloc(1, mapsize);
460204076Spjd	if (buf == NULL) {
461204076Spjd		primary_exitx(EX_TEMPFAIL,
462204076Spjd		    "Unable to allocate buffer for activemap.");
463204076Spjd	}
464204076Spjd	if (pread(res->hr_localfd, buf, mapsize, METADATA_SIZE) !=
465204076Spjd	    (ssize_t)mapsize) {
466204076Spjd		primary_exit(EX_NOINPUT, "Unable to read activemap");
467204076Spjd	}
468204076Spjd	activemap_copyin(res->hr_amp, buf, mapsize);
469209181Spjd	free(buf);
470204076Spjd	if (res->hr_resuid != 0)
471204076Spjd		return;
472204076Spjd	/*
473214284Spjd	 * We're using provider for the first time. Initialize local and remote
474214284Spjd	 * counters. We don't initialize resuid here, as we want to do it just
475214284Spjd	 * in time. The reason for this is that we want to inform secondary
476214284Spjd	 * that there were no writes yet, so there is no need to synchronize
477214284Spjd	 * anything.
478204076Spjd	 */
479204076Spjd	res->hr_primary_localcnt = 1;
480204076Spjd	res->hr_primary_remotecnt = 0;
481204076Spjd	if (metadata_write(res) < 0)
482204076Spjd		exit(EX_NOINPUT);
483204076Spjd}
484204076Spjd
485205738Spjdstatic bool
486205738Spjdinit_remote(struct hast_resource *res, struct proto_conn **inp,
487205738Spjd    struct proto_conn **outp)
488204076Spjd{
489205738Spjd	struct proto_conn *in, *out;
490204076Spjd	struct nv *nvout, *nvin;
491204076Spjd	const unsigned char *token;
492204076Spjd	unsigned char *map;
493204076Spjd	const char *errmsg;
494204076Spjd	int32_t extentsize;
495204076Spjd	int64_t datasize;
496204076Spjd	uint32_t mapsize;
497204076Spjd	size_t size;
498204076Spjd
499205738Spjd	assert((inp == NULL && outp == NULL) || (inp != NULL && outp != NULL));
500210881Spjd	assert(real_remote(res));
501205738Spjd
502205738Spjd	in = out = NULL;
503211983Spjd	errmsg = NULL;
504205738Spjd
505204076Spjd	/* Prepare outgoing connection with remote node. */
506205738Spjd	if (proto_client(res->hr_remoteaddr, &out) < 0) {
507207347Spjd		primary_exit(EX_TEMPFAIL, "Unable to create connection to %s",
508204076Spjd		    res->hr_remoteaddr);
509204076Spjd	}
510204076Spjd	/* Try to connect, but accept failure. */
511205738Spjd	if (proto_connect(out) < 0) {
512204076Spjd		pjdlog_errno(LOG_WARNING, "Unable to connect to %s",
513204076Spjd		    res->hr_remoteaddr);
514204076Spjd		goto close;
515204076Spjd	}
516207371Spjd	/* Error in setting timeout is not critical, but why should it fail? */
517207371Spjd	if (proto_timeout(out, res->hr_timeout) < 0)
518207371Spjd		pjdlog_errno(LOG_WARNING, "Unable to set connection timeout");
519204076Spjd	/*
520204076Spjd	 * First handshake step.
521204076Spjd	 * Setup outgoing connection with remote node.
522204076Spjd	 */
523204076Spjd	nvout = nv_alloc();
524204076Spjd	nv_add_string(nvout, res->hr_name, "resource");
525204076Spjd	if (nv_error(nvout) != 0) {
526204076Spjd		pjdlog_common(LOG_WARNING, 0, nv_error(nvout),
527204076Spjd		    "Unable to allocate header for connection with %s",
528204076Spjd		    res->hr_remoteaddr);
529204076Spjd		nv_free(nvout);
530204076Spjd		goto close;
531204076Spjd	}
532205738Spjd	if (hast_proto_send(res, out, nvout, NULL, 0) < 0) {
533204076Spjd		pjdlog_errno(LOG_WARNING,
534204076Spjd		    "Unable to send handshake header to %s",
535204076Spjd		    res->hr_remoteaddr);
536204076Spjd		nv_free(nvout);
537204076Spjd		goto close;
538204076Spjd	}
539204076Spjd	nv_free(nvout);
540205738Spjd	if (hast_proto_recv_hdr(out, &nvin) < 0) {
541204076Spjd		pjdlog_errno(LOG_WARNING,
542204076Spjd		    "Unable to receive handshake header from %s",
543204076Spjd		    res->hr_remoteaddr);
544204076Spjd		goto close;
545204076Spjd	}
546204076Spjd	errmsg = nv_get_string(nvin, "errmsg");
547204076Spjd	if (errmsg != NULL) {
548204076Spjd		pjdlog_warning("%s", errmsg);
549204076Spjd		nv_free(nvin);
550204076Spjd		goto close;
551204076Spjd	}
552204076Spjd	token = nv_get_uint8_array(nvin, &size, "token");
553204076Spjd	if (token == NULL) {
554204076Spjd		pjdlog_warning("Handshake header from %s has no 'token' field.",
555204076Spjd		    res->hr_remoteaddr);
556204076Spjd		nv_free(nvin);
557204076Spjd		goto close;
558204076Spjd	}
559204076Spjd	if (size != sizeof(res->hr_token)) {
560204076Spjd		pjdlog_warning("Handshake header from %s contains 'token' of wrong size (got %zu, expected %zu).",
561204076Spjd		    res->hr_remoteaddr, size, sizeof(res->hr_token));
562204076Spjd		nv_free(nvin);
563204076Spjd		goto close;
564204076Spjd	}
565204076Spjd	bcopy(token, res->hr_token, sizeof(res->hr_token));
566204076Spjd	nv_free(nvin);
567204076Spjd
568204076Spjd	/*
569204076Spjd	 * Second handshake step.
570204076Spjd	 * Setup incoming connection with remote node.
571204076Spjd	 */
572205738Spjd	if (proto_client(res->hr_remoteaddr, &in) < 0) {
573204076Spjd		pjdlog_errno(LOG_WARNING, "Unable to create connection to %s",
574204076Spjd		    res->hr_remoteaddr);
575204076Spjd	}
576204076Spjd	/* Try to connect, but accept failure. */
577205738Spjd	if (proto_connect(in) < 0) {
578204076Spjd		pjdlog_errno(LOG_WARNING, "Unable to connect to %s",
579204076Spjd		    res->hr_remoteaddr);
580204076Spjd		goto close;
581204076Spjd	}
582207371Spjd	/* Error in setting timeout is not critical, but why should it fail? */
583207371Spjd	if (proto_timeout(in, res->hr_timeout) < 0)
584207371Spjd		pjdlog_errno(LOG_WARNING, "Unable to set connection timeout");
585204076Spjd	nvout = nv_alloc();
586204076Spjd	nv_add_string(nvout, res->hr_name, "resource");
587204076Spjd	nv_add_uint8_array(nvout, res->hr_token, sizeof(res->hr_token),
588204076Spjd	    "token");
589214284Spjd	if (res->hr_resuid == 0) {
590214284Spjd		/*
591214284Spjd		 * The resuid field was not yet initialized.
592214284Spjd		 * Because we do synchronization inside init_resuid(), it is
593214284Spjd		 * possible that someone already initialized it, the function
594214284Spjd		 * will return false then, but if we successfully initialized
595214284Spjd		 * it, we will get true. True means that there were no writes
596214284Spjd		 * to this resource yet and we want to inform secondary that
597214284Spjd		 * synchronization is not needed by sending "virgin" argument.
598214284Spjd		 */
599214284Spjd		if (init_resuid(res))
600214284Spjd			nv_add_int8(nvout, 1, "virgin");
601214284Spjd	}
602204076Spjd	nv_add_uint64(nvout, res->hr_resuid, "resuid");
603204076Spjd	nv_add_uint64(nvout, res->hr_primary_localcnt, "localcnt");
604204076Spjd	nv_add_uint64(nvout, res->hr_primary_remotecnt, "remotecnt");
605204076Spjd	if (nv_error(nvout) != 0) {
606204076Spjd		pjdlog_common(LOG_WARNING, 0, nv_error(nvout),
607204076Spjd		    "Unable to allocate header for connection with %s",
608204076Spjd		    res->hr_remoteaddr);
609204076Spjd		nv_free(nvout);
610204076Spjd		goto close;
611204076Spjd	}
612205738Spjd	if (hast_proto_send(res, in, nvout, NULL, 0) < 0) {
613204076Spjd		pjdlog_errno(LOG_WARNING,
614204076Spjd		    "Unable to send handshake header to %s",
615204076Spjd		    res->hr_remoteaddr);
616204076Spjd		nv_free(nvout);
617204076Spjd		goto close;
618204076Spjd	}
619204076Spjd	nv_free(nvout);
620205738Spjd	if (hast_proto_recv_hdr(out, &nvin) < 0) {
621204076Spjd		pjdlog_errno(LOG_WARNING,
622204076Spjd		    "Unable to receive handshake header from %s",
623204076Spjd		    res->hr_remoteaddr);
624204076Spjd		goto close;
625204076Spjd	}
626204076Spjd	errmsg = nv_get_string(nvin, "errmsg");
627204076Spjd	if (errmsg != NULL) {
628204076Spjd		pjdlog_warning("%s", errmsg);
629204076Spjd		nv_free(nvin);
630204076Spjd		goto close;
631204076Spjd	}
632204076Spjd	datasize = nv_get_int64(nvin, "datasize");
633204076Spjd	if (datasize != res->hr_datasize) {
634204076Spjd		pjdlog_warning("Data size differs between nodes (local=%jd, remote=%jd).",
635204076Spjd		    (intmax_t)res->hr_datasize, (intmax_t)datasize);
636204076Spjd		nv_free(nvin);
637204076Spjd		goto close;
638204076Spjd	}
639204076Spjd	extentsize = nv_get_int32(nvin, "extentsize");
640204076Spjd	if (extentsize != res->hr_extentsize) {
641204076Spjd		pjdlog_warning("Extent size differs between nodes (local=%zd, remote=%zd).",
642204076Spjd		    (ssize_t)res->hr_extentsize, (ssize_t)extentsize);
643204076Spjd		nv_free(nvin);
644204076Spjd		goto close;
645204076Spjd	}
646204076Spjd	res->hr_secondary_localcnt = nv_get_uint64(nvin, "localcnt");
647204076Spjd	res->hr_secondary_remotecnt = nv_get_uint64(nvin, "remotecnt");
648204076Spjd	res->hr_syncsrc = nv_get_uint8(nvin, "syncsrc");
649204076Spjd	map = NULL;
650204076Spjd	mapsize = nv_get_uint32(nvin, "mapsize");
651204076Spjd	if (mapsize > 0) {
652204076Spjd		map = malloc(mapsize);
653204076Spjd		if (map == NULL) {
654204076Spjd			pjdlog_error("Unable to allocate memory for remote activemap (mapsize=%ju).",
655204076Spjd			    (uintmax_t)mapsize);
656204076Spjd			nv_free(nvin);
657204076Spjd			goto close;
658204076Spjd		}
659204076Spjd		/*
660204076Spjd		 * Remote node have some dirty extents on its own, lets
661204076Spjd		 * download its activemap.
662204076Spjd		 */
663205738Spjd		if (hast_proto_recv_data(res, out, nvin, map,
664204076Spjd		    mapsize) < 0) {
665204076Spjd			pjdlog_errno(LOG_ERR,
666204076Spjd			    "Unable to receive remote activemap");
667204076Spjd			nv_free(nvin);
668204076Spjd			free(map);
669204076Spjd			goto close;
670204076Spjd		}
671204076Spjd		/*
672204076Spjd		 * Merge local and remote bitmaps.
673204076Spjd		 */
674204076Spjd		activemap_merge(res->hr_amp, map, mapsize);
675204076Spjd		free(map);
676204076Spjd		/*
677204076Spjd		 * Now that we merged bitmaps from both nodes, flush it to the
678204076Spjd		 * disk before we start to synchronize.
679204076Spjd		 */
680204076Spjd		(void)hast_activemap_flush(res);
681204076Spjd	}
682214274Spjd	nv_free(nvin);
683204076Spjd	pjdlog_info("Connected to %s.", res->hr_remoteaddr);
684205738Spjd	if (inp != NULL && outp != NULL) {
685205738Spjd		*inp = in;
686205738Spjd		*outp = out;
687205738Spjd	} else {
688205738Spjd		res->hr_remotein = in;
689205738Spjd		res->hr_remoteout = out;
690205738Spjd	}
691212038Spjd	event_send(res, EVENT_CONNECT);
692205738Spjd	return (true);
693205738Spjdclose:
694211983Spjd	if (errmsg != NULL && strcmp(errmsg, "Split-brain condition!") == 0)
695212038Spjd		event_send(res, EVENT_SPLITBRAIN);
696205738Spjd	proto_close(out);
697205738Spjd	if (in != NULL)
698205738Spjd		proto_close(in);
699205738Spjd	return (false);
700205738Spjd}
701205738Spjd
702205738Spjdstatic void
703205738Spjdsync_start(void)
704205738Spjd{
705205738Spjd
706204076Spjd	mtx_lock(&sync_lock);
707204076Spjd	sync_inprogress = true;
708204076Spjd	mtx_unlock(&sync_lock);
709204076Spjd	cv_signal(&sync_cond);
710204076Spjd}
711204076Spjd
712204076Spjdstatic void
713211878Spjdsync_stop(void)
714211878Spjd{
715211878Spjd
716211878Spjd	mtx_lock(&sync_lock);
717211878Spjd	if (sync_inprogress)
718211878Spjd		sync_inprogress = false;
719211878Spjd	mtx_unlock(&sync_lock);
720211878Spjd}
721211878Spjd
722211878Spjdstatic void
723204076Spjdinit_ggate(struct hast_resource *res)
724204076Spjd{
725204076Spjd	struct g_gate_ctl_create ggiocreate;
726204076Spjd	struct g_gate_ctl_cancel ggiocancel;
727204076Spjd
728204076Spjd	/*
729204076Spjd	 * We communicate with ggate via /dev/ggctl. Open it.
730204076Spjd	 */
731204076Spjd	res->hr_ggatefd = open("/dev/" G_GATE_CTL_NAME, O_RDWR);
732204076Spjd	if (res->hr_ggatefd < 0)
733204076Spjd		primary_exit(EX_OSFILE, "Unable to open /dev/" G_GATE_CTL_NAME);
734204076Spjd	/*
735204076Spjd	 * Create provider before trying to connect, as connection failure
736204076Spjd	 * is not critical, but may take some time.
737204076Spjd	 */
738213533Spjd	bzero(&ggiocreate, sizeof(ggiocreate));
739204076Spjd	ggiocreate.gctl_version = G_GATE_VERSION;
740204076Spjd	ggiocreate.gctl_mediasize = res->hr_datasize;
741204076Spjd	ggiocreate.gctl_sectorsize = res->hr_local_sectorsize;
742204076Spjd	ggiocreate.gctl_flags = 0;
743206669Spjd	ggiocreate.gctl_maxcount = G_GATE_MAX_QUEUE_SIZE;
744204076Spjd	ggiocreate.gctl_timeout = 0;
745204076Spjd	ggiocreate.gctl_unit = G_GATE_NAME_GIVEN;
746204076Spjd	snprintf(ggiocreate.gctl_name, sizeof(ggiocreate.gctl_name), "hast/%s",
747204076Spjd	    res->hr_provname);
748204076Spjd	if (ioctl(res->hr_ggatefd, G_GATE_CMD_CREATE, &ggiocreate) == 0) {
749204076Spjd		pjdlog_info("Device hast/%s created.", res->hr_provname);
750204076Spjd		res->hr_ggateunit = ggiocreate.gctl_unit;
751204076Spjd		return;
752204076Spjd	}
753204076Spjd	if (errno != EEXIST) {
754204076Spjd		primary_exit(EX_OSERR, "Unable to create hast/%s device",
755204076Spjd		    res->hr_provname);
756204076Spjd	}
757204076Spjd	pjdlog_debug(1,
758204076Spjd	    "Device hast/%s already exists, we will try to take it over.",
759204076Spjd	    res->hr_provname);
760204076Spjd	/*
761204076Spjd	 * If we received EEXIST, we assume that the process who created the
762204076Spjd	 * provider died and didn't clean up. In that case we will start from
763204076Spjd	 * where he left of.
764204076Spjd	 */
765213533Spjd	bzero(&ggiocancel, sizeof(ggiocancel));
766204076Spjd	ggiocancel.gctl_version = G_GATE_VERSION;
767204076Spjd	ggiocancel.gctl_unit = G_GATE_NAME_GIVEN;
768204076Spjd	snprintf(ggiocancel.gctl_name, sizeof(ggiocancel.gctl_name), "hast/%s",
769204076Spjd	    res->hr_provname);
770204076Spjd	if (ioctl(res->hr_ggatefd, G_GATE_CMD_CANCEL, &ggiocancel) == 0) {
771204076Spjd		pjdlog_info("Device hast/%s recovered.", res->hr_provname);
772204076Spjd		res->hr_ggateunit = ggiocancel.gctl_unit;
773204076Spjd		return;
774204076Spjd	}
775204076Spjd	primary_exit(EX_OSERR, "Unable to take over hast/%s device",
776204076Spjd	    res->hr_provname);
777204076Spjd}
778204076Spjd
779204076Spjdvoid
780204076Spjdhastd_primary(struct hast_resource *res)
781204076Spjd{
782204076Spjd	pthread_t td;
783204076Spjd	pid_t pid;
784204076Spjd	int error;
785204076Spjd
786204076Spjd	/*
787204076Spjd	 * Create communication channel between parent and child.
788204076Spjd	 */
789204076Spjd	if (proto_client("socketpair://", &res->hr_ctrl) < 0) {
790204076Spjd		KEEP_ERRNO((void)pidfile_remove(pfh));
791212034Spjd		pjdlog_exit(EX_OSERR,
792204076Spjd		    "Unable to create control sockets between parent and child");
793204076Spjd	}
794212038Spjd	/*
795212038Spjd	 * Create communication channel between child and parent.
796212038Spjd	 */
797212038Spjd	if (proto_client("socketpair://", &res->hr_event) < 0) {
798212038Spjd		KEEP_ERRNO((void)pidfile_remove(pfh));
799212038Spjd		pjdlog_exit(EX_OSERR,
800212038Spjd		    "Unable to create event sockets between child and parent");
801212038Spjd	}
802204076Spjd
803204076Spjd	pid = fork();
804204076Spjd	if (pid < 0) {
805204076Spjd		KEEP_ERRNO((void)pidfile_remove(pfh));
806212034Spjd		pjdlog_exit(EX_TEMPFAIL, "Unable to fork");
807204076Spjd	}
808204076Spjd
809204076Spjd	if (pid > 0) {
810204076Spjd		/* This is parent. */
811212038Spjd		/* Declare that we are receiver. */
812212038Spjd		proto_recv(res->hr_event, NULL, 0);
813204076Spjd		res->hr_workerpid = pid;
814204076Spjd		return;
815204076Spjd	}
816211977Spjd
817211984Spjd	gres = res;
818211984Spjd
819204076Spjd	(void)pidfile_close(pfh);
820211977Spjd	hook_fini();
821204076Spjd
822204076Spjd	setproctitle("%s (primary)", res->hr_name);
823204076Spjd
824212038Spjd	/* Declare that we are sender. */
825212038Spjd	proto_send(res->hr_event, NULL, 0);
826212038Spjd
827204076Spjd	init_local(res);
828213007Spjd	init_ggate(res);
829213007Spjd	init_environment(res);
830213007Spjd	/*
831213530Spjd	 * Create the guard thread first, so we can handle signals from the
832213530Spjd	 * very begining.
833213530Spjd	 */
834213530Spjd	error = pthread_create(&td, NULL, guard_thread, res);
835213530Spjd	assert(error == 0);
836213530Spjd	/*
837213007Spjd	 * Create the control thread before sending any event to the parent,
838213007Spjd	 * as we can deadlock when parent sends control request to worker,
839213007Spjd	 * but worker has no control thread started yet, so parent waits.
840213007Spjd	 * In the meantime worker sends an event to the parent, but parent
841213007Spjd	 * is unable to handle the event, because it waits for control
842213007Spjd	 * request response.
843213007Spjd	 */
844213007Spjd	error = pthread_create(&td, NULL, ctrl_thread, res);
845213007Spjd	assert(error == 0);
846210881Spjd	if (real_remote(res) && init_remote(res, NULL, NULL))
847205738Spjd		sync_start();
848204076Spjd	error = pthread_create(&td, NULL, ggate_recv_thread, res);
849204076Spjd	assert(error == 0);
850204076Spjd	error = pthread_create(&td, NULL, local_send_thread, res);
851204076Spjd	assert(error == 0);
852204076Spjd	error = pthread_create(&td, NULL, remote_send_thread, res);
853204076Spjd	assert(error == 0);
854204076Spjd	error = pthread_create(&td, NULL, remote_recv_thread, res);
855204076Spjd	assert(error == 0);
856204076Spjd	error = pthread_create(&td, NULL, ggate_send_thread, res);
857204076Spjd	assert(error == 0);
858213530Spjd	(void)sync_thread(res);
859204076Spjd}
860204076Spjd
861204076Spjdstatic void
862204076Spjdreqlog(int loglevel, int debuglevel, struct g_gate_ctl_io *ggio, const char *fmt, ...)
863204076Spjd{
864204076Spjd	char msg[1024];
865204076Spjd	va_list ap;
866204076Spjd	int len;
867204076Spjd
868204076Spjd	va_start(ap, fmt);
869204076Spjd	len = vsnprintf(msg, sizeof(msg), fmt, ap);
870204076Spjd	va_end(ap);
871204076Spjd	if ((size_t)len < sizeof(msg)) {
872204076Spjd		switch (ggio->gctl_cmd) {
873204076Spjd		case BIO_READ:
874204076Spjd			(void)snprintf(msg + len, sizeof(msg) - len,
875204076Spjd			    "READ(%ju, %ju).", (uintmax_t)ggio->gctl_offset,
876204076Spjd			    (uintmax_t)ggio->gctl_length);
877204076Spjd			break;
878204076Spjd		case BIO_DELETE:
879204076Spjd			(void)snprintf(msg + len, sizeof(msg) - len,
880204076Spjd			    "DELETE(%ju, %ju).", (uintmax_t)ggio->gctl_offset,
881204076Spjd			    (uintmax_t)ggio->gctl_length);
882204076Spjd			break;
883204076Spjd		case BIO_FLUSH:
884204076Spjd			(void)snprintf(msg + len, sizeof(msg) - len, "FLUSH.");
885204076Spjd			break;
886204076Spjd		case BIO_WRITE:
887204076Spjd			(void)snprintf(msg + len, sizeof(msg) - len,
888204076Spjd			    "WRITE(%ju, %ju).", (uintmax_t)ggio->gctl_offset,
889204076Spjd			    (uintmax_t)ggio->gctl_length);
890204076Spjd			break;
891204076Spjd		default:
892204076Spjd			(void)snprintf(msg + len, sizeof(msg) - len,
893204076Spjd			    "UNKNOWN(%u).", (unsigned int)ggio->gctl_cmd);
894204076Spjd			break;
895204076Spjd		}
896204076Spjd	}
897204076Spjd	pjdlog_common(loglevel, debuglevel, -1, "%s", msg);
898204076Spjd}
899204076Spjd
900204076Spjdstatic void
901204076Spjdremote_close(struct hast_resource *res, int ncomp)
902204076Spjd{
903204076Spjd
904204076Spjd	rw_wlock(&hio_remote_lock[ncomp]);
905204076Spjd	/*
906204076Spjd	 * A race is possible between dropping rlock and acquiring wlock -
907204076Spjd	 * another thread can close connection in-between.
908204076Spjd	 */
909204076Spjd	if (!ISCONNECTED(res, ncomp)) {
910204076Spjd		assert(res->hr_remotein == NULL);
911204076Spjd		assert(res->hr_remoteout == NULL);
912204076Spjd		rw_unlock(&hio_remote_lock[ncomp]);
913204076Spjd		return;
914204076Spjd	}
915204076Spjd
916204076Spjd	assert(res->hr_remotein != NULL);
917204076Spjd	assert(res->hr_remoteout != NULL);
918204076Spjd
919211881Spjd	pjdlog_debug(2, "Closing incoming connection to %s.",
920204076Spjd	    res->hr_remoteaddr);
921204076Spjd	proto_close(res->hr_remotein);
922204076Spjd	res->hr_remotein = NULL;
923211881Spjd	pjdlog_debug(2, "Closing outgoing connection to %s.",
924204076Spjd	    res->hr_remoteaddr);
925204076Spjd	proto_close(res->hr_remoteout);
926204076Spjd	res->hr_remoteout = NULL;
927204076Spjd
928204076Spjd	rw_unlock(&hio_remote_lock[ncomp]);
929204076Spjd
930211881Spjd	pjdlog_warning("Disconnected from %s.", res->hr_remoteaddr);
931211881Spjd
932204076Spjd	/*
933204076Spjd	 * Stop synchronization if in-progress.
934204076Spjd	 */
935211878Spjd	sync_stop();
936211984Spjd
937212038Spjd	event_send(res, EVENT_DISCONNECT);
938204076Spjd}
939204076Spjd
940204076Spjd/*
941204076Spjd * Thread receives ggate I/O requests from the kernel and passes them to
942204076Spjd * appropriate threads:
943204076Spjd * WRITE - always goes to both local_send and remote_send threads
944204076Spjd * READ (when the block is up-to-date on local component) -
945204076Spjd *	only local_send thread
946204076Spjd * READ (when the block isn't up-to-date on local component) -
947204076Spjd *	only remote_send thread
948204076Spjd * DELETE - always goes to both local_send and remote_send threads
949204076Spjd * FLUSH - always goes to both local_send and remote_send threads
950204076Spjd */
951204076Spjdstatic void *
952204076Spjdggate_recv_thread(void *arg)
953204076Spjd{
954204076Spjd	struct hast_resource *res = arg;
955204076Spjd	struct g_gate_ctl_io *ggio;
956204076Spjd	struct hio *hio;
957204076Spjd	unsigned int ii, ncomp, ncomps;
958204076Spjd	int error;
959204076Spjd
960204076Spjd	ncomps = HAST_NCOMPONENTS;
961204076Spjd
962204076Spjd	for (;;) {
963204076Spjd		pjdlog_debug(2, "ggate_recv: Taking free request.");
964204076Spjd		QUEUE_TAKE2(hio, free);
965204076Spjd		pjdlog_debug(2, "ggate_recv: (%p) Got free request.", hio);
966204076Spjd		ggio = &hio->hio_ggio;
967204076Spjd		ggio->gctl_unit = res->hr_ggateunit;
968204076Spjd		ggio->gctl_length = MAXPHYS;
969204076Spjd		ggio->gctl_error = 0;
970204076Spjd		pjdlog_debug(2,
971204076Spjd		    "ggate_recv: (%p) Waiting for request from the kernel.",
972204076Spjd		    hio);
973204076Spjd		if (ioctl(res->hr_ggatefd, G_GATE_CMD_START, ggio) < 0) {
974204076Spjd			if (sigexit_received)
975204076Spjd				pthread_exit(NULL);
976204076Spjd			primary_exit(EX_OSERR, "G_GATE_CMD_START failed");
977204076Spjd		}
978204076Spjd		error = ggio->gctl_error;
979204076Spjd		switch (error) {
980204076Spjd		case 0:
981204076Spjd			break;
982204076Spjd		case ECANCELED:
983204076Spjd			/* Exit gracefully. */
984204076Spjd			if (!sigexit_received) {
985204076Spjd				pjdlog_debug(2,
986204076Spjd				    "ggate_recv: (%p) Received cancel from the kernel.",
987204076Spjd				    hio);
988204076Spjd				pjdlog_info("Received cancel from the kernel, exiting.");
989204076Spjd			}
990204076Spjd			pthread_exit(NULL);
991204076Spjd		case ENOMEM:
992204076Spjd			/*
993204076Spjd			 * Buffer too small? Impossible, we allocate MAXPHYS
994204076Spjd			 * bytes - request can't be bigger than that.
995204076Spjd			 */
996204076Spjd			/* FALLTHROUGH */
997204076Spjd		case ENXIO:
998204076Spjd		default:
999204076Spjd			primary_exitx(EX_OSERR, "G_GATE_CMD_START failed: %s.",
1000204076Spjd			    strerror(error));
1001204076Spjd		}
1002204076Spjd		for (ii = 0; ii < ncomps; ii++)
1003204076Spjd			hio->hio_errors[ii] = EINVAL;
1004204076Spjd		reqlog(LOG_DEBUG, 2, ggio,
1005204076Spjd		    "ggate_recv: (%p) Request received from the kernel: ",
1006204076Spjd		    hio);
1007204076Spjd		/*
1008204076Spjd		 * Inform all components about new write request.
1009204076Spjd		 * For read request prefer local component unless the given
1010204076Spjd		 * range is out-of-date, then use remote component.
1011204076Spjd		 */
1012204076Spjd		switch (ggio->gctl_cmd) {
1013204076Spjd		case BIO_READ:
1014204076Spjd			pjdlog_debug(2,
1015204076Spjd			    "ggate_recv: (%p) Moving request to the send queue.",
1016204076Spjd			    hio);
1017204076Spjd			refcount_init(&hio->hio_countdown, 1);
1018204076Spjd			mtx_lock(&metadata_lock);
1019204076Spjd			if (res->hr_syncsrc == HAST_SYNCSRC_UNDEF ||
1020204076Spjd			    res->hr_syncsrc == HAST_SYNCSRC_PRIMARY) {
1021204076Spjd				/*
1022204076Spjd				 * This range is up-to-date on local component,
1023204076Spjd				 * so handle request locally.
1024204076Spjd				 */
1025204076Spjd				 /* Local component is 0 for now. */
1026204076Spjd				ncomp = 0;
1027204076Spjd			} else /* if (res->hr_syncsrc ==
1028204076Spjd			    HAST_SYNCSRC_SECONDARY) */ {
1029204076Spjd				assert(res->hr_syncsrc ==
1030204076Spjd				    HAST_SYNCSRC_SECONDARY);
1031204076Spjd				/*
1032204076Spjd				 * This range is out-of-date on local component,
1033204076Spjd				 * so send request to the remote node.
1034204076Spjd				 */
1035204076Spjd				 /* Remote component is 1 for now. */
1036204076Spjd				ncomp = 1;
1037204076Spjd			}
1038204076Spjd			mtx_unlock(&metadata_lock);
1039204076Spjd			QUEUE_INSERT1(hio, send, ncomp);
1040204076Spjd			break;
1041204076Spjd		case BIO_WRITE:
1042214284Spjd			if (res->hr_resuid == 0) {
1043214284Spjd				/* This is first write, initialize resuid. */
1044214284Spjd				(void)init_resuid(res);
1045214284Spjd			}
1046204076Spjd			for (;;) {
1047204076Spjd				mtx_lock(&range_lock);
1048204076Spjd				if (rangelock_islocked(range_sync,
1049204076Spjd				    ggio->gctl_offset, ggio->gctl_length)) {
1050204076Spjd					pjdlog_debug(2,
1051204076Spjd					    "regular: Range offset=%jd length=%zu locked.",
1052204076Spjd					    (intmax_t)ggio->gctl_offset,
1053204076Spjd					    (size_t)ggio->gctl_length);
1054204076Spjd					range_regular_wait = true;
1055204076Spjd					cv_wait(&range_regular_cond, &range_lock);
1056204076Spjd					range_regular_wait = false;
1057204076Spjd					mtx_unlock(&range_lock);
1058204076Spjd					continue;
1059204076Spjd				}
1060204076Spjd				if (rangelock_add(range_regular,
1061204076Spjd				    ggio->gctl_offset, ggio->gctl_length) < 0) {
1062204076Spjd					mtx_unlock(&range_lock);
1063204076Spjd					pjdlog_debug(2,
1064204076Spjd					    "regular: Range offset=%jd length=%zu is already locked, waiting.",
1065204076Spjd					    (intmax_t)ggio->gctl_offset,
1066204076Spjd					    (size_t)ggio->gctl_length);
1067204076Spjd					sleep(1);
1068204076Spjd					continue;
1069204076Spjd				}
1070204076Spjd				mtx_unlock(&range_lock);
1071204076Spjd				break;
1072204076Spjd			}
1073204076Spjd			mtx_lock(&res->hr_amp_lock);
1074204076Spjd			if (activemap_write_start(res->hr_amp,
1075204076Spjd			    ggio->gctl_offset, ggio->gctl_length)) {
1076204076Spjd				(void)hast_activemap_flush(res);
1077204076Spjd			}
1078204076Spjd			mtx_unlock(&res->hr_amp_lock);
1079204076Spjd			/* FALLTHROUGH */
1080204076Spjd		case BIO_DELETE:
1081204076Spjd		case BIO_FLUSH:
1082204076Spjd			pjdlog_debug(2,
1083204076Spjd			    "ggate_recv: (%p) Moving request to the send queues.",
1084204076Spjd			    hio);
1085204076Spjd			refcount_init(&hio->hio_countdown, ncomps);
1086204076Spjd			for (ii = 0; ii < ncomps; ii++)
1087204076Spjd				QUEUE_INSERT1(hio, send, ii);
1088204076Spjd			break;
1089204076Spjd		}
1090204076Spjd	}
1091204076Spjd	/* NOTREACHED */
1092204076Spjd	return (NULL);
1093204076Spjd}
1094204076Spjd
1095204076Spjd/*
1096204076Spjd * Thread reads from or writes to local component.
1097204076Spjd * If local read fails, it redirects it to remote_send thread.
1098204076Spjd */
1099204076Spjdstatic void *
1100204076Spjdlocal_send_thread(void *arg)
1101204076Spjd{
1102204076Spjd	struct hast_resource *res = arg;
1103204076Spjd	struct g_gate_ctl_io *ggio;
1104204076Spjd	struct hio *hio;
1105204076Spjd	unsigned int ncomp, rncomp;
1106204076Spjd	ssize_t ret;
1107204076Spjd
1108204076Spjd	/* Local component is 0 for now. */
1109204076Spjd	ncomp = 0;
1110204076Spjd	/* Remote component is 1 for now. */
1111204076Spjd	rncomp = 1;
1112204076Spjd
1113204076Spjd	for (;;) {
1114204076Spjd		pjdlog_debug(2, "local_send: Taking request.");
1115204076Spjd		QUEUE_TAKE1(hio, send, ncomp);
1116204076Spjd		pjdlog_debug(2, "local_send: (%p) Got request.", hio);
1117204076Spjd		ggio = &hio->hio_ggio;
1118204076Spjd		switch (ggio->gctl_cmd) {
1119204076Spjd		case BIO_READ:
1120204076Spjd			ret = pread(res->hr_localfd, ggio->gctl_data,
1121204076Spjd			    ggio->gctl_length,
1122204076Spjd			    ggio->gctl_offset + res->hr_localoff);
1123204076Spjd			if (ret == ggio->gctl_length)
1124204076Spjd				hio->hio_errors[ncomp] = 0;
1125204076Spjd			else {
1126204076Spjd				/*
1127204076Spjd				 * If READ failed, try to read from remote node.
1128204076Spjd				 */
1129204076Spjd				QUEUE_INSERT1(hio, send, rncomp);
1130204076Spjd				continue;
1131204076Spjd			}
1132204076Spjd			break;
1133204076Spjd		case BIO_WRITE:
1134204076Spjd			ret = pwrite(res->hr_localfd, ggio->gctl_data,
1135204076Spjd			    ggio->gctl_length,
1136204076Spjd			    ggio->gctl_offset + res->hr_localoff);
1137204076Spjd			if (ret < 0)
1138204076Spjd				hio->hio_errors[ncomp] = errno;
1139204076Spjd			else if (ret != ggio->gctl_length)
1140204076Spjd				hio->hio_errors[ncomp] = EIO;
1141204076Spjd			else
1142204076Spjd				hio->hio_errors[ncomp] = 0;
1143204076Spjd			break;
1144204076Spjd		case BIO_DELETE:
1145204076Spjd			ret = g_delete(res->hr_localfd,
1146204076Spjd			    ggio->gctl_offset + res->hr_localoff,
1147204076Spjd			    ggio->gctl_length);
1148204076Spjd			if (ret < 0)
1149204076Spjd				hio->hio_errors[ncomp] = errno;
1150204076Spjd			else
1151204076Spjd				hio->hio_errors[ncomp] = 0;
1152204076Spjd			break;
1153204076Spjd		case BIO_FLUSH:
1154204076Spjd			ret = g_flush(res->hr_localfd);
1155204076Spjd			if (ret < 0)
1156204076Spjd				hio->hio_errors[ncomp] = errno;
1157204076Spjd			else
1158204076Spjd				hio->hio_errors[ncomp] = 0;
1159204076Spjd			break;
1160204076Spjd		}
1161204076Spjd		if (refcount_release(&hio->hio_countdown)) {
1162204076Spjd			if (ISSYNCREQ(hio)) {
1163204076Spjd				mtx_lock(&sync_lock);
1164204076Spjd				SYNCREQDONE(hio);
1165204076Spjd				mtx_unlock(&sync_lock);
1166204076Spjd				cv_signal(&sync_cond);
1167204076Spjd			} else {
1168204076Spjd				pjdlog_debug(2,
1169204076Spjd				    "local_send: (%p) Moving request to the done queue.",
1170204076Spjd				    hio);
1171204076Spjd				QUEUE_INSERT2(hio, done);
1172204076Spjd			}
1173204076Spjd		}
1174204076Spjd	}
1175204076Spjd	/* NOTREACHED */
1176204076Spjd	return (NULL);
1177204076Spjd}
1178204076Spjd
1179204076Spjd/*
1180204076Spjd * Thread sends request to secondary node.
1181204076Spjd */
1182204076Spjdstatic void *
1183204076Spjdremote_send_thread(void *arg)
1184204076Spjd{
1185204076Spjd	struct hast_resource *res = arg;
1186204076Spjd	struct g_gate_ctl_io *ggio;
1187204076Spjd	struct hio *hio;
1188204076Spjd	struct nv *nv;
1189204076Spjd	unsigned int ncomp;
1190204076Spjd	bool wakeup;
1191204076Spjd	uint64_t offset, length;
1192204076Spjd	uint8_t cmd;
1193204076Spjd	void *data;
1194204076Spjd
1195204076Spjd	/* Remote component is 1 for now. */
1196204076Spjd	ncomp = 1;
1197204076Spjd
1198204076Spjd	for (;;) {
1199204076Spjd		pjdlog_debug(2, "remote_send: Taking request.");
1200204076Spjd		QUEUE_TAKE1(hio, send, ncomp);
1201204076Spjd		pjdlog_debug(2, "remote_send: (%p) Got request.", hio);
1202204076Spjd		ggio = &hio->hio_ggio;
1203204076Spjd		switch (ggio->gctl_cmd) {
1204204076Spjd		case BIO_READ:
1205204076Spjd			cmd = HIO_READ;
1206204076Spjd			data = NULL;
1207204076Spjd			offset = ggio->gctl_offset;
1208204076Spjd			length = ggio->gctl_length;
1209204076Spjd			break;
1210204076Spjd		case BIO_WRITE:
1211204076Spjd			cmd = HIO_WRITE;
1212204076Spjd			data = ggio->gctl_data;
1213204076Spjd			offset = ggio->gctl_offset;
1214204076Spjd			length = ggio->gctl_length;
1215204076Spjd			break;
1216204076Spjd		case BIO_DELETE:
1217204076Spjd			cmd = HIO_DELETE;
1218204076Spjd			data = NULL;
1219204076Spjd			offset = ggio->gctl_offset;
1220204076Spjd			length = ggio->gctl_length;
1221204076Spjd			break;
1222204076Spjd		case BIO_FLUSH:
1223204076Spjd			cmd = HIO_FLUSH;
1224204076Spjd			data = NULL;
1225204076Spjd			offset = 0;
1226204076Spjd			length = 0;
1227204076Spjd			break;
1228204076Spjd		default:
1229204076Spjd			assert(!"invalid condition");
1230204076Spjd			abort();
1231204076Spjd		}
1232204076Spjd		nv = nv_alloc();
1233204076Spjd		nv_add_uint8(nv, cmd, "cmd");
1234204076Spjd		nv_add_uint64(nv, (uint64_t)ggio->gctl_seq, "seq");
1235204076Spjd		nv_add_uint64(nv, offset, "offset");
1236204076Spjd		nv_add_uint64(nv, length, "length");
1237204076Spjd		if (nv_error(nv) != 0) {
1238204076Spjd			hio->hio_errors[ncomp] = nv_error(nv);
1239204076Spjd			pjdlog_debug(2,
1240204076Spjd			    "remote_send: (%p) Unable to prepare header to send.",
1241204076Spjd			    hio);
1242204076Spjd			reqlog(LOG_ERR, 0, ggio,
1243204076Spjd			    "Unable to prepare header to send (%s): ",
1244204076Spjd			    strerror(nv_error(nv)));
1245204076Spjd			/* Move failed request immediately to the done queue. */
1246204076Spjd			goto done_queue;
1247204076Spjd		}
1248204076Spjd		pjdlog_debug(2,
1249204076Spjd		    "remote_send: (%p) Moving request to the recv queue.",
1250204076Spjd		    hio);
1251204076Spjd		/*
1252204076Spjd		 * Protect connection from disappearing.
1253204076Spjd		 */
1254204076Spjd		rw_rlock(&hio_remote_lock[ncomp]);
1255204076Spjd		if (!ISCONNECTED(res, ncomp)) {
1256204076Spjd			rw_unlock(&hio_remote_lock[ncomp]);
1257204076Spjd			hio->hio_errors[ncomp] = ENOTCONN;
1258204076Spjd			goto done_queue;
1259204076Spjd		}
1260204076Spjd		/*
1261204076Spjd		 * Move the request to recv queue before sending it, because
1262204076Spjd		 * in different order we can get reply before we move request
1263204076Spjd		 * to recv queue.
1264204076Spjd		 */
1265204076Spjd		mtx_lock(&hio_recv_list_lock[ncomp]);
1266204076Spjd		wakeup = TAILQ_EMPTY(&hio_recv_list[ncomp]);
1267204076Spjd		TAILQ_INSERT_TAIL(&hio_recv_list[ncomp], hio, hio_next[ncomp]);
1268204076Spjd		mtx_unlock(&hio_recv_list_lock[ncomp]);
1269204076Spjd		if (hast_proto_send(res, res->hr_remoteout, nv, data,
1270204076Spjd		    data != NULL ? length : 0) < 0) {
1271204076Spjd			hio->hio_errors[ncomp] = errno;
1272204076Spjd			rw_unlock(&hio_remote_lock[ncomp]);
1273204076Spjd			pjdlog_debug(2,
1274204076Spjd			    "remote_send: (%p) Unable to send request.", hio);
1275204076Spjd			reqlog(LOG_ERR, 0, ggio,
1276204076Spjd			    "Unable to send request (%s): ",
1277204076Spjd			    strerror(hio->hio_errors[ncomp]));
1278211979Spjd			remote_close(res, ncomp);
1279204076Spjd			/*
1280204076Spjd			 * Take request back from the receive queue and move
1281204076Spjd			 * it immediately to the done queue.
1282204076Spjd			 */
1283204076Spjd			mtx_lock(&hio_recv_list_lock[ncomp]);
1284204076Spjd			TAILQ_REMOVE(&hio_recv_list[ncomp], hio, hio_next[ncomp]);
1285204076Spjd			mtx_unlock(&hio_recv_list_lock[ncomp]);
1286204076Spjd			goto done_queue;
1287204076Spjd		}
1288204076Spjd		rw_unlock(&hio_remote_lock[ncomp]);
1289204076Spjd		nv_free(nv);
1290204076Spjd		if (wakeup)
1291204076Spjd			cv_signal(&hio_recv_list_cond[ncomp]);
1292204076Spjd		continue;
1293204076Spjddone_queue:
1294204076Spjd		nv_free(nv);
1295204076Spjd		if (ISSYNCREQ(hio)) {
1296204076Spjd			if (!refcount_release(&hio->hio_countdown))
1297204076Spjd				continue;
1298204076Spjd			mtx_lock(&sync_lock);
1299204076Spjd			SYNCREQDONE(hio);
1300204076Spjd			mtx_unlock(&sync_lock);
1301204076Spjd			cv_signal(&sync_cond);
1302204076Spjd			continue;
1303204076Spjd		}
1304204076Spjd		if (ggio->gctl_cmd == BIO_WRITE) {
1305204076Spjd			mtx_lock(&res->hr_amp_lock);
1306204076Spjd			if (activemap_need_sync(res->hr_amp, ggio->gctl_offset,
1307204076Spjd			    ggio->gctl_length)) {
1308204076Spjd				(void)hast_activemap_flush(res);
1309204076Spjd			}
1310204076Spjd			mtx_unlock(&res->hr_amp_lock);
1311204076Spjd		}
1312204076Spjd		if (!refcount_release(&hio->hio_countdown))
1313204076Spjd			continue;
1314204076Spjd		pjdlog_debug(2,
1315204076Spjd		    "remote_send: (%p) Moving request to the done queue.",
1316204076Spjd		    hio);
1317204076Spjd		QUEUE_INSERT2(hio, done);
1318204076Spjd	}
1319204076Spjd	/* NOTREACHED */
1320204076Spjd	return (NULL);
1321204076Spjd}
1322204076Spjd
1323204076Spjd/*
1324204076Spjd * Thread receives answer from secondary node and passes it to ggate_send
1325204076Spjd * thread.
1326204076Spjd */
1327204076Spjdstatic void *
1328204076Spjdremote_recv_thread(void *arg)
1329204076Spjd{
1330204076Spjd	struct hast_resource *res = arg;
1331204076Spjd	struct g_gate_ctl_io *ggio;
1332204076Spjd	struct hio *hio;
1333204076Spjd	struct nv *nv;
1334204076Spjd	unsigned int ncomp;
1335204076Spjd	uint64_t seq;
1336204076Spjd	int error;
1337204076Spjd
1338204076Spjd	/* Remote component is 1 for now. */
1339204076Spjd	ncomp = 1;
1340204076Spjd
1341204076Spjd	for (;;) {
1342204076Spjd		/* Wait until there is anything to receive. */
1343204076Spjd		mtx_lock(&hio_recv_list_lock[ncomp]);
1344204076Spjd		while (TAILQ_EMPTY(&hio_recv_list[ncomp])) {
1345204076Spjd			pjdlog_debug(2, "remote_recv: No requests, waiting.");
1346204076Spjd			cv_wait(&hio_recv_list_cond[ncomp],
1347204076Spjd			    &hio_recv_list_lock[ncomp]);
1348204076Spjd		}
1349204076Spjd		mtx_unlock(&hio_recv_list_lock[ncomp]);
1350204076Spjd		rw_rlock(&hio_remote_lock[ncomp]);
1351204076Spjd		if (!ISCONNECTED(res, ncomp)) {
1352204076Spjd			rw_unlock(&hio_remote_lock[ncomp]);
1353204076Spjd			/*
1354204076Spjd			 * Connection is dead, so move all pending requests to
1355204076Spjd			 * the done queue (one-by-one).
1356204076Spjd			 */
1357204076Spjd			mtx_lock(&hio_recv_list_lock[ncomp]);
1358204076Spjd			hio = TAILQ_FIRST(&hio_recv_list[ncomp]);
1359204076Spjd			assert(hio != NULL);
1360204076Spjd			TAILQ_REMOVE(&hio_recv_list[ncomp], hio,
1361204076Spjd			    hio_next[ncomp]);
1362204076Spjd			mtx_unlock(&hio_recv_list_lock[ncomp]);
1363204076Spjd			goto done_queue;
1364204076Spjd		}
1365204076Spjd		if (hast_proto_recv_hdr(res->hr_remotein, &nv) < 0) {
1366204076Spjd			pjdlog_errno(LOG_ERR,
1367204076Spjd			    "Unable to receive reply header");
1368204076Spjd			rw_unlock(&hio_remote_lock[ncomp]);
1369204076Spjd			remote_close(res, ncomp);
1370204076Spjd			continue;
1371204076Spjd		}
1372204076Spjd		rw_unlock(&hio_remote_lock[ncomp]);
1373204076Spjd		seq = nv_get_uint64(nv, "seq");
1374204076Spjd		if (seq == 0) {
1375204076Spjd			pjdlog_error("Header contains no 'seq' field.");
1376204076Spjd			nv_free(nv);
1377204076Spjd			continue;
1378204076Spjd		}
1379204076Spjd		mtx_lock(&hio_recv_list_lock[ncomp]);
1380204076Spjd		TAILQ_FOREACH(hio, &hio_recv_list[ncomp], hio_next[ncomp]) {
1381204076Spjd			if (hio->hio_ggio.gctl_seq == seq) {
1382204076Spjd				TAILQ_REMOVE(&hio_recv_list[ncomp], hio,
1383204076Spjd				    hio_next[ncomp]);
1384204076Spjd				break;
1385204076Spjd			}
1386204076Spjd		}
1387204076Spjd		mtx_unlock(&hio_recv_list_lock[ncomp]);
1388204076Spjd		if (hio == NULL) {
1389204076Spjd			pjdlog_error("Found no request matching received 'seq' field (%ju).",
1390204076Spjd			    (uintmax_t)seq);
1391204076Spjd			nv_free(nv);
1392204076Spjd			continue;
1393204076Spjd		}
1394204076Spjd		error = nv_get_int16(nv, "error");
1395204076Spjd		if (error != 0) {
1396204076Spjd			/* Request failed on remote side. */
1397204076Spjd			hio->hio_errors[ncomp] = 0;
1398204076Spjd			nv_free(nv);
1399204076Spjd			goto done_queue;
1400204076Spjd		}
1401204076Spjd		ggio = &hio->hio_ggio;
1402204076Spjd		switch (ggio->gctl_cmd) {
1403204076Spjd		case BIO_READ:
1404204076Spjd			rw_rlock(&hio_remote_lock[ncomp]);
1405204076Spjd			if (!ISCONNECTED(res, ncomp)) {
1406204076Spjd				rw_unlock(&hio_remote_lock[ncomp]);
1407204076Spjd				nv_free(nv);
1408204076Spjd				goto done_queue;
1409204076Spjd			}
1410204076Spjd			if (hast_proto_recv_data(res, res->hr_remotein, nv,
1411204076Spjd			    ggio->gctl_data, ggio->gctl_length) < 0) {
1412204076Spjd				hio->hio_errors[ncomp] = errno;
1413204076Spjd				pjdlog_errno(LOG_ERR,
1414204076Spjd				    "Unable to receive reply data");
1415204076Spjd				rw_unlock(&hio_remote_lock[ncomp]);
1416204076Spjd				nv_free(nv);
1417204076Spjd				remote_close(res, ncomp);
1418204076Spjd				goto done_queue;
1419204076Spjd			}
1420204076Spjd			rw_unlock(&hio_remote_lock[ncomp]);
1421204076Spjd			break;
1422204076Spjd		case BIO_WRITE:
1423204076Spjd		case BIO_DELETE:
1424204076Spjd		case BIO_FLUSH:
1425204076Spjd			break;
1426204076Spjd		default:
1427204076Spjd			assert(!"invalid condition");
1428204076Spjd			abort();
1429204076Spjd		}
1430204076Spjd		hio->hio_errors[ncomp] = 0;
1431204076Spjd		nv_free(nv);
1432204076Spjddone_queue:
1433204076Spjd		if (refcount_release(&hio->hio_countdown)) {
1434204076Spjd			if (ISSYNCREQ(hio)) {
1435204076Spjd				mtx_lock(&sync_lock);
1436204076Spjd				SYNCREQDONE(hio);
1437204076Spjd				mtx_unlock(&sync_lock);
1438204076Spjd				cv_signal(&sync_cond);
1439204076Spjd			} else {
1440204076Spjd				pjdlog_debug(2,
1441204076Spjd				    "remote_recv: (%p) Moving request to the done queue.",
1442204076Spjd				    hio);
1443204076Spjd				QUEUE_INSERT2(hio, done);
1444204076Spjd			}
1445204076Spjd		}
1446204076Spjd	}
1447204076Spjd	/* NOTREACHED */
1448204076Spjd	return (NULL);
1449204076Spjd}
1450204076Spjd
1451204076Spjd/*
1452204076Spjd * Thread sends answer to the kernel.
1453204076Spjd */
1454204076Spjdstatic void *
1455204076Spjdggate_send_thread(void *arg)
1456204076Spjd{
1457204076Spjd	struct hast_resource *res = arg;
1458204076Spjd	struct g_gate_ctl_io *ggio;
1459204076Spjd	struct hio *hio;
1460204076Spjd	unsigned int ii, ncomp, ncomps;
1461204076Spjd
1462204076Spjd	ncomps = HAST_NCOMPONENTS;
1463204076Spjd
1464204076Spjd	for (;;) {
1465204076Spjd		pjdlog_debug(2, "ggate_send: Taking request.");
1466204076Spjd		QUEUE_TAKE2(hio, done);
1467204076Spjd		pjdlog_debug(2, "ggate_send: (%p) Got request.", hio);
1468204076Spjd		ggio = &hio->hio_ggio;
1469204076Spjd		for (ii = 0; ii < ncomps; ii++) {
1470204076Spjd			if (hio->hio_errors[ii] == 0) {
1471204076Spjd				/*
1472204076Spjd				 * One successful request is enough to declare
1473204076Spjd				 * success.
1474204076Spjd				 */
1475204076Spjd				ggio->gctl_error = 0;
1476204076Spjd				break;
1477204076Spjd			}
1478204076Spjd		}
1479204076Spjd		if (ii == ncomps) {
1480204076Spjd			/*
1481204076Spjd			 * None of the requests were successful.
1482204076Spjd			 * Use first error.
1483204076Spjd			 */
1484204076Spjd			ggio->gctl_error = hio->hio_errors[0];
1485204076Spjd		}
1486204076Spjd		if (ggio->gctl_error == 0 && ggio->gctl_cmd == BIO_WRITE) {
1487204076Spjd			mtx_lock(&res->hr_amp_lock);
1488204076Spjd			activemap_write_complete(res->hr_amp,
1489204076Spjd			    ggio->gctl_offset, ggio->gctl_length);
1490204076Spjd			mtx_unlock(&res->hr_amp_lock);
1491204076Spjd		}
1492204076Spjd		if (ggio->gctl_cmd == BIO_WRITE) {
1493204076Spjd			/*
1494204076Spjd			 * Unlock range we locked.
1495204076Spjd			 */
1496204076Spjd			mtx_lock(&range_lock);
1497204076Spjd			rangelock_del(range_regular, ggio->gctl_offset,
1498204076Spjd			    ggio->gctl_length);
1499204076Spjd			if (range_sync_wait)
1500204076Spjd				cv_signal(&range_sync_cond);
1501204076Spjd			mtx_unlock(&range_lock);
1502204076Spjd			/*
1503204076Spjd			 * Bump local count if this is first write after
1504204076Spjd			 * connection failure with remote node.
1505204076Spjd			 */
1506204076Spjd			ncomp = 1;
1507204076Spjd			rw_rlock(&hio_remote_lock[ncomp]);
1508204076Spjd			if (!ISCONNECTED(res, ncomp)) {
1509204076Spjd				mtx_lock(&metadata_lock);
1510204076Spjd				if (res->hr_primary_localcnt ==
1511204076Spjd				    res->hr_secondary_remotecnt) {
1512204076Spjd					res->hr_primary_localcnt++;
1513204076Spjd					pjdlog_debug(1,
1514204076Spjd					    "Increasing localcnt to %ju.",
1515204076Spjd					    (uintmax_t)res->hr_primary_localcnt);
1516204076Spjd					(void)metadata_write(res);
1517204076Spjd				}
1518204076Spjd				mtx_unlock(&metadata_lock);
1519204076Spjd			}
1520204076Spjd			rw_unlock(&hio_remote_lock[ncomp]);
1521204076Spjd		}
1522204076Spjd		if (ioctl(res->hr_ggatefd, G_GATE_CMD_DONE, ggio) < 0)
1523204076Spjd			primary_exit(EX_OSERR, "G_GATE_CMD_DONE failed");
1524204076Spjd		pjdlog_debug(2,
1525204076Spjd		    "ggate_send: (%p) Moving request to the free queue.", hio);
1526204076Spjd		QUEUE_INSERT2(hio, free);
1527204076Spjd	}
1528204076Spjd	/* NOTREACHED */
1529204076Spjd	return (NULL);
1530204076Spjd}
1531204076Spjd
1532204076Spjd/*
1533204076Spjd * Thread synchronize local and remote components.
1534204076Spjd */
1535204076Spjdstatic void *
1536204076Spjdsync_thread(void *arg __unused)
1537204076Spjd{
1538204076Spjd	struct hast_resource *res = arg;
1539204076Spjd	struct hio *hio;
1540204076Spjd	struct g_gate_ctl_io *ggio;
1541204076Spjd	unsigned int ii, ncomp, ncomps;
1542204076Spjd	off_t offset, length, synced;
1543204076Spjd	bool dorewind;
1544204076Spjd	int syncext;
1545204076Spjd
1546204076Spjd	ncomps = HAST_NCOMPONENTS;
1547204076Spjd	dorewind = true;
1548211897Spjd	synced = 0;
1549211897Spjd	offset = -1;
1550204076Spjd
1551204076Spjd	for (;;) {
1552204076Spjd		mtx_lock(&sync_lock);
1553211897Spjd		if (offset >= 0 && !sync_inprogress) {
1554211879Spjd			pjdlog_info("Synchronization interrupted. "
1555211879Spjd			    "%jd bytes synchronized so far.",
1556211879Spjd			    (intmax_t)synced);
1557212038Spjd			event_send(res, EVENT_SYNCINTR);
1558211879Spjd		}
1559204076Spjd		while (!sync_inprogress) {
1560204076Spjd			dorewind = true;
1561204076Spjd			synced = 0;
1562204076Spjd			cv_wait(&sync_cond, &sync_lock);
1563204076Spjd		}
1564204076Spjd		mtx_unlock(&sync_lock);
1565204076Spjd		/*
1566204076Spjd		 * Obtain offset at which we should synchronize.
1567204076Spjd		 * Rewind synchronization if needed.
1568204076Spjd		 */
1569204076Spjd		mtx_lock(&res->hr_amp_lock);
1570204076Spjd		if (dorewind)
1571204076Spjd			activemap_sync_rewind(res->hr_amp);
1572204076Spjd		offset = activemap_sync_offset(res->hr_amp, &length, &syncext);
1573204076Spjd		if (syncext != -1) {
1574204076Spjd			/*
1575204076Spjd			 * We synchronized entire syncext extent, we can mark
1576204076Spjd			 * it as clean now.
1577204076Spjd			 */
1578204076Spjd			if (activemap_extent_complete(res->hr_amp, syncext))
1579204076Spjd				(void)hast_activemap_flush(res);
1580204076Spjd		}
1581204076Spjd		mtx_unlock(&res->hr_amp_lock);
1582204076Spjd		if (dorewind) {
1583204076Spjd			dorewind = false;
1584204076Spjd			if (offset < 0)
1585204076Spjd				pjdlog_info("Nodes are in sync.");
1586204076Spjd			else {
1587204076Spjd				pjdlog_info("Synchronization started. %ju bytes to go.",
1588204076Spjd				    (uintmax_t)(res->hr_extentsize *
1589204076Spjd				    activemap_ndirty(res->hr_amp)));
1590212038Spjd				event_send(res, EVENT_SYNCSTART);
1591204076Spjd			}
1592204076Spjd		}
1593204076Spjd		if (offset < 0) {
1594211878Spjd			sync_stop();
1595204076Spjd			pjdlog_debug(1, "Nothing to synchronize.");
1596204076Spjd			/*
1597204076Spjd			 * Synchronization complete, make both localcnt and
1598204076Spjd			 * remotecnt equal.
1599204076Spjd			 */
1600204076Spjd			ncomp = 1;
1601204076Spjd			rw_rlock(&hio_remote_lock[ncomp]);
1602204076Spjd			if (ISCONNECTED(res, ncomp)) {
1603204076Spjd				if (synced > 0) {
1604204076Spjd					pjdlog_info("Synchronization complete. "
1605204076Spjd					    "%jd bytes synchronized.",
1606204076Spjd					    (intmax_t)synced);
1607212038Spjd					event_send(res, EVENT_SYNCDONE);
1608204076Spjd				}
1609204076Spjd				mtx_lock(&metadata_lock);
1610204076Spjd				res->hr_syncsrc = HAST_SYNCSRC_UNDEF;
1611204076Spjd				res->hr_primary_localcnt =
1612204076Spjd				    res->hr_secondary_localcnt;
1613204076Spjd				res->hr_primary_remotecnt =
1614204076Spjd				    res->hr_secondary_remotecnt;
1615204076Spjd				pjdlog_debug(1,
1616204076Spjd				    "Setting localcnt to %ju and remotecnt to %ju.",
1617204076Spjd				    (uintmax_t)res->hr_primary_localcnt,
1618204076Spjd				    (uintmax_t)res->hr_secondary_localcnt);
1619204076Spjd				(void)metadata_write(res);
1620204076Spjd				mtx_unlock(&metadata_lock);
1621204076Spjd			}
1622204076Spjd			rw_unlock(&hio_remote_lock[ncomp]);
1623204076Spjd			continue;
1624204076Spjd		}
1625204076Spjd		pjdlog_debug(2, "sync: Taking free request.");
1626204076Spjd		QUEUE_TAKE2(hio, free);
1627204076Spjd		pjdlog_debug(2, "sync: (%p) Got free request.", hio);
1628204076Spjd		/*
1629204076Spjd		 * Lock the range we are going to synchronize. We don't want
1630204076Spjd		 * race where someone writes between our read and write.
1631204076Spjd		 */
1632204076Spjd		for (;;) {
1633204076Spjd			mtx_lock(&range_lock);
1634204076Spjd			if (rangelock_islocked(range_regular, offset, length)) {
1635204076Spjd				pjdlog_debug(2,
1636204076Spjd				    "sync: Range offset=%jd length=%jd locked.",
1637204076Spjd				    (intmax_t)offset, (intmax_t)length);
1638204076Spjd				range_sync_wait = true;
1639204076Spjd				cv_wait(&range_sync_cond, &range_lock);
1640204076Spjd				range_sync_wait = false;
1641204076Spjd				mtx_unlock(&range_lock);
1642204076Spjd				continue;
1643204076Spjd			}
1644204076Spjd			if (rangelock_add(range_sync, offset, length) < 0) {
1645204076Spjd				mtx_unlock(&range_lock);
1646204076Spjd				pjdlog_debug(2,
1647204076Spjd				    "sync: Range offset=%jd length=%jd is already locked, waiting.",
1648204076Spjd				    (intmax_t)offset, (intmax_t)length);
1649204076Spjd				sleep(1);
1650204076Spjd				continue;
1651204076Spjd			}
1652204076Spjd			mtx_unlock(&range_lock);
1653204076Spjd			break;
1654204076Spjd		}
1655204076Spjd		/*
1656204076Spjd		 * First read the data from synchronization source.
1657204076Spjd		 */
1658204076Spjd		SYNCREQ(hio);
1659204076Spjd		ggio = &hio->hio_ggio;
1660204076Spjd		ggio->gctl_cmd = BIO_READ;
1661204076Spjd		ggio->gctl_offset = offset;
1662204076Spjd		ggio->gctl_length = length;
1663204076Spjd		ggio->gctl_error = 0;
1664204076Spjd		for (ii = 0; ii < ncomps; ii++)
1665204076Spjd			hio->hio_errors[ii] = EINVAL;
1666204076Spjd		reqlog(LOG_DEBUG, 2, ggio, "sync: (%p) Sending sync request: ",
1667204076Spjd		    hio);
1668204076Spjd		pjdlog_debug(2, "sync: (%p) Moving request to the send queue.",
1669204076Spjd		    hio);
1670204076Spjd		mtx_lock(&metadata_lock);
1671204076Spjd		if (res->hr_syncsrc == HAST_SYNCSRC_PRIMARY) {
1672204076Spjd			/*
1673204076Spjd			 * This range is up-to-date on local component,
1674204076Spjd			 * so handle request locally.
1675204076Spjd			 */
1676204076Spjd			 /* Local component is 0 for now. */
1677204076Spjd			ncomp = 0;
1678204076Spjd		} else /* if (res->hr_syncsrc == HAST_SYNCSRC_SECONDARY) */ {
1679204076Spjd			assert(res->hr_syncsrc == HAST_SYNCSRC_SECONDARY);
1680204076Spjd			/*
1681204076Spjd			 * This range is out-of-date on local component,
1682204076Spjd			 * so send request to the remote node.
1683204076Spjd			 */
1684204076Spjd			 /* Remote component is 1 for now. */
1685204076Spjd			ncomp = 1;
1686204076Spjd		}
1687204076Spjd		mtx_unlock(&metadata_lock);
1688204076Spjd		refcount_init(&hio->hio_countdown, 1);
1689204076Spjd		QUEUE_INSERT1(hio, send, ncomp);
1690204076Spjd
1691204076Spjd		/*
1692204076Spjd		 * Let's wait for READ to finish.
1693204076Spjd		 */
1694204076Spjd		mtx_lock(&sync_lock);
1695204076Spjd		while (!ISSYNCREQDONE(hio))
1696204076Spjd			cv_wait(&sync_cond, &sync_lock);
1697204076Spjd		mtx_unlock(&sync_lock);
1698204076Spjd
1699204076Spjd		if (hio->hio_errors[ncomp] != 0) {
1700204076Spjd			pjdlog_error("Unable to read synchronization data: %s.",
1701204076Spjd			    strerror(hio->hio_errors[ncomp]));
1702204076Spjd			goto free_queue;
1703204076Spjd		}
1704204076Spjd
1705204076Spjd		/*
1706204076Spjd		 * We read the data from synchronization source, now write it
1707204076Spjd		 * to synchronization target.
1708204076Spjd		 */
1709204076Spjd		SYNCREQ(hio);
1710204076Spjd		ggio->gctl_cmd = BIO_WRITE;
1711204076Spjd		for (ii = 0; ii < ncomps; ii++)
1712204076Spjd			hio->hio_errors[ii] = EINVAL;
1713204076Spjd		reqlog(LOG_DEBUG, 2, ggio, "sync: (%p) Sending sync request: ",
1714204076Spjd		    hio);
1715204076Spjd		pjdlog_debug(2, "sync: (%p) Moving request to the send queue.",
1716204076Spjd		    hio);
1717204076Spjd		mtx_lock(&metadata_lock);
1718204076Spjd		if (res->hr_syncsrc == HAST_SYNCSRC_PRIMARY) {
1719204076Spjd			/*
1720204076Spjd			 * This range is up-to-date on local component,
1721204076Spjd			 * so we update remote component.
1722204076Spjd			 */
1723204076Spjd			 /* Remote component is 1 for now. */
1724204076Spjd			ncomp = 1;
1725204076Spjd		} else /* if (res->hr_syncsrc == HAST_SYNCSRC_SECONDARY) */ {
1726204076Spjd			assert(res->hr_syncsrc == HAST_SYNCSRC_SECONDARY);
1727204076Spjd			/*
1728204076Spjd			 * This range is out-of-date on local component,
1729204076Spjd			 * so we update it.
1730204076Spjd			 */
1731204076Spjd			 /* Local component is 0 for now. */
1732204076Spjd			ncomp = 0;
1733204076Spjd		}
1734204076Spjd		mtx_unlock(&metadata_lock);
1735204076Spjd
1736204076Spjd		pjdlog_debug(2, "sync: (%p) Moving request to the send queues.",
1737204076Spjd		    hio);
1738204076Spjd		refcount_init(&hio->hio_countdown, 1);
1739204076Spjd		QUEUE_INSERT1(hio, send, ncomp);
1740204076Spjd
1741204076Spjd		/*
1742204076Spjd		 * Let's wait for WRITE to finish.
1743204076Spjd		 */
1744204076Spjd		mtx_lock(&sync_lock);
1745204076Spjd		while (!ISSYNCREQDONE(hio))
1746204076Spjd			cv_wait(&sync_cond, &sync_lock);
1747204076Spjd		mtx_unlock(&sync_lock);
1748204076Spjd
1749204076Spjd		if (hio->hio_errors[ncomp] != 0) {
1750204076Spjd			pjdlog_error("Unable to write synchronization data: %s.",
1751204076Spjd			    strerror(hio->hio_errors[ncomp]));
1752204076Spjd			goto free_queue;
1753204076Spjd		}
1754211880Spjd
1755211880Spjd		synced += length;
1756204076Spjdfree_queue:
1757204076Spjd		mtx_lock(&range_lock);
1758204076Spjd		rangelock_del(range_sync, offset, length);
1759204076Spjd		if (range_regular_wait)
1760204076Spjd			cv_signal(&range_regular_cond);
1761204076Spjd		mtx_unlock(&range_lock);
1762204076Spjd		pjdlog_debug(2, "sync: (%p) Moving request to the free queue.",
1763204076Spjd		    hio);
1764204076Spjd		QUEUE_INSERT2(hio, free);
1765204076Spjd	}
1766204076Spjd	/* NOTREACHED */
1767204076Spjd	return (NULL);
1768204076Spjd}
1769204076Spjd
1770204076Spjdstatic void
1771210886Spjdconfig_reload(void)
1772210886Spjd{
1773210886Spjd	struct hastd_config *newcfg;
1774210886Spjd	struct hast_resource *res;
1775210886Spjd	unsigned int ii, ncomps;
1776210886Spjd	int modified;
1777210886Spjd
1778210886Spjd	pjdlog_info("Reloading configuration...");
1779210886Spjd
1780210886Spjd	ncomps = HAST_NCOMPONENTS;
1781210886Spjd
1782210886Spjd	newcfg = yy_config_parse(cfgpath, false);
1783210886Spjd	if (newcfg == NULL)
1784210886Spjd		goto failed;
1785210886Spjd
1786210886Spjd	TAILQ_FOREACH(res, &newcfg->hc_resources, hr_next) {
1787210886Spjd		if (strcmp(res->hr_name, gres->hr_name) == 0)
1788210886Spjd			break;
1789210886Spjd	}
1790210886Spjd	/*
1791210886Spjd	 * If resource was removed from the configuration file, resource
1792210886Spjd	 * name, provider name or path to local component was modified we
1793210886Spjd	 * shouldn't be here. This means that someone modified configuration
1794210886Spjd	 * file and send SIGHUP to us instead of main hastd process.
1795210886Spjd	 * Log advice and ignore the signal.
1796210886Spjd	 */
1797210886Spjd	if (res == NULL || strcmp(gres->hr_name, res->hr_name) != 0 ||
1798210886Spjd	    strcmp(gres->hr_provname, res->hr_provname) != 0 ||
1799210886Spjd	    strcmp(gres->hr_localpath, res->hr_localpath) != 0) {
1800210886Spjd		pjdlog_warning("To reload configuration send SIGHUP to the main hastd process (pid %u).",
1801210886Spjd		    (unsigned int)getppid());
1802210886Spjd		goto failed;
1803210886Spjd	}
1804210886Spjd
1805210886Spjd#define MODIFIED_REMOTEADDR	0x1
1806210886Spjd#define MODIFIED_REPLICATION	0x2
1807210886Spjd#define MODIFIED_TIMEOUT	0x4
1808211886Spjd#define MODIFIED_EXEC		0x8
1809210886Spjd	modified = 0;
1810210886Spjd	if (strcmp(gres->hr_remoteaddr, res->hr_remoteaddr) != 0) {
1811210886Spjd		/*
1812210886Spjd		 * Don't copy res->hr_remoteaddr to gres just yet.
1813210886Spjd		 * We want remote_close() to log disconnect from the old
1814210886Spjd		 * addresses, not from the new ones.
1815210886Spjd		 */
1816210886Spjd		modified |= MODIFIED_REMOTEADDR;
1817210886Spjd	}
1818210886Spjd	if (gres->hr_replication != res->hr_replication) {
1819210886Spjd		gres->hr_replication = res->hr_replication;
1820210886Spjd		modified |= MODIFIED_REPLICATION;
1821210886Spjd	}
1822210886Spjd	if (gres->hr_timeout != res->hr_timeout) {
1823210886Spjd		gres->hr_timeout = res->hr_timeout;
1824210886Spjd		modified |= MODIFIED_TIMEOUT;
1825210886Spjd	}
1826211886Spjd	if (strcmp(gres->hr_exec, res->hr_exec) != 0) {
1827211886Spjd		strlcpy(gres->hr_exec, res->hr_exec, sizeof(gres->hr_exec));
1828211886Spjd		modified |= MODIFIED_EXEC;
1829211886Spjd	}
1830210886Spjd	/*
1831210886Spjd	 * If only timeout was modified we only need to change it without
1832210886Spjd	 * reconnecting.
1833210886Spjd	 */
1834210886Spjd	if (modified == MODIFIED_TIMEOUT) {
1835210886Spjd		for (ii = 0; ii < ncomps; ii++) {
1836210886Spjd			if (!ISREMOTE(ii))
1837210886Spjd				continue;
1838210886Spjd			rw_rlock(&hio_remote_lock[ii]);
1839210886Spjd			if (!ISCONNECTED(gres, ii)) {
1840210886Spjd				rw_unlock(&hio_remote_lock[ii]);
1841210886Spjd				continue;
1842210886Spjd			}
1843210886Spjd			rw_unlock(&hio_remote_lock[ii]);
1844210886Spjd			if (proto_timeout(gres->hr_remotein,
1845210886Spjd			    gres->hr_timeout) < 0) {
1846210886Spjd				pjdlog_errno(LOG_WARNING,
1847210886Spjd				    "Unable to set connection timeout");
1848210886Spjd			}
1849210886Spjd			if (proto_timeout(gres->hr_remoteout,
1850210886Spjd			    gres->hr_timeout) < 0) {
1851210886Spjd				pjdlog_errno(LOG_WARNING,
1852210886Spjd				    "Unable to set connection timeout");
1853210886Spjd			}
1854210886Spjd		}
1855211886Spjd	} else if ((modified &
1856211886Spjd	    (MODIFIED_REMOTEADDR | MODIFIED_REPLICATION)) != 0) {
1857210886Spjd		for (ii = 0; ii < ncomps; ii++) {
1858210886Spjd			if (!ISREMOTE(ii))
1859210886Spjd				continue;
1860210886Spjd			remote_close(gres, ii);
1861210886Spjd		}
1862210886Spjd		if (modified & MODIFIED_REMOTEADDR) {
1863210886Spjd			strlcpy(gres->hr_remoteaddr, res->hr_remoteaddr,
1864210886Spjd			    sizeof(gres->hr_remoteaddr));
1865210886Spjd		}
1866210886Spjd	}
1867210886Spjd#undef	MODIFIED_REMOTEADDR
1868210886Spjd#undef	MODIFIED_REPLICATION
1869210886Spjd#undef	MODIFIED_TIMEOUT
1870211886Spjd#undef	MODIFIED_EXEC
1871210886Spjd
1872210886Spjd	pjdlog_info("Configuration reloaded successfully.");
1873210886Spjd	return;
1874210886Spjdfailed:
1875210886Spjd	if (newcfg != NULL) {
1876210886Spjd		if (newcfg->hc_controlconn != NULL)
1877210886Spjd			proto_close(newcfg->hc_controlconn);
1878210886Spjd		if (newcfg->hc_listenconn != NULL)
1879210886Spjd			proto_close(newcfg->hc_listenconn);
1880210886Spjd		yy_config_free(newcfg);
1881210886Spjd	}
1882210886Spjd	pjdlog_warning("Configuration not reloaded.");
1883210886Spjd}
1884210886Spjd
1885211882Spjdstatic void
1886211882Spjdkeepalive_send(struct hast_resource *res, unsigned int ncomp)
1887211882Spjd{
1888211882Spjd	struct nv *nv;
1889211882Spjd
1890211882Spjd	nv = nv_alloc();
1891211882Spjd	nv_add_uint8(nv, HIO_KEEPALIVE, "cmd");
1892211882Spjd	if (nv_error(nv) != 0) {
1893211882Spjd		nv_free(nv);
1894211882Spjd		pjdlog_debug(1,
1895211882Spjd		    "keepalive_send: Unable to prepare header to send.");
1896211882Spjd		return;
1897211882Spjd	}
1898211882Spjd	if (hast_proto_send(res, res->hr_remoteout, nv, NULL, 0) < 0) {
1899211882Spjd		pjdlog_common(LOG_DEBUG, 1, errno,
1900211882Spjd		    "keepalive_send: Unable to send request");
1901211882Spjd		nv_free(nv);
1902211882Spjd		rw_unlock(&hio_remote_lock[ncomp]);
1903211882Spjd		remote_close(res, ncomp);
1904211882Spjd		rw_rlock(&hio_remote_lock[ncomp]);
1905211882Spjd		return;
1906211882Spjd	}
1907211882Spjd	nv_free(nv);
1908211882Spjd	pjdlog_debug(2, "keepalive_send: Request sent.");
1909211882Spjd}
1910211882Spjd
1911211981Spjdstatic void
1912211981Spjdguard_one(struct hast_resource *res, unsigned int ncomp)
1913211981Spjd{
1914211981Spjd	struct proto_conn *in, *out;
1915211981Spjd
1916211981Spjd	if (!ISREMOTE(ncomp))
1917211981Spjd		return;
1918211981Spjd
1919211981Spjd	rw_rlock(&hio_remote_lock[ncomp]);
1920211981Spjd
1921211981Spjd	if (!real_remote(res)) {
1922211981Spjd		rw_unlock(&hio_remote_lock[ncomp]);
1923211981Spjd		return;
1924211981Spjd	}
1925211981Spjd
1926211981Spjd	if (ISCONNECTED(res, ncomp)) {
1927211981Spjd		assert(res->hr_remotein != NULL);
1928211981Spjd		assert(res->hr_remoteout != NULL);
1929211981Spjd		keepalive_send(res, ncomp);
1930211981Spjd	}
1931211981Spjd
1932211981Spjd	if (ISCONNECTED(res, ncomp)) {
1933211981Spjd		assert(res->hr_remotein != NULL);
1934211981Spjd		assert(res->hr_remoteout != NULL);
1935211981Spjd		rw_unlock(&hio_remote_lock[ncomp]);
1936211981Spjd		pjdlog_debug(2, "remote_guard: Connection to %s is ok.",
1937211981Spjd		    res->hr_remoteaddr);
1938211981Spjd		return;
1939211981Spjd	}
1940211981Spjd
1941211981Spjd	assert(res->hr_remotein == NULL);
1942211981Spjd	assert(res->hr_remoteout == NULL);
1943211981Spjd	/*
1944211981Spjd	 * Upgrade the lock. It doesn't have to be atomic as no other thread
1945211981Spjd	 * can change connection status from disconnected to connected.
1946211981Spjd	 */
1947211981Spjd	rw_unlock(&hio_remote_lock[ncomp]);
1948211981Spjd	pjdlog_debug(2, "remote_guard: Reconnecting to %s.",
1949211981Spjd	    res->hr_remoteaddr);
1950211981Spjd	in = out = NULL;
1951211981Spjd	if (init_remote(res, &in, &out)) {
1952211981Spjd		rw_wlock(&hio_remote_lock[ncomp]);
1953211981Spjd		assert(res->hr_remotein == NULL);
1954211981Spjd		assert(res->hr_remoteout == NULL);
1955211981Spjd		assert(in != NULL && out != NULL);
1956211981Spjd		res->hr_remotein = in;
1957211981Spjd		res->hr_remoteout = out;
1958211981Spjd		rw_unlock(&hio_remote_lock[ncomp]);
1959211981Spjd		pjdlog_info("Successfully reconnected to %s.",
1960211981Spjd		    res->hr_remoteaddr);
1961211981Spjd		sync_start();
1962211981Spjd	} else {
1963211981Spjd		/* Both connections should be NULL. */
1964211981Spjd		assert(res->hr_remotein == NULL);
1965211981Spjd		assert(res->hr_remoteout == NULL);
1966211981Spjd		assert(in == NULL && out == NULL);
1967211981Spjd		pjdlog_debug(2, "remote_guard: Reconnect to %s failed.",
1968211981Spjd		    res->hr_remoteaddr);
1969211981Spjd	}
1970211981Spjd}
1971211981Spjd
1972204076Spjd/*
1973204076Spjd * Thread guards remote connections and reconnects when needed, handles
1974204076Spjd * signals, etc.
1975204076Spjd */
1976204076Spjdstatic void *
1977204076Spjdguard_thread(void *arg)
1978204076Spjd{
1979204076Spjd	struct hast_resource *res = arg;
1980204076Spjd	unsigned int ii, ncomps;
1981211982Spjd	struct timespec timeout;
1982211981Spjd	time_t lastcheck, now;
1983211982Spjd	sigset_t mask;
1984211982Spjd	int signo;
1985204076Spjd
1986204076Spjd	ncomps = HAST_NCOMPONENTS;
1987211981Spjd	lastcheck = time(NULL);
1988204076Spjd
1989211982Spjd	PJDLOG_VERIFY(sigemptyset(&mask) == 0);
1990211982Spjd	PJDLOG_VERIFY(sigaddset(&mask, SIGHUP) == 0);
1991211982Spjd	PJDLOG_VERIFY(sigaddset(&mask, SIGINT) == 0);
1992211982Spjd	PJDLOG_VERIFY(sigaddset(&mask, SIGTERM) == 0);
1993211982Spjd
1994211982Spjd	timeout.tv_nsec = 0;
1995211982Spjd	signo = -1;
1996211982Spjd
1997204076Spjd	for (;;) {
1998211982Spjd		switch (signo) {
1999211982Spjd		case SIGHUP:
2000211982Spjd			config_reload();
2001211982Spjd			break;
2002211982Spjd		case SIGINT:
2003211982Spjd		case SIGTERM:
2004211982Spjd			sigexit_received = true;
2005204076Spjd			primary_exitx(EX_OK,
2006204076Spjd			    "Termination signal received, exiting.");
2007211982Spjd			break;
2008211982Spjd		default:
2009211982Spjd			break;
2010204076Spjd		}
2011211882Spjd
2012204076Spjd		pjdlog_debug(2, "remote_guard: Checking connections.");
2013211981Spjd		now = time(NULL);
2014211982Spjd		if (lastcheck + RETRY_SLEEP <= now) {
2015211982Spjd			for (ii = 0; ii < ncomps; ii++)
2016211981Spjd				guard_one(res, ii);
2017211981Spjd			lastcheck = now;
2018204076Spjd		}
2019211982Spjd		timeout.tv_sec = RETRY_SLEEP;
2020211982Spjd		signo = sigtimedwait(&mask, NULL, &timeout);
2021204076Spjd	}
2022204076Spjd	/* NOTREACHED */
2023204076Spjd	return (NULL);
2024204076Spjd}
2025