primary.c revision 211897
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 211897 2010-08-27 21:20:32Z 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"
63211886Spjd#include "hooks.h"
64204076Spjd#include "metadata.h"
65204076Spjd#include "proto.h"
66204076Spjd#include "pjdlog.h"
67204076Spjd#include "subr.h"
68204076Spjd#include "synch.h"
69204076Spjd
70210886Spjd/* The is only one remote component for now. */
71210886Spjd#define	ISREMOTE(no)	((no) == 1)
72210886Spjd
73204076Spjdstruct hio {
74204076Spjd	/*
75204076Spjd	 * Number of components we are still waiting for.
76204076Spjd	 * When this field goes to 0, we can send the request back to the
77204076Spjd	 * kernel. Each component has to decrease this counter by one
78204076Spjd	 * even on failure.
79204076Spjd	 */
80204076Spjd	unsigned int		 hio_countdown;
81204076Spjd	/*
82204076Spjd	 * Each component has a place to store its own error.
83204076Spjd	 * Once the request is handled by all components we can decide if the
84204076Spjd	 * request overall is successful or not.
85204076Spjd	 */
86204076Spjd	int			*hio_errors;
87204076Spjd	/*
88204076Spjd	 * Structure used to comunicate with GEOM Gate class.
89204076Spjd	 */
90204076Spjd	struct g_gate_ctl_io	 hio_ggio;
91204076Spjd	TAILQ_ENTRY(hio)	*hio_next;
92204076Spjd};
93204076Spjd#define	hio_free_next	hio_next[0]
94204076Spjd#define	hio_done_next	hio_next[0]
95204076Spjd
96204076Spjd/*
97204076Spjd * Free list holds unused structures. When free list is empty, we have to wait
98204076Spjd * until some in-progress requests are freed.
99204076Spjd */
100204076Spjdstatic TAILQ_HEAD(, hio) hio_free_list;
101204076Spjdstatic pthread_mutex_t hio_free_list_lock;
102204076Spjdstatic pthread_cond_t hio_free_list_cond;
103204076Spjd/*
104204076Spjd * There is one send list for every component. One requests is placed on all
105204076Spjd * send lists - each component gets the same request, but each component is
106204076Spjd * responsible for managing his own send list.
107204076Spjd */
108204076Spjdstatic TAILQ_HEAD(, hio) *hio_send_list;
109204076Spjdstatic pthread_mutex_t *hio_send_list_lock;
110204076Spjdstatic pthread_cond_t *hio_send_list_cond;
111204076Spjd/*
112204076Spjd * There is one recv list for every component, although local components don't
113204076Spjd * use recv lists as local requests are done synchronously.
114204076Spjd */
115204076Spjdstatic TAILQ_HEAD(, hio) *hio_recv_list;
116204076Spjdstatic pthread_mutex_t *hio_recv_list_lock;
117204076Spjdstatic pthread_cond_t *hio_recv_list_cond;
118204076Spjd/*
119204076Spjd * Request is placed on done list by the slowest component (the one that
120204076Spjd * decreased hio_countdown from 1 to 0).
121204076Spjd */
122204076Spjdstatic TAILQ_HEAD(, hio) hio_done_list;
123204076Spjdstatic pthread_mutex_t hio_done_list_lock;
124204076Spjdstatic pthread_cond_t hio_done_list_cond;
125204076Spjd/*
126204076Spjd * Structure below are for interaction with sync thread.
127204076Spjd */
128204076Spjdstatic bool sync_inprogress;
129204076Spjdstatic pthread_mutex_t sync_lock;
130204076Spjdstatic pthread_cond_t sync_cond;
131204076Spjd/*
132204076Spjd * The lock below allows to synchornize access to remote connections.
133204076Spjd */
134204076Spjdstatic pthread_rwlock_t *hio_remote_lock;
135204076Spjdstatic pthread_mutex_t hio_guard_lock;
136204076Spjdstatic pthread_cond_t hio_guard_cond;
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/*
155211882Spjd * Number of seconds to sleep between keepalive packets.
156204076Spjd */
157211882Spjd#define	KEEPALIVE_SLEEP		10
158211882Spjd/*
159211882Spjd * Number of seconds to sleep between reconnect retries.
160211882Spjd */
161204076Spjd#define	RECONNECT_SLEEP		5
162204076Spjd
163204076Spjd#define	ISCONNECTED(res, no)	\
164204076Spjd	((res)->hr_remotein != NULL && (res)->hr_remoteout != NULL)
165204076Spjd
166204076Spjd#define	QUEUE_INSERT1(hio, name, ncomp)	do {				\
167204076Spjd	bool _wakeup;							\
168204076Spjd									\
169204076Spjd	mtx_lock(&hio_##name##_list_lock[(ncomp)]);			\
170204076Spjd	_wakeup = TAILQ_EMPTY(&hio_##name##_list[(ncomp)]);		\
171204076Spjd	TAILQ_INSERT_TAIL(&hio_##name##_list[(ncomp)], (hio),		\
172204076Spjd	    hio_next[(ncomp)]);						\
173204076Spjd	mtx_unlock(&hio_##name##_list_lock[ncomp]);			\
174204076Spjd	if (_wakeup)							\
175204076Spjd		cv_signal(&hio_##name##_list_cond[(ncomp)]);		\
176204076Spjd} while (0)
177204076Spjd#define	QUEUE_INSERT2(hio, name)	do {				\
178204076Spjd	bool _wakeup;							\
179204076Spjd									\
180204076Spjd	mtx_lock(&hio_##name##_list_lock);				\
181204076Spjd	_wakeup = TAILQ_EMPTY(&hio_##name##_list);			\
182204076Spjd	TAILQ_INSERT_TAIL(&hio_##name##_list, (hio), hio_##name##_next);\
183204076Spjd	mtx_unlock(&hio_##name##_list_lock);				\
184204076Spjd	if (_wakeup)							\
185204076Spjd		cv_signal(&hio_##name##_list_cond);			\
186204076Spjd} while (0)
187204076Spjd#define	QUEUE_TAKE1(hio, name, ncomp)	do {				\
188204076Spjd	mtx_lock(&hio_##name##_list_lock[(ncomp)]);			\
189204076Spjd	while (((hio) = TAILQ_FIRST(&hio_##name##_list[(ncomp)])) == NULL) { \
190204076Spjd		cv_wait(&hio_##name##_list_cond[(ncomp)],		\
191204076Spjd		    &hio_##name##_list_lock[(ncomp)]);			\
192204076Spjd	}								\
193204076Spjd	TAILQ_REMOVE(&hio_##name##_list[(ncomp)], (hio),		\
194204076Spjd	    hio_next[(ncomp)]);						\
195204076Spjd	mtx_unlock(&hio_##name##_list_lock[(ncomp)]);			\
196204076Spjd} while (0)
197204076Spjd#define	QUEUE_TAKE2(hio, name)	do {					\
198204076Spjd	mtx_lock(&hio_##name##_list_lock);				\
199204076Spjd	while (((hio) = TAILQ_FIRST(&hio_##name##_list)) == NULL) {	\
200204076Spjd		cv_wait(&hio_##name##_list_cond,			\
201204076Spjd		    &hio_##name##_list_lock);				\
202204076Spjd	}								\
203204076Spjd	TAILQ_REMOVE(&hio_##name##_list, (hio), hio_##name##_next);	\
204204076Spjd	mtx_unlock(&hio_##name##_list_lock);				\
205204076Spjd} while (0)
206204076Spjd
207209183Spjd#define	SYNCREQ(hio)		do {					\
208209183Spjd	(hio)->hio_ggio.gctl_unit = -1;					\
209209183Spjd	(hio)->hio_ggio.gctl_seq = 1;					\
210209183Spjd} while (0)
211204076Spjd#define	ISSYNCREQ(hio)		((hio)->hio_ggio.gctl_unit == -1)
212204076Spjd#define	SYNCREQDONE(hio)	do { (hio)->hio_ggio.gctl_unit = -2; } while (0)
213204076Spjd#define	ISSYNCREQDONE(hio)	((hio)->hio_ggio.gctl_unit == -2)
214204076Spjd
215204076Spjdstatic struct hast_resource *gres;
216204076Spjd
217204076Spjdstatic pthread_mutex_t range_lock;
218204076Spjdstatic struct rangelocks *range_regular;
219204076Spjdstatic bool range_regular_wait;
220204076Spjdstatic pthread_cond_t range_regular_cond;
221204076Spjdstatic struct rangelocks *range_sync;
222204076Spjdstatic bool range_sync_wait;
223204076Spjdstatic pthread_cond_t range_sync_cond;
224204076Spjd
225204076Spjdstatic void *ggate_recv_thread(void *arg);
226204076Spjdstatic void *local_send_thread(void *arg);
227204076Spjdstatic void *remote_send_thread(void *arg);
228204076Spjdstatic void *remote_recv_thread(void *arg);
229204076Spjdstatic void *ggate_send_thread(void *arg);
230204076Spjdstatic void *sync_thread(void *arg);
231204076Spjdstatic void *guard_thread(void *arg);
232204076Spjd
233204076Spjdstatic void sighandler(int sig);
234204076Spjd
235204076Spjdstatic void
236204076Spjdcleanup(struct hast_resource *res)
237204076Spjd{
238204076Spjd	int rerrno;
239204076Spjd
240204076Spjd	/* Remember errno. */
241204076Spjd	rerrno = errno;
242204076Spjd
243204076Spjd	/*
244204076Spjd	 * Close descriptor to /dev/hast/<name>
245204076Spjd	 * to work-around race in the kernel.
246204076Spjd	 */
247204076Spjd	close(res->hr_localfd);
248204076Spjd
249204076Spjd	/* Destroy ggate provider if we created one. */
250204076Spjd	if (res->hr_ggateunit >= 0) {
251204076Spjd		struct g_gate_ctl_destroy ggiod;
252204076Spjd
253204076Spjd		ggiod.gctl_version = G_GATE_VERSION;
254204076Spjd		ggiod.gctl_unit = res->hr_ggateunit;
255204076Spjd		ggiod.gctl_force = 1;
256204076Spjd		if (ioctl(res->hr_ggatefd, G_GATE_CMD_DESTROY, &ggiod) < 0) {
257204076Spjd			pjdlog_warning("Unable to destroy hast/%s device",
258204076Spjd			    res->hr_provname);
259204076Spjd		}
260204076Spjd		res->hr_ggateunit = -1;
261204076Spjd	}
262204076Spjd
263204076Spjd	/* Restore errno. */
264204076Spjd	errno = rerrno;
265204076Spjd}
266204076Spjd
267204076Spjdstatic void
268204076Spjdprimary_exit(int exitcode, const char *fmt, ...)
269204076Spjd{
270204076Spjd	va_list ap;
271204076Spjd
272204076Spjd	assert(exitcode != EX_OK);
273204076Spjd	va_start(ap, fmt);
274204076Spjd	pjdlogv_errno(LOG_ERR, fmt, ap);
275204076Spjd	va_end(ap);
276204076Spjd	cleanup(gres);
277204076Spjd	exit(exitcode);
278204076Spjd}
279204076Spjd
280204076Spjdstatic void
281204076Spjdprimary_exitx(int exitcode, const char *fmt, ...)
282204076Spjd{
283204076Spjd	va_list ap;
284204076Spjd
285204076Spjd	va_start(ap, fmt);
286204076Spjd	pjdlogv(exitcode == EX_OK ? LOG_INFO : LOG_ERR, fmt, ap);
287204076Spjd	va_end(ap);
288204076Spjd	cleanup(gres);
289204076Spjd	exit(exitcode);
290204076Spjd}
291204076Spjd
292204076Spjdstatic int
293204076Spjdhast_activemap_flush(struct hast_resource *res)
294204076Spjd{
295204076Spjd	const unsigned char *buf;
296204076Spjd	size_t size;
297204076Spjd
298204076Spjd	buf = activemap_bitmap(res->hr_amp, &size);
299204076Spjd	assert(buf != NULL);
300204076Spjd	assert((size % res->hr_local_sectorsize) == 0);
301204076Spjd	if (pwrite(res->hr_localfd, buf, size, METADATA_SIZE) !=
302204076Spjd	    (ssize_t)size) {
303204076Spjd		KEEP_ERRNO(pjdlog_errno(LOG_ERR,
304204076Spjd		    "Unable to flush activemap to disk"));
305204076Spjd		return (-1);
306204076Spjd	}
307204076Spjd	return (0);
308204076Spjd}
309204076Spjd
310210881Spjdstatic bool
311210881Spjdreal_remote(const struct hast_resource *res)
312210881Spjd{
313210881Spjd
314210881Spjd	return (strcmp(res->hr_remoteaddr, "none") != 0);
315210881Spjd}
316210881Spjd
317204076Spjdstatic void
318204076Spjdinit_environment(struct hast_resource *res __unused)
319204076Spjd{
320204076Spjd	struct hio *hio;
321204076Spjd	unsigned int ii, ncomps;
322204076Spjd
323204076Spjd	/*
324204076Spjd	 * In the future it might be per-resource value.
325204076Spjd	 */
326204076Spjd	ncomps = HAST_NCOMPONENTS;
327204076Spjd
328204076Spjd	/*
329204076Spjd	 * Allocate memory needed by lists.
330204076Spjd	 */
331204076Spjd	hio_send_list = malloc(sizeof(hio_send_list[0]) * ncomps);
332204076Spjd	if (hio_send_list == NULL) {
333204076Spjd		primary_exitx(EX_TEMPFAIL,
334204076Spjd		    "Unable to allocate %zu bytes of memory for send lists.",
335204076Spjd		    sizeof(hio_send_list[0]) * ncomps);
336204076Spjd	}
337204076Spjd	hio_send_list_lock = malloc(sizeof(hio_send_list_lock[0]) * ncomps);
338204076Spjd	if (hio_send_list_lock == NULL) {
339204076Spjd		primary_exitx(EX_TEMPFAIL,
340204076Spjd		    "Unable to allocate %zu bytes of memory for send list locks.",
341204076Spjd		    sizeof(hio_send_list_lock[0]) * ncomps);
342204076Spjd	}
343204076Spjd	hio_send_list_cond = malloc(sizeof(hio_send_list_cond[0]) * ncomps);
344204076Spjd	if (hio_send_list_cond == NULL) {
345204076Spjd		primary_exitx(EX_TEMPFAIL,
346204076Spjd		    "Unable to allocate %zu bytes of memory for send list condition variables.",
347204076Spjd		    sizeof(hio_send_list_cond[0]) * ncomps);
348204076Spjd	}
349204076Spjd	hio_recv_list = malloc(sizeof(hio_recv_list[0]) * ncomps);
350204076Spjd	if (hio_recv_list == NULL) {
351204076Spjd		primary_exitx(EX_TEMPFAIL,
352204076Spjd		    "Unable to allocate %zu bytes of memory for recv lists.",
353204076Spjd		    sizeof(hio_recv_list[0]) * ncomps);
354204076Spjd	}
355204076Spjd	hio_recv_list_lock = malloc(sizeof(hio_recv_list_lock[0]) * ncomps);
356204076Spjd	if (hio_recv_list_lock == NULL) {
357204076Spjd		primary_exitx(EX_TEMPFAIL,
358204076Spjd		    "Unable to allocate %zu bytes of memory for recv list locks.",
359204076Spjd		    sizeof(hio_recv_list_lock[0]) * ncomps);
360204076Spjd	}
361204076Spjd	hio_recv_list_cond = malloc(sizeof(hio_recv_list_cond[0]) * ncomps);
362204076Spjd	if (hio_recv_list_cond == NULL) {
363204076Spjd		primary_exitx(EX_TEMPFAIL,
364204076Spjd		    "Unable to allocate %zu bytes of memory for recv list condition variables.",
365204076Spjd		    sizeof(hio_recv_list_cond[0]) * ncomps);
366204076Spjd	}
367204076Spjd	hio_remote_lock = malloc(sizeof(hio_remote_lock[0]) * ncomps);
368204076Spjd	if (hio_remote_lock == NULL) {
369204076Spjd		primary_exitx(EX_TEMPFAIL,
370204076Spjd		    "Unable to allocate %zu bytes of memory for remote connections locks.",
371204076Spjd		    sizeof(hio_remote_lock[0]) * ncomps);
372204076Spjd	}
373204076Spjd
374204076Spjd	/*
375204076Spjd	 * Initialize lists, their locks and theirs condition variables.
376204076Spjd	 */
377204076Spjd	TAILQ_INIT(&hio_free_list);
378204076Spjd	mtx_init(&hio_free_list_lock);
379204076Spjd	cv_init(&hio_free_list_cond);
380204076Spjd	for (ii = 0; ii < HAST_NCOMPONENTS; ii++) {
381204076Spjd		TAILQ_INIT(&hio_send_list[ii]);
382204076Spjd		mtx_init(&hio_send_list_lock[ii]);
383204076Spjd		cv_init(&hio_send_list_cond[ii]);
384204076Spjd		TAILQ_INIT(&hio_recv_list[ii]);
385204076Spjd		mtx_init(&hio_recv_list_lock[ii]);
386204076Spjd		cv_init(&hio_recv_list_cond[ii]);
387204076Spjd		rw_init(&hio_remote_lock[ii]);
388204076Spjd	}
389204076Spjd	TAILQ_INIT(&hio_done_list);
390204076Spjd	mtx_init(&hio_done_list_lock);
391204076Spjd	cv_init(&hio_done_list_cond);
392204076Spjd	mtx_init(&hio_guard_lock);
393204076Spjd	cv_init(&hio_guard_cond);
394204076Spjd	mtx_init(&metadata_lock);
395204076Spjd
396204076Spjd	/*
397204076Spjd	 * Allocate requests pool and initialize requests.
398204076Spjd	 */
399204076Spjd	for (ii = 0; ii < HAST_HIO_MAX; ii++) {
400204076Spjd		hio = malloc(sizeof(*hio));
401204076Spjd		if (hio == NULL) {
402204076Spjd			primary_exitx(EX_TEMPFAIL,
403204076Spjd			    "Unable to allocate %zu bytes of memory for hio request.",
404204076Spjd			    sizeof(*hio));
405204076Spjd		}
406204076Spjd		hio->hio_countdown = 0;
407204076Spjd		hio->hio_errors = malloc(sizeof(hio->hio_errors[0]) * ncomps);
408204076Spjd		if (hio->hio_errors == NULL) {
409204076Spjd			primary_exitx(EX_TEMPFAIL,
410204076Spjd			    "Unable allocate %zu bytes of memory for hio errors.",
411204076Spjd			    sizeof(hio->hio_errors[0]) * ncomps);
412204076Spjd		}
413204076Spjd		hio->hio_next = malloc(sizeof(hio->hio_next[0]) * ncomps);
414204076Spjd		if (hio->hio_next == NULL) {
415204076Spjd			primary_exitx(EX_TEMPFAIL,
416204076Spjd			    "Unable allocate %zu bytes of memory for hio_next field.",
417204076Spjd			    sizeof(hio->hio_next[0]) * ncomps);
418204076Spjd		}
419204076Spjd		hio->hio_ggio.gctl_version = G_GATE_VERSION;
420204076Spjd		hio->hio_ggio.gctl_data = malloc(MAXPHYS);
421204076Spjd		if (hio->hio_ggio.gctl_data == NULL) {
422204076Spjd			primary_exitx(EX_TEMPFAIL,
423204076Spjd			    "Unable to allocate %zu bytes of memory for gctl_data.",
424204076Spjd			    MAXPHYS);
425204076Spjd		}
426204076Spjd		hio->hio_ggio.gctl_length = MAXPHYS;
427204076Spjd		hio->hio_ggio.gctl_error = 0;
428204076Spjd		TAILQ_INSERT_HEAD(&hio_free_list, hio, hio_free_next);
429204076Spjd	}
430204076Spjd
431204076Spjd	/*
432204076Spjd	 * Turn on signals handling.
433204076Spjd	 */
434204076Spjd	signal(SIGINT, sighandler);
435204076Spjd	signal(SIGTERM, sighandler);
436210886Spjd	signal(SIGHUP, sighandler);
437211886Spjd	signal(SIGCHLD, sighandler);
438204076Spjd}
439204076Spjd
440204076Spjdstatic void
441204076Spjdinit_local(struct hast_resource *res)
442204076Spjd{
443204076Spjd	unsigned char *buf;
444204076Spjd	size_t mapsize;
445204076Spjd
446204076Spjd	if (metadata_read(res, true) < 0)
447204076Spjd		exit(EX_NOINPUT);
448204076Spjd	mtx_init(&res->hr_amp_lock);
449204076Spjd	if (activemap_init(&res->hr_amp, res->hr_datasize, res->hr_extentsize,
450204076Spjd	    res->hr_local_sectorsize, res->hr_keepdirty) < 0) {
451204076Spjd		primary_exit(EX_TEMPFAIL, "Unable to create activemap");
452204076Spjd	}
453204076Spjd	mtx_init(&range_lock);
454204076Spjd	cv_init(&range_regular_cond);
455204076Spjd	if (rangelock_init(&range_regular) < 0)
456204076Spjd		primary_exit(EX_TEMPFAIL, "Unable to create regular range lock");
457204076Spjd	cv_init(&range_sync_cond);
458204076Spjd	if (rangelock_init(&range_sync) < 0)
459204076Spjd		primary_exit(EX_TEMPFAIL, "Unable to create sync range lock");
460204076Spjd	mapsize = activemap_ondisk_size(res->hr_amp);
461204076Spjd	buf = calloc(1, mapsize);
462204076Spjd	if (buf == NULL) {
463204076Spjd		primary_exitx(EX_TEMPFAIL,
464204076Spjd		    "Unable to allocate buffer for activemap.");
465204076Spjd	}
466204076Spjd	if (pread(res->hr_localfd, buf, mapsize, METADATA_SIZE) !=
467204076Spjd	    (ssize_t)mapsize) {
468204076Spjd		primary_exit(EX_NOINPUT, "Unable to read activemap");
469204076Spjd	}
470204076Spjd	activemap_copyin(res->hr_amp, buf, mapsize);
471209181Spjd	free(buf);
472204076Spjd	if (res->hr_resuid != 0)
473204076Spjd		return;
474204076Spjd	/*
475204076Spjd	 * We're using provider for the first time, so we have to generate
476204076Spjd	 * resource unique identifier and initialize local and remote counts.
477204076Spjd	 */
478204076Spjd	arc4random_buf(&res->hr_resuid, sizeof(res->hr_resuid));
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;
503205738Spjd
504204076Spjd	/* Prepare outgoing connection with remote node. */
505205738Spjd	if (proto_client(res->hr_remoteaddr, &out) < 0) {
506207347Spjd		primary_exit(EX_TEMPFAIL, "Unable to create connection to %s",
507204076Spjd		    res->hr_remoteaddr);
508204076Spjd	}
509204076Spjd	/* Try to connect, but accept failure. */
510205738Spjd	if (proto_connect(out) < 0) {
511204076Spjd		pjdlog_errno(LOG_WARNING, "Unable to connect to %s",
512204076Spjd		    res->hr_remoteaddr);
513204076Spjd		goto close;
514204076Spjd	}
515207371Spjd	/* Error in setting timeout is not critical, but why should it fail? */
516207371Spjd	if (proto_timeout(out, res->hr_timeout) < 0)
517207371Spjd		pjdlog_errno(LOG_WARNING, "Unable to set connection timeout");
518204076Spjd	/*
519204076Spjd	 * First handshake step.
520204076Spjd	 * Setup outgoing connection with remote node.
521204076Spjd	 */
522204076Spjd	nvout = nv_alloc();
523204076Spjd	nv_add_string(nvout, res->hr_name, "resource");
524204076Spjd	if (nv_error(nvout) != 0) {
525204076Spjd		pjdlog_common(LOG_WARNING, 0, nv_error(nvout),
526204076Spjd		    "Unable to allocate header for connection with %s",
527204076Spjd		    res->hr_remoteaddr);
528204076Spjd		nv_free(nvout);
529204076Spjd		goto close;
530204076Spjd	}
531205738Spjd	if (hast_proto_send(res, out, nvout, NULL, 0) < 0) {
532204076Spjd		pjdlog_errno(LOG_WARNING,
533204076Spjd		    "Unable to send handshake header to %s",
534204076Spjd		    res->hr_remoteaddr);
535204076Spjd		nv_free(nvout);
536204076Spjd		goto close;
537204076Spjd	}
538204076Spjd	nv_free(nvout);
539205738Spjd	if (hast_proto_recv_hdr(out, &nvin) < 0) {
540204076Spjd		pjdlog_errno(LOG_WARNING,
541204076Spjd		    "Unable to receive handshake header from %s",
542204076Spjd		    res->hr_remoteaddr);
543204076Spjd		goto close;
544204076Spjd	}
545204076Spjd	errmsg = nv_get_string(nvin, "errmsg");
546204076Spjd	if (errmsg != NULL) {
547204076Spjd		pjdlog_warning("%s", errmsg);
548204076Spjd		nv_free(nvin);
549204076Spjd		goto close;
550204076Spjd	}
551204076Spjd	token = nv_get_uint8_array(nvin, &size, "token");
552204076Spjd	if (token == NULL) {
553204076Spjd		pjdlog_warning("Handshake header from %s has no 'token' field.",
554204076Spjd		    res->hr_remoteaddr);
555204076Spjd		nv_free(nvin);
556204076Spjd		goto close;
557204076Spjd	}
558204076Spjd	if (size != sizeof(res->hr_token)) {
559204076Spjd		pjdlog_warning("Handshake header from %s contains 'token' of wrong size (got %zu, expected %zu).",
560204076Spjd		    res->hr_remoteaddr, size, sizeof(res->hr_token));
561204076Spjd		nv_free(nvin);
562204076Spjd		goto close;
563204076Spjd	}
564204076Spjd	bcopy(token, res->hr_token, sizeof(res->hr_token));
565204076Spjd	nv_free(nvin);
566204076Spjd
567204076Spjd	/*
568204076Spjd	 * Second handshake step.
569204076Spjd	 * Setup incoming connection with remote node.
570204076Spjd	 */
571205738Spjd	if (proto_client(res->hr_remoteaddr, &in) < 0) {
572204076Spjd		pjdlog_errno(LOG_WARNING, "Unable to create connection to %s",
573204076Spjd		    res->hr_remoteaddr);
574204076Spjd	}
575204076Spjd	/* Try to connect, but accept failure. */
576205738Spjd	if (proto_connect(in) < 0) {
577204076Spjd		pjdlog_errno(LOG_WARNING, "Unable to connect to %s",
578204076Spjd		    res->hr_remoteaddr);
579204076Spjd		goto close;
580204076Spjd	}
581207371Spjd	/* Error in setting timeout is not critical, but why should it fail? */
582207371Spjd	if (proto_timeout(in, res->hr_timeout) < 0)
583207371Spjd		pjdlog_errno(LOG_WARNING, "Unable to set connection timeout");
584204076Spjd	nvout = nv_alloc();
585204076Spjd	nv_add_string(nvout, res->hr_name, "resource");
586204076Spjd	nv_add_uint8_array(nvout, res->hr_token, sizeof(res->hr_token),
587204076Spjd	    "token");
588204076Spjd	nv_add_uint64(nvout, res->hr_resuid, "resuid");
589204076Spjd	nv_add_uint64(nvout, res->hr_primary_localcnt, "localcnt");
590204076Spjd	nv_add_uint64(nvout, res->hr_primary_remotecnt, "remotecnt");
591204076Spjd	if (nv_error(nvout) != 0) {
592204076Spjd		pjdlog_common(LOG_WARNING, 0, nv_error(nvout),
593204076Spjd		    "Unable to allocate header for connection with %s",
594204076Spjd		    res->hr_remoteaddr);
595204076Spjd		nv_free(nvout);
596204076Spjd		goto close;
597204076Spjd	}
598205738Spjd	if (hast_proto_send(res, in, nvout, NULL, 0) < 0) {
599204076Spjd		pjdlog_errno(LOG_WARNING,
600204076Spjd		    "Unable to send handshake header to %s",
601204076Spjd		    res->hr_remoteaddr);
602204076Spjd		nv_free(nvout);
603204076Spjd		goto close;
604204076Spjd	}
605204076Spjd	nv_free(nvout);
606205738Spjd	if (hast_proto_recv_hdr(out, &nvin) < 0) {
607204076Spjd		pjdlog_errno(LOG_WARNING,
608204076Spjd		    "Unable to receive handshake header from %s",
609204076Spjd		    res->hr_remoteaddr);
610204076Spjd		goto close;
611204076Spjd	}
612204076Spjd	errmsg = nv_get_string(nvin, "errmsg");
613204076Spjd	if (errmsg != NULL) {
614204076Spjd		pjdlog_warning("%s", errmsg);
615204076Spjd		nv_free(nvin);
616204076Spjd		goto close;
617204076Spjd	}
618204076Spjd	datasize = nv_get_int64(nvin, "datasize");
619204076Spjd	if (datasize != res->hr_datasize) {
620204076Spjd		pjdlog_warning("Data size differs between nodes (local=%jd, remote=%jd).",
621204076Spjd		    (intmax_t)res->hr_datasize, (intmax_t)datasize);
622204076Spjd		nv_free(nvin);
623204076Spjd		goto close;
624204076Spjd	}
625204076Spjd	extentsize = nv_get_int32(nvin, "extentsize");
626204076Spjd	if (extentsize != res->hr_extentsize) {
627204076Spjd		pjdlog_warning("Extent size differs between nodes (local=%zd, remote=%zd).",
628204076Spjd		    (ssize_t)res->hr_extentsize, (ssize_t)extentsize);
629204076Spjd		nv_free(nvin);
630204076Spjd		goto close;
631204076Spjd	}
632204076Spjd	res->hr_secondary_localcnt = nv_get_uint64(nvin, "localcnt");
633204076Spjd	res->hr_secondary_remotecnt = nv_get_uint64(nvin, "remotecnt");
634204076Spjd	res->hr_syncsrc = nv_get_uint8(nvin, "syncsrc");
635204076Spjd	map = NULL;
636204076Spjd	mapsize = nv_get_uint32(nvin, "mapsize");
637204076Spjd	if (mapsize > 0) {
638204076Spjd		map = malloc(mapsize);
639204076Spjd		if (map == NULL) {
640204076Spjd			pjdlog_error("Unable to allocate memory for remote activemap (mapsize=%ju).",
641204076Spjd			    (uintmax_t)mapsize);
642204076Spjd			nv_free(nvin);
643204076Spjd			goto close;
644204076Spjd		}
645204076Spjd		/*
646204076Spjd		 * Remote node have some dirty extents on its own, lets
647204076Spjd		 * download its activemap.
648204076Spjd		 */
649205738Spjd		if (hast_proto_recv_data(res, out, nvin, map,
650204076Spjd		    mapsize) < 0) {
651204076Spjd			pjdlog_errno(LOG_ERR,
652204076Spjd			    "Unable to receive remote activemap");
653204076Spjd			nv_free(nvin);
654204076Spjd			free(map);
655204076Spjd			goto close;
656204076Spjd		}
657204076Spjd		/*
658204076Spjd		 * Merge local and remote bitmaps.
659204076Spjd		 */
660204076Spjd		activemap_merge(res->hr_amp, map, mapsize);
661204076Spjd		free(map);
662204076Spjd		/*
663204076Spjd		 * Now that we merged bitmaps from both nodes, flush it to the
664204076Spjd		 * disk before we start to synchronize.
665204076Spjd		 */
666204076Spjd		(void)hast_activemap_flush(res);
667204076Spjd	}
668204076Spjd	pjdlog_info("Connected to %s.", res->hr_remoteaddr);
669205738Spjd	if (inp != NULL && outp != NULL) {
670205738Spjd		*inp = in;
671205738Spjd		*outp = out;
672205738Spjd	} else {
673205738Spjd		res->hr_remotein = in;
674205738Spjd		res->hr_remoteout = out;
675205738Spjd	}
676205738Spjd	return (true);
677205738Spjdclose:
678205738Spjd	proto_close(out);
679205738Spjd	if (in != NULL)
680205738Spjd		proto_close(in);
681205738Spjd	return (false);
682205738Spjd}
683205738Spjd
684205738Spjdstatic void
685205738Spjdsync_start(void)
686205738Spjd{
687205738Spjd
688204076Spjd	mtx_lock(&sync_lock);
689204076Spjd	sync_inprogress = true;
690204076Spjd	mtx_unlock(&sync_lock);
691204076Spjd	cv_signal(&sync_cond);
692204076Spjd}
693204076Spjd
694204076Spjdstatic void
695211878Spjdsync_stop(void)
696211878Spjd{
697211878Spjd
698211878Spjd	mtx_lock(&sync_lock);
699211878Spjd	if (sync_inprogress)
700211878Spjd		sync_inprogress = false;
701211878Spjd	mtx_unlock(&sync_lock);
702211878Spjd}
703211878Spjd
704211878Spjdstatic void
705204076Spjdinit_ggate(struct hast_resource *res)
706204076Spjd{
707204076Spjd	struct g_gate_ctl_create ggiocreate;
708204076Spjd	struct g_gate_ctl_cancel ggiocancel;
709204076Spjd
710204076Spjd	/*
711204076Spjd	 * We communicate with ggate via /dev/ggctl. Open it.
712204076Spjd	 */
713204076Spjd	res->hr_ggatefd = open("/dev/" G_GATE_CTL_NAME, O_RDWR);
714204076Spjd	if (res->hr_ggatefd < 0)
715204076Spjd		primary_exit(EX_OSFILE, "Unable to open /dev/" G_GATE_CTL_NAME);
716204076Spjd	/*
717204076Spjd	 * Create provider before trying to connect, as connection failure
718204076Spjd	 * is not critical, but may take some time.
719204076Spjd	 */
720204076Spjd	ggiocreate.gctl_version = G_GATE_VERSION;
721204076Spjd	ggiocreate.gctl_mediasize = res->hr_datasize;
722204076Spjd	ggiocreate.gctl_sectorsize = res->hr_local_sectorsize;
723204076Spjd	ggiocreate.gctl_flags = 0;
724206669Spjd	ggiocreate.gctl_maxcount = G_GATE_MAX_QUEUE_SIZE;
725204076Spjd	ggiocreate.gctl_timeout = 0;
726204076Spjd	ggiocreate.gctl_unit = G_GATE_NAME_GIVEN;
727204076Spjd	snprintf(ggiocreate.gctl_name, sizeof(ggiocreate.gctl_name), "hast/%s",
728204076Spjd	    res->hr_provname);
729204076Spjd	bzero(ggiocreate.gctl_info, sizeof(ggiocreate.gctl_info));
730204076Spjd	if (ioctl(res->hr_ggatefd, G_GATE_CMD_CREATE, &ggiocreate) == 0) {
731204076Spjd		pjdlog_info("Device hast/%s created.", res->hr_provname);
732204076Spjd		res->hr_ggateunit = ggiocreate.gctl_unit;
733204076Spjd		return;
734204076Spjd	}
735204076Spjd	if (errno != EEXIST) {
736204076Spjd		primary_exit(EX_OSERR, "Unable to create hast/%s device",
737204076Spjd		    res->hr_provname);
738204076Spjd	}
739204076Spjd	pjdlog_debug(1,
740204076Spjd	    "Device hast/%s already exists, we will try to take it over.",
741204076Spjd	    res->hr_provname);
742204076Spjd	/*
743204076Spjd	 * If we received EEXIST, we assume that the process who created the
744204076Spjd	 * provider died and didn't clean up. In that case we will start from
745204076Spjd	 * where he left of.
746204076Spjd	 */
747204076Spjd	ggiocancel.gctl_version = G_GATE_VERSION;
748204076Spjd	ggiocancel.gctl_unit = G_GATE_NAME_GIVEN;
749204076Spjd	snprintf(ggiocancel.gctl_name, sizeof(ggiocancel.gctl_name), "hast/%s",
750204076Spjd	    res->hr_provname);
751204076Spjd	if (ioctl(res->hr_ggatefd, G_GATE_CMD_CANCEL, &ggiocancel) == 0) {
752204076Spjd		pjdlog_info("Device hast/%s recovered.", res->hr_provname);
753204076Spjd		res->hr_ggateunit = ggiocancel.gctl_unit;
754204076Spjd		return;
755204076Spjd	}
756204076Spjd	primary_exit(EX_OSERR, "Unable to take over hast/%s device",
757204076Spjd	    res->hr_provname);
758204076Spjd}
759204076Spjd
760204076Spjdvoid
761204076Spjdhastd_primary(struct hast_resource *res)
762204076Spjd{
763204076Spjd	pthread_t td;
764204076Spjd	pid_t pid;
765204076Spjd	int error;
766204076Spjd
767204076Spjd	gres = res;
768204076Spjd
769204076Spjd	/*
770204076Spjd	 * Create communication channel between parent and child.
771204076Spjd	 */
772204076Spjd	if (proto_client("socketpair://", &res->hr_ctrl) < 0) {
773204076Spjd		KEEP_ERRNO((void)pidfile_remove(pfh));
774204076Spjd		primary_exit(EX_OSERR,
775204076Spjd		    "Unable to create control sockets between parent and child");
776204076Spjd	}
777204076Spjd
778204076Spjd	pid = fork();
779204076Spjd	if (pid < 0) {
780204076Spjd		KEEP_ERRNO((void)pidfile_remove(pfh));
781207347Spjd		primary_exit(EX_TEMPFAIL, "Unable to fork");
782204076Spjd	}
783204076Spjd
784204076Spjd	if (pid > 0) {
785204076Spjd		/* This is parent. */
786204076Spjd		res->hr_workerpid = pid;
787204076Spjd		return;
788204076Spjd	}
789204076Spjd	(void)pidfile_close(pfh);
790204076Spjd
791204076Spjd	setproctitle("%s (primary)", res->hr_name);
792204076Spjd
793210880Spjd	signal(SIGHUP, SIG_DFL);
794210880Spjd	signal(SIGCHLD, SIG_DFL);
795210880Spjd
796211886Spjd	hook_init();
797204076Spjd	init_local(res);
798210881Spjd	if (real_remote(res) && init_remote(res, NULL, NULL))
799205738Spjd		sync_start();
800204076Spjd	init_ggate(res);
801204076Spjd	init_environment(res);
802204076Spjd	error = pthread_create(&td, NULL, ggate_recv_thread, res);
803204076Spjd	assert(error == 0);
804204076Spjd	error = pthread_create(&td, NULL, local_send_thread, res);
805204076Spjd	assert(error == 0);
806204076Spjd	error = pthread_create(&td, NULL, remote_send_thread, res);
807204076Spjd	assert(error == 0);
808204076Spjd	error = pthread_create(&td, NULL, remote_recv_thread, res);
809204076Spjd	assert(error == 0);
810204076Spjd	error = pthread_create(&td, NULL, ggate_send_thread, res);
811204076Spjd	assert(error == 0);
812204076Spjd	error = pthread_create(&td, NULL, sync_thread, res);
813204076Spjd	assert(error == 0);
814204076Spjd	error = pthread_create(&td, NULL, ctrl_thread, res);
815204076Spjd	assert(error == 0);
816204076Spjd	(void)guard_thread(res);
817204076Spjd}
818204076Spjd
819204076Spjdstatic void
820204076Spjdreqlog(int loglevel, int debuglevel, struct g_gate_ctl_io *ggio, const char *fmt, ...)
821204076Spjd{
822204076Spjd	char msg[1024];
823204076Spjd	va_list ap;
824204076Spjd	int len;
825204076Spjd
826204076Spjd	va_start(ap, fmt);
827204076Spjd	len = vsnprintf(msg, sizeof(msg), fmt, ap);
828204076Spjd	va_end(ap);
829204076Spjd	if ((size_t)len < sizeof(msg)) {
830204076Spjd		switch (ggio->gctl_cmd) {
831204076Spjd		case BIO_READ:
832204076Spjd			(void)snprintf(msg + len, sizeof(msg) - len,
833204076Spjd			    "READ(%ju, %ju).", (uintmax_t)ggio->gctl_offset,
834204076Spjd			    (uintmax_t)ggio->gctl_length);
835204076Spjd			break;
836204076Spjd		case BIO_DELETE:
837204076Spjd			(void)snprintf(msg + len, sizeof(msg) - len,
838204076Spjd			    "DELETE(%ju, %ju).", (uintmax_t)ggio->gctl_offset,
839204076Spjd			    (uintmax_t)ggio->gctl_length);
840204076Spjd			break;
841204076Spjd		case BIO_FLUSH:
842204076Spjd			(void)snprintf(msg + len, sizeof(msg) - len, "FLUSH.");
843204076Spjd			break;
844204076Spjd		case BIO_WRITE:
845204076Spjd			(void)snprintf(msg + len, sizeof(msg) - len,
846204076Spjd			    "WRITE(%ju, %ju).", (uintmax_t)ggio->gctl_offset,
847204076Spjd			    (uintmax_t)ggio->gctl_length);
848204076Spjd			break;
849204076Spjd		default:
850204076Spjd			(void)snprintf(msg + len, sizeof(msg) - len,
851204076Spjd			    "UNKNOWN(%u).", (unsigned int)ggio->gctl_cmd);
852204076Spjd			break;
853204076Spjd		}
854204076Spjd	}
855204076Spjd	pjdlog_common(loglevel, debuglevel, -1, "%s", msg);
856204076Spjd}
857204076Spjd
858204076Spjdstatic void
859204076Spjdremote_close(struct hast_resource *res, int ncomp)
860204076Spjd{
861204076Spjd
862204076Spjd	rw_wlock(&hio_remote_lock[ncomp]);
863204076Spjd	/*
864204076Spjd	 * A race is possible between dropping rlock and acquiring wlock -
865204076Spjd	 * another thread can close connection in-between.
866204076Spjd	 */
867204076Spjd	if (!ISCONNECTED(res, ncomp)) {
868204076Spjd		assert(res->hr_remotein == NULL);
869204076Spjd		assert(res->hr_remoteout == NULL);
870204076Spjd		rw_unlock(&hio_remote_lock[ncomp]);
871204076Spjd		return;
872204076Spjd	}
873204076Spjd
874204076Spjd	assert(res->hr_remotein != NULL);
875204076Spjd	assert(res->hr_remoteout != NULL);
876204076Spjd
877211881Spjd	pjdlog_debug(2, "Closing incoming connection to %s.",
878204076Spjd	    res->hr_remoteaddr);
879204076Spjd	proto_close(res->hr_remotein);
880204076Spjd	res->hr_remotein = NULL;
881211881Spjd	pjdlog_debug(2, "Closing outgoing connection to %s.",
882204076Spjd	    res->hr_remoteaddr);
883204076Spjd	proto_close(res->hr_remoteout);
884204076Spjd	res->hr_remoteout = NULL;
885204076Spjd
886204076Spjd	rw_unlock(&hio_remote_lock[ncomp]);
887204076Spjd
888211881Spjd	pjdlog_warning("Disconnected from %s.", res->hr_remoteaddr);
889211881Spjd
890204076Spjd	/*
891204076Spjd	 * Stop synchronization if in-progress.
892204076Spjd	 */
893211878Spjd	sync_stop();
894204076Spjd
895204076Spjd	/*
896211882Spjd	 * Wake up guard thread (if we are not called from within guard thread),
897211882Spjd	 * so it can immediately start reconnect.
898204076Spjd	 */
899211882Spjd	if (!mtx_owned(&hio_guard_lock)) {
900211882Spjd		mtx_lock(&hio_guard_lock);
901211882Spjd		cv_signal(&hio_guard_cond);
902211882Spjd		mtx_unlock(&hio_guard_lock);
903211882Spjd	}
904204076Spjd}
905204076Spjd
906204076Spjd/*
907204076Spjd * Thread receives ggate I/O requests from the kernel and passes them to
908204076Spjd * appropriate threads:
909204076Spjd * WRITE - always goes to both local_send and remote_send threads
910204076Spjd * READ (when the block is up-to-date on local component) -
911204076Spjd *	only local_send thread
912204076Spjd * READ (when the block isn't up-to-date on local component) -
913204076Spjd *	only remote_send thread
914204076Spjd * DELETE - always goes to both local_send and remote_send threads
915204076Spjd * FLUSH - always goes to both local_send and remote_send threads
916204076Spjd */
917204076Spjdstatic void *
918204076Spjdggate_recv_thread(void *arg)
919204076Spjd{
920204076Spjd	struct hast_resource *res = arg;
921204076Spjd	struct g_gate_ctl_io *ggio;
922204076Spjd	struct hio *hio;
923204076Spjd	unsigned int ii, ncomp, ncomps;
924204076Spjd	int error;
925204076Spjd
926204076Spjd	ncomps = HAST_NCOMPONENTS;
927204076Spjd
928204076Spjd	for (;;) {
929204076Spjd		pjdlog_debug(2, "ggate_recv: Taking free request.");
930204076Spjd		QUEUE_TAKE2(hio, free);
931204076Spjd		pjdlog_debug(2, "ggate_recv: (%p) Got free request.", hio);
932204076Spjd		ggio = &hio->hio_ggio;
933204076Spjd		ggio->gctl_unit = res->hr_ggateunit;
934204076Spjd		ggio->gctl_length = MAXPHYS;
935204076Spjd		ggio->gctl_error = 0;
936204076Spjd		pjdlog_debug(2,
937204076Spjd		    "ggate_recv: (%p) Waiting for request from the kernel.",
938204076Spjd		    hio);
939204076Spjd		if (ioctl(res->hr_ggatefd, G_GATE_CMD_START, ggio) < 0) {
940204076Spjd			if (sigexit_received)
941204076Spjd				pthread_exit(NULL);
942204076Spjd			primary_exit(EX_OSERR, "G_GATE_CMD_START failed");
943204076Spjd		}
944204076Spjd		error = ggio->gctl_error;
945204076Spjd		switch (error) {
946204076Spjd		case 0:
947204076Spjd			break;
948204076Spjd		case ECANCELED:
949204076Spjd			/* Exit gracefully. */
950204076Spjd			if (!sigexit_received) {
951204076Spjd				pjdlog_debug(2,
952204076Spjd				    "ggate_recv: (%p) Received cancel from the kernel.",
953204076Spjd				    hio);
954204076Spjd				pjdlog_info("Received cancel from the kernel, exiting.");
955204076Spjd			}
956204076Spjd			pthread_exit(NULL);
957204076Spjd		case ENOMEM:
958204076Spjd			/*
959204076Spjd			 * Buffer too small? Impossible, we allocate MAXPHYS
960204076Spjd			 * bytes - request can't be bigger than that.
961204076Spjd			 */
962204076Spjd			/* FALLTHROUGH */
963204076Spjd		case ENXIO:
964204076Spjd		default:
965204076Spjd			primary_exitx(EX_OSERR, "G_GATE_CMD_START failed: %s.",
966204076Spjd			    strerror(error));
967204076Spjd		}
968204076Spjd		for (ii = 0; ii < ncomps; ii++)
969204076Spjd			hio->hio_errors[ii] = EINVAL;
970204076Spjd		reqlog(LOG_DEBUG, 2, ggio,
971204076Spjd		    "ggate_recv: (%p) Request received from the kernel: ",
972204076Spjd		    hio);
973204076Spjd		/*
974204076Spjd		 * Inform all components about new write request.
975204076Spjd		 * For read request prefer local component unless the given
976204076Spjd		 * range is out-of-date, then use remote component.
977204076Spjd		 */
978204076Spjd		switch (ggio->gctl_cmd) {
979204076Spjd		case BIO_READ:
980204076Spjd			pjdlog_debug(2,
981204076Spjd			    "ggate_recv: (%p) Moving request to the send queue.",
982204076Spjd			    hio);
983204076Spjd			refcount_init(&hio->hio_countdown, 1);
984204076Spjd			mtx_lock(&metadata_lock);
985204076Spjd			if (res->hr_syncsrc == HAST_SYNCSRC_UNDEF ||
986204076Spjd			    res->hr_syncsrc == HAST_SYNCSRC_PRIMARY) {
987204076Spjd				/*
988204076Spjd				 * This range is up-to-date on local component,
989204076Spjd				 * so handle request locally.
990204076Spjd				 */
991204076Spjd				 /* Local component is 0 for now. */
992204076Spjd				ncomp = 0;
993204076Spjd			} else /* if (res->hr_syncsrc ==
994204076Spjd			    HAST_SYNCSRC_SECONDARY) */ {
995204076Spjd				assert(res->hr_syncsrc ==
996204076Spjd				    HAST_SYNCSRC_SECONDARY);
997204076Spjd				/*
998204076Spjd				 * This range is out-of-date on local component,
999204076Spjd				 * so send request to the remote node.
1000204076Spjd				 */
1001204076Spjd				 /* Remote component is 1 for now. */
1002204076Spjd				ncomp = 1;
1003204076Spjd			}
1004204076Spjd			mtx_unlock(&metadata_lock);
1005204076Spjd			QUEUE_INSERT1(hio, send, ncomp);
1006204076Spjd			break;
1007204076Spjd		case BIO_WRITE:
1008204076Spjd			for (;;) {
1009204076Spjd				mtx_lock(&range_lock);
1010204076Spjd				if (rangelock_islocked(range_sync,
1011204076Spjd				    ggio->gctl_offset, ggio->gctl_length)) {
1012204076Spjd					pjdlog_debug(2,
1013204076Spjd					    "regular: Range offset=%jd length=%zu locked.",
1014204076Spjd					    (intmax_t)ggio->gctl_offset,
1015204076Spjd					    (size_t)ggio->gctl_length);
1016204076Spjd					range_regular_wait = true;
1017204076Spjd					cv_wait(&range_regular_cond, &range_lock);
1018204076Spjd					range_regular_wait = false;
1019204076Spjd					mtx_unlock(&range_lock);
1020204076Spjd					continue;
1021204076Spjd				}
1022204076Spjd				if (rangelock_add(range_regular,
1023204076Spjd				    ggio->gctl_offset, ggio->gctl_length) < 0) {
1024204076Spjd					mtx_unlock(&range_lock);
1025204076Spjd					pjdlog_debug(2,
1026204076Spjd					    "regular: Range offset=%jd length=%zu is already locked, waiting.",
1027204076Spjd					    (intmax_t)ggio->gctl_offset,
1028204076Spjd					    (size_t)ggio->gctl_length);
1029204076Spjd					sleep(1);
1030204076Spjd					continue;
1031204076Spjd				}
1032204076Spjd				mtx_unlock(&range_lock);
1033204076Spjd				break;
1034204076Spjd			}
1035204076Spjd			mtx_lock(&res->hr_amp_lock);
1036204076Spjd			if (activemap_write_start(res->hr_amp,
1037204076Spjd			    ggio->gctl_offset, ggio->gctl_length)) {
1038204076Spjd				(void)hast_activemap_flush(res);
1039204076Spjd			}
1040204076Spjd			mtx_unlock(&res->hr_amp_lock);
1041204076Spjd			/* FALLTHROUGH */
1042204076Spjd		case BIO_DELETE:
1043204076Spjd		case BIO_FLUSH:
1044204076Spjd			pjdlog_debug(2,
1045204076Spjd			    "ggate_recv: (%p) Moving request to the send queues.",
1046204076Spjd			    hio);
1047204076Spjd			refcount_init(&hio->hio_countdown, ncomps);
1048204076Spjd			for (ii = 0; ii < ncomps; ii++)
1049204076Spjd				QUEUE_INSERT1(hio, send, ii);
1050204076Spjd			break;
1051204076Spjd		}
1052204076Spjd	}
1053204076Spjd	/* NOTREACHED */
1054204076Spjd	return (NULL);
1055204076Spjd}
1056204076Spjd
1057204076Spjd/*
1058204076Spjd * Thread reads from or writes to local component.
1059204076Spjd * If local read fails, it redirects it to remote_send thread.
1060204076Spjd */
1061204076Spjdstatic void *
1062204076Spjdlocal_send_thread(void *arg)
1063204076Spjd{
1064204076Spjd	struct hast_resource *res = arg;
1065204076Spjd	struct g_gate_ctl_io *ggio;
1066204076Spjd	struct hio *hio;
1067204076Spjd	unsigned int ncomp, rncomp;
1068204076Spjd	ssize_t ret;
1069204076Spjd
1070204076Spjd	/* Local component is 0 for now. */
1071204076Spjd	ncomp = 0;
1072204076Spjd	/* Remote component is 1 for now. */
1073204076Spjd	rncomp = 1;
1074204076Spjd
1075204076Spjd	for (;;) {
1076204076Spjd		pjdlog_debug(2, "local_send: Taking request.");
1077204076Spjd		QUEUE_TAKE1(hio, send, ncomp);
1078204076Spjd		pjdlog_debug(2, "local_send: (%p) Got request.", hio);
1079204076Spjd		ggio = &hio->hio_ggio;
1080204076Spjd		switch (ggio->gctl_cmd) {
1081204076Spjd		case BIO_READ:
1082204076Spjd			ret = pread(res->hr_localfd, ggio->gctl_data,
1083204076Spjd			    ggio->gctl_length,
1084204076Spjd			    ggio->gctl_offset + res->hr_localoff);
1085204076Spjd			if (ret == ggio->gctl_length)
1086204076Spjd				hio->hio_errors[ncomp] = 0;
1087204076Spjd			else {
1088204076Spjd				/*
1089204076Spjd				 * If READ failed, try to read from remote node.
1090204076Spjd				 */
1091204076Spjd				QUEUE_INSERT1(hio, send, rncomp);
1092204076Spjd				continue;
1093204076Spjd			}
1094204076Spjd			break;
1095204076Spjd		case BIO_WRITE:
1096204076Spjd			ret = pwrite(res->hr_localfd, ggio->gctl_data,
1097204076Spjd			    ggio->gctl_length,
1098204076Spjd			    ggio->gctl_offset + res->hr_localoff);
1099204076Spjd			if (ret < 0)
1100204076Spjd				hio->hio_errors[ncomp] = errno;
1101204076Spjd			else if (ret != ggio->gctl_length)
1102204076Spjd				hio->hio_errors[ncomp] = EIO;
1103204076Spjd			else
1104204076Spjd				hio->hio_errors[ncomp] = 0;
1105204076Spjd			break;
1106204076Spjd		case BIO_DELETE:
1107204076Spjd			ret = g_delete(res->hr_localfd,
1108204076Spjd			    ggio->gctl_offset + res->hr_localoff,
1109204076Spjd			    ggio->gctl_length);
1110204076Spjd			if (ret < 0)
1111204076Spjd				hio->hio_errors[ncomp] = errno;
1112204076Spjd			else
1113204076Spjd				hio->hio_errors[ncomp] = 0;
1114204076Spjd			break;
1115204076Spjd		case BIO_FLUSH:
1116204076Spjd			ret = g_flush(res->hr_localfd);
1117204076Spjd			if (ret < 0)
1118204076Spjd				hio->hio_errors[ncomp] = errno;
1119204076Spjd			else
1120204076Spjd				hio->hio_errors[ncomp] = 0;
1121204076Spjd			break;
1122204076Spjd		}
1123204076Spjd		if (refcount_release(&hio->hio_countdown)) {
1124204076Spjd			if (ISSYNCREQ(hio)) {
1125204076Spjd				mtx_lock(&sync_lock);
1126204076Spjd				SYNCREQDONE(hio);
1127204076Spjd				mtx_unlock(&sync_lock);
1128204076Spjd				cv_signal(&sync_cond);
1129204076Spjd			} else {
1130204076Spjd				pjdlog_debug(2,
1131204076Spjd				    "local_send: (%p) Moving request to the done queue.",
1132204076Spjd				    hio);
1133204076Spjd				QUEUE_INSERT2(hio, done);
1134204076Spjd			}
1135204076Spjd		}
1136204076Spjd	}
1137204076Spjd	/* NOTREACHED */
1138204076Spjd	return (NULL);
1139204076Spjd}
1140204076Spjd
1141204076Spjd/*
1142204076Spjd * Thread sends request to secondary node.
1143204076Spjd */
1144204076Spjdstatic void *
1145204076Spjdremote_send_thread(void *arg)
1146204076Spjd{
1147204076Spjd	struct hast_resource *res = arg;
1148204076Spjd	struct g_gate_ctl_io *ggio;
1149204076Spjd	struct hio *hio;
1150204076Spjd	struct nv *nv;
1151204076Spjd	unsigned int ncomp;
1152204076Spjd	bool wakeup;
1153204076Spjd	uint64_t offset, length;
1154204076Spjd	uint8_t cmd;
1155204076Spjd	void *data;
1156204076Spjd
1157204076Spjd	/* Remote component is 1 for now. */
1158204076Spjd	ncomp = 1;
1159204076Spjd
1160204076Spjd	for (;;) {
1161204076Spjd		pjdlog_debug(2, "remote_send: Taking request.");
1162204076Spjd		QUEUE_TAKE1(hio, send, ncomp);
1163204076Spjd		pjdlog_debug(2, "remote_send: (%p) Got request.", hio);
1164204076Spjd		ggio = &hio->hio_ggio;
1165204076Spjd		switch (ggio->gctl_cmd) {
1166204076Spjd		case BIO_READ:
1167204076Spjd			cmd = HIO_READ;
1168204076Spjd			data = NULL;
1169204076Spjd			offset = ggio->gctl_offset;
1170204076Spjd			length = ggio->gctl_length;
1171204076Spjd			break;
1172204076Spjd		case BIO_WRITE:
1173204076Spjd			cmd = HIO_WRITE;
1174204076Spjd			data = ggio->gctl_data;
1175204076Spjd			offset = ggio->gctl_offset;
1176204076Spjd			length = ggio->gctl_length;
1177204076Spjd			break;
1178204076Spjd		case BIO_DELETE:
1179204076Spjd			cmd = HIO_DELETE;
1180204076Spjd			data = NULL;
1181204076Spjd			offset = ggio->gctl_offset;
1182204076Spjd			length = ggio->gctl_length;
1183204076Spjd			break;
1184204076Spjd		case BIO_FLUSH:
1185204076Spjd			cmd = HIO_FLUSH;
1186204076Spjd			data = NULL;
1187204076Spjd			offset = 0;
1188204076Spjd			length = 0;
1189204076Spjd			break;
1190204076Spjd		default:
1191204076Spjd			assert(!"invalid condition");
1192204076Spjd			abort();
1193204076Spjd		}
1194204076Spjd		nv = nv_alloc();
1195204076Spjd		nv_add_uint8(nv, cmd, "cmd");
1196204076Spjd		nv_add_uint64(nv, (uint64_t)ggio->gctl_seq, "seq");
1197204076Spjd		nv_add_uint64(nv, offset, "offset");
1198204076Spjd		nv_add_uint64(nv, length, "length");
1199204076Spjd		if (nv_error(nv) != 0) {
1200204076Spjd			hio->hio_errors[ncomp] = nv_error(nv);
1201204076Spjd			pjdlog_debug(2,
1202204076Spjd			    "remote_send: (%p) Unable to prepare header to send.",
1203204076Spjd			    hio);
1204204076Spjd			reqlog(LOG_ERR, 0, ggio,
1205204076Spjd			    "Unable to prepare header to send (%s): ",
1206204076Spjd			    strerror(nv_error(nv)));
1207204076Spjd			/* Move failed request immediately to the done queue. */
1208204076Spjd			goto done_queue;
1209204076Spjd		}
1210204076Spjd		pjdlog_debug(2,
1211204076Spjd		    "remote_send: (%p) Moving request to the recv queue.",
1212204076Spjd		    hio);
1213204076Spjd		/*
1214204076Spjd		 * Protect connection from disappearing.
1215204076Spjd		 */
1216204076Spjd		rw_rlock(&hio_remote_lock[ncomp]);
1217204076Spjd		if (!ISCONNECTED(res, ncomp)) {
1218204076Spjd			rw_unlock(&hio_remote_lock[ncomp]);
1219204076Spjd			hio->hio_errors[ncomp] = ENOTCONN;
1220204076Spjd			goto done_queue;
1221204076Spjd		}
1222204076Spjd		/*
1223204076Spjd		 * Move the request to recv queue before sending it, because
1224204076Spjd		 * in different order we can get reply before we move request
1225204076Spjd		 * to recv queue.
1226204076Spjd		 */
1227204076Spjd		mtx_lock(&hio_recv_list_lock[ncomp]);
1228204076Spjd		wakeup = TAILQ_EMPTY(&hio_recv_list[ncomp]);
1229204076Spjd		TAILQ_INSERT_TAIL(&hio_recv_list[ncomp], hio, hio_next[ncomp]);
1230204076Spjd		mtx_unlock(&hio_recv_list_lock[ncomp]);
1231204076Spjd		if (hast_proto_send(res, res->hr_remoteout, nv, data,
1232204076Spjd		    data != NULL ? length : 0) < 0) {
1233204076Spjd			hio->hio_errors[ncomp] = errno;
1234204076Spjd			rw_unlock(&hio_remote_lock[ncomp]);
1235204076Spjd			remote_close(res, ncomp);
1236204076Spjd			pjdlog_debug(2,
1237204076Spjd			    "remote_send: (%p) Unable to send request.", hio);
1238204076Spjd			reqlog(LOG_ERR, 0, ggio,
1239204076Spjd			    "Unable to send request (%s): ",
1240204076Spjd			    strerror(hio->hio_errors[ncomp]));
1241204076Spjd			/*
1242204076Spjd			 * Take request back from the receive queue and move
1243204076Spjd			 * it immediately to the done queue.
1244204076Spjd			 */
1245204076Spjd			mtx_lock(&hio_recv_list_lock[ncomp]);
1246204076Spjd			TAILQ_REMOVE(&hio_recv_list[ncomp], hio, hio_next[ncomp]);
1247204076Spjd			mtx_unlock(&hio_recv_list_lock[ncomp]);
1248204076Spjd			goto done_queue;
1249204076Spjd		}
1250204076Spjd		rw_unlock(&hio_remote_lock[ncomp]);
1251204076Spjd		nv_free(nv);
1252204076Spjd		if (wakeup)
1253204076Spjd			cv_signal(&hio_recv_list_cond[ncomp]);
1254204076Spjd		continue;
1255204076Spjddone_queue:
1256204076Spjd		nv_free(nv);
1257204076Spjd		if (ISSYNCREQ(hio)) {
1258204076Spjd			if (!refcount_release(&hio->hio_countdown))
1259204076Spjd				continue;
1260204076Spjd			mtx_lock(&sync_lock);
1261204076Spjd			SYNCREQDONE(hio);
1262204076Spjd			mtx_unlock(&sync_lock);
1263204076Spjd			cv_signal(&sync_cond);
1264204076Spjd			continue;
1265204076Spjd		}
1266204076Spjd		if (ggio->gctl_cmd == BIO_WRITE) {
1267204076Spjd			mtx_lock(&res->hr_amp_lock);
1268204076Spjd			if (activemap_need_sync(res->hr_amp, ggio->gctl_offset,
1269204076Spjd			    ggio->gctl_length)) {
1270204076Spjd				(void)hast_activemap_flush(res);
1271204076Spjd			}
1272204076Spjd			mtx_unlock(&res->hr_amp_lock);
1273204076Spjd		}
1274204076Spjd		if (!refcount_release(&hio->hio_countdown))
1275204076Spjd			continue;
1276204076Spjd		pjdlog_debug(2,
1277204076Spjd		    "remote_send: (%p) Moving request to the done queue.",
1278204076Spjd		    hio);
1279204076Spjd		QUEUE_INSERT2(hio, done);
1280204076Spjd	}
1281204076Spjd	/* NOTREACHED */
1282204076Spjd	return (NULL);
1283204076Spjd}
1284204076Spjd
1285204076Spjd/*
1286204076Spjd * Thread receives answer from secondary node and passes it to ggate_send
1287204076Spjd * thread.
1288204076Spjd */
1289204076Spjdstatic void *
1290204076Spjdremote_recv_thread(void *arg)
1291204076Spjd{
1292204076Spjd	struct hast_resource *res = arg;
1293204076Spjd	struct g_gate_ctl_io *ggio;
1294204076Spjd	struct hio *hio;
1295204076Spjd	struct nv *nv;
1296204076Spjd	unsigned int ncomp;
1297204076Spjd	uint64_t seq;
1298204076Spjd	int error;
1299204076Spjd
1300204076Spjd	/* Remote component is 1 for now. */
1301204076Spjd	ncomp = 1;
1302204076Spjd
1303204076Spjd	for (;;) {
1304204076Spjd		/* Wait until there is anything to receive. */
1305204076Spjd		mtx_lock(&hio_recv_list_lock[ncomp]);
1306204076Spjd		while (TAILQ_EMPTY(&hio_recv_list[ncomp])) {
1307204076Spjd			pjdlog_debug(2, "remote_recv: No requests, waiting.");
1308204076Spjd			cv_wait(&hio_recv_list_cond[ncomp],
1309204076Spjd			    &hio_recv_list_lock[ncomp]);
1310204076Spjd		}
1311204076Spjd		mtx_unlock(&hio_recv_list_lock[ncomp]);
1312204076Spjd		rw_rlock(&hio_remote_lock[ncomp]);
1313204076Spjd		if (!ISCONNECTED(res, ncomp)) {
1314204076Spjd			rw_unlock(&hio_remote_lock[ncomp]);
1315204076Spjd			/*
1316204076Spjd			 * Connection is dead, so move all pending requests to
1317204076Spjd			 * the done queue (one-by-one).
1318204076Spjd			 */
1319204076Spjd			mtx_lock(&hio_recv_list_lock[ncomp]);
1320204076Spjd			hio = TAILQ_FIRST(&hio_recv_list[ncomp]);
1321204076Spjd			assert(hio != NULL);
1322204076Spjd			TAILQ_REMOVE(&hio_recv_list[ncomp], hio,
1323204076Spjd			    hio_next[ncomp]);
1324204076Spjd			mtx_unlock(&hio_recv_list_lock[ncomp]);
1325204076Spjd			goto done_queue;
1326204076Spjd		}
1327204076Spjd		if (hast_proto_recv_hdr(res->hr_remotein, &nv) < 0) {
1328204076Spjd			pjdlog_errno(LOG_ERR,
1329204076Spjd			    "Unable to receive reply header");
1330204076Spjd			rw_unlock(&hio_remote_lock[ncomp]);
1331204076Spjd			remote_close(res, ncomp);
1332204076Spjd			continue;
1333204076Spjd		}
1334204076Spjd		rw_unlock(&hio_remote_lock[ncomp]);
1335204076Spjd		seq = nv_get_uint64(nv, "seq");
1336204076Spjd		if (seq == 0) {
1337204076Spjd			pjdlog_error("Header contains no 'seq' field.");
1338204076Spjd			nv_free(nv);
1339204076Spjd			continue;
1340204076Spjd		}
1341204076Spjd		mtx_lock(&hio_recv_list_lock[ncomp]);
1342204076Spjd		TAILQ_FOREACH(hio, &hio_recv_list[ncomp], hio_next[ncomp]) {
1343204076Spjd			if (hio->hio_ggio.gctl_seq == seq) {
1344204076Spjd				TAILQ_REMOVE(&hio_recv_list[ncomp], hio,
1345204076Spjd				    hio_next[ncomp]);
1346204076Spjd				break;
1347204076Spjd			}
1348204076Spjd		}
1349204076Spjd		mtx_unlock(&hio_recv_list_lock[ncomp]);
1350204076Spjd		if (hio == NULL) {
1351204076Spjd			pjdlog_error("Found no request matching received 'seq' field (%ju).",
1352204076Spjd			    (uintmax_t)seq);
1353204076Spjd			nv_free(nv);
1354204076Spjd			continue;
1355204076Spjd		}
1356204076Spjd		error = nv_get_int16(nv, "error");
1357204076Spjd		if (error != 0) {
1358204076Spjd			/* Request failed on remote side. */
1359204076Spjd			hio->hio_errors[ncomp] = 0;
1360204076Spjd			nv_free(nv);
1361204076Spjd			goto done_queue;
1362204076Spjd		}
1363204076Spjd		ggio = &hio->hio_ggio;
1364204076Spjd		switch (ggio->gctl_cmd) {
1365204076Spjd		case BIO_READ:
1366204076Spjd			rw_rlock(&hio_remote_lock[ncomp]);
1367204076Spjd			if (!ISCONNECTED(res, ncomp)) {
1368204076Spjd				rw_unlock(&hio_remote_lock[ncomp]);
1369204076Spjd				nv_free(nv);
1370204076Spjd				goto done_queue;
1371204076Spjd			}
1372204076Spjd			if (hast_proto_recv_data(res, res->hr_remotein, nv,
1373204076Spjd			    ggio->gctl_data, ggio->gctl_length) < 0) {
1374204076Spjd				hio->hio_errors[ncomp] = errno;
1375204076Spjd				pjdlog_errno(LOG_ERR,
1376204076Spjd				    "Unable to receive reply data");
1377204076Spjd				rw_unlock(&hio_remote_lock[ncomp]);
1378204076Spjd				nv_free(nv);
1379204076Spjd				remote_close(res, ncomp);
1380204076Spjd				goto done_queue;
1381204076Spjd			}
1382204076Spjd			rw_unlock(&hio_remote_lock[ncomp]);
1383204076Spjd			break;
1384204076Spjd		case BIO_WRITE:
1385204076Spjd		case BIO_DELETE:
1386204076Spjd		case BIO_FLUSH:
1387204076Spjd			break;
1388204076Spjd		default:
1389204076Spjd			assert(!"invalid condition");
1390204076Spjd			abort();
1391204076Spjd		}
1392204076Spjd		hio->hio_errors[ncomp] = 0;
1393204076Spjd		nv_free(nv);
1394204076Spjddone_queue:
1395204076Spjd		if (refcount_release(&hio->hio_countdown)) {
1396204076Spjd			if (ISSYNCREQ(hio)) {
1397204076Spjd				mtx_lock(&sync_lock);
1398204076Spjd				SYNCREQDONE(hio);
1399204076Spjd				mtx_unlock(&sync_lock);
1400204076Spjd				cv_signal(&sync_cond);
1401204076Spjd			} else {
1402204076Spjd				pjdlog_debug(2,
1403204076Spjd				    "remote_recv: (%p) Moving request to the done queue.",
1404204076Spjd				    hio);
1405204076Spjd				QUEUE_INSERT2(hio, done);
1406204076Spjd			}
1407204076Spjd		}
1408204076Spjd	}
1409204076Spjd	/* NOTREACHED */
1410204076Spjd	return (NULL);
1411204076Spjd}
1412204076Spjd
1413204076Spjd/*
1414204076Spjd * Thread sends answer to the kernel.
1415204076Spjd */
1416204076Spjdstatic void *
1417204076Spjdggate_send_thread(void *arg)
1418204076Spjd{
1419204076Spjd	struct hast_resource *res = arg;
1420204076Spjd	struct g_gate_ctl_io *ggio;
1421204076Spjd	struct hio *hio;
1422204076Spjd	unsigned int ii, ncomp, ncomps;
1423204076Spjd
1424204076Spjd	ncomps = HAST_NCOMPONENTS;
1425204076Spjd
1426204076Spjd	for (;;) {
1427204076Spjd		pjdlog_debug(2, "ggate_send: Taking request.");
1428204076Spjd		QUEUE_TAKE2(hio, done);
1429204076Spjd		pjdlog_debug(2, "ggate_send: (%p) Got request.", hio);
1430204076Spjd		ggio = &hio->hio_ggio;
1431204076Spjd		for (ii = 0; ii < ncomps; ii++) {
1432204076Spjd			if (hio->hio_errors[ii] == 0) {
1433204076Spjd				/*
1434204076Spjd				 * One successful request is enough to declare
1435204076Spjd				 * success.
1436204076Spjd				 */
1437204076Spjd				ggio->gctl_error = 0;
1438204076Spjd				break;
1439204076Spjd			}
1440204076Spjd		}
1441204076Spjd		if (ii == ncomps) {
1442204076Spjd			/*
1443204076Spjd			 * None of the requests were successful.
1444204076Spjd			 * Use first error.
1445204076Spjd			 */
1446204076Spjd			ggio->gctl_error = hio->hio_errors[0];
1447204076Spjd		}
1448204076Spjd		if (ggio->gctl_error == 0 && ggio->gctl_cmd == BIO_WRITE) {
1449204076Spjd			mtx_lock(&res->hr_amp_lock);
1450204076Spjd			activemap_write_complete(res->hr_amp,
1451204076Spjd			    ggio->gctl_offset, ggio->gctl_length);
1452204076Spjd			mtx_unlock(&res->hr_amp_lock);
1453204076Spjd		}
1454204076Spjd		if (ggio->gctl_cmd == BIO_WRITE) {
1455204076Spjd			/*
1456204076Spjd			 * Unlock range we locked.
1457204076Spjd			 */
1458204076Spjd			mtx_lock(&range_lock);
1459204076Spjd			rangelock_del(range_regular, ggio->gctl_offset,
1460204076Spjd			    ggio->gctl_length);
1461204076Spjd			if (range_sync_wait)
1462204076Spjd				cv_signal(&range_sync_cond);
1463204076Spjd			mtx_unlock(&range_lock);
1464204076Spjd			/*
1465204076Spjd			 * Bump local count if this is first write after
1466204076Spjd			 * connection failure with remote node.
1467204076Spjd			 */
1468204076Spjd			ncomp = 1;
1469204076Spjd			rw_rlock(&hio_remote_lock[ncomp]);
1470204076Spjd			if (!ISCONNECTED(res, ncomp)) {
1471204076Spjd				mtx_lock(&metadata_lock);
1472204076Spjd				if (res->hr_primary_localcnt ==
1473204076Spjd				    res->hr_secondary_remotecnt) {
1474204076Spjd					res->hr_primary_localcnt++;
1475204076Spjd					pjdlog_debug(1,
1476204076Spjd					    "Increasing localcnt to %ju.",
1477204076Spjd					    (uintmax_t)res->hr_primary_localcnt);
1478204076Spjd					(void)metadata_write(res);
1479204076Spjd				}
1480204076Spjd				mtx_unlock(&metadata_lock);
1481204076Spjd			}
1482204076Spjd			rw_unlock(&hio_remote_lock[ncomp]);
1483204076Spjd		}
1484204076Spjd		if (ioctl(res->hr_ggatefd, G_GATE_CMD_DONE, ggio) < 0)
1485204076Spjd			primary_exit(EX_OSERR, "G_GATE_CMD_DONE failed");
1486204076Spjd		pjdlog_debug(2,
1487204076Spjd		    "ggate_send: (%p) Moving request to the free queue.", hio);
1488204076Spjd		QUEUE_INSERT2(hio, free);
1489204076Spjd	}
1490204076Spjd	/* NOTREACHED */
1491204076Spjd	return (NULL);
1492204076Spjd}
1493204076Spjd
1494204076Spjd/*
1495204076Spjd * Thread synchronize local and remote components.
1496204076Spjd */
1497204076Spjdstatic void *
1498204076Spjdsync_thread(void *arg __unused)
1499204076Spjd{
1500204076Spjd	struct hast_resource *res = arg;
1501204076Spjd	struct hio *hio;
1502204076Spjd	struct g_gate_ctl_io *ggio;
1503204076Spjd	unsigned int ii, ncomp, ncomps;
1504204076Spjd	off_t offset, length, synced;
1505204076Spjd	bool dorewind;
1506204076Spjd	int syncext;
1507204076Spjd
1508204076Spjd	ncomps = HAST_NCOMPONENTS;
1509204076Spjd	dorewind = true;
1510211897Spjd	synced = 0;
1511211897Spjd	offset = -1;
1512204076Spjd
1513204076Spjd	for (;;) {
1514204076Spjd		mtx_lock(&sync_lock);
1515211897Spjd		if (offset >= 0 && !sync_inprogress) {
1516211879Spjd			pjdlog_info("Synchronization interrupted. "
1517211879Spjd			    "%jd bytes synchronized so far.",
1518211879Spjd			    (intmax_t)synced);
1519211897Spjd			hook_exec(res->hr_exec, "syncintr", res->hr_name, NULL);
1520211879Spjd		}
1521204076Spjd		while (!sync_inprogress) {
1522204076Spjd			dorewind = true;
1523204076Spjd			synced = 0;
1524204076Spjd			cv_wait(&sync_cond, &sync_lock);
1525204076Spjd		}
1526204076Spjd		mtx_unlock(&sync_lock);
1527204076Spjd		/*
1528204076Spjd		 * Obtain offset at which we should synchronize.
1529204076Spjd		 * Rewind synchronization if needed.
1530204076Spjd		 */
1531204076Spjd		mtx_lock(&res->hr_amp_lock);
1532204076Spjd		if (dorewind)
1533204076Spjd			activemap_sync_rewind(res->hr_amp);
1534204076Spjd		offset = activemap_sync_offset(res->hr_amp, &length, &syncext);
1535204076Spjd		if (syncext != -1) {
1536204076Spjd			/*
1537204076Spjd			 * We synchronized entire syncext extent, we can mark
1538204076Spjd			 * it as clean now.
1539204076Spjd			 */
1540204076Spjd			if (activemap_extent_complete(res->hr_amp, syncext))
1541204076Spjd				(void)hast_activemap_flush(res);
1542204076Spjd		}
1543204076Spjd		mtx_unlock(&res->hr_amp_lock);
1544204076Spjd		if (dorewind) {
1545204076Spjd			dorewind = false;
1546204076Spjd			if (offset < 0)
1547204076Spjd				pjdlog_info("Nodes are in sync.");
1548204076Spjd			else {
1549204076Spjd				pjdlog_info("Synchronization started. %ju bytes to go.",
1550204076Spjd				    (uintmax_t)(res->hr_extentsize *
1551204076Spjd				    activemap_ndirty(res->hr_amp)));
1552211895Spjd				hook_exec(res->hr_exec, "syncstart",
1553211895Spjd				    res->hr_name, NULL);
1554204076Spjd			}
1555204076Spjd		}
1556204076Spjd		if (offset < 0) {
1557211878Spjd			sync_stop();
1558204076Spjd			pjdlog_debug(1, "Nothing to synchronize.");
1559204076Spjd			/*
1560204076Spjd			 * Synchronization complete, make both localcnt and
1561204076Spjd			 * remotecnt equal.
1562204076Spjd			 */
1563204076Spjd			ncomp = 1;
1564204076Spjd			rw_rlock(&hio_remote_lock[ncomp]);
1565204076Spjd			if (ISCONNECTED(res, ncomp)) {
1566204076Spjd				if (synced > 0) {
1567204076Spjd					pjdlog_info("Synchronization complete. "
1568204076Spjd					    "%jd bytes synchronized.",
1569204076Spjd					    (intmax_t)synced);
1570211895Spjd					hook_exec(res->hr_exec, "syncdone",
1571211895Spjd					    res->hr_name, NULL);
1572204076Spjd				}
1573204076Spjd				mtx_lock(&metadata_lock);
1574204076Spjd				res->hr_syncsrc = HAST_SYNCSRC_UNDEF;
1575204076Spjd				res->hr_primary_localcnt =
1576204076Spjd				    res->hr_secondary_localcnt;
1577204076Spjd				res->hr_primary_remotecnt =
1578204076Spjd				    res->hr_secondary_remotecnt;
1579204076Spjd				pjdlog_debug(1,
1580204076Spjd				    "Setting localcnt to %ju and remotecnt to %ju.",
1581204076Spjd				    (uintmax_t)res->hr_primary_localcnt,
1582204076Spjd				    (uintmax_t)res->hr_secondary_localcnt);
1583204076Spjd				(void)metadata_write(res);
1584204076Spjd				mtx_unlock(&metadata_lock);
1585204076Spjd			}
1586204076Spjd			rw_unlock(&hio_remote_lock[ncomp]);
1587204076Spjd			continue;
1588204076Spjd		}
1589204076Spjd		pjdlog_debug(2, "sync: Taking free request.");
1590204076Spjd		QUEUE_TAKE2(hio, free);
1591204076Spjd		pjdlog_debug(2, "sync: (%p) Got free request.", hio);
1592204076Spjd		/*
1593204076Spjd		 * Lock the range we are going to synchronize. We don't want
1594204076Spjd		 * race where someone writes between our read and write.
1595204076Spjd		 */
1596204076Spjd		for (;;) {
1597204076Spjd			mtx_lock(&range_lock);
1598204076Spjd			if (rangelock_islocked(range_regular, offset, length)) {
1599204076Spjd				pjdlog_debug(2,
1600204076Spjd				    "sync: Range offset=%jd length=%jd locked.",
1601204076Spjd				    (intmax_t)offset, (intmax_t)length);
1602204076Spjd				range_sync_wait = true;
1603204076Spjd				cv_wait(&range_sync_cond, &range_lock);
1604204076Spjd				range_sync_wait = false;
1605204076Spjd				mtx_unlock(&range_lock);
1606204076Spjd				continue;
1607204076Spjd			}
1608204076Spjd			if (rangelock_add(range_sync, offset, length) < 0) {
1609204076Spjd				mtx_unlock(&range_lock);
1610204076Spjd				pjdlog_debug(2,
1611204076Spjd				    "sync: Range offset=%jd length=%jd is already locked, waiting.",
1612204076Spjd				    (intmax_t)offset, (intmax_t)length);
1613204076Spjd				sleep(1);
1614204076Spjd				continue;
1615204076Spjd			}
1616204076Spjd			mtx_unlock(&range_lock);
1617204076Spjd			break;
1618204076Spjd		}
1619204076Spjd		/*
1620204076Spjd		 * First read the data from synchronization source.
1621204076Spjd		 */
1622204076Spjd		SYNCREQ(hio);
1623204076Spjd		ggio = &hio->hio_ggio;
1624204076Spjd		ggio->gctl_cmd = BIO_READ;
1625204076Spjd		ggio->gctl_offset = offset;
1626204076Spjd		ggio->gctl_length = length;
1627204076Spjd		ggio->gctl_error = 0;
1628204076Spjd		for (ii = 0; ii < ncomps; ii++)
1629204076Spjd			hio->hio_errors[ii] = EINVAL;
1630204076Spjd		reqlog(LOG_DEBUG, 2, ggio, "sync: (%p) Sending sync request: ",
1631204076Spjd		    hio);
1632204076Spjd		pjdlog_debug(2, "sync: (%p) Moving request to the send queue.",
1633204076Spjd		    hio);
1634204076Spjd		mtx_lock(&metadata_lock);
1635204076Spjd		if (res->hr_syncsrc == HAST_SYNCSRC_PRIMARY) {
1636204076Spjd			/*
1637204076Spjd			 * This range is up-to-date on local component,
1638204076Spjd			 * so handle request locally.
1639204076Spjd			 */
1640204076Spjd			 /* Local component is 0 for now. */
1641204076Spjd			ncomp = 0;
1642204076Spjd		} else /* if (res->hr_syncsrc == HAST_SYNCSRC_SECONDARY) */ {
1643204076Spjd			assert(res->hr_syncsrc == HAST_SYNCSRC_SECONDARY);
1644204076Spjd			/*
1645204076Spjd			 * This range is out-of-date on local component,
1646204076Spjd			 * so send request to the remote node.
1647204076Spjd			 */
1648204076Spjd			 /* Remote component is 1 for now. */
1649204076Spjd			ncomp = 1;
1650204076Spjd		}
1651204076Spjd		mtx_unlock(&metadata_lock);
1652204076Spjd		refcount_init(&hio->hio_countdown, 1);
1653204076Spjd		QUEUE_INSERT1(hio, send, ncomp);
1654204076Spjd
1655204076Spjd		/*
1656204076Spjd		 * Let's wait for READ to finish.
1657204076Spjd		 */
1658204076Spjd		mtx_lock(&sync_lock);
1659204076Spjd		while (!ISSYNCREQDONE(hio))
1660204076Spjd			cv_wait(&sync_cond, &sync_lock);
1661204076Spjd		mtx_unlock(&sync_lock);
1662204076Spjd
1663204076Spjd		if (hio->hio_errors[ncomp] != 0) {
1664204076Spjd			pjdlog_error("Unable to read synchronization data: %s.",
1665204076Spjd			    strerror(hio->hio_errors[ncomp]));
1666204076Spjd			goto free_queue;
1667204076Spjd		}
1668204076Spjd
1669204076Spjd		/*
1670204076Spjd		 * We read the data from synchronization source, now write it
1671204076Spjd		 * to synchronization target.
1672204076Spjd		 */
1673204076Spjd		SYNCREQ(hio);
1674204076Spjd		ggio->gctl_cmd = BIO_WRITE;
1675204076Spjd		for (ii = 0; ii < ncomps; ii++)
1676204076Spjd			hio->hio_errors[ii] = EINVAL;
1677204076Spjd		reqlog(LOG_DEBUG, 2, ggio, "sync: (%p) Sending sync request: ",
1678204076Spjd		    hio);
1679204076Spjd		pjdlog_debug(2, "sync: (%p) Moving request to the send queue.",
1680204076Spjd		    hio);
1681204076Spjd		mtx_lock(&metadata_lock);
1682204076Spjd		if (res->hr_syncsrc == HAST_SYNCSRC_PRIMARY) {
1683204076Spjd			/*
1684204076Spjd			 * This range is up-to-date on local component,
1685204076Spjd			 * so we update remote component.
1686204076Spjd			 */
1687204076Spjd			 /* Remote component is 1 for now. */
1688204076Spjd			ncomp = 1;
1689204076Spjd		} else /* if (res->hr_syncsrc == HAST_SYNCSRC_SECONDARY) */ {
1690204076Spjd			assert(res->hr_syncsrc == HAST_SYNCSRC_SECONDARY);
1691204076Spjd			/*
1692204076Spjd			 * This range is out-of-date on local component,
1693204076Spjd			 * so we update it.
1694204076Spjd			 */
1695204076Spjd			 /* Local component is 0 for now. */
1696204076Spjd			ncomp = 0;
1697204076Spjd		}
1698204076Spjd		mtx_unlock(&metadata_lock);
1699204076Spjd
1700204076Spjd		pjdlog_debug(2, "sync: (%p) Moving request to the send queues.",
1701204076Spjd		    hio);
1702204076Spjd		refcount_init(&hio->hio_countdown, 1);
1703204076Spjd		QUEUE_INSERT1(hio, send, ncomp);
1704204076Spjd
1705204076Spjd		/*
1706204076Spjd		 * Let's wait for WRITE to finish.
1707204076Spjd		 */
1708204076Spjd		mtx_lock(&sync_lock);
1709204076Spjd		while (!ISSYNCREQDONE(hio))
1710204076Spjd			cv_wait(&sync_cond, &sync_lock);
1711204076Spjd		mtx_unlock(&sync_lock);
1712204076Spjd
1713204076Spjd		if (hio->hio_errors[ncomp] != 0) {
1714204076Spjd			pjdlog_error("Unable to write synchronization data: %s.",
1715204076Spjd			    strerror(hio->hio_errors[ncomp]));
1716204076Spjd			goto free_queue;
1717204076Spjd		}
1718211880Spjd
1719211880Spjd		synced += length;
1720204076Spjdfree_queue:
1721204076Spjd		mtx_lock(&range_lock);
1722204076Spjd		rangelock_del(range_sync, offset, length);
1723204076Spjd		if (range_regular_wait)
1724204076Spjd			cv_signal(&range_regular_cond);
1725204076Spjd		mtx_unlock(&range_lock);
1726204076Spjd		pjdlog_debug(2, "sync: (%p) Moving request to the free queue.",
1727204076Spjd		    hio);
1728204076Spjd		QUEUE_INSERT2(hio, free);
1729204076Spjd	}
1730204076Spjd	/* NOTREACHED */
1731204076Spjd	return (NULL);
1732204076Spjd}
1733204076Spjd
1734204076Spjdstatic void
1735204076Spjdsighandler(int sig)
1736204076Spjd{
1737204076Spjd	bool unlock;
1738204076Spjd
1739204076Spjd	switch (sig) {
1740204076Spjd	case SIGINT:
1741204076Spjd	case SIGTERM:
1742204076Spjd		sigexit_received = true;
1743204076Spjd		break;
1744210886Spjd	case SIGHUP:
1745210886Spjd		sighup_received = true;
1746210886Spjd		break;
1747211886Spjd	case SIGCHLD:
1748211886Spjd		sigchld_received = true;
1749211886Spjd		break;
1750204076Spjd	default:
1751204076Spjd		assert(!"invalid condition");
1752204076Spjd	}
1753204076Spjd	/*
1754211882Spjd	 * Racy, but if we cannot obtain hio_guard_lock here, we don't
1755204076Spjd	 * want to risk deadlock.
1756204076Spjd	 */
1757204076Spjd	unlock = mtx_trylock(&hio_guard_lock);
1758204076Spjd	cv_signal(&hio_guard_cond);
1759204076Spjd	if (unlock)
1760204076Spjd		mtx_unlock(&hio_guard_lock);
1761204076Spjd}
1762204076Spjd
1763210886Spjdstatic void
1764210886Spjdconfig_reload(void)
1765210886Spjd{
1766210886Spjd	struct hastd_config *newcfg;
1767210886Spjd	struct hast_resource *res;
1768210886Spjd	unsigned int ii, ncomps;
1769210886Spjd	int modified;
1770210886Spjd
1771210886Spjd	pjdlog_info("Reloading configuration...");
1772210886Spjd
1773210886Spjd	ncomps = HAST_NCOMPONENTS;
1774210886Spjd
1775210886Spjd	newcfg = yy_config_parse(cfgpath, false);
1776210886Spjd	if (newcfg == NULL)
1777210886Spjd		goto failed;
1778210886Spjd
1779210886Spjd	TAILQ_FOREACH(res, &newcfg->hc_resources, hr_next) {
1780210886Spjd		if (strcmp(res->hr_name, gres->hr_name) == 0)
1781210886Spjd			break;
1782210886Spjd	}
1783210886Spjd	/*
1784210886Spjd	 * If resource was removed from the configuration file, resource
1785210886Spjd	 * name, provider name or path to local component was modified we
1786210886Spjd	 * shouldn't be here. This means that someone modified configuration
1787210886Spjd	 * file and send SIGHUP to us instead of main hastd process.
1788210886Spjd	 * Log advice and ignore the signal.
1789210886Spjd	 */
1790210886Spjd	if (res == NULL || strcmp(gres->hr_name, res->hr_name) != 0 ||
1791210886Spjd	    strcmp(gres->hr_provname, res->hr_provname) != 0 ||
1792210886Spjd	    strcmp(gres->hr_localpath, res->hr_localpath) != 0) {
1793210886Spjd		pjdlog_warning("To reload configuration send SIGHUP to the main hastd process (pid %u).",
1794210886Spjd		    (unsigned int)getppid());
1795210886Spjd		goto failed;
1796210886Spjd	}
1797210886Spjd
1798210886Spjd#define MODIFIED_REMOTEADDR	0x1
1799210886Spjd#define MODIFIED_REPLICATION	0x2
1800210886Spjd#define MODIFIED_TIMEOUT	0x4
1801211886Spjd#define MODIFIED_EXEC		0x8
1802210886Spjd	modified = 0;
1803210886Spjd	if (strcmp(gres->hr_remoteaddr, res->hr_remoteaddr) != 0) {
1804210886Spjd		/*
1805210886Spjd		 * Don't copy res->hr_remoteaddr to gres just yet.
1806210886Spjd		 * We want remote_close() to log disconnect from the old
1807210886Spjd		 * addresses, not from the new ones.
1808210886Spjd		 */
1809210886Spjd		modified |= MODIFIED_REMOTEADDR;
1810210886Spjd	}
1811210886Spjd	if (gres->hr_replication != res->hr_replication) {
1812210886Spjd		gres->hr_replication = res->hr_replication;
1813210886Spjd		modified |= MODIFIED_REPLICATION;
1814210886Spjd	}
1815210886Spjd	if (gres->hr_timeout != res->hr_timeout) {
1816210886Spjd		gres->hr_timeout = res->hr_timeout;
1817210886Spjd		modified |= MODIFIED_TIMEOUT;
1818210886Spjd	}
1819211886Spjd	if (strcmp(gres->hr_exec, res->hr_exec) != 0) {
1820211886Spjd		strlcpy(gres->hr_exec, res->hr_exec, sizeof(gres->hr_exec));
1821211886Spjd		modified |= MODIFIED_EXEC;
1822211886Spjd	}
1823210886Spjd	/*
1824210886Spjd	 * If only timeout was modified we only need to change it without
1825210886Spjd	 * reconnecting.
1826210886Spjd	 */
1827210886Spjd	if (modified == MODIFIED_TIMEOUT) {
1828210886Spjd		for (ii = 0; ii < ncomps; ii++) {
1829210886Spjd			if (!ISREMOTE(ii))
1830210886Spjd				continue;
1831210886Spjd			rw_rlock(&hio_remote_lock[ii]);
1832210886Spjd			if (!ISCONNECTED(gres, ii)) {
1833210886Spjd				rw_unlock(&hio_remote_lock[ii]);
1834210886Spjd				continue;
1835210886Spjd			}
1836210886Spjd			rw_unlock(&hio_remote_lock[ii]);
1837210886Spjd			if (proto_timeout(gres->hr_remotein,
1838210886Spjd			    gres->hr_timeout) < 0) {
1839210886Spjd				pjdlog_errno(LOG_WARNING,
1840210886Spjd				    "Unable to set connection timeout");
1841210886Spjd			}
1842210886Spjd			if (proto_timeout(gres->hr_remoteout,
1843210886Spjd			    gres->hr_timeout) < 0) {
1844210886Spjd				pjdlog_errno(LOG_WARNING,
1845210886Spjd				    "Unable to set connection timeout");
1846210886Spjd			}
1847210886Spjd		}
1848211886Spjd	} else if ((modified &
1849211886Spjd	    (MODIFIED_REMOTEADDR | MODIFIED_REPLICATION)) != 0) {
1850210886Spjd		for (ii = 0; ii < ncomps; ii++) {
1851210886Spjd			if (!ISREMOTE(ii))
1852210886Spjd				continue;
1853210886Spjd			remote_close(gres, ii);
1854210886Spjd		}
1855210886Spjd		if (modified & MODIFIED_REMOTEADDR) {
1856210886Spjd			strlcpy(gres->hr_remoteaddr, res->hr_remoteaddr,
1857210886Spjd			    sizeof(gres->hr_remoteaddr));
1858210886Spjd		}
1859210886Spjd	}
1860210886Spjd#undef	MODIFIED_REMOTEADDR
1861210886Spjd#undef	MODIFIED_REPLICATION
1862210886Spjd#undef	MODIFIED_TIMEOUT
1863211886Spjd#undef	MODIFIED_EXEC
1864210886Spjd
1865210886Spjd	pjdlog_info("Configuration reloaded successfully.");
1866210886Spjd	return;
1867210886Spjdfailed:
1868210886Spjd	if (newcfg != NULL) {
1869210886Spjd		if (newcfg->hc_controlconn != NULL)
1870210886Spjd			proto_close(newcfg->hc_controlconn);
1871210886Spjd		if (newcfg->hc_listenconn != NULL)
1872210886Spjd			proto_close(newcfg->hc_listenconn);
1873210886Spjd		yy_config_free(newcfg);
1874210886Spjd	}
1875210886Spjd	pjdlog_warning("Configuration not reloaded.");
1876210886Spjd}
1877210886Spjd
1878211882Spjdstatic void
1879211882Spjdkeepalive_send(struct hast_resource *res, unsigned int ncomp)
1880211882Spjd{
1881211882Spjd	struct nv *nv;
1882211882Spjd
1883211882Spjd	nv = nv_alloc();
1884211882Spjd	nv_add_uint8(nv, HIO_KEEPALIVE, "cmd");
1885211882Spjd	if (nv_error(nv) != 0) {
1886211882Spjd		nv_free(nv);
1887211882Spjd		pjdlog_debug(1,
1888211882Spjd		    "keepalive_send: Unable to prepare header to send.");
1889211882Spjd		return;
1890211882Spjd	}
1891211882Spjd	if (hast_proto_send(res, res->hr_remoteout, nv, NULL, 0) < 0) {
1892211882Spjd		pjdlog_common(LOG_DEBUG, 1, errno,
1893211882Spjd		    "keepalive_send: Unable to send request");
1894211882Spjd		nv_free(nv);
1895211882Spjd		rw_unlock(&hio_remote_lock[ncomp]);
1896211882Spjd		remote_close(res, ncomp);
1897211882Spjd		rw_rlock(&hio_remote_lock[ncomp]);
1898211882Spjd		return;
1899211882Spjd	}
1900211882Spjd	nv_free(nv);
1901211882Spjd	pjdlog_debug(2, "keepalive_send: Request sent.");
1902211882Spjd}
1903211882Spjd
1904204076Spjd/*
1905204076Spjd * Thread guards remote connections and reconnects when needed, handles
1906204076Spjd * signals, etc.
1907204076Spjd */
1908204076Spjdstatic void *
1909204076Spjdguard_thread(void *arg)
1910204076Spjd{
1911204076Spjd	struct hast_resource *res = arg;
1912205738Spjd	struct proto_conn *in, *out;
1913204076Spjd	unsigned int ii, ncomps;
1914204076Spjd	int timeout;
1915204076Spjd
1916204076Spjd	ncomps = HAST_NCOMPONENTS;
1917204076Spjd
1918204076Spjd	for (;;) {
1919204076Spjd		if (sigexit_received) {
1920204076Spjd			primary_exitx(EX_OK,
1921204076Spjd			    "Termination signal received, exiting.");
1922204076Spjd		}
1923210886Spjd		if (sighup_received) {
1924210886Spjd			sighup_received = false;
1925210886Spjd			config_reload();
1926210886Spjd		}
1927211886Spjd		hook_check(sigchld_received);
1928211886Spjd		if (sigchld_received)
1929211886Spjd			sigchld_received = false;
1930211882Spjd
1931211882Spjd		timeout = KEEPALIVE_SLEEP;
1932204076Spjd		pjdlog_debug(2, "remote_guard: Checking connections.");
1933204076Spjd		mtx_lock(&hio_guard_lock);
1934204076Spjd		for (ii = 0; ii < ncomps; ii++) {
1935204076Spjd			if (!ISREMOTE(ii))
1936204076Spjd				continue;
1937204076Spjd			rw_rlock(&hio_remote_lock[ii]);
1938204076Spjd			if (ISCONNECTED(res, ii)) {
1939204076Spjd				assert(res->hr_remotein != NULL);
1940204076Spjd				assert(res->hr_remoteout != NULL);
1941211882Spjd				keepalive_send(res, ii);
1942211882Spjd			}
1943211882Spjd			if (ISCONNECTED(res, ii)) {
1944211882Spjd				assert(res->hr_remotein != NULL);
1945211882Spjd				assert(res->hr_remoteout != NULL);
1946204076Spjd				rw_unlock(&hio_remote_lock[ii]);
1947204076Spjd				pjdlog_debug(2,
1948204076Spjd				    "remote_guard: Connection to %s is ok.",
1949204076Spjd				    res->hr_remoteaddr);
1950210881Spjd			} else if (real_remote(res)) {
1951204076Spjd				assert(res->hr_remotein == NULL);
1952204076Spjd				assert(res->hr_remoteout == NULL);
1953204076Spjd				/*
1954204076Spjd				 * Upgrade the lock. It doesn't have to be
1955204076Spjd				 * atomic as no other thread can change
1956204076Spjd				 * connection status from disconnected to
1957204076Spjd				 * connected.
1958204076Spjd				 */
1959204076Spjd				rw_unlock(&hio_remote_lock[ii]);
1960204076Spjd				pjdlog_debug(2,
1961204076Spjd				    "remote_guard: Reconnecting to %s.",
1962204076Spjd				    res->hr_remoteaddr);
1963205738Spjd				in = out = NULL;
1964205738Spjd				if (init_remote(res, &in, &out)) {
1965205738Spjd					rw_wlock(&hio_remote_lock[ii]);
1966205738Spjd					assert(res->hr_remotein == NULL);
1967205738Spjd					assert(res->hr_remoteout == NULL);
1968205738Spjd					assert(in != NULL && out != NULL);
1969205738Spjd					res->hr_remotein = in;
1970205738Spjd					res->hr_remoteout = out;
1971205738Spjd					rw_unlock(&hio_remote_lock[ii]);
1972204076Spjd					pjdlog_info("Successfully reconnected to %s.",
1973204076Spjd					    res->hr_remoteaddr);
1974205738Spjd					sync_start();
1975204076Spjd				} else {
1976204076Spjd					/* Both connections should be NULL. */
1977204076Spjd					assert(res->hr_remotein == NULL);
1978204076Spjd					assert(res->hr_remoteout == NULL);
1979205738Spjd					assert(in == NULL && out == NULL);
1980204076Spjd					pjdlog_debug(2,
1981204076Spjd					    "remote_guard: Reconnect to %s failed.",
1982204076Spjd					    res->hr_remoteaddr);
1983204076Spjd					timeout = RECONNECT_SLEEP;
1984204076Spjd				}
1985210881Spjd			} else {
1986210881Spjd				rw_unlock(&hio_remote_lock[ii]);
1987204076Spjd			}
1988204076Spjd		}
1989211896Spjd		/* Sleep only if a signal wasn't delivered in the meantime. */
1990211896Spjd		if (!sigexit_received && !sighup_received && !sigchld_received)
1991211896Spjd			cv_timedwait(&hio_guard_cond, &hio_guard_lock, timeout);
1992204076Spjd		mtx_unlock(&hio_guard_lock);
1993204076Spjd	}
1994204076Spjd	/* NOTREACHED */
1995204076Spjd	return (NULL);
1996204076Spjd}
1997