primary.c revision 211881
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 211881 2010-08-27 14:12:53Z 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>
49204076Spjd#include <stdint.h>
50204076Spjd#include <stdio.h>
51204076Spjd#include <string.h>
52204076Spjd#include <sysexits.h>
53204076Spjd#include <unistd.h>
54204076Spjd
55204076Spjd#include <activemap.h>
56204076Spjd#include <nv.h>
57204076Spjd#include <rangelock.h>
58204076Spjd
59204076Spjd#include "control.h"
60204076Spjd#include "hast.h"
61204076Spjd#include "hast_proto.h"
62204076Spjd#include "hastd.h"
63204076Spjd#include "metadata.h"
64204076Spjd#include "proto.h"
65204076Spjd#include "pjdlog.h"
66204076Spjd#include "subr.h"
67204076Spjd#include "synch.h"
68204076Spjd
69210886Spjd/* The is only one remote component for now. */
70210886Spjd#define	ISREMOTE(no)	((no) == 1)
71210886Spjd
72204076Spjdstruct hio {
73204076Spjd	/*
74204076Spjd	 * Number of components we are still waiting for.
75204076Spjd	 * When this field goes to 0, we can send the request back to the
76204076Spjd	 * kernel. Each component has to decrease this counter by one
77204076Spjd	 * even on failure.
78204076Spjd	 */
79204076Spjd	unsigned int		 hio_countdown;
80204076Spjd	/*
81204076Spjd	 * Each component has a place to store its own error.
82204076Spjd	 * Once the request is handled by all components we can decide if the
83204076Spjd	 * request overall is successful or not.
84204076Spjd	 */
85204076Spjd	int			*hio_errors;
86204076Spjd	/*
87204076Spjd	 * Structure used to comunicate with GEOM Gate class.
88204076Spjd	 */
89204076Spjd	struct g_gate_ctl_io	 hio_ggio;
90204076Spjd	TAILQ_ENTRY(hio)	*hio_next;
91204076Spjd};
92204076Spjd#define	hio_free_next	hio_next[0]
93204076Spjd#define	hio_done_next	hio_next[0]
94204076Spjd
95204076Spjd/*
96204076Spjd * Free list holds unused structures. When free list is empty, we have to wait
97204076Spjd * until some in-progress requests are freed.
98204076Spjd */
99204076Spjdstatic TAILQ_HEAD(, hio) hio_free_list;
100204076Spjdstatic pthread_mutex_t hio_free_list_lock;
101204076Spjdstatic pthread_cond_t hio_free_list_cond;
102204076Spjd/*
103204076Spjd * There is one send list for every component. One requests is placed on all
104204076Spjd * send lists - each component gets the same request, but each component is
105204076Spjd * responsible for managing his own send list.
106204076Spjd */
107204076Spjdstatic TAILQ_HEAD(, hio) *hio_send_list;
108204076Spjdstatic pthread_mutex_t *hio_send_list_lock;
109204076Spjdstatic pthread_cond_t *hio_send_list_cond;
110204076Spjd/*
111204076Spjd * There is one recv list for every component, although local components don't
112204076Spjd * use recv lists as local requests are done synchronously.
113204076Spjd */
114204076Spjdstatic TAILQ_HEAD(, hio) *hio_recv_list;
115204076Spjdstatic pthread_mutex_t *hio_recv_list_lock;
116204076Spjdstatic pthread_cond_t *hio_recv_list_cond;
117204076Spjd/*
118204076Spjd * Request is placed on done list by the slowest component (the one that
119204076Spjd * decreased hio_countdown from 1 to 0).
120204076Spjd */
121204076Spjdstatic TAILQ_HEAD(, hio) hio_done_list;
122204076Spjdstatic pthread_mutex_t hio_done_list_lock;
123204076Spjdstatic pthread_cond_t hio_done_list_cond;
124204076Spjd/*
125204076Spjd * Structure below are for interaction with sync thread.
126204076Spjd */
127204076Spjdstatic bool sync_inprogress;
128204076Spjdstatic pthread_mutex_t sync_lock;
129204076Spjdstatic pthread_cond_t sync_cond;
130204076Spjd/*
131204076Spjd * The lock below allows to synchornize access to remote connections.
132204076Spjd */
133204076Spjdstatic pthread_rwlock_t *hio_remote_lock;
134204076Spjdstatic pthread_mutex_t hio_guard_lock;
135204076Spjdstatic pthread_cond_t hio_guard_cond;
136204076Spjd
137204076Spjd/*
138204076Spjd * Lock to synchronize metadata updates. Also synchronize access to
139204076Spjd * hr_primary_localcnt and hr_primary_remotecnt fields.
140204076Spjd */
141204076Spjdstatic pthread_mutex_t metadata_lock;
142204076Spjd
143204076Spjd/*
144204076Spjd * Maximum number of outstanding I/O requests.
145204076Spjd */
146204076Spjd#define	HAST_HIO_MAX	256
147204076Spjd/*
148204076Spjd * Number of components. At this point there are only two components: local
149204076Spjd * and remote, but in the future it might be possible to use multiple local
150204076Spjd * and remote components.
151204076Spjd */
152204076Spjd#define	HAST_NCOMPONENTS	2
153204076Spjd/*
154204076Spjd * Number of seconds to sleep before next reconnect try.
155204076Spjd */
156204076Spjd#define	RECONNECT_SLEEP		5
157204076Spjd
158204076Spjd#define	ISCONNECTED(res, no)	\
159204076Spjd	((res)->hr_remotein != NULL && (res)->hr_remoteout != NULL)
160204076Spjd
161204076Spjd#define	QUEUE_INSERT1(hio, name, ncomp)	do {				\
162204076Spjd	bool _wakeup;							\
163204076Spjd									\
164204076Spjd	mtx_lock(&hio_##name##_list_lock[(ncomp)]);			\
165204076Spjd	_wakeup = TAILQ_EMPTY(&hio_##name##_list[(ncomp)]);		\
166204076Spjd	TAILQ_INSERT_TAIL(&hio_##name##_list[(ncomp)], (hio),		\
167204076Spjd	    hio_next[(ncomp)]);						\
168204076Spjd	mtx_unlock(&hio_##name##_list_lock[ncomp]);			\
169204076Spjd	if (_wakeup)							\
170204076Spjd		cv_signal(&hio_##name##_list_cond[(ncomp)]);		\
171204076Spjd} while (0)
172204076Spjd#define	QUEUE_INSERT2(hio, name)	do {				\
173204076Spjd	bool _wakeup;							\
174204076Spjd									\
175204076Spjd	mtx_lock(&hio_##name##_list_lock);				\
176204076Spjd	_wakeup = TAILQ_EMPTY(&hio_##name##_list);			\
177204076Spjd	TAILQ_INSERT_TAIL(&hio_##name##_list, (hio), hio_##name##_next);\
178204076Spjd	mtx_unlock(&hio_##name##_list_lock);				\
179204076Spjd	if (_wakeup)							\
180204076Spjd		cv_signal(&hio_##name##_list_cond);			\
181204076Spjd} while (0)
182204076Spjd#define	QUEUE_TAKE1(hio, name, ncomp)	do {				\
183204076Spjd	mtx_lock(&hio_##name##_list_lock[(ncomp)]);			\
184204076Spjd	while (((hio) = TAILQ_FIRST(&hio_##name##_list[(ncomp)])) == NULL) { \
185204076Spjd		cv_wait(&hio_##name##_list_cond[(ncomp)],		\
186204076Spjd		    &hio_##name##_list_lock[(ncomp)]);			\
187204076Spjd	}								\
188204076Spjd	TAILQ_REMOVE(&hio_##name##_list[(ncomp)], (hio),		\
189204076Spjd	    hio_next[(ncomp)]);						\
190204076Spjd	mtx_unlock(&hio_##name##_list_lock[(ncomp)]);			\
191204076Spjd} while (0)
192204076Spjd#define	QUEUE_TAKE2(hio, name)	do {					\
193204076Spjd	mtx_lock(&hio_##name##_list_lock);				\
194204076Spjd	while (((hio) = TAILQ_FIRST(&hio_##name##_list)) == NULL) {	\
195204076Spjd		cv_wait(&hio_##name##_list_cond,			\
196204076Spjd		    &hio_##name##_list_lock);				\
197204076Spjd	}								\
198204076Spjd	TAILQ_REMOVE(&hio_##name##_list, (hio), hio_##name##_next);	\
199204076Spjd	mtx_unlock(&hio_##name##_list_lock);				\
200204076Spjd} while (0)
201204076Spjd
202209183Spjd#define	SYNCREQ(hio)		do {					\
203209183Spjd	(hio)->hio_ggio.gctl_unit = -1;					\
204209183Spjd	(hio)->hio_ggio.gctl_seq = 1;					\
205209183Spjd} while (0)
206204076Spjd#define	ISSYNCREQ(hio)		((hio)->hio_ggio.gctl_unit == -1)
207204076Spjd#define	SYNCREQDONE(hio)	do { (hio)->hio_ggio.gctl_unit = -2; } while (0)
208204076Spjd#define	ISSYNCREQDONE(hio)	((hio)->hio_ggio.gctl_unit == -2)
209204076Spjd
210204076Spjdstatic struct hast_resource *gres;
211204076Spjd
212204076Spjdstatic pthread_mutex_t range_lock;
213204076Spjdstatic struct rangelocks *range_regular;
214204076Spjdstatic bool range_regular_wait;
215204076Spjdstatic pthread_cond_t range_regular_cond;
216204076Spjdstatic struct rangelocks *range_sync;
217204076Spjdstatic bool range_sync_wait;
218204076Spjdstatic pthread_cond_t range_sync_cond;
219204076Spjd
220204076Spjdstatic void *ggate_recv_thread(void *arg);
221204076Spjdstatic void *local_send_thread(void *arg);
222204076Spjdstatic void *remote_send_thread(void *arg);
223204076Spjdstatic void *remote_recv_thread(void *arg);
224204076Spjdstatic void *ggate_send_thread(void *arg);
225204076Spjdstatic void *sync_thread(void *arg);
226204076Spjdstatic void *guard_thread(void *arg);
227204076Spjd
228204076Spjdstatic void sighandler(int sig);
229204076Spjd
230204076Spjdstatic void
231204076Spjdcleanup(struct hast_resource *res)
232204076Spjd{
233204076Spjd	int rerrno;
234204076Spjd
235204076Spjd	/* Remember errno. */
236204076Spjd	rerrno = errno;
237204076Spjd
238204076Spjd	/*
239204076Spjd	 * Close descriptor to /dev/hast/<name>
240204076Spjd	 * to work-around race in the kernel.
241204076Spjd	 */
242204076Spjd	close(res->hr_localfd);
243204076Spjd
244204076Spjd	/* Destroy ggate provider if we created one. */
245204076Spjd	if (res->hr_ggateunit >= 0) {
246204076Spjd		struct g_gate_ctl_destroy ggiod;
247204076Spjd
248204076Spjd		ggiod.gctl_version = G_GATE_VERSION;
249204076Spjd		ggiod.gctl_unit = res->hr_ggateunit;
250204076Spjd		ggiod.gctl_force = 1;
251204076Spjd		if (ioctl(res->hr_ggatefd, G_GATE_CMD_DESTROY, &ggiod) < 0) {
252204076Spjd			pjdlog_warning("Unable to destroy hast/%s device",
253204076Spjd			    res->hr_provname);
254204076Spjd		}
255204076Spjd		res->hr_ggateunit = -1;
256204076Spjd	}
257204076Spjd
258204076Spjd	/* Restore errno. */
259204076Spjd	errno = rerrno;
260204076Spjd}
261204076Spjd
262204076Spjdstatic void
263204076Spjdprimary_exit(int exitcode, const char *fmt, ...)
264204076Spjd{
265204076Spjd	va_list ap;
266204076Spjd
267204076Spjd	assert(exitcode != EX_OK);
268204076Spjd	va_start(ap, fmt);
269204076Spjd	pjdlogv_errno(LOG_ERR, fmt, ap);
270204076Spjd	va_end(ap);
271204076Spjd	cleanup(gres);
272204076Spjd	exit(exitcode);
273204076Spjd}
274204076Spjd
275204076Spjdstatic void
276204076Spjdprimary_exitx(int exitcode, const char *fmt, ...)
277204076Spjd{
278204076Spjd	va_list ap;
279204076Spjd
280204076Spjd	va_start(ap, fmt);
281204076Spjd	pjdlogv(exitcode == EX_OK ? LOG_INFO : LOG_ERR, fmt, ap);
282204076Spjd	va_end(ap);
283204076Spjd	cleanup(gres);
284204076Spjd	exit(exitcode);
285204076Spjd}
286204076Spjd
287204076Spjdstatic int
288204076Spjdhast_activemap_flush(struct hast_resource *res)
289204076Spjd{
290204076Spjd	const unsigned char *buf;
291204076Spjd	size_t size;
292204076Spjd
293204076Spjd	buf = activemap_bitmap(res->hr_amp, &size);
294204076Spjd	assert(buf != NULL);
295204076Spjd	assert((size % res->hr_local_sectorsize) == 0);
296204076Spjd	if (pwrite(res->hr_localfd, buf, size, METADATA_SIZE) !=
297204076Spjd	    (ssize_t)size) {
298204076Spjd		KEEP_ERRNO(pjdlog_errno(LOG_ERR,
299204076Spjd		    "Unable to flush activemap to disk"));
300204076Spjd		return (-1);
301204076Spjd	}
302204076Spjd	return (0);
303204076Spjd}
304204076Spjd
305210881Spjdstatic bool
306210881Spjdreal_remote(const struct hast_resource *res)
307210881Spjd{
308210881Spjd
309210881Spjd	return (strcmp(res->hr_remoteaddr, "none") != 0);
310210881Spjd}
311210881Spjd
312204076Spjdstatic void
313204076Spjdinit_environment(struct hast_resource *res __unused)
314204076Spjd{
315204076Spjd	struct hio *hio;
316204076Spjd	unsigned int ii, ncomps;
317204076Spjd
318204076Spjd	/*
319204076Spjd	 * In the future it might be per-resource value.
320204076Spjd	 */
321204076Spjd	ncomps = HAST_NCOMPONENTS;
322204076Spjd
323204076Spjd	/*
324204076Spjd	 * Allocate memory needed by lists.
325204076Spjd	 */
326204076Spjd	hio_send_list = malloc(sizeof(hio_send_list[0]) * ncomps);
327204076Spjd	if (hio_send_list == NULL) {
328204076Spjd		primary_exitx(EX_TEMPFAIL,
329204076Spjd		    "Unable to allocate %zu bytes of memory for send lists.",
330204076Spjd		    sizeof(hio_send_list[0]) * ncomps);
331204076Spjd	}
332204076Spjd	hio_send_list_lock = malloc(sizeof(hio_send_list_lock[0]) * ncomps);
333204076Spjd	if (hio_send_list_lock == NULL) {
334204076Spjd		primary_exitx(EX_TEMPFAIL,
335204076Spjd		    "Unable to allocate %zu bytes of memory for send list locks.",
336204076Spjd		    sizeof(hio_send_list_lock[0]) * ncomps);
337204076Spjd	}
338204076Spjd	hio_send_list_cond = malloc(sizeof(hio_send_list_cond[0]) * ncomps);
339204076Spjd	if (hio_send_list_cond == NULL) {
340204076Spjd		primary_exitx(EX_TEMPFAIL,
341204076Spjd		    "Unable to allocate %zu bytes of memory for send list condition variables.",
342204076Spjd		    sizeof(hio_send_list_cond[0]) * ncomps);
343204076Spjd	}
344204076Spjd	hio_recv_list = malloc(sizeof(hio_recv_list[0]) * ncomps);
345204076Spjd	if (hio_recv_list == NULL) {
346204076Spjd		primary_exitx(EX_TEMPFAIL,
347204076Spjd		    "Unable to allocate %zu bytes of memory for recv lists.",
348204076Spjd		    sizeof(hio_recv_list[0]) * ncomps);
349204076Spjd	}
350204076Spjd	hio_recv_list_lock = malloc(sizeof(hio_recv_list_lock[0]) * ncomps);
351204076Spjd	if (hio_recv_list_lock == NULL) {
352204076Spjd		primary_exitx(EX_TEMPFAIL,
353204076Spjd		    "Unable to allocate %zu bytes of memory for recv list locks.",
354204076Spjd		    sizeof(hio_recv_list_lock[0]) * ncomps);
355204076Spjd	}
356204076Spjd	hio_recv_list_cond = malloc(sizeof(hio_recv_list_cond[0]) * ncomps);
357204076Spjd	if (hio_recv_list_cond == NULL) {
358204076Spjd		primary_exitx(EX_TEMPFAIL,
359204076Spjd		    "Unable to allocate %zu bytes of memory for recv list condition variables.",
360204076Spjd		    sizeof(hio_recv_list_cond[0]) * ncomps);
361204076Spjd	}
362204076Spjd	hio_remote_lock = malloc(sizeof(hio_remote_lock[0]) * ncomps);
363204076Spjd	if (hio_remote_lock == NULL) {
364204076Spjd		primary_exitx(EX_TEMPFAIL,
365204076Spjd		    "Unable to allocate %zu bytes of memory for remote connections locks.",
366204076Spjd		    sizeof(hio_remote_lock[0]) * ncomps);
367204076Spjd	}
368204076Spjd
369204076Spjd	/*
370204076Spjd	 * Initialize lists, their locks and theirs condition variables.
371204076Spjd	 */
372204076Spjd	TAILQ_INIT(&hio_free_list);
373204076Spjd	mtx_init(&hio_free_list_lock);
374204076Spjd	cv_init(&hio_free_list_cond);
375204076Spjd	for (ii = 0; ii < HAST_NCOMPONENTS; ii++) {
376204076Spjd		TAILQ_INIT(&hio_send_list[ii]);
377204076Spjd		mtx_init(&hio_send_list_lock[ii]);
378204076Spjd		cv_init(&hio_send_list_cond[ii]);
379204076Spjd		TAILQ_INIT(&hio_recv_list[ii]);
380204076Spjd		mtx_init(&hio_recv_list_lock[ii]);
381204076Spjd		cv_init(&hio_recv_list_cond[ii]);
382204076Spjd		rw_init(&hio_remote_lock[ii]);
383204076Spjd	}
384204076Spjd	TAILQ_INIT(&hio_done_list);
385204076Spjd	mtx_init(&hio_done_list_lock);
386204076Spjd	cv_init(&hio_done_list_cond);
387204076Spjd	mtx_init(&hio_guard_lock);
388204076Spjd	cv_init(&hio_guard_cond);
389204076Spjd	mtx_init(&metadata_lock);
390204076Spjd
391204076Spjd	/*
392204076Spjd	 * Allocate requests pool and initialize requests.
393204076Spjd	 */
394204076Spjd	for (ii = 0; ii < HAST_HIO_MAX; ii++) {
395204076Spjd		hio = malloc(sizeof(*hio));
396204076Spjd		if (hio == NULL) {
397204076Spjd			primary_exitx(EX_TEMPFAIL,
398204076Spjd			    "Unable to allocate %zu bytes of memory for hio request.",
399204076Spjd			    sizeof(*hio));
400204076Spjd		}
401204076Spjd		hio->hio_countdown = 0;
402204076Spjd		hio->hio_errors = malloc(sizeof(hio->hio_errors[0]) * ncomps);
403204076Spjd		if (hio->hio_errors == NULL) {
404204076Spjd			primary_exitx(EX_TEMPFAIL,
405204076Spjd			    "Unable allocate %zu bytes of memory for hio errors.",
406204076Spjd			    sizeof(hio->hio_errors[0]) * ncomps);
407204076Spjd		}
408204076Spjd		hio->hio_next = malloc(sizeof(hio->hio_next[0]) * ncomps);
409204076Spjd		if (hio->hio_next == NULL) {
410204076Spjd			primary_exitx(EX_TEMPFAIL,
411204076Spjd			    "Unable allocate %zu bytes of memory for hio_next field.",
412204076Spjd			    sizeof(hio->hio_next[0]) * ncomps);
413204076Spjd		}
414204076Spjd		hio->hio_ggio.gctl_version = G_GATE_VERSION;
415204076Spjd		hio->hio_ggio.gctl_data = malloc(MAXPHYS);
416204076Spjd		if (hio->hio_ggio.gctl_data == NULL) {
417204076Spjd			primary_exitx(EX_TEMPFAIL,
418204076Spjd			    "Unable to allocate %zu bytes of memory for gctl_data.",
419204076Spjd			    MAXPHYS);
420204076Spjd		}
421204076Spjd		hio->hio_ggio.gctl_length = MAXPHYS;
422204076Spjd		hio->hio_ggio.gctl_error = 0;
423204076Spjd		TAILQ_INSERT_HEAD(&hio_free_list, hio, hio_free_next);
424204076Spjd	}
425204076Spjd
426204076Spjd	/*
427204076Spjd	 * Turn on signals handling.
428204076Spjd	 */
429204076Spjd	signal(SIGINT, sighandler);
430204076Spjd	signal(SIGTERM, sighandler);
431210886Spjd	signal(SIGHUP, sighandler);
432204076Spjd}
433204076Spjd
434204076Spjdstatic void
435204076Spjdinit_local(struct hast_resource *res)
436204076Spjd{
437204076Spjd	unsigned char *buf;
438204076Spjd	size_t mapsize;
439204076Spjd
440204076Spjd	if (metadata_read(res, true) < 0)
441204076Spjd		exit(EX_NOINPUT);
442204076Spjd	mtx_init(&res->hr_amp_lock);
443204076Spjd	if (activemap_init(&res->hr_amp, res->hr_datasize, res->hr_extentsize,
444204076Spjd	    res->hr_local_sectorsize, res->hr_keepdirty) < 0) {
445204076Spjd		primary_exit(EX_TEMPFAIL, "Unable to create activemap");
446204076Spjd	}
447204076Spjd	mtx_init(&range_lock);
448204076Spjd	cv_init(&range_regular_cond);
449204076Spjd	if (rangelock_init(&range_regular) < 0)
450204076Spjd		primary_exit(EX_TEMPFAIL, "Unable to create regular range lock");
451204076Spjd	cv_init(&range_sync_cond);
452204076Spjd	if (rangelock_init(&range_sync) < 0)
453204076Spjd		primary_exit(EX_TEMPFAIL, "Unable to create sync range lock");
454204076Spjd	mapsize = activemap_ondisk_size(res->hr_amp);
455204076Spjd	buf = calloc(1, mapsize);
456204076Spjd	if (buf == NULL) {
457204076Spjd		primary_exitx(EX_TEMPFAIL,
458204076Spjd		    "Unable to allocate buffer for activemap.");
459204076Spjd	}
460204076Spjd	if (pread(res->hr_localfd, buf, mapsize, METADATA_SIZE) !=
461204076Spjd	    (ssize_t)mapsize) {
462204076Spjd		primary_exit(EX_NOINPUT, "Unable to read activemap");
463204076Spjd	}
464204076Spjd	activemap_copyin(res->hr_amp, buf, mapsize);
465209181Spjd	free(buf);
466204076Spjd	if (res->hr_resuid != 0)
467204076Spjd		return;
468204076Spjd	/*
469204076Spjd	 * We're using provider for the first time, so we have to generate
470204076Spjd	 * resource unique identifier and initialize local and remote counts.
471204076Spjd	 */
472204076Spjd	arc4random_buf(&res->hr_resuid, sizeof(res->hr_resuid));
473204076Spjd	res->hr_primary_localcnt = 1;
474204076Spjd	res->hr_primary_remotecnt = 0;
475204076Spjd	if (metadata_write(res) < 0)
476204076Spjd		exit(EX_NOINPUT);
477204076Spjd}
478204076Spjd
479205738Spjdstatic bool
480205738Spjdinit_remote(struct hast_resource *res, struct proto_conn **inp,
481205738Spjd    struct proto_conn **outp)
482204076Spjd{
483205738Spjd	struct proto_conn *in, *out;
484204076Spjd	struct nv *nvout, *nvin;
485204076Spjd	const unsigned char *token;
486204076Spjd	unsigned char *map;
487204076Spjd	const char *errmsg;
488204076Spjd	int32_t extentsize;
489204076Spjd	int64_t datasize;
490204076Spjd	uint32_t mapsize;
491204076Spjd	size_t size;
492204076Spjd
493205738Spjd	assert((inp == NULL && outp == NULL) || (inp != NULL && outp != NULL));
494210881Spjd	assert(real_remote(res));
495205738Spjd
496205738Spjd	in = out = NULL;
497205738Spjd
498204076Spjd	/* Prepare outgoing connection with remote node. */
499205738Spjd	if (proto_client(res->hr_remoteaddr, &out) < 0) {
500207347Spjd		primary_exit(EX_TEMPFAIL, "Unable to create connection to %s",
501204076Spjd		    res->hr_remoteaddr);
502204076Spjd	}
503204076Spjd	/* Try to connect, but accept failure. */
504205738Spjd	if (proto_connect(out) < 0) {
505204076Spjd		pjdlog_errno(LOG_WARNING, "Unable to connect to %s",
506204076Spjd		    res->hr_remoteaddr);
507204076Spjd		goto close;
508204076Spjd	}
509207371Spjd	/* Error in setting timeout is not critical, but why should it fail? */
510207371Spjd	if (proto_timeout(out, res->hr_timeout) < 0)
511207371Spjd		pjdlog_errno(LOG_WARNING, "Unable to set connection timeout");
512204076Spjd	/*
513204076Spjd	 * First handshake step.
514204076Spjd	 * Setup outgoing connection with remote node.
515204076Spjd	 */
516204076Spjd	nvout = nv_alloc();
517204076Spjd	nv_add_string(nvout, res->hr_name, "resource");
518204076Spjd	if (nv_error(nvout) != 0) {
519204076Spjd		pjdlog_common(LOG_WARNING, 0, nv_error(nvout),
520204076Spjd		    "Unable to allocate header for connection with %s",
521204076Spjd		    res->hr_remoteaddr);
522204076Spjd		nv_free(nvout);
523204076Spjd		goto close;
524204076Spjd	}
525205738Spjd	if (hast_proto_send(res, out, nvout, NULL, 0) < 0) {
526204076Spjd		pjdlog_errno(LOG_WARNING,
527204076Spjd		    "Unable to send handshake header to %s",
528204076Spjd		    res->hr_remoteaddr);
529204076Spjd		nv_free(nvout);
530204076Spjd		goto close;
531204076Spjd	}
532204076Spjd	nv_free(nvout);
533205738Spjd	if (hast_proto_recv_hdr(out, &nvin) < 0) {
534204076Spjd		pjdlog_errno(LOG_WARNING,
535204076Spjd		    "Unable to receive handshake header from %s",
536204076Spjd		    res->hr_remoteaddr);
537204076Spjd		goto close;
538204076Spjd	}
539204076Spjd	errmsg = nv_get_string(nvin, "errmsg");
540204076Spjd	if (errmsg != NULL) {
541204076Spjd		pjdlog_warning("%s", errmsg);
542204076Spjd		nv_free(nvin);
543204076Spjd		goto close;
544204076Spjd	}
545204076Spjd	token = nv_get_uint8_array(nvin, &size, "token");
546204076Spjd	if (token == NULL) {
547204076Spjd		pjdlog_warning("Handshake header from %s has no 'token' field.",
548204076Spjd		    res->hr_remoteaddr);
549204076Spjd		nv_free(nvin);
550204076Spjd		goto close;
551204076Spjd	}
552204076Spjd	if (size != sizeof(res->hr_token)) {
553204076Spjd		pjdlog_warning("Handshake header from %s contains 'token' of wrong size (got %zu, expected %zu).",
554204076Spjd		    res->hr_remoteaddr, size, sizeof(res->hr_token));
555204076Spjd		nv_free(nvin);
556204076Spjd		goto close;
557204076Spjd	}
558204076Spjd	bcopy(token, res->hr_token, sizeof(res->hr_token));
559204076Spjd	nv_free(nvin);
560204076Spjd
561204076Spjd	/*
562204076Spjd	 * Second handshake step.
563204076Spjd	 * Setup incoming connection with remote node.
564204076Spjd	 */
565205738Spjd	if (proto_client(res->hr_remoteaddr, &in) < 0) {
566204076Spjd		pjdlog_errno(LOG_WARNING, "Unable to create connection to %s",
567204076Spjd		    res->hr_remoteaddr);
568204076Spjd	}
569204076Spjd	/* Try to connect, but accept failure. */
570205738Spjd	if (proto_connect(in) < 0) {
571204076Spjd		pjdlog_errno(LOG_WARNING, "Unable to connect to %s",
572204076Spjd		    res->hr_remoteaddr);
573204076Spjd		goto close;
574204076Spjd	}
575207371Spjd	/* Error in setting timeout is not critical, but why should it fail? */
576207371Spjd	if (proto_timeout(in, res->hr_timeout) < 0)
577207371Spjd		pjdlog_errno(LOG_WARNING, "Unable to set connection timeout");
578204076Spjd	nvout = nv_alloc();
579204076Spjd	nv_add_string(nvout, res->hr_name, "resource");
580204076Spjd	nv_add_uint8_array(nvout, res->hr_token, sizeof(res->hr_token),
581204076Spjd	    "token");
582204076Spjd	nv_add_uint64(nvout, res->hr_resuid, "resuid");
583204076Spjd	nv_add_uint64(nvout, res->hr_primary_localcnt, "localcnt");
584204076Spjd	nv_add_uint64(nvout, res->hr_primary_remotecnt, "remotecnt");
585204076Spjd	if (nv_error(nvout) != 0) {
586204076Spjd		pjdlog_common(LOG_WARNING, 0, nv_error(nvout),
587204076Spjd		    "Unable to allocate header for connection with %s",
588204076Spjd		    res->hr_remoteaddr);
589204076Spjd		nv_free(nvout);
590204076Spjd		goto close;
591204076Spjd	}
592205738Spjd	if (hast_proto_send(res, in, nvout, NULL, 0) < 0) {
593204076Spjd		pjdlog_errno(LOG_WARNING,
594204076Spjd		    "Unable to send handshake header to %s",
595204076Spjd		    res->hr_remoteaddr);
596204076Spjd		nv_free(nvout);
597204076Spjd		goto close;
598204076Spjd	}
599204076Spjd	nv_free(nvout);
600205738Spjd	if (hast_proto_recv_hdr(out, &nvin) < 0) {
601204076Spjd		pjdlog_errno(LOG_WARNING,
602204076Spjd		    "Unable to receive handshake header from %s",
603204076Spjd		    res->hr_remoteaddr);
604204076Spjd		goto close;
605204076Spjd	}
606204076Spjd	errmsg = nv_get_string(nvin, "errmsg");
607204076Spjd	if (errmsg != NULL) {
608204076Spjd		pjdlog_warning("%s", errmsg);
609204076Spjd		nv_free(nvin);
610204076Spjd		goto close;
611204076Spjd	}
612204076Spjd	datasize = nv_get_int64(nvin, "datasize");
613204076Spjd	if (datasize != res->hr_datasize) {
614204076Spjd		pjdlog_warning("Data size differs between nodes (local=%jd, remote=%jd).",
615204076Spjd		    (intmax_t)res->hr_datasize, (intmax_t)datasize);
616204076Spjd		nv_free(nvin);
617204076Spjd		goto close;
618204076Spjd	}
619204076Spjd	extentsize = nv_get_int32(nvin, "extentsize");
620204076Spjd	if (extentsize != res->hr_extentsize) {
621204076Spjd		pjdlog_warning("Extent size differs between nodes (local=%zd, remote=%zd).",
622204076Spjd		    (ssize_t)res->hr_extentsize, (ssize_t)extentsize);
623204076Spjd		nv_free(nvin);
624204076Spjd		goto close;
625204076Spjd	}
626204076Spjd	res->hr_secondary_localcnt = nv_get_uint64(nvin, "localcnt");
627204076Spjd	res->hr_secondary_remotecnt = nv_get_uint64(nvin, "remotecnt");
628204076Spjd	res->hr_syncsrc = nv_get_uint8(nvin, "syncsrc");
629204076Spjd	map = NULL;
630204076Spjd	mapsize = nv_get_uint32(nvin, "mapsize");
631204076Spjd	if (mapsize > 0) {
632204076Spjd		map = malloc(mapsize);
633204076Spjd		if (map == NULL) {
634204076Spjd			pjdlog_error("Unable to allocate memory for remote activemap (mapsize=%ju).",
635204076Spjd			    (uintmax_t)mapsize);
636204076Spjd			nv_free(nvin);
637204076Spjd			goto close;
638204076Spjd		}
639204076Spjd		/*
640204076Spjd		 * Remote node have some dirty extents on its own, lets
641204076Spjd		 * download its activemap.
642204076Spjd		 */
643205738Spjd		if (hast_proto_recv_data(res, out, nvin, map,
644204076Spjd		    mapsize) < 0) {
645204076Spjd			pjdlog_errno(LOG_ERR,
646204076Spjd			    "Unable to receive remote activemap");
647204076Spjd			nv_free(nvin);
648204076Spjd			free(map);
649204076Spjd			goto close;
650204076Spjd		}
651204076Spjd		/*
652204076Spjd		 * Merge local and remote bitmaps.
653204076Spjd		 */
654204076Spjd		activemap_merge(res->hr_amp, map, mapsize);
655204076Spjd		free(map);
656204076Spjd		/*
657204076Spjd		 * Now that we merged bitmaps from both nodes, flush it to the
658204076Spjd		 * disk before we start to synchronize.
659204076Spjd		 */
660204076Spjd		(void)hast_activemap_flush(res);
661204076Spjd	}
662204076Spjd	pjdlog_info("Connected to %s.", res->hr_remoteaddr);
663205738Spjd	if (inp != NULL && outp != NULL) {
664205738Spjd		*inp = in;
665205738Spjd		*outp = out;
666205738Spjd	} else {
667205738Spjd		res->hr_remotein = in;
668205738Spjd		res->hr_remoteout = out;
669205738Spjd	}
670205738Spjd	return (true);
671205738Spjdclose:
672205738Spjd	proto_close(out);
673205738Spjd	if (in != NULL)
674205738Spjd		proto_close(in);
675205738Spjd	return (false);
676205738Spjd}
677205738Spjd
678205738Spjdstatic void
679205738Spjdsync_start(void)
680205738Spjd{
681205738Spjd
682204076Spjd	mtx_lock(&sync_lock);
683204076Spjd	sync_inprogress = true;
684204076Spjd	mtx_unlock(&sync_lock);
685204076Spjd	cv_signal(&sync_cond);
686204076Spjd}
687204076Spjd
688204076Spjdstatic void
689211878Spjdsync_stop(void)
690211878Spjd{
691211878Spjd
692211878Spjd	mtx_lock(&sync_lock);
693211878Spjd	if (sync_inprogress)
694211878Spjd		sync_inprogress = false;
695211878Spjd	mtx_unlock(&sync_lock);
696211878Spjd}
697211878Spjd
698211878Spjdstatic void
699204076Spjdinit_ggate(struct hast_resource *res)
700204076Spjd{
701204076Spjd	struct g_gate_ctl_create ggiocreate;
702204076Spjd	struct g_gate_ctl_cancel ggiocancel;
703204076Spjd
704204076Spjd	/*
705204076Spjd	 * We communicate with ggate via /dev/ggctl. Open it.
706204076Spjd	 */
707204076Spjd	res->hr_ggatefd = open("/dev/" G_GATE_CTL_NAME, O_RDWR);
708204076Spjd	if (res->hr_ggatefd < 0)
709204076Spjd		primary_exit(EX_OSFILE, "Unable to open /dev/" G_GATE_CTL_NAME);
710204076Spjd	/*
711204076Spjd	 * Create provider before trying to connect, as connection failure
712204076Spjd	 * is not critical, but may take some time.
713204076Spjd	 */
714204076Spjd	ggiocreate.gctl_version = G_GATE_VERSION;
715204076Spjd	ggiocreate.gctl_mediasize = res->hr_datasize;
716204076Spjd	ggiocreate.gctl_sectorsize = res->hr_local_sectorsize;
717204076Spjd	ggiocreate.gctl_flags = 0;
718206669Spjd	ggiocreate.gctl_maxcount = G_GATE_MAX_QUEUE_SIZE;
719204076Spjd	ggiocreate.gctl_timeout = 0;
720204076Spjd	ggiocreate.gctl_unit = G_GATE_NAME_GIVEN;
721204076Spjd	snprintf(ggiocreate.gctl_name, sizeof(ggiocreate.gctl_name), "hast/%s",
722204076Spjd	    res->hr_provname);
723204076Spjd	bzero(ggiocreate.gctl_info, sizeof(ggiocreate.gctl_info));
724204076Spjd	if (ioctl(res->hr_ggatefd, G_GATE_CMD_CREATE, &ggiocreate) == 0) {
725204076Spjd		pjdlog_info("Device hast/%s created.", res->hr_provname);
726204076Spjd		res->hr_ggateunit = ggiocreate.gctl_unit;
727204076Spjd		return;
728204076Spjd	}
729204076Spjd	if (errno != EEXIST) {
730204076Spjd		primary_exit(EX_OSERR, "Unable to create hast/%s device",
731204076Spjd		    res->hr_provname);
732204076Spjd	}
733204076Spjd	pjdlog_debug(1,
734204076Spjd	    "Device hast/%s already exists, we will try to take it over.",
735204076Spjd	    res->hr_provname);
736204076Spjd	/*
737204076Spjd	 * If we received EEXIST, we assume that the process who created the
738204076Spjd	 * provider died and didn't clean up. In that case we will start from
739204076Spjd	 * where he left of.
740204076Spjd	 */
741204076Spjd	ggiocancel.gctl_version = G_GATE_VERSION;
742204076Spjd	ggiocancel.gctl_unit = G_GATE_NAME_GIVEN;
743204076Spjd	snprintf(ggiocancel.gctl_name, sizeof(ggiocancel.gctl_name), "hast/%s",
744204076Spjd	    res->hr_provname);
745204076Spjd	if (ioctl(res->hr_ggatefd, G_GATE_CMD_CANCEL, &ggiocancel) == 0) {
746204076Spjd		pjdlog_info("Device hast/%s recovered.", res->hr_provname);
747204076Spjd		res->hr_ggateunit = ggiocancel.gctl_unit;
748204076Spjd		return;
749204076Spjd	}
750204076Spjd	primary_exit(EX_OSERR, "Unable to take over hast/%s device",
751204076Spjd	    res->hr_provname);
752204076Spjd}
753204076Spjd
754204076Spjdvoid
755204076Spjdhastd_primary(struct hast_resource *res)
756204076Spjd{
757204076Spjd	pthread_t td;
758204076Spjd	pid_t pid;
759204076Spjd	int error;
760204076Spjd
761204076Spjd	gres = res;
762204076Spjd
763204076Spjd	/*
764204076Spjd	 * Create communication channel between parent and child.
765204076Spjd	 */
766204076Spjd	if (proto_client("socketpair://", &res->hr_ctrl) < 0) {
767204076Spjd		KEEP_ERRNO((void)pidfile_remove(pfh));
768204076Spjd		primary_exit(EX_OSERR,
769204076Spjd		    "Unable to create control sockets between parent and child");
770204076Spjd	}
771204076Spjd
772204076Spjd	pid = fork();
773204076Spjd	if (pid < 0) {
774204076Spjd		KEEP_ERRNO((void)pidfile_remove(pfh));
775207347Spjd		primary_exit(EX_TEMPFAIL, "Unable to fork");
776204076Spjd	}
777204076Spjd
778204076Spjd	if (pid > 0) {
779204076Spjd		/* This is parent. */
780204076Spjd		res->hr_workerpid = pid;
781204076Spjd		return;
782204076Spjd	}
783204076Spjd	(void)pidfile_close(pfh);
784204076Spjd
785204076Spjd	setproctitle("%s (primary)", res->hr_name);
786204076Spjd
787210880Spjd	signal(SIGHUP, SIG_DFL);
788210880Spjd	signal(SIGCHLD, SIG_DFL);
789210880Spjd
790204076Spjd	init_local(res);
791210881Spjd	if (real_remote(res) && init_remote(res, NULL, NULL))
792205738Spjd		sync_start();
793204076Spjd	init_ggate(res);
794204076Spjd	init_environment(res);
795204076Spjd	error = pthread_create(&td, NULL, ggate_recv_thread, res);
796204076Spjd	assert(error == 0);
797204076Spjd	error = pthread_create(&td, NULL, local_send_thread, res);
798204076Spjd	assert(error == 0);
799204076Spjd	error = pthread_create(&td, NULL, remote_send_thread, res);
800204076Spjd	assert(error == 0);
801204076Spjd	error = pthread_create(&td, NULL, remote_recv_thread, res);
802204076Spjd	assert(error == 0);
803204076Spjd	error = pthread_create(&td, NULL, ggate_send_thread, res);
804204076Spjd	assert(error == 0);
805204076Spjd	error = pthread_create(&td, NULL, sync_thread, res);
806204076Spjd	assert(error == 0);
807204076Spjd	error = pthread_create(&td, NULL, ctrl_thread, res);
808204076Spjd	assert(error == 0);
809204076Spjd	(void)guard_thread(res);
810204076Spjd}
811204076Spjd
812204076Spjdstatic void
813204076Spjdreqlog(int loglevel, int debuglevel, struct g_gate_ctl_io *ggio, const char *fmt, ...)
814204076Spjd{
815204076Spjd	char msg[1024];
816204076Spjd	va_list ap;
817204076Spjd	int len;
818204076Spjd
819204076Spjd	va_start(ap, fmt);
820204076Spjd	len = vsnprintf(msg, sizeof(msg), fmt, ap);
821204076Spjd	va_end(ap);
822204076Spjd	if ((size_t)len < sizeof(msg)) {
823204076Spjd		switch (ggio->gctl_cmd) {
824204076Spjd		case BIO_READ:
825204076Spjd			(void)snprintf(msg + len, sizeof(msg) - len,
826204076Spjd			    "READ(%ju, %ju).", (uintmax_t)ggio->gctl_offset,
827204076Spjd			    (uintmax_t)ggio->gctl_length);
828204076Spjd			break;
829204076Spjd		case BIO_DELETE:
830204076Spjd			(void)snprintf(msg + len, sizeof(msg) - len,
831204076Spjd			    "DELETE(%ju, %ju).", (uintmax_t)ggio->gctl_offset,
832204076Spjd			    (uintmax_t)ggio->gctl_length);
833204076Spjd			break;
834204076Spjd		case BIO_FLUSH:
835204076Spjd			(void)snprintf(msg + len, sizeof(msg) - len, "FLUSH.");
836204076Spjd			break;
837204076Spjd		case BIO_WRITE:
838204076Spjd			(void)snprintf(msg + len, sizeof(msg) - len,
839204076Spjd			    "WRITE(%ju, %ju).", (uintmax_t)ggio->gctl_offset,
840204076Spjd			    (uintmax_t)ggio->gctl_length);
841204076Spjd			break;
842204076Spjd		default:
843204076Spjd			(void)snprintf(msg + len, sizeof(msg) - len,
844204076Spjd			    "UNKNOWN(%u).", (unsigned int)ggio->gctl_cmd);
845204076Spjd			break;
846204076Spjd		}
847204076Spjd	}
848204076Spjd	pjdlog_common(loglevel, debuglevel, -1, "%s", msg);
849204076Spjd}
850204076Spjd
851204076Spjdstatic void
852204076Spjdremote_close(struct hast_resource *res, int ncomp)
853204076Spjd{
854204076Spjd
855204076Spjd	rw_wlock(&hio_remote_lock[ncomp]);
856204076Spjd	/*
857204076Spjd	 * A race is possible between dropping rlock and acquiring wlock -
858204076Spjd	 * another thread can close connection in-between.
859204076Spjd	 */
860204076Spjd	if (!ISCONNECTED(res, ncomp)) {
861204076Spjd		assert(res->hr_remotein == NULL);
862204076Spjd		assert(res->hr_remoteout == NULL);
863204076Spjd		rw_unlock(&hio_remote_lock[ncomp]);
864204076Spjd		return;
865204076Spjd	}
866204076Spjd
867204076Spjd	assert(res->hr_remotein != NULL);
868204076Spjd	assert(res->hr_remoteout != NULL);
869204076Spjd
870211881Spjd	pjdlog_debug(2, "Closing incoming connection to %s.",
871204076Spjd	    res->hr_remoteaddr);
872204076Spjd	proto_close(res->hr_remotein);
873204076Spjd	res->hr_remotein = NULL;
874211881Spjd	pjdlog_debug(2, "Closing outgoing connection to %s.",
875204076Spjd	    res->hr_remoteaddr);
876204076Spjd	proto_close(res->hr_remoteout);
877204076Spjd	res->hr_remoteout = NULL;
878204076Spjd
879204076Spjd	rw_unlock(&hio_remote_lock[ncomp]);
880204076Spjd
881211881Spjd	pjdlog_warning("Disconnected from %s.", res->hr_remoteaddr);
882211881Spjd
883204076Spjd	/*
884204076Spjd	 * Stop synchronization if in-progress.
885204076Spjd	 */
886211878Spjd	sync_stop();
887204076Spjd
888204076Spjd	/*
889204076Spjd	 * Wake up guard thread, so it can immediately start reconnect.
890204076Spjd	 */
891204076Spjd	mtx_lock(&hio_guard_lock);
892204076Spjd	cv_signal(&hio_guard_cond);
893204076Spjd	mtx_unlock(&hio_guard_lock);
894204076Spjd}
895204076Spjd
896204076Spjd/*
897204076Spjd * Thread receives ggate I/O requests from the kernel and passes them to
898204076Spjd * appropriate threads:
899204076Spjd * WRITE - always goes to both local_send and remote_send threads
900204076Spjd * READ (when the block is up-to-date on local component) -
901204076Spjd *	only local_send thread
902204076Spjd * READ (when the block isn't up-to-date on local component) -
903204076Spjd *	only remote_send thread
904204076Spjd * DELETE - always goes to both local_send and remote_send threads
905204076Spjd * FLUSH - always goes to both local_send and remote_send threads
906204076Spjd */
907204076Spjdstatic void *
908204076Spjdggate_recv_thread(void *arg)
909204076Spjd{
910204076Spjd	struct hast_resource *res = arg;
911204076Spjd	struct g_gate_ctl_io *ggio;
912204076Spjd	struct hio *hio;
913204076Spjd	unsigned int ii, ncomp, ncomps;
914204076Spjd	int error;
915204076Spjd
916204076Spjd	ncomps = HAST_NCOMPONENTS;
917204076Spjd
918204076Spjd	for (;;) {
919204076Spjd		pjdlog_debug(2, "ggate_recv: Taking free request.");
920204076Spjd		QUEUE_TAKE2(hio, free);
921204076Spjd		pjdlog_debug(2, "ggate_recv: (%p) Got free request.", hio);
922204076Spjd		ggio = &hio->hio_ggio;
923204076Spjd		ggio->gctl_unit = res->hr_ggateunit;
924204076Spjd		ggio->gctl_length = MAXPHYS;
925204076Spjd		ggio->gctl_error = 0;
926204076Spjd		pjdlog_debug(2,
927204076Spjd		    "ggate_recv: (%p) Waiting for request from the kernel.",
928204076Spjd		    hio);
929204076Spjd		if (ioctl(res->hr_ggatefd, G_GATE_CMD_START, ggio) < 0) {
930204076Spjd			if (sigexit_received)
931204076Spjd				pthread_exit(NULL);
932204076Spjd			primary_exit(EX_OSERR, "G_GATE_CMD_START failed");
933204076Spjd		}
934204076Spjd		error = ggio->gctl_error;
935204076Spjd		switch (error) {
936204076Spjd		case 0:
937204076Spjd			break;
938204076Spjd		case ECANCELED:
939204076Spjd			/* Exit gracefully. */
940204076Spjd			if (!sigexit_received) {
941204076Spjd				pjdlog_debug(2,
942204076Spjd				    "ggate_recv: (%p) Received cancel from the kernel.",
943204076Spjd				    hio);
944204076Spjd				pjdlog_info("Received cancel from the kernel, exiting.");
945204076Spjd			}
946204076Spjd			pthread_exit(NULL);
947204076Spjd		case ENOMEM:
948204076Spjd			/*
949204076Spjd			 * Buffer too small? Impossible, we allocate MAXPHYS
950204076Spjd			 * bytes - request can't be bigger than that.
951204076Spjd			 */
952204076Spjd			/* FALLTHROUGH */
953204076Spjd		case ENXIO:
954204076Spjd		default:
955204076Spjd			primary_exitx(EX_OSERR, "G_GATE_CMD_START failed: %s.",
956204076Spjd			    strerror(error));
957204076Spjd		}
958204076Spjd		for (ii = 0; ii < ncomps; ii++)
959204076Spjd			hio->hio_errors[ii] = EINVAL;
960204076Spjd		reqlog(LOG_DEBUG, 2, ggio,
961204076Spjd		    "ggate_recv: (%p) Request received from the kernel: ",
962204076Spjd		    hio);
963204076Spjd		/*
964204076Spjd		 * Inform all components about new write request.
965204076Spjd		 * For read request prefer local component unless the given
966204076Spjd		 * range is out-of-date, then use remote component.
967204076Spjd		 */
968204076Spjd		switch (ggio->gctl_cmd) {
969204076Spjd		case BIO_READ:
970204076Spjd			pjdlog_debug(2,
971204076Spjd			    "ggate_recv: (%p) Moving request to the send queue.",
972204076Spjd			    hio);
973204076Spjd			refcount_init(&hio->hio_countdown, 1);
974204076Spjd			mtx_lock(&metadata_lock);
975204076Spjd			if (res->hr_syncsrc == HAST_SYNCSRC_UNDEF ||
976204076Spjd			    res->hr_syncsrc == HAST_SYNCSRC_PRIMARY) {
977204076Spjd				/*
978204076Spjd				 * This range is up-to-date on local component,
979204076Spjd				 * so handle request locally.
980204076Spjd				 */
981204076Spjd				 /* Local component is 0 for now. */
982204076Spjd				ncomp = 0;
983204076Spjd			} else /* if (res->hr_syncsrc ==
984204076Spjd			    HAST_SYNCSRC_SECONDARY) */ {
985204076Spjd				assert(res->hr_syncsrc ==
986204076Spjd				    HAST_SYNCSRC_SECONDARY);
987204076Spjd				/*
988204076Spjd				 * This range is out-of-date on local component,
989204076Spjd				 * so send request to the remote node.
990204076Spjd				 */
991204076Spjd				 /* Remote component is 1 for now. */
992204076Spjd				ncomp = 1;
993204076Spjd			}
994204076Spjd			mtx_unlock(&metadata_lock);
995204076Spjd			QUEUE_INSERT1(hio, send, ncomp);
996204076Spjd			break;
997204076Spjd		case BIO_WRITE:
998204076Spjd			for (;;) {
999204076Spjd				mtx_lock(&range_lock);
1000204076Spjd				if (rangelock_islocked(range_sync,
1001204076Spjd				    ggio->gctl_offset, ggio->gctl_length)) {
1002204076Spjd					pjdlog_debug(2,
1003204076Spjd					    "regular: Range offset=%jd length=%zu locked.",
1004204076Spjd					    (intmax_t)ggio->gctl_offset,
1005204076Spjd					    (size_t)ggio->gctl_length);
1006204076Spjd					range_regular_wait = true;
1007204076Spjd					cv_wait(&range_regular_cond, &range_lock);
1008204076Spjd					range_regular_wait = false;
1009204076Spjd					mtx_unlock(&range_lock);
1010204076Spjd					continue;
1011204076Spjd				}
1012204076Spjd				if (rangelock_add(range_regular,
1013204076Spjd				    ggio->gctl_offset, ggio->gctl_length) < 0) {
1014204076Spjd					mtx_unlock(&range_lock);
1015204076Spjd					pjdlog_debug(2,
1016204076Spjd					    "regular: Range offset=%jd length=%zu is already locked, waiting.",
1017204076Spjd					    (intmax_t)ggio->gctl_offset,
1018204076Spjd					    (size_t)ggio->gctl_length);
1019204076Spjd					sleep(1);
1020204076Spjd					continue;
1021204076Spjd				}
1022204076Spjd				mtx_unlock(&range_lock);
1023204076Spjd				break;
1024204076Spjd			}
1025204076Spjd			mtx_lock(&res->hr_amp_lock);
1026204076Spjd			if (activemap_write_start(res->hr_amp,
1027204076Spjd			    ggio->gctl_offset, ggio->gctl_length)) {
1028204076Spjd				(void)hast_activemap_flush(res);
1029204076Spjd			}
1030204076Spjd			mtx_unlock(&res->hr_amp_lock);
1031204076Spjd			/* FALLTHROUGH */
1032204076Spjd		case BIO_DELETE:
1033204076Spjd		case BIO_FLUSH:
1034204076Spjd			pjdlog_debug(2,
1035204076Spjd			    "ggate_recv: (%p) Moving request to the send queues.",
1036204076Spjd			    hio);
1037204076Spjd			refcount_init(&hio->hio_countdown, ncomps);
1038204076Spjd			for (ii = 0; ii < ncomps; ii++)
1039204076Spjd				QUEUE_INSERT1(hio, send, ii);
1040204076Spjd			break;
1041204076Spjd		}
1042204076Spjd	}
1043204076Spjd	/* NOTREACHED */
1044204076Spjd	return (NULL);
1045204076Spjd}
1046204076Spjd
1047204076Spjd/*
1048204076Spjd * Thread reads from or writes to local component.
1049204076Spjd * If local read fails, it redirects it to remote_send thread.
1050204076Spjd */
1051204076Spjdstatic void *
1052204076Spjdlocal_send_thread(void *arg)
1053204076Spjd{
1054204076Spjd	struct hast_resource *res = arg;
1055204076Spjd	struct g_gate_ctl_io *ggio;
1056204076Spjd	struct hio *hio;
1057204076Spjd	unsigned int ncomp, rncomp;
1058204076Spjd	ssize_t ret;
1059204076Spjd
1060204076Spjd	/* Local component is 0 for now. */
1061204076Spjd	ncomp = 0;
1062204076Spjd	/* Remote component is 1 for now. */
1063204076Spjd	rncomp = 1;
1064204076Spjd
1065204076Spjd	for (;;) {
1066204076Spjd		pjdlog_debug(2, "local_send: Taking request.");
1067204076Spjd		QUEUE_TAKE1(hio, send, ncomp);
1068204076Spjd		pjdlog_debug(2, "local_send: (%p) Got request.", hio);
1069204076Spjd		ggio = &hio->hio_ggio;
1070204076Spjd		switch (ggio->gctl_cmd) {
1071204076Spjd		case BIO_READ:
1072204076Spjd			ret = pread(res->hr_localfd, ggio->gctl_data,
1073204076Spjd			    ggio->gctl_length,
1074204076Spjd			    ggio->gctl_offset + res->hr_localoff);
1075204076Spjd			if (ret == ggio->gctl_length)
1076204076Spjd				hio->hio_errors[ncomp] = 0;
1077204076Spjd			else {
1078204076Spjd				/*
1079204076Spjd				 * If READ failed, try to read from remote node.
1080204076Spjd				 */
1081204076Spjd				QUEUE_INSERT1(hio, send, rncomp);
1082204076Spjd				continue;
1083204076Spjd			}
1084204076Spjd			break;
1085204076Spjd		case BIO_WRITE:
1086204076Spjd			ret = pwrite(res->hr_localfd, ggio->gctl_data,
1087204076Spjd			    ggio->gctl_length,
1088204076Spjd			    ggio->gctl_offset + res->hr_localoff);
1089204076Spjd			if (ret < 0)
1090204076Spjd				hio->hio_errors[ncomp] = errno;
1091204076Spjd			else if (ret != ggio->gctl_length)
1092204076Spjd				hio->hio_errors[ncomp] = EIO;
1093204076Spjd			else
1094204076Spjd				hio->hio_errors[ncomp] = 0;
1095204076Spjd			break;
1096204076Spjd		case BIO_DELETE:
1097204076Spjd			ret = g_delete(res->hr_localfd,
1098204076Spjd			    ggio->gctl_offset + res->hr_localoff,
1099204076Spjd			    ggio->gctl_length);
1100204076Spjd			if (ret < 0)
1101204076Spjd				hio->hio_errors[ncomp] = errno;
1102204076Spjd			else
1103204076Spjd				hio->hio_errors[ncomp] = 0;
1104204076Spjd			break;
1105204076Spjd		case BIO_FLUSH:
1106204076Spjd			ret = g_flush(res->hr_localfd);
1107204076Spjd			if (ret < 0)
1108204076Spjd				hio->hio_errors[ncomp] = errno;
1109204076Spjd			else
1110204076Spjd				hio->hio_errors[ncomp] = 0;
1111204076Spjd			break;
1112204076Spjd		}
1113204076Spjd		if (refcount_release(&hio->hio_countdown)) {
1114204076Spjd			if (ISSYNCREQ(hio)) {
1115204076Spjd				mtx_lock(&sync_lock);
1116204076Spjd				SYNCREQDONE(hio);
1117204076Spjd				mtx_unlock(&sync_lock);
1118204076Spjd				cv_signal(&sync_cond);
1119204076Spjd			} else {
1120204076Spjd				pjdlog_debug(2,
1121204076Spjd				    "local_send: (%p) Moving request to the done queue.",
1122204076Spjd				    hio);
1123204076Spjd				QUEUE_INSERT2(hio, done);
1124204076Spjd			}
1125204076Spjd		}
1126204076Spjd	}
1127204076Spjd	/* NOTREACHED */
1128204076Spjd	return (NULL);
1129204076Spjd}
1130204076Spjd
1131204076Spjd/*
1132204076Spjd * Thread sends request to secondary node.
1133204076Spjd */
1134204076Spjdstatic void *
1135204076Spjdremote_send_thread(void *arg)
1136204076Spjd{
1137204076Spjd	struct hast_resource *res = arg;
1138204076Spjd	struct g_gate_ctl_io *ggio;
1139204076Spjd	struct hio *hio;
1140204076Spjd	struct nv *nv;
1141204076Spjd	unsigned int ncomp;
1142204076Spjd	bool wakeup;
1143204076Spjd	uint64_t offset, length;
1144204076Spjd	uint8_t cmd;
1145204076Spjd	void *data;
1146204076Spjd
1147204076Spjd	/* Remote component is 1 for now. */
1148204076Spjd	ncomp = 1;
1149204076Spjd
1150204076Spjd	for (;;) {
1151204076Spjd		pjdlog_debug(2, "remote_send: Taking request.");
1152204076Spjd		QUEUE_TAKE1(hio, send, ncomp);
1153204076Spjd		pjdlog_debug(2, "remote_send: (%p) Got request.", hio);
1154204076Spjd		ggio = &hio->hio_ggio;
1155204076Spjd		switch (ggio->gctl_cmd) {
1156204076Spjd		case BIO_READ:
1157204076Spjd			cmd = HIO_READ;
1158204076Spjd			data = NULL;
1159204076Spjd			offset = ggio->gctl_offset;
1160204076Spjd			length = ggio->gctl_length;
1161204076Spjd			break;
1162204076Spjd		case BIO_WRITE:
1163204076Spjd			cmd = HIO_WRITE;
1164204076Spjd			data = ggio->gctl_data;
1165204076Spjd			offset = ggio->gctl_offset;
1166204076Spjd			length = ggio->gctl_length;
1167204076Spjd			break;
1168204076Spjd		case BIO_DELETE:
1169204076Spjd			cmd = HIO_DELETE;
1170204076Spjd			data = NULL;
1171204076Spjd			offset = ggio->gctl_offset;
1172204076Spjd			length = ggio->gctl_length;
1173204076Spjd			break;
1174204076Spjd		case BIO_FLUSH:
1175204076Spjd			cmd = HIO_FLUSH;
1176204076Spjd			data = NULL;
1177204076Spjd			offset = 0;
1178204076Spjd			length = 0;
1179204076Spjd			break;
1180204076Spjd		default:
1181204076Spjd			assert(!"invalid condition");
1182204076Spjd			abort();
1183204076Spjd		}
1184204076Spjd		nv = nv_alloc();
1185204076Spjd		nv_add_uint8(nv, cmd, "cmd");
1186204076Spjd		nv_add_uint64(nv, (uint64_t)ggio->gctl_seq, "seq");
1187204076Spjd		nv_add_uint64(nv, offset, "offset");
1188204076Spjd		nv_add_uint64(nv, length, "length");
1189204076Spjd		if (nv_error(nv) != 0) {
1190204076Spjd			hio->hio_errors[ncomp] = nv_error(nv);
1191204076Spjd			pjdlog_debug(2,
1192204076Spjd			    "remote_send: (%p) Unable to prepare header to send.",
1193204076Spjd			    hio);
1194204076Spjd			reqlog(LOG_ERR, 0, ggio,
1195204076Spjd			    "Unable to prepare header to send (%s): ",
1196204076Spjd			    strerror(nv_error(nv)));
1197204076Spjd			/* Move failed request immediately to the done queue. */
1198204076Spjd			goto done_queue;
1199204076Spjd		}
1200204076Spjd		pjdlog_debug(2,
1201204076Spjd		    "remote_send: (%p) Moving request to the recv queue.",
1202204076Spjd		    hio);
1203204076Spjd		/*
1204204076Spjd		 * Protect connection from disappearing.
1205204076Spjd		 */
1206204076Spjd		rw_rlock(&hio_remote_lock[ncomp]);
1207204076Spjd		if (!ISCONNECTED(res, ncomp)) {
1208204076Spjd			rw_unlock(&hio_remote_lock[ncomp]);
1209204076Spjd			hio->hio_errors[ncomp] = ENOTCONN;
1210204076Spjd			goto done_queue;
1211204076Spjd		}
1212204076Spjd		/*
1213204076Spjd		 * Move the request to recv queue before sending it, because
1214204076Spjd		 * in different order we can get reply before we move request
1215204076Spjd		 * to recv queue.
1216204076Spjd		 */
1217204076Spjd		mtx_lock(&hio_recv_list_lock[ncomp]);
1218204076Spjd		wakeup = TAILQ_EMPTY(&hio_recv_list[ncomp]);
1219204076Spjd		TAILQ_INSERT_TAIL(&hio_recv_list[ncomp], hio, hio_next[ncomp]);
1220204076Spjd		mtx_unlock(&hio_recv_list_lock[ncomp]);
1221204076Spjd		if (hast_proto_send(res, res->hr_remoteout, nv, data,
1222204076Spjd		    data != NULL ? length : 0) < 0) {
1223204076Spjd			hio->hio_errors[ncomp] = errno;
1224204076Spjd			rw_unlock(&hio_remote_lock[ncomp]);
1225204076Spjd			remote_close(res, ncomp);
1226204076Spjd			pjdlog_debug(2,
1227204076Spjd			    "remote_send: (%p) Unable to send request.", hio);
1228204076Spjd			reqlog(LOG_ERR, 0, ggio,
1229204076Spjd			    "Unable to send request (%s): ",
1230204076Spjd			    strerror(hio->hio_errors[ncomp]));
1231204076Spjd			/*
1232204076Spjd			 * Take request back from the receive queue and move
1233204076Spjd			 * it immediately to the done queue.
1234204076Spjd			 */
1235204076Spjd			mtx_lock(&hio_recv_list_lock[ncomp]);
1236204076Spjd			TAILQ_REMOVE(&hio_recv_list[ncomp], hio, hio_next[ncomp]);
1237204076Spjd			mtx_unlock(&hio_recv_list_lock[ncomp]);
1238204076Spjd			goto done_queue;
1239204076Spjd		}
1240204076Spjd		rw_unlock(&hio_remote_lock[ncomp]);
1241204076Spjd		nv_free(nv);
1242204076Spjd		if (wakeup)
1243204076Spjd			cv_signal(&hio_recv_list_cond[ncomp]);
1244204076Spjd		continue;
1245204076Spjddone_queue:
1246204076Spjd		nv_free(nv);
1247204076Spjd		if (ISSYNCREQ(hio)) {
1248204076Spjd			if (!refcount_release(&hio->hio_countdown))
1249204076Spjd				continue;
1250204076Spjd			mtx_lock(&sync_lock);
1251204076Spjd			SYNCREQDONE(hio);
1252204076Spjd			mtx_unlock(&sync_lock);
1253204076Spjd			cv_signal(&sync_cond);
1254204076Spjd			continue;
1255204076Spjd		}
1256204076Spjd		if (ggio->gctl_cmd == BIO_WRITE) {
1257204076Spjd			mtx_lock(&res->hr_amp_lock);
1258204076Spjd			if (activemap_need_sync(res->hr_amp, ggio->gctl_offset,
1259204076Spjd			    ggio->gctl_length)) {
1260204076Spjd				(void)hast_activemap_flush(res);
1261204076Spjd			}
1262204076Spjd			mtx_unlock(&res->hr_amp_lock);
1263204076Spjd		}
1264204076Spjd		if (!refcount_release(&hio->hio_countdown))
1265204076Spjd			continue;
1266204076Spjd		pjdlog_debug(2,
1267204076Spjd		    "remote_send: (%p) Moving request to the done queue.",
1268204076Spjd		    hio);
1269204076Spjd		QUEUE_INSERT2(hio, done);
1270204076Spjd	}
1271204076Spjd	/* NOTREACHED */
1272204076Spjd	return (NULL);
1273204076Spjd}
1274204076Spjd
1275204076Spjd/*
1276204076Spjd * Thread receives answer from secondary node and passes it to ggate_send
1277204076Spjd * thread.
1278204076Spjd */
1279204076Spjdstatic void *
1280204076Spjdremote_recv_thread(void *arg)
1281204076Spjd{
1282204076Spjd	struct hast_resource *res = arg;
1283204076Spjd	struct g_gate_ctl_io *ggio;
1284204076Spjd	struct hio *hio;
1285204076Spjd	struct nv *nv;
1286204076Spjd	unsigned int ncomp;
1287204076Spjd	uint64_t seq;
1288204076Spjd	int error;
1289204076Spjd
1290204076Spjd	/* Remote component is 1 for now. */
1291204076Spjd	ncomp = 1;
1292204076Spjd
1293204076Spjd	for (;;) {
1294204076Spjd		/* Wait until there is anything to receive. */
1295204076Spjd		mtx_lock(&hio_recv_list_lock[ncomp]);
1296204076Spjd		while (TAILQ_EMPTY(&hio_recv_list[ncomp])) {
1297204076Spjd			pjdlog_debug(2, "remote_recv: No requests, waiting.");
1298204076Spjd			cv_wait(&hio_recv_list_cond[ncomp],
1299204076Spjd			    &hio_recv_list_lock[ncomp]);
1300204076Spjd		}
1301204076Spjd		mtx_unlock(&hio_recv_list_lock[ncomp]);
1302204076Spjd		rw_rlock(&hio_remote_lock[ncomp]);
1303204076Spjd		if (!ISCONNECTED(res, ncomp)) {
1304204076Spjd			rw_unlock(&hio_remote_lock[ncomp]);
1305204076Spjd			/*
1306204076Spjd			 * Connection is dead, so move all pending requests to
1307204076Spjd			 * the done queue (one-by-one).
1308204076Spjd			 */
1309204076Spjd			mtx_lock(&hio_recv_list_lock[ncomp]);
1310204076Spjd			hio = TAILQ_FIRST(&hio_recv_list[ncomp]);
1311204076Spjd			assert(hio != NULL);
1312204076Spjd			TAILQ_REMOVE(&hio_recv_list[ncomp], hio,
1313204076Spjd			    hio_next[ncomp]);
1314204076Spjd			mtx_unlock(&hio_recv_list_lock[ncomp]);
1315204076Spjd			goto done_queue;
1316204076Spjd		}
1317204076Spjd		if (hast_proto_recv_hdr(res->hr_remotein, &nv) < 0) {
1318204076Spjd			pjdlog_errno(LOG_ERR,
1319204076Spjd			    "Unable to receive reply header");
1320204076Spjd			rw_unlock(&hio_remote_lock[ncomp]);
1321204076Spjd			remote_close(res, ncomp);
1322204076Spjd			continue;
1323204076Spjd		}
1324204076Spjd		rw_unlock(&hio_remote_lock[ncomp]);
1325204076Spjd		seq = nv_get_uint64(nv, "seq");
1326204076Spjd		if (seq == 0) {
1327204076Spjd			pjdlog_error("Header contains no 'seq' field.");
1328204076Spjd			nv_free(nv);
1329204076Spjd			continue;
1330204076Spjd		}
1331204076Spjd		mtx_lock(&hio_recv_list_lock[ncomp]);
1332204076Spjd		TAILQ_FOREACH(hio, &hio_recv_list[ncomp], hio_next[ncomp]) {
1333204076Spjd			if (hio->hio_ggio.gctl_seq == seq) {
1334204076Spjd				TAILQ_REMOVE(&hio_recv_list[ncomp], hio,
1335204076Spjd				    hio_next[ncomp]);
1336204076Spjd				break;
1337204076Spjd			}
1338204076Spjd		}
1339204076Spjd		mtx_unlock(&hio_recv_list_lock[ncomp]);
1340204076Spjd		if (hio == NULL) {
1341204076Spjd			pjdlog_error("Found no request matching received 'seq' field (%ju).",
1342204076Spjd			    (uintmax_t)seq);
1343204076Spjd			nv_free(nv);
1344204076Spjd			continue;
1345204076Spjd		}
1346204076Spjd		error = nv_get_int16(nv, "error");
1347204076Spjd		if (error != 0) {
1348204076Spjd			/* Request failed on remote side. */
1349204076Spjd			hio->hio_errors[ncomp] = 0;
1350204076Spjd			nv_free(nv);
1351204076Spjd			goto done_queue;
1352204076Spjd		}
1353204076Spjd		ggio = &hio->hio_ggio;
1354204076Spjd		switch (ggio->gctl_cmd) {
1355204076Spjd		case BIO_READ:
1356204076Spjd			rw_rlock(&hio_remote_lock[ncomp]);
1357204076Spjd			if (!ISCONNECTED(res, ncomp)) {
1358204076Spjd				rw_unlock(&hio_remote_lock[ncomp]);
1359204076Spjd				nv_free(nv);
1360204076Spjd				goto done_queue;
1361204076Spjd			}
1362204076Spjd			if (hast_proto_recv_data(res, res->hr_remotein, nv,
1363204076Spjd			    ggio->gctl_data, ggio->gctl_length) < 0) {
1364204076Spjd				hio->hio_errors[ncomp] = errno;
1365204076Spjd				pjdlog_errno(LOG_ERR,
1366204076Spjd				    "Unable to receive reply data");
1367204076Spjd				rw_unlock(&hio_remote_lock[ncomp]);
1368204076Spjd				nv_free(nv);
1369204076Spjd				remote_close(res, ncomp);
1370204076Spjd				goto done_queue;
1371204076Spjd			}
1372204076Spjd			rw_unlock(&hio_remote_lock[ncomp]);
1373204076Spjd			break;
1374204076Spjd		case BIO_WRITE:
1375204076Spjd		case BIO_DELETE:
1376204076Spjd		case BIO_FLUSH:
1377204076Spjd			break;
1378204076Spjd		default:
1379204076Spjd			assert(!"invalid condition");
1380204076Spjd			abort();
1381204076Spjd		}
1382204076Spjd		hio->hio_errors[ncomp] = 0;
1383204076Spjd		nv_free(nv);
1384204076Spjddone_queue:
1385204076Spjd		if (refcount_release(&hio->hio_countdown)) {
1386204076Spjd			if (ISSYNCREQ(hio)) {
1387204076Spjd				mtx_lock(&sync_lock);
1388204076Spjd				SYNCREQDONE(hio);
1389204076Spjd				mtx_unlock(&sync_lock);
1390204076Spjd				cv_signal(&sync_cond);
1391204076Spjd			} else {
1392204076Spjd				pjdlog_debug(2,
1393204076Spjd				    "remote_recv: (%p) Moving request to the done queue.",
1394204076Spjd				    hio);
1395204076Spjd				QUEUE_INSERT2(hio, done);
1396204076Spjd			}
1397204076Spjd		}
1398204076Spjd	}
1399204076Spjd	/* NOTREACHED */
1400204076Spjd	return (NULL);
1401204076Spjd}
1402204076Spjd
1403204076Spjd/*
1404204076Spjd * Thread sends answer to the kernel.
1405204076Spjd */
1406204076Spjdstatic void *
1407204076Spjdggate_send_thread(void *arg)
1408204076Spjd{
1409204076Spjd	struct hast_resource *res = arg;
1410204076Spjd	struct g_gate_ctl_io *ggio;
1411204076Spjd	struct hio *hio;
1412204076Spjd	unsigned int ii, ncomp, ncomps;
1413204076Spjd
1414204076Spjd	ncomps = HAST_NCOMPONENTS;
1415204076Spjd
1416204076Spjd	for (;;) {
1417204076Spjd		pjdlog_debug(2, "ggate_send: Taking request.");
1418204076Spjd		QUEUE_TAKE2(hio, done);
1419204076Spjd		pjdlog_debug(2, "ggate_send: (%p) Got request.", hio);
1420204076Spjd		ggio = &hio->hio_ggio;
1421204076Spjd		for (ii = 0; ii < ncomps; ii++) {
1422204076Spjd			if (hio->hio_errors[ii] == 0) {
1423204076Spjd				/*
1424204076Spjd				 * One successful request is enough to declare
1425204076Spjd				 * success.
1426204076Spjd				 */
1427204076Spjd				ggio->gctl_error = 0;
1428204076Spjd				break;
1429204076Spjd			}
1430204076Spjd		}
1431204076Spjd		if (ii == ncomps) {
1432204076Spjd			/*
1433204076Spjd			 * None of the requests were successful.
1434204076Spjd			 * Use first error.
1435204076Spjd			 */
1436204076Spjd			ggio->gctl_error = hio->hio_errors[0];
1437204076Spjd		}
1438204076Spjd		if (ggio->gctl_error == 0 && ggio->gctl_cmd == BIO_WRITE) {
1439204076Spjd			mtx_lock(&res->hr_amp_lock);
1440204076Spjd			activemap_write_complete(res->hr_amp,
1441204076Spjd			    ggio->gctl_offset, ggio->gctl_length);
1442204076Spjd			mtx_unlock(&res->hr_amp_lock);
1443204076Spjd		}
1444204076Spjd		if (ggio->gctl_cmd == BIO_WRITE) {
1445204076Spjd			/*
1446204076Spjd			 * Unlock range we locked.
1447204076Spjd			 */
1448204076Spjd			mtx_lock(&range_lock);
1449204076Spjd			rangelock_del(range_regular, ggio->gctl_offset,
1450204076Spjd			    ggio->gctl_length);
1451204076Spjd			if (range_sync_wait)
1452204076Spjd				cv_signal(&range_sync_cond);
1453204076Spjd			mtx_unlock(&range_lock);
1454204076Spjd			/*
1455204076Spjd			 * Bump local count if this is first write after
1456204076Spjd			 * connection failure with remote node.
1457204076Spjd			 */
1458204076Spjd			ncomp = 1;
1459204076Spjd			rw_rlock(&hio_remote_lock[ncomp]);
1460204076Spjd			if (!ISCONNECTED(res, ncomp)) {
1461204076Spjd				mtx_lock(&metadata_lock);
1462204076Spjd				if (res->hr_primary_localcnt ==
1463204076Spjd				    res->hr_secondary_remotecnt) {
1464204076Spjd					res->hr_primary_localcnt++;
1465204076Spjd					pjdlog_debug(1,
1466204076Spjd					    "Increasing localcnt to %ju.",
1467204076Spjd					    (uintmax_t)res->hr_primary_localcnt);
1468204076Spjd					(void)metadata_write(res);
1469204076Spjd				}
1470204076Spjd				mtx_unlock(&metadata_lock);
1471204076Spjd			}
1472204076Spjd			rw_unlock(&hio_remote_lock[ncomp]);
1473204076Spjd		}
1474204076Spjd		if (ioctl(res->hr_ggatefd, G_GATE_CMD_DONE, ggio) < 0)
1475204076Spjd			primary_exit(EX_OSERR, "G_GATE_CMD_DONE failed");
1476204076Spjd		pjdlog_debug(2,
1477204076Spjd		    "ggate_send: (%p) Moving request to the free queue.", hio);
1478204076Spjd		QUEUE_INSERT2(hio, free);
1479204076Spjd	}
1480204076Spjd	/* NOTREACHED */
1481204076Spjd	return (NULL);
1482204076Spjd}
1483204076Spjd
1484204076Spjd/*
1485204076Spjd * Thread synchronize local and remote components.
1486204076Spjd */
1487204076Spjdstatic void *
1488204076Spjdsync_thread(void *arg __unused)
1489204076Spjd{
1490204076Spjd	struct hast_resource *res = arg;
1491204076Spjd	struct hio *hio;
1492204076Spjd	struct g_gate_ctl_io *ggio;
1493204076Spjd	unsigned int ii, ncomp, ncomps;
1494204076Spjd	off_t offset, length, synced;
1495204076Spjd	bool dorewind;
1496204076Spjd	int syncext;
1497204076Spjd
1498204076Spjd	ncomps = HAST_NCOMPONENTS;
1499204076Spjd	dorewind = true;
1500211879Spjd	synced = -1;
1501204076Spjd
1502204076Spjd	for (;;) {
1503204076Spjd		mtx_lock(&sync_lock);
1504211879Spjd		if (synced == -1)
1505211879Spjd			synced = 0;
1506211879Spjd		else if (!sync_inprogress) {
1507211879Spjd			pjdlog_info("Synchronization interrupted. "
1508211879Spjd			    "%jd bytes synchronized so far.",
1509211879Spjd			    (intmax_t)synced);
1510211879Spjd		}
1511204076Spjd		while (!sync_inprogress) {
1512204076Spjd			dorewind = true;
1513204076Spjd			synced = 0;
1514204076Spjd			cv_wait(&sync_cond, &sync_lock);
1515204076Spjd		}
1516204076Spjd		mtx_unlock(&sync_lock);
1517204076Spjd		/*
1518204076Spjd		 * Obtain offset at which we should synchronize.
1519204076Spjd		 * Rewind synchronization if needed.
1520204076Spjd		 */
1521204076Spjd		mtx_lock(&res->hr_amp_lock);
1522204076Spjd		if (dorewind)
1523204076Spjd			activemap_sync_rewind(res->hr_amp);
1524204076Spjd		offset = activemap_sync_offset(res->hr_amp, &length, &syncext);
1525204076Spjd		if (syncext != -1) {
1526204076Spjd			/*
1527204076Spjd			 * We synchronized entire syncext extent, we can mark
1528204076Spjd			 * it as clean now.
1529204076Spjd			 */
1530204076Spjd			if (activemap_extent_complete(res->hr_amp, syncext))
1531204076Spjd				(void)hast_activemap_flush(res);
1532204076Spjd		}
1533204076Spjd		mtx_unlock(&res->hr_amp_lock);
1534204076Spjd		if (dorewind) {
1535204076Spjd			dorewind = false;
1536204076Spjd			if (offset < 0)
1537204076Spjd				pjdlog_info("Nodes are in sync.");
1538204076Spjd			else {
1539204076Spjd				pjdlog_info("Synchronization started. %ju bytes to go.",
1540204076Spjd				    (uintmax_t)(res->hr_extentsize *
1541204076Spjd				    activemap_ndirty(res->hr_amp)));
1542204076Spjd			}
1543204076Spjd		}
1544204076Spjd		if (offset < 0) {
1545211878Spjd			sync_stop();
1546204076Spjd			pjdlog_debug(1, "Nothing to synchronize.");
1547204076Spjd			/*
1548204076Spjd			 * Synchronization complete, make both localcnt and
1549204076Spjd			 * remotecnt equal.
1550204076Spjd			 */
1551204076Spjd			ncomp = 1;
1552204076Spjd			rw_rlock(&hio_remote_lock[ncomp]);
1553204076Spjd			if (ISCONNECTED(res, ncomp)) {
1554204076Spjd				if (synced > 0) {
1555204076Spjd					pjdlog_info("Synchronization complete. "
1556204076Spjd					    "%jd bytes synchronized.",
1557204076Spjd					    (intmax_t)synced);
1558204076Spjd				}
1559204076Spjd				mtx_lock(&metadata_lock);
1560204076Spjd				res->hr_syncsrc = HAST_SYNCSRC_UNDEF;
1561204076Spjd				res->hr_primary_localcnt =
1562204076Spjd				    res->hr_secondary_localcnt;
1563204076Spjd				res->hr_primary_remotecnt =
1564204076Spjd				    res->hr_secondary_remotecnt;
1565204076Spjd				pjdlog_debug(1,
1566204076Spjd				    "Setting localcnt to %ju and remotecnt to %ju.",
1567204076Spjd				    (uintmax_t)res->hr_primary_localcnt,
1568204076Spjd				    (uintmax_t)res->hr_secondary_localcnt);
1569204076Spjd				(void)metadata_write(res);
1570204076Spjd				mtx_unlock(&metadata_lock);
1571204076Spjd			}
1572204076Spjd			rw_unlock(&hio_remote_lock[ncomp]);
1573204076Spjd			continue;
1574204076Spjd		}
1575204076Spjd		pjdlog_debug(2, "sync: Taking free request.");
1576204076Spjd		QUEUE_TAKE2(hio, free);
1577204076Spjd		pjdlog_debug(2, "sync: (%p) Got free request.", hio);
1578204076Spjd		/*
1579204076Spjd		 * Lock the range we are going to synchronize. We don't want
1580204076Spjd		 * race where someone writes between our read and write.
1581204076Spjd		 */
1582204076Spjd		for (;;) {
1583204076Spjd			mtx_lock(&range_lock);
1584204076Spjd			if (rangelock_islocked(range_regular, offset, length)) {
1585204076Spjd				pjdlog_debug(2,
1586204076Spjd				    "sync: Range offset=%jd length=%jd locked.",
1587204076Spjd				    (intmax_t)offset, (intmax_t)length);
1588204076Spjd				range_sync_wait = true;
1589204076Spjd				cv_wait(&range_sync_cond, &range_lock);
1590204076Spjd				range_sync_wait = false;
1591204076Spjd				mtx_unlock(&range_lock);
1592204076Spjd				continue;
1593204076Spjd			}
1594204076Spjd			if (rangelock_add(range_sync, offset, length) < 0) {
1595204076Spjd				mtx_unlock(&range_lock);
1596204076Spjd				pjdlog_debug(2,
1597204076Spjd				    "sync: Range offset=%jd length=%jd is already locked, waiting.",
1598204076Spjd				    (intmax_t)offset, (intmax_t)length);
1599204076Spjd				sleep(1);
1600204076Spjd				continue;
1601204076Spjd			}
1602204076Spjd			mtx_unlock(&range_lock);
1603204076Spjd			break;
1604204076Spjd		}
1605204076Spjd		/*
1606204076Spjd		 * First read the data from synchronization source.
1607204076Spjd		 */
1608204076Spjd		SYNCREQ(hio);
1609204076Spjd		ggio = &hio->hio_ggio;
1610204076Spjd		ggio->gctl_cmd = BIO_READ;
1611204076Spjd		ggio->gctl_offset = offset;
1612204076Spjd		ggio->gctl_length = length;
1613204076Spjd		ggio->gctl_error = 0;
1614204076Spjd		for (ii = 0; ii < ncomps; ii++)
1615204076Spjd			hio->hio_errors[ii] = EINVAL;
1616204076Spjd		reqlog(LOG_DEBUG, 2, ggio, "sync: (%p) Sending sync request: ",
1617204076Spjd		    hio);
1618204076Spjd		pjdlog_debug(2, "sync: (%p) Moving request to the send queue.",
1619204076Spjd		    hio);
1620204076Spjd		mtx_lock(&metadata_lock);
1621204076Spjd		if (res->hr_syncsrc == HAST_SYNCSRC_PRIMARY) {
1622204076Spjd			/*
1623204076Spjd			 * This range is up-to-date on local component,
1624204076Spjd			 * so handle request locally.
1625204076Spjd			 */
1626204076Spjd			 /* Local component is 0 for now. */
1627204076Spjd			ncomp = 0;
1628204076Spjd		} else /* if (res->hr_syncsrc == HAST_SYNCSRC_SECONDARY) */ {
1629204076Spjd			assert(res->hr_syncsrc == HAST_SYNCSRC_SECONDARY);
1630204076Spjd			/*
1631204076Spjd			 * This range is out-of-date on local component,
1632204076Spjd			 * so send request to the remote node.
1633204076Spjd			 */
1634204076Spjd			 /* Remote component is 1 for now. */
1635204076Spjd			ncomp = 1;
1636204076Spjd		}
1637204076Spjd		mtx_unlock(&metadata_lock);
1638204076Spjd		refcount_init(&hio->hio_countdown, 1);
1639204076Spjd		QUEUE_INSERT1(hio, send, ncomp);
1640204076Spjd
1641204076Spjd		/*
1642204076Spjd		 * Let's wait for READ to finish.
1643204076Spjd		 */
1644204076Spjd		mtx_lock(&sync_lock);
1645204076Spjd		while (!ISSYNCREQDONE(hio))
1646204076Spjd			cv_wait(&sync_cond, &sync_lock);
1647204076Spjd		mtx_unlock(&sync_lock);
1648204076Spjd
1649204076Spjd		if (hio->hio_errors[ncomp] != 0) {
1650204076Spjd			pjdlog_error("Unable to read synchronization data: %s.",
1651204076Spjd			    strerror(hio->hio_errors[ncomp]));
1652204076Spjd			goto free_queue;
1653204076Spjd		}
1654204076Spjd
1655204076Spjd		/*
1656204076Spjd		 * We read the data from synchronization source, now write it
1657204076Spjd		 * to synchronization target.
1658204076Spjd		 */
1659204076Spjd		SYNCREQ(hio);
1660204076Spjd		ggio->gctl_cmd = BIO_WRITE;
1661204076Spjd		for (ii = 0; ii < ncomps; ii++)
1662204076Spjd			hio->hio_errors[ii] = EINVAL;
1663204076Spjd		reqlog(LOG_DEBUG, 2, ggio, "sync: (%p) Sending sync request: ",
1664204076Spjd		    hio);
1665204076Spjd		pjdlog_debug(2, "sync: (%p) Moving request to the send queue.",
1666204076Spjd		    hio);
1667204076Spjd		mtx_lock(&metadata_lock);
1668204076Spjd		if (res->hr_syncsrc == HAST_SYNCSRC_PRIMARY) {
1669204076Spjd			/*
1670204076Spjd			 * This range is up-to-date on local component,
1671204076Spjd			 * so we update remote component.
1672204076Spjd			 */
1673204076Spjd			 /* Remote component is 1 for now. */
1674204076Spjd			ncomp = 1;
1675204076Spjd		} else /* if (res->hr_syncsrc == HAST_SYNCSRC_SECONDARY) */ {
1676204076Spjd			assert(res->hr_syncsrc == HAST_SYNCSRC_SECONDARY);
1677204076Spjd			/*
1678204076Spjd			 * This range is out-of-date on local component,
1679204076Spjd			 * so we update it.
1680204076Spjd			 */
1681204076Spjd			 /* Local component is 0 for now. */
1682204076Spjd			ncomp = 0;
1683204076Spjd		}
1684204076Spjd		mtx_unlock(&metadata_lock);
1685204076Spjd
1686204076Spjd		pjdlog_debug(2, "sync: (%p) Moving request to the send queues.",
1687204076Spjd		    hio);
1688204076Spjd		refcount_init(&hio->hio_countdown, 1);
1689204076Spjd		QUEUE_INSERT1(hio, send, ncomp);
1690204076Spjd
1691204076Spjd		/*
1692204076Spjd		 * Let's wait for WRITE 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 write synchronization data: %s.",
1701204076Spjd			    strerror(hio->hio_errors[ncomp]));
1702204076Spjd			goto free_queue;
1703204076Spjd		}
1704211880Spjd
1705211880Spjd		synced += length;
1706204076Spjdfree_queue:
1707204076Spjd		mtx_lock(&range_lock);
1708204076Spjd		rangelock_del(range_sync, offset, length);
1709204076Spjd		if (range_regular_wait)
1710204076Spjd			cv_signal(&range_regular_cond);
1711204076Spjd		mtx_unlock(&range_lock);
1712204076Spjd		pjdlog_debug(2, "sync: (%p) Moving request to the free queue.",
1713204076Spjd		    hio);
1714204076Spjd		QUEUE_INSERT2(hio, free);
1715204076Spjd	}
1716204076Spjd	/* NOTREACHED */
1717204076Spjd	return (NULL);
1718204076Spjd}
1719204076Spjd
1720204076Spjdstatic void
1721204076Spjdsighandler(int sig)
1722204076Spjd{
1723204076Spjd	bool unlock;
1724204076Spjd
1725204076Spjd	switch (sig) {
1726204076Spjd	case SIGINT:
1727204076Spjd	case SIGTERM:
1728204076Spjd		sigexit_received = true;
1729204076Spjd		break;
1730210886Spjd	case SIGHUP:
1731210886Spjd		sighup_received = true;
1732210886Spjd		break;
1733204076Spjd	default:
1734204076Spjd		assert(!"invalid condition");
1735204076Spjd	}
1736204076Spjd	/*
1737204076Spjd	 * XXX: Racy, but if we cannot obtain hio_guard_lock here, we don't
1738204076Spjd	 * want to risk deadlock.
1739204076Spjd	 */
1740204076Spjd	unlock = mtx_trylock(&hio_guard_lock);
1741204076Spjd	cv_signal(&hio_guard_cond);
1742204076Spjd	if (unlock)
1743204076Spjd		mtx_unlock(&hio_guard_lock);
1744204076Spjd}
1745204076Spjd
1746210886Spjdstatic void
1747210886Spjdconfig_reload(void)
1748210886Spjd{
1749210886Spjd	struct hastd_config *newcfg;
1750210886Spjd	struct hast_resource *res;
1751210886Spjd	unsigned int ii, ncomps;
1752210886Spjd	int modified;
1753210886Spjd
1754210886Spjd	pjdlog_info("Reloading configuration...");
1755210886Spjd
1756210886Spjd	ncomps = HAST_NCOMPONENTS;
1757210886Spjd
1758210886Spjd	newcfg = yy_config_parse(cfgpath, false);
1759210886Spjd	if (newcfg == NULL)
1760210886Spjd		goto failed;
1761210886Spjd
1762210886Spjd	TAILQ_FOREACH(res, &newcfg->hc_resources, hr_next) {
1763210886Spjd		if (strcmp(res->hr_name, gres->hr_name) == 0)
1764210886Spjd			break;
1765210886Spjd	}
1766210886Spjd	/*
1767210886Spjd	 * If resource was removed from the configuration file, resource
1768210886Spjd	 * name, provider name or path to local component was modified we
1769210886Spjd	 * shouldn't be here. This means that someone modified configuration
1770210886Spjd	 * file and send SIGHUP to us instead of main hastd process.
1771210886Spjd	 * Log advice and ignore the signal.
1772210886Spjd	 */
1773210886Spjd	if (res == NULL || strcmp(gres->hr_name, res->hr_name) != 0 ||
1774210886Spjd	    strcmp(gres->hr_provname, res->hr_provname) != 0 ||
1775210886Spjd	    strcmp(gres->hr_localpath, res->hr_localpath) != 0) {
1776210886Spjd		pjdlog_warning("To reload configuration send SIGHUP to the main hastd process (pid %u).",
1777210886Spjd		    (unsigned int)getppid());
1778210886Spjd		goto failed;
1779210886Spjd	}
1780210886Spjd
1781210886Spjd#define MODIFIED_REMOTEADDR	0x1
1782210886Spjd#define MODIFIED_REPLICATION	0x2
1783210886Spjd#define MODIFIED_TIMEOUT	0x4
1784210886Spjd	modified = 0;
1785210886Spjd	if (strcmp(gres->hr_remoteaddr, res->hr_remoteaddr) != 0) {
1786210886Spjd		/*
1787210886Spjd		 * Don't copy res->hr_remoteaddr to gres just yet.
1788210886Spjd		 * We want remote_close() to log disconnect from the old
1789210886Spjd		 * addresses, not from the new ones.
1790210886Spjd		 */
1791210886Spjd		modified |= MODIFIED_REMOTEADDR;
1792210886Spjd	}
1793210886Spjd	if (gres->hr_replication != res->hr_replication) {
1794210886Spjd		gres->hr_replication = res->hr_replication;
1795210886Spjd		modified |= MODIFIED_REPLICATION;
1796210886Spjd	}
1797210886Spjd	if (gres->hr_timeout != res->hr_timeout) {
1798210886Spjd		gres->hr_timeout = res->hr_timeout;
1799210886Spjd		modified |= MODIFIED_TIMEOUT;
1800210886Spjd	}
1801210886Spjd	/*
1802210886Spjd	 * If only timeout was modified we only need to change it without
1803210886Spjd	 * reconnecting.
1804210886Spjd	 */
1805210886Spjd	if (modified == MODIFIED_TIMEOUT) {
1806210886Spjd		for (ii = 0; ii < ncomps; ii++) {
1807210886Spjd			if (!ISREMOTE(ii))
1808210886Spjd				continue;
1809210886Spjd			rw_rlock(&hio_remote_lock[ii]);
1810210886Spjd			if (!ISCONNECTED(gres, ii)) {
1811210886Spjd				rw_unlock(&hio_remote_lock[ii]);
1812210886Spjd				continue;
1813210886Spjd			}
1814210886Spjd			rw_unlock(&hio_remote_lock[ii]);
1815210886Spjd			if (proto_timeout(gres->hr_remotein,
1816210886Spjd			    gres->hr_timeout) < 0) {
1817210886Spjd				pjdlog_errno(LOG_WARNING,
1818210886Spjd				    "Unable to set connection timeout");
1819210886Spjd			}
1820210886Spjd			if (proto_timeout(gres->hr_remoteout,
1821210886Spjd			    gres->hr_timeout) < 0) {
1822210886Spjd				pjdlog_errno(LOG_WARNING,
1823210886Spjd				    "Unable to set connection timeout");
1824210886Spjd			}
1825210886Spjd		}
1826210886Spjd	} else {
1827210886Spjd		for (ii = 0; ii < ncomps; ii++) {
1828210886Spjd			if (!ISREMOTE(ii))
1829210886Spjd				continue;
1830210886Spjd			remote_close(gres, ii);
1831210886Spjd		}
1832210886Spjd		if (modified & MODIFIED_REMOTEADDR) {
1833210886Spjd			strlcpy(gres->hr_remoteaddr, res->hr_remoteaddr,
1834210886Spjd			    sizeof(gres->hr_remoteaddr));
1835210886Spjd		}
1836210886Spjd	}
1837210886Spjd#undef	MODIFIED_REMOTEADDR
1838210886Spjd#undef	MODIFIED_REPLICATION
1839210886Spjd#undef	MODIFIED_TIMEOUT
1840210886Spjd
1841210886Spjd	pjdlog_info("Configuration reloaded successfully.");
1842210886Spjd	return;
1843210886Spjdfailed:
1844210886Spjd	if (newcfg != NULL) {
1845210886Spjd		if (newcfg->hc_controlconn != NULL)
1846210886Spjd			proto_close(newcfg->hc_controlconn);
1847210886Spjd		if (newcfg->hc_listenconn != NULL)
1848210886Spjd			proto_close(newcfg->hc_listenconn);
1849210886Spjd		yy_config_free(newcfg);
1850210886Spjd	}
1851210886Spjd	pjdlog_warning("Configuration not reloaded.");
1852210886Spjd}
1853210886Spjd
1854204076Spjd/*
1855204076Spjd * Thread guards remote connections and reconnects when needed, handles
1856204076Spjd * signals, etc.
1857204076Spjd */
1858204076Spjdstatic void *
1859204076Spjdguard_thread(void *arg)
1860204076Spjd{
1861204076Spjd	struct hast_resource *res = arg;
1862205738Spjd	struct proto_conn *in, *out;
1863204076Spjd	unsigned int ii, ncomps;
1864204076Spjd	int timeout;
1865204076Spjd
1866204076Spjd	ncomps = HAST_NCOMPONENTS;
1867204076Spjd
1868204076Spjd	for (;;) {
1869204076Spjd		if (sigexit_received) {
1870204076Spjd			primary_exitx(EX_OK,
1871204076Spjd			    "Termination signal received, exiting.");
1872204076Spjd		}
1873210886Spjd		if (sighup_received) {
1874210886Spjd			sighup_received = false;
1875210886Spjd			config_reload();
1876210886Spjd		}
1877204076Spjd		/*
1878204076Spjd		 * If all the connection will be fine, we will sleep until
1879204076Spjd		 * someone wakes us up.
1880204076Spjd		 * If any of the connections will be broken and we won't be
1881204076Spjd		 * able to connect, we will sleep only for RECONNECT_SLEEP
1882204076Spjd		 * seconds so we can retry soon.
1883204076Spjd		 */
1884204076Spjd		timeout = 0;
1885204076Spjd		pjdlog_debug(2, "remote_guard: Checking connections.");
1886204076Spjd		mtx_lock(&hio_guard_lock);
1887204076Spjd		for (ii = 0; ii < ncomps; ii++) {
1888204076Spjd			if (!ISREMOTE(ii))
1889204076Spjd				continue;
1890204076Spjd			rw_rlock(&hio_remote_lock[ii]);
1891204076Spjd			if (ISCONNECTED(res, ii)) {
1892204076Spjd				assert(res->hr_remotein != NULL);
1893204076Spjd				assert(res->hr_remoteout != NULL);
1894204076Spjd				rw_unlock(&hio_remote_lock[ii]);
1895204076Spjd				pjdlog_debug(2,
1896204076Spjd				    "remote_guard: Connection to %s is ok.",
1897204076Spjd				    res->hr_remoteaddr);
1898210881Spjd			} else if (real_remote(res)) {
1899204076Spjd				assert(res->hr_remotein == NULL);
1900204076Spjd				assert(res->hr_remoteout == NULL);
1901204076Spjd				/*
1902204076Spjd				 * Upgrade the lock. It doesn't have to be
1903204076Spjd				 * atomic as no other thread can change
1904204076Spjd				 * connection status from disconnected to
1905204076Spjd				 * connected.
1906204076Spjd				 */
1907204076Spjd				rw_unlock(&hio_remote_lock[ii]);
1908204076Spjd				pjdlog_debug(2,
1909204076Spjd				    "remote_guard: Reconnecting to %s.",
1910204076Spjd				    res->hr_remoteaddr);
1911205738Spjd				in = out = NULL;
1912205738Spjd				if (init_remote(res, &in, &out)) {
1913205738Spjd					rw_wlock(&hio_remote_lock[ii]);
1914205738Spjd					assert(res->hr_remotein == NULL);
1915205738Spjd					assert(res->hr_remoteout == NULL);
1916205738Spjd					assert(in != NULL && out != NULL);
1917205738Spjd					res->hr_remotein = in;
1918205738Spjd					res->hr_remoteout = out;
1919205738Spjd					rw_unlock(&hio_remote_lock[ii]);
1920204076Spjd					pjdlog_info("Successfully reconnected to %s.",
1921204076Spjd					    res->hr_remoteaddr);
1922205738Spjd					sync_start();
1923204076Spjd				} else {
1924204076Spjd					/* Both connections should be NULL. */
1925204076Spjd					assert(res->hr_remotein == NULL);
1926204076Spjd					assert(res->hr_remoteout == NULL);
1927205738Spjd					assert(in == NULL && out == NULL);
1928204076Spjd					pjdlog_debug(2,
1929204076Spjd					    "remote_guard: Reconnect to %s failed.",
1930204076Spjd					    res->hr_remoteaddr);
1931204076Spjd					timeout = RECONNECT_SLEEP;
1932204076Spjd				}
1933210881Spjd			} else {
1934210881Spjd				rw_unlock(&hio_remote_lock[ii]);
1935204076Spjd			}
1936204076Spjd		}
1937204076Spjd		(void)cv_timedwait(&hio_guard_cond, &hio_guard_lock, timeout);
1938204076Spjd		mtx_unlock(&hio_guard_lock);
1939204076Spjd	}
1940204076Spjd	/* NOTREACHED */
1941204076Spjd	return (NULL);
1942204076Spjd}
1943