primary.c revision 211979
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 211979 2010-08-29 22:17: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"
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	}
789211977Spjd
790204076Spjd	(void)pidfile_close(pfh);
791211977Spjd	hook_fini();
792204076Spjd
793204076Spjd	setproctitle("%s (primary)", res->hr_name);
794204076Spjd
795210880Spjd	signal(SIGHUP, SIG_DFL);
796210880Spjd	signal(SIGCHLD, SIG_DFL);
797210880Spjd
798211886Spjd	hook_init();
799204076Spjd	init_local(res);
800210881Spjd	if (real_remote(res) && init_remote(res, NULL, NULL))
801205738Spjd		sync_start();
802204076Spjd	init_ggate(res);
803204076Spjd	init_environment(res);
804204076Spjd	error = pthread_create(&td, NULL, ggate_recv_thread, res);
805204076Spjd	assert(error == 0);
806204076Spjd	error = pthread_create(&td, NULL, local_send_thread, res);
807204076Spjd	assert(error == 0);
808204076Spjd	error = pthread_create(&td, NULL, remote_send_thread, res);
809204076Spjd	assert(error == 0);
810204076Spjd	error = pthread_create(&td, NULL, remote_recv_thread, res);
811204076Spjd	assert(error == 0);
812204076Spjd	error = pthread_create(&td, NULL, ggate_send_thread, res);
813204076Spjd	assert(error == 0);
814204076Spjd	error = pthread_create(&td, NULL, sync_thread, res);
815204076Spjd	assert(error == 0);
816204076Spjd	error = pthread_create(&td, NULL, ctrl_thread, res);
817204076Spjd	assert(error == 0);
818204076Spjd	(void)guard_thread(res);
819204076Spjd}
820204076Spjd
821204076Spjdstatic void
822204076Spjdreqlog(int loglevel, int debuglevel, struct g_gate_ctl_io *ggio, const char *fmt, ...)
823204076Spjd{
824204076Spjd	char msg[1024];
825204076Spjd	va_list ap;
826204076Spjd	int len;
827204076Spjd
828204076Spjd	va_start(ap, fmt);
829204076Spjd	len = vsnprintf(msg, sizeof(msg), fmt, ap);
830204076Spjd	va_end(ap);
831204076Spjd	if ((size_t)len < sizeof(msg)) {
832204076Spjd		switch (ggio->gctl_cmd) {
833204076Spjd		case BIO_READ:
834204076Spjd			(void)snprintf(msg + len, sizeof(msg) - len,
835204076Spjd			    "READ(%ju, %ju).", (uintmax_t)ggio->gctl_offset,
836204076Spjd			    (uintmax_t)ggio->gctl_length);
837204076Spjd			break;
838204076Spjd		case BIO_DELETE:
839204076Spjd			(void)snprintf(msg + len, sizeof(msg) - len,
840204076Spjd			    "DELETE(%ju, %ju).", (uintmax_t)ggio->gctl_offset,
841204076Spjd			    (uintmax_t)ggio->gctl_length);
842204076Spjd			break;
843204076Spjd		case BIO_FLUSH:
844204076Spjd			(void)snprintf(msg + len, sizeof(msg) - len, "FLUSH.");
845204076Spjd			break;
846204076Spjd		case BIO_WRITE:
847204076Spjd			(void)snprintf(msg + len, sizeof(msg) - len,
848204076Spjd			    "WRITE(%ju, %ju).", (uintmax_t)ggio->gctl_offset,
849204076Spjd			    (uintmax_t)ggio->gctl_length);
850204076Spjd			break;
851204076Spjd		default:
852204076Spjd			(void)snprintf(msg + len, sizeof(msg) - len,
853204076Spjd			    "UNKNOWN(%u).", (unsigned int)ggio->gctl_cmd);
854204076Spjd			break;
855204076Spjd		}
856204076Spjd	}
857204076Spjd	pjdlog_common(loglevel, debuglevel, -1, "%s", msg);
858204076Spjd}
859204076Spjd
860204076Spjdstatic void
861204076Spjdremote_close(struct hast_resource *res, int ncomp)
862204076Spjd{
863204076Spjd
864204076Spjd	rw_wlock(&hio_remote_lock[ncomp]);
865204076Spjd	/*
866204076Spjd	 * A race is possible between dropping rlock and acquiring wlock -
867204076Spjd	 * another thread can close connection in-between.
868204076Spjd	 */
869204076Spjd	if (!ISCONNECTED(res, ncomp)) {
870204076Spjd		assert(res->hr_remotein == NULL);
871204076Spjd		assert(res->hr_remoteout == NULL);
872204076Spjd		rw_unlock(&hio_remote_lock[ncomp]);
873204076Spjd		return;
874204076Spjd	}
875204076Spjd
876204076Spjd	assert(res->hr_remotein != NULL);
877204076Spjd	assert(res->hr_remoteout != NULL);
878204076Spjd
879211881Spjd	pjdlog_debug(2, "Closing incoming connection to %s.",
880204076Spjd	    res->hr_remoteaddr);
881204076Spjd	proto_close(res->hr_remotein);
882204076Spjd	res->hr_remotein = NULL;
883211881Spjd	pjdlog_debug(2, "Closing outgoing connection to %s.",
884204076Spjd	    res->hr_remoteaddr);
885204076Spjd	proto_close(res->hr_remoteout);
886204076Spjd	res->hr_remoteout = NULL;
887204076Spjd
888204076Spjd	rw_unlock(&hio_remote_lock[ncomp]);
889204076Spjd
890211881Spjd	pjdlog_warning("Disconnected from %s.", res->hr_remoteaddr);
891211881Spjd
892204076Spjd	/*
893204076Spjd	 * Stop synchronization if in-progress.
894204076Spjd	 */
895211878Spjd	sync_stop();
896204076Spjd
897204076Spjd	/*
898211882Spjd	 * Wake up guard thread (if we are not called from within guard thread),
899211882Spjd	 * so it can immediately start reconnect.
900204076Spjd	 */
901211882Spjd	if (!mtx_owned(&hio_guard_lock)) {
902211882Spjd		mtx_lock(&hio_guard_lock);
903211882Spjd		cv_signal(&hio_guard_cond);
904211882Spjd		mtx_unlock(&hio_guard_lock);
905211882Spjd	}
906204076Spjd}
907204076Spjd
908204076Spjd/*
909204076Spjd * Thread receives ggate I/O requests from the kernel and passes them to
910204076Spjd * appropriate threads:
911204076Spjd * WRITE - always goes to both local_send and remote_send threads
912204076Spjd * READ (when the block is up-to-date on local component) -
913204076Spjd *	only local_send thread
914204076Spjd * READ (when the block isn't up-to-date on local component) -
915204076Spjd *	only remote_send thread
916204076Spjd * DELETE - always goes to both local_send and remote_send threads
917204076Spjd * FLUSH - always goes to both local_send and remote_send threads
918204076Spjd */
919204076Spjdstatic void *
920204076Spjdggate_recv_thread(void *arg)
921204076Spjd{
922204076Spjd	struct hast_resource *res = arg;
923204076Spjd	struct g_gate_ctl_io *ggio;
924204076Spjd	struct hio *hio;
925204076Spjd	unsigned int ii, ncomp, ncomps;
926204076Spjd	int error;
927204076Spjd
928204076Spjd	ncomps = HAST_NCOMPONENTS;
929204076Spjd
930204076Spjd	for (;;) {
931204076Spjd		pjdlog_debug(2, "ggate_recv: Taking free request.");
932204076Spjd		QUEUE_TAKE2(hio, free);
933204076Spjd		pjdlog_debug(2, "ggate_recv: (%p) Got free request.", hio);
934204076Spjd		ggio = &hio->hio_ggio;
935204076Spjd		ggio->gctl_unit = res->hr_ggateunit;
936204076Spjd		ggio->gctl_length = MAXPHYS;
937204076Spjd		ggio->gctl_error = 0;
938204076Spjd		pjdlog_debug(2,
939204076Spjd		    "ggate_recv: (%p) Waiting for request from the kernel.",
940204076Spjd		    hio);
941204076Spjd		if (ioctl(res->hr_ggatefd, G_GATE_CMD_START, ggio) < 0) {
942204076Spjd			if (sigexit_received)
943204076Spjd				pthread_exit(NULL);
944204076Spjd			primary_exit(EX_OSERR, "G_GATE_CMD_START failed");
945204076Spjd		}
946204076Spjd		error = ggio->gctl_error;
947204076Spjd		switch (error) {
948204076Spjd		case 0:
949204076Spjd			break;
950204076Spjd		case ECANCELED:
951204076Spjd			/* Exit gracefully. */
952204076Spjd			if (!sigexit_received) {
953204076Spjd				pjdlog_debug(2,
954204076Spjd				    "ggate_recv: (%p) Received cancel from the kernel.",
955204076Spjd				    hio);
956204076Spjd				pjdlog_info("Received cancel from the kernel, exiting.");
957204076Spjd			}
958204076Spjd			pthread_exit(NULL);
959204076Spjd		case ENOMEM:
960204076Spjd			/*
961204076Spjd			 * Buffer too small? Impossible, we allocate MAXPHYS
962204076Spjd			 * bytes - request can't be bigger than that.
963204076Spjd			 */
964204076Spjd			/* FALLTHROUGH */
965204076Spjd		case ENXIO:
966204076Spjd		default:
967204076Spjd			primary_exitx(EX_OSERR, "G_GATE_CMD_START failed: %s.",
968204076Spjd			    strerror(error));
969204076Spjd		}
970204076Spjd		for (ii = 0; ii < ncomps; ii++)
971204076Spjd			hio->hio_errors[ii] = EINVAL;
972204076Spjd		reqlog(LOG_DEBUG, 2, ggio,
973204076Spjd		    "ggate_recv: (%p) Request received from the kernel: ",
974204076Spjd		    hio);
975204076Spjd		/*
976204076Spjd		 * Inform all components about new write request.
977204076Spjd		 * For read request prefer local component unless the given
978204076Spjd		 * range is out-of-date, then use remote component.
979204076Spjd		 */
980204076Spjd		switch (ggio->gctl_cmd) {
981204076Spjd		case BIO_READ:
982204076Spjd			pjdlog_debug(2,
983204076Spjd			    "ggate_recv: (%p) Moving request to the send queue.",
984204076Spjd			    hio);
985204076Spjd			refcount_init(&hio->hio_countdown, 1);
986204076Spjd			mtx_lock(&metadata_lock);
987204076Spjd			if (res->hr_syncsrc == HAST_SYNCSRC_UNDEF ||
988204076Spjd			    res->hr_syncsrc == HAST_SYNCSRC_PRIMARY) {
989204076Spjd				/*
990204076Spjd				 * This range is up-to-date on local component,
991204076Spjd				 * so handle request locally.
992204076Spjd				 */
993204076Spjd				 /* Local component is 0 for now. */
994204076Spjd				ncomp = 0;
995204076Spjd			} else /* if (res->hr_syncsrc ==
996204076Spjd			    HAST_SYNCSRC_SECONDARY) */ {
997204076Spjd				assert(res->hr_syncsrc ==
998204076Spjd				    HAST_SYNCSRC_SECONDARY);
999204076Spjd				/*
1000204076Spjd				 * This range is out-of-date on local component,
1001204076Spjd				 * so send request to the remote node.
1002204076Spjd				 */
1003204076Spjd				 /* Remote component is 1 for now. */
1004204076Spjd				ncomp = 1;
1005204076Spjd			}
1006204076Spjd			mtx_unlock(&metadata_lock);
1007204076Spjd			QUEUE_INSERT1(hio, send, ncomp);
1008204076Spjd			break;
1009204076Spjd		case BIO_WRITE:
1010204076Spjd			for (;;) {
1011204076Spjd				mtx_lock(&range_lock);
1012204076Spjd				if (rangelock_islocked(range_sync,
1013204076Spjd				    ggio->gctl_offset, ggio->gctl_length)) {
1014204076Spjd					pjdlog_debug(2,
1015204076Spjd					    "regular: Range offset=%jd length=%zu locked.",
1016204076Spjd					    (intmax_t)ggio->gctl_offset,
1017204076Spjd					    (size_t)ggio->gctl_length);
1018204076Spjd					range_regular_wait = true;
1019204076Spjd					cv_wait(&range_regular_cond, &range_lock);
1020204076Spjd					range_regular_wait = false;
1021204076Spjd					mtx_unlock(&range_lock);
1022204076Spjd					continue;
1023204076Spjd				}
1024204076Spjd				if (rangelock_add(range_regular,
1025204076Spjd				    ggio->gctl_offset, ggio->gctl_length) < 0) {
1026204076Spjd					mtx_unlock(&range_lock);
1027204076Spjd					pjdlog_debug(2,
1028204076Spjd					    "regular: Range offset=%jd length=%zu is already locked, waiting.",
1029204076Spjd					    (intmax_t)ggio->gctl_offset,
1030204076Spjd					    (size_t)ggio->gctl_length);
1031204076Spjd					sleep(1);
1032204076Spjd					continue;
1033204076Spjd				}
1034204076Spjd				mtx_unlock(&range_lock);
1035204076Spjd				break;
1036204076Spjd			}
1037204076Spjd			mtx_lock(&res->hr_amp_lock);
1038204076Spjd			if (activemap_write_start(res->hr_amp,
1039204076Spjd			    ggio->gctl_offset, ggio->gctl_length)) {
1040204076Spjd				(void)hast_activemap_flush(res);
1041204076Spjd			}
1042204076Spjd			mtx_unlock(&res->hr_amp_lock);
1043204076Spjd			/* FALLTHROUGH */
1044204076Spjd		case BIO_DELETE:
1045204076Spjd		case BIO_FLUSH:
1046204076Spjd			pjdlog_debug(2,
1047204076Spjd			    "ggate_recv: (%p) Moving request to the send queues.",
1048204076Spjd			    hio);
1049204076Spjd			refcount_init(&hio->hio_countdown, ncomps);
1050204076Spjd			for (ii = 0; ii < ncomps; ii++)
1051204076Spjd				QUEUE_INSERT1(hio, send, ii);
1052204076Spjd			break;
1053204076Spjd		}
1054204076Spjd	}
1055204076Spjd	/* NOTREACHED */
1056204076Spjd	return (NULL);
1057204076Spjd}
1058204076Spjd
1059204076Spjd/*
1060204076Spjd * Thread reads from or writes to local component.
1061204076Spjd * If local read fails, it redirects it to remote_send thread.
1062204076Spjd */
1063204076Spjdstatic void *
1064204076Spjdlocal_send_thread(void *arg)
1065204076Spjd{
1066204076Spjd	struct hast_resource *res = arg;
1067204076Spjd	struct g_gate_ctl_io *ggio;
1068204076Spjd	struct hio *hio;
1069204076Spjd	unsigned int ncomp, rncomp;
1070204076Spjd	ssize_t ret;
1071204076Spjd
1072204076Spjd	/* Local component is 0 for now. */
1073204076Spjd	ncomp = 0;
1074204076Spjd	/* Remote component is 1 for now. */
1075204076Spjd	rncomp = 1;
1076204076Spjd
1077204076Spjd	for (;;) {
1078204076Spjd		pjdlog_debug(2, "local_send: Taking request.");
1079204076Spjd		QUEUE_TAKE1(hio, send, ncomp);
1080204076Spjd		pjdlog_debug(2, "local_send: (%p) Got request.", hio);
1081204076Spjd		ggio = &hio->hio_ggio;
1082204076Spjd		switch (ggio->gctl_cmd) {
1083204076Spjd		case BIO_READ:
1084204076Spjd			ret = pread(res->hr_localfd, ggio->gctl_data,
1085204076Spjd			    ggio->gctl_length,
1086204076Spjd			    ggio->gctl_offset + res->hr_localoff);
1087204076Spjd			if (ret == ggio->gctl_length)
1088204076Spjd				hio->hio_errors[ncomp] = 0;
1089204076Spjd			else {
1090204076Spjd				/*
1091204076Spjd				 * If READ failed, try to read from remote node.
1092204076Spjd				 */
1093204076Spjd				QUEUE_INSERT1(hio, send, rncomp);
1094204076Spjd				continue;
1095204076Spjd			}
1096204076Spjd			break;
1097204076Spjd		case BIO_WRITE:
1098204076Spjd			ret = pwrite(res->hr_localfd, ggio->gctl_data,
1099204076Spjd			    ggio->gctl_length,
1100204076Spjd			    ggio->gctl_offset + res->hr_localoff);
1101204076Spjd			if (ret < 0)
1102204076Spjd				hio->hio_errors[ncomp] = errno;
1103204076Spjd			else if (ret != ggio->gctl_length)
1104204076Spjd				hio->hio_errors[ncomp] = EIO;
1105204076Spjd			else
1106204076Spjd				hio->hio_errors[ncomp] = 0;
1107204076Spjd			break;
1108204076Spjd		case BIO_DELETE:
1109204076Spjd			ret = g_delete(res->hr_localfd,
1110204076Spjd			    ggio->gctl_offset + res->hr_localoff,
1111204076Spjd			    ggio->gctl_length);
1112204076Spjd			if (ret < 0)
1113204076Spjd				hio->hio_errors[ncomp] = errno;
1114204076Spjd			else
1115204076Spjd				hio->hio_errors[ncomp] = 0;
1116204076Spjd			break;
1117204076Spjd		case BIO_FLUSH:
1118204076Spjd			ret = g_flush(res->hr_localfd);
1119204076Spjd			if (ret < 0)
1120204076Spjd				hio->hio_errors[ncomp] = errno;
1121204076Spjd			else
1122204076Spjd				hio->hio_errors[ncomp] = 0;
1123204076Spjd			break;
1124204076Spjd		}
1125204076Spjd		if (refcount_release(&hio->hio_countdown)) {
1126204076Spjd			if (ISSYNCREQ(hio)) {
1127204076Spjd				mtx_lock(&sync_lock);
1128204076Spjd				SYNCREQDONE(hio);
1129204076Spjd				mtx_unlock(&sync_lock);
1130204076Spjd				cv_signal(&sync_cond);
1131204076Spjd			} else {
1132204076Spjd				pjdlog_debug(2,
1133204076Spjd				    "local_send: (%p) Moving request to the done queue.",
1134204076Spjd				    hio);
1135204076Spjd				QUEUE_INSERT2(hio, done);
1136204076Spjd			}
1137204076Spjd		}
1138204076Spjd	}
1139204076Spjd	/* NOTREACHED */
1140204076Spjd	return (NULL);
1141204076Spjd}
1142204076Spjd
1143204076Spjd/*
1144204076Spjd * Thread sends request to secondary node.
1145204076Spjd */
1146204076Spjdstatic void *
1147204076Spjdremote_send_thread(void *arg)
1148204076Spjd{
1149204076Spjd	struct hast_resource *res = arg;
1150204076Spjd	struct g_gate_ctl_io *ggio;
1151204076Spjd	struct hio *hio;
1152204076Spjd	struct nv *nv;
1153204076Spjd	unsigned int ncomp;
1154204076Spjd	bool wakeup;
1155204076Spjd	uint64_t offset, length;
1156204076Spjd	uint8_t cmd;
1157204076Spjd	void *data;
1158204076Spjd
1159204076Spjd	/* Remote component is 1 for now. */
1160204076Spjd	ncomp = 1;
1161204076Spjd
1162204076Spjd	for (;;) {
1163204076Spjd		pjdlog_debug(2, "remote_send: Taking request.");
1164204076Spjd		QUEUE_TAKE1(hio, send, ncomp);
1165204076Spjd		pjdlog_debug(2, "remote_send: (%p) Got request.", hio);
1166204076Spjd		ggio = &hio->hio_ggio;
1167204076Spjd		switch (ggio->gctl_cmd) {
1168204076Spjd		case BIO_READ:
1169204076Spjd			cmd = HIO_READ;
1170204076Spjd			data = NULL;
1171204076Spjd			offset = ggio->gctl_offset;
1172204076Spjd			length = ggio->gctl_length;
1173204076Spjd			break;
1174204076Spjd		case BIO_WRITE:
1175204076Spjd			cmd = HIO_WRITE;
1176204076Spjd			data = ggio->gctl_data;
1177204076Spjd			offset = ggio->gctl_offset;
1178204076Spjd			length = ggio->gctl_length;
1179204076Spjd			break;
1180204076Spjd		case BIO_DELETE:
1181204076Spjd			cmd = HIO_DELETE;
1182204076Spjd			data = NULL;
1183204076Spjd			offset = ggio->gctl_offset;
1184204076Spjd			length = ggio->gctl_length;
1185204076Spjd			break;
1186204076Spjd		case BIO_FLUSH:
1187204076Spjd			cmd = HIO_FLUSH;
1188204076Spjd			data = NULL;
1189204076Spjd			offset = 0;
1190204076Spjd			length = 0;
1191204076Spjd			break;
1192204076Spjd		default:
1193204076Spjd			assert(!"invalid condition");
1194204076Spjd			abort();
1195204076Spjd		}
1196204076Spjd		nv = nv_alloc();
1197204076Spjd		nv_add_uint8(nv, cmd, "cmd");
1198204076Spjd		nv_add_uint64(nv, (uint64_t)ggio->gctl_seq, "seq");
1199204076Spjd		nv_add_uint64(nv, offset, "offset");
1200204076Spjd		nv_add_uint64(nv, length, "length");
1201204076Spjd		if (nv_error(nv) != 0) {
1202204076Spjd			hio->hio_errors[ncomp] = nv_error(nv);
1203204076Spjd			pjdlog_debug(2,
1204204076Spjd			    "remote_send: (%p) Unable to prepare header to send.",
1205204076Spjd			    hio);
1206204076Spjd			reqlog(LOG_ERR, 0, ggio,
1207204076Spjd			    "Unable to prepare header to send (%s): ",
1208204076Spjd			    strerror(nv_error(nv)));
1209204076Spjd			/* Move failed request immediately to the done queue. */
1210204076Spjd			goto done_queue;
1211204076Spjd		}
1212204076Spjd		pjdlog_debug(2,
1213204076Spjd		    "remote_send: (%p) Moving request to the recv queue.",
1214204076Spjd		    hio);
1215204076Spjd		/*
1216204076Spjd		 * Protect connection from disappearing.
1217204076Spjd		 */
1218204076Spjd		rw_rlock(&hio_remote_lock[ncomp]);
1219204076Spjd		if (!ISCONNECTED(res, ncomp)) {
1220204076Spjd			rw_unlock(&hio_remote_lock[ncomp]);
1221204076Spjd			hio->hio_errors[ncomp] = ENOTCONN;
1222204076Spjd			goto done_queue;
1223204076Spjd		}
1224204076Spjd		/*
1225204076Spjd		 * Move the request to recv queue before sending it, because
1226204076Spjd		 * in different order we can get reply before we move request
1227204076Spjd		 * to recv queue.
1228204076Spjd		 */
1229204076Spjd		mtx_lock(&hio_recv_list_lock[ncomp]);
1230204076Spjd		wakeup = TAILQ_EMPTY(&hio_recv_list[ncomp]);
1231204076Spjd		TAILQ_INSERT_TAIL(&hio_recv_list[ncomp], hio, hio_next[ncomp]);
1232204076Spjd		mtx_unlock(&hio_recv_list_lock[ncomp]);
1233204076Spjd		if (hast_proto_send(res, res->hr_remoteout, nv, data,
1234204076Spjd		    data != NULL ? length : 0) < 0) {
1235204076Spjd			hio->hio_errors[ncomp] = errno;
1236204076Spjd			rw_unlock(&hio_remote_lock[ncomp]);
1237204076Spjd			pjdlog_debug(2,
1238204076Spjd			    "remote_send: (%p) Unable to send request.", hio);
1239204076Spjd			reqlog(LOG_ERR, 0, ggio,
1240204076Spjd			    "Unable to send request (%s): ",
1241204076Spjd			    strerror(hio->hio_errors[ncomp]));
1242211979Spjd			remote_close(res, ncomp);
1243204076Spjd			/*
1244204076Spjd			 * Take request back from the receive queue and move
1245204076Spjd			 * it immediately to the done queue.
1246204076Spjd			 */
1247204076Spjd			mtx_lock(&hio_recv_list_lock[ncomp]);
1248204076Spjd			TAILQ_REMOVE(&hio_recv_list[ncomp], hio, hio_next[ncomp]);
1249204076Spjd			mtx_unlock(&hio_recv_list_lock[ncomp]);
1250204076Spjd			goto done_queue;
1251204076Spjd		}
1252204076Spjd		rw_unlock(&hio_remote_lock[ncomp]);
1253204076Spjd		nv_free(nv);
1254204076Spjd		if (wakeup)
1255204076Spjd			cv_signal(&hio_recv_list_cond[ncomp]);
1256204076Spjd		continue;
1257204076Spjddone_queue:
1258204076Spjd		nv_free(nv);
1259204076Spjd		if (ISSYNCREQ(hio)) {
1260204076Spjd			if (!refcount_release(&hio->hio_countdown))
1261204076Spjd				continue;
1262204076Spjd			mtx_lock(&sync_lock);
1263204076Spjd			SYNCREQDONE(hio);
1264204076Spjd			mtx_unlock(&sync_lock);
1265204076Spjd			cv_signal(&sync_cond);
1266204076Spjd			continue;
1267204076Spjd		}
1268204076Spjd		if (ggio->gctl_cmd == BIO_WRITE) {
1269204076Spjd			mtx_lock(&res->hr_amp_lock);
1270204076Spjd			if (activemap_need_sync(res->hr_amp, ggio->gctl_offset,
1271204076Spjd			    ggio->gctl_length)) {
1272204076Spjd				(void)hast_activemap_flush(res);
1273204076Spjd			}
1274204076Spjd			mtx_unlock(&res->hr_amp_lock);
1275204076Spjd		}
1276204076Spjd		if (!refcount_release(&hio->hio_countdown))
1277204076Spjd			continue;
1278204076Spjd		pjdlog_debug(2,
1279204076Spjd		    "remote_send: (%p) Moving request to the done queue.",
1280204076Spjd		    hio);
1281204076Spjd		QUEUE_INSERT2(hio, done);
1282204076Spjd	}
1283204076Spjd	/* NOTREACHED */
1284204076Spjd	return (NULL);
1285204076Spjd}
1286204076Spjd
1287204076Spjd/*
1288204076Spjd * Thread receives answer from secondary node and passes it to ggate_send
1289204076Spjd * thread.
1290204076Spjd */
1291204076Spjdstatic void *
1292204076Spjdremote_recv_thread(void *arg)
1293204076Spjd{
1294204076Spjd	struct hast_resource *res = arg;
1295204076Spjd	struct g_gate_ctl_io *ggio;
1296204076Spjd	struct hio *hio;
1297204076Spjd	struct nv *nv;
1298204076Spjd	unsigned int ncomp;
1299204076Spjd	uint64_t seq;
1300204076Spjd	int error;
1301204076Spjd
1302204076Spjd	/* Remote component is 1 for now. */
1303204076Spjd	ncomp = 1;
1304204076Spjd
1305204076Spjd	for (;;) {
1306204076Spjd		/* Wait until there is anything to receive. */
1307204076Spjd		mtx_lock(&hio_recv_list_lock[ncomp]);
1308204076Spjd		while (TAILQ_EMPTY(&hio_recv_list[ncomp])) {
1309204076Spjd			pjdlog_debug(2, "remote_recv: No requests, waiting.");
1310204076Spjd			cv_wait(&hio_recv_list_cond[ncomp],
1311204076Spjd			    &hio_recv_list_lock[ncomp]);
1312204076Spjd		}
1313204076Spjd		mtx_unlock(&hio_recv_list_lock[ncomp]);
1314204076Spjd		rw_rlock(&hio_remote_lock[ncomp]);
1315204076Spjd		if (!ISCONNECTED(res, ncomp)) {
1316204076Spjd			rw_unlock(&hio_remote_lock[ncomp]);
1317204076Spjd			/*
1318204076Spjd			 * Connection is dead, so move all pending requests to
1319204076Spjd			 * the done queue (one-by-one).
1320204076Spjd			 */
1321204076Spjd			mtx_lock(&hio_recv_list_lock[ncomp]);
1322204076Spjd			hio = TAILQ_FIRST(&hio_recv_list[ncomp]);
1323204076Spjd			assert(hio != NULL);
1324204076Spjd			TAILQ_REMOVE(&hio_recv_list[ncomp], hio,
1325204076Spjd			    hio_next[ncomp]);
1326204076Spjd			mtx_unlock(&hio_recv_list_lock[ncomp]);
1327204076Spjd			goto done_queue;
1328204076Spjd		}
1329204076Spjd		if (hast_proto_recv_hdr(res->hr_remotein, &nv) < 0) {
1330204076Spjd			pjdlog_errno(LOG_ERR,
1331204076Spjd			    "Unable to receive reply header");
1332204076Spjd			rw_unlock(&hio_remote_lock[ncomp]);
1333204076Spjd			remote_close(res, ncomp);
1334204076Spjd			continue;
1335204076Spjd		}
1336204076Spjd		rw_unlock(&hio_remote_lock[ncomp]);
1337204076Spjd		seq = nv_get_uint64(nv, "seq");
1338204076Spjd		if (seq == 0) {
1339204076Spjd			pjdlog_error("Header contains no 'seq' field.");
1340204076Spjd			nv_free(nv);
1341204076Spjd			continue;
1342204076Spjd		}
1343204076Spjd		mtx_lock(&hio_recv_list_lock[ncomp]);
1344204076Spjd		TAILQ_FOREACH(hio, &hio_recv_list[ncomp], hio_next[ncomp]) {
1345204076Spjd			if (hio->hio_ggio.gctl_seq == seq) {
1346204076Spjd				TAILQ_REMOVE(&hio_recv_list[ncomp], hio,
1347204076Spjd				    hio_next[ncomp]);
1348204076Spjd				break;
1349204076Spjd			}
1350204076Spjd		}
1351204076Spjd		mtx_unlock(&hio_recv_list_lock[ncomp]);
1352204076Spjd		if (hio == NULL) {
1353204076Spjd			pjdlog_error("Found no request matching received 'seq' field (%ju).",
1354204076Spjd			    (uintmax_t)seq);
1355204076Spjd			nv_free(nv);
1356204076Spjd			continue;
1357204076Spjd		}
1358204076Spjd		error = nv_get_int16(nv, "error");
1359204076Spjd		if (error != 0) {
1360204076Spjd			/* Request failed on remote side. */
1361204076Spjd			hio->hio_errors[ncomp] = 0;
1362204076Spjd			nv_free(nv);
1363204076Spjd			goto done_queue;
1364204076Spjd		}
1365204076Spjd		ggio = &hio->hio_ggio;
1366204076Spjd		switch (ggio->gctl_cmd) {
1367204076Spjd		case BIO_READ:
1368204076Spjd			rw_rlock(&hio_remote_lock[ncomp]);
1369204076Spjd			if (!ISCONNECTED(res, ncomp)) {
1370204076Spjd				rw_unlock(&hio_remote_lock[ncomp]);
1371204076Spjd				nv_free(nv);
1372204076Spjd				goto done_queue;
1373204076Spjd			}
1374204076Spjd			if (hast_proto_recv_data(res, res->hr_remotein, nv,
1375204076Spjd			    ggio->gctl_data, ggio->gctl_length) < 0) {
1376204076Spjd				hio->hio_errors[ncomp] = errno;
1377204076Spjd				pjdlog_errno(LOG_ERR,
1378204076Spjd				    "Unable to receive reply data");
1379204076Spjd				rw_unlock(&hio_remote_lock[ncomp]);
1380204076Spjd				nv_free(nv);
1381204076Spjd				remote_close(res, ncomp);
1382204076Spjd				goto done_queue;
1383204076Spjd			}
1384204076Spjd			rw_unlock(&hio_remote_lock[ncomp]);
1385204076Spjd			break;
1386204076Spjd		case BIO_WRITE:
1387204076Spjd		case BIO_DELETE:
1388204076Spjd		case BIO_FLUSH:
1389204076Spjd			break;
1390204076Spjd		default:
1391204076Spjd			assert(!"invalid condition");
1392204076Spjd			abort();
1393204076Spjd		}
1394204076Spjd		hio->hio_errors[ncomp] = 0;
1395204076Spjd		nv_free(nv);
1396204076Spjddone_queue:
1397204076Spjd		if (refcount_release(&hio->hio_countdown)) {
1398204076Spjd			if (ISSYNCREQ(hio)) {
1399204076Spjd				mtx_lock(&sync_lock);
1400204076Spjd				SYNCREQDONE(hio);
1401204076Spjd				mtx_unlock(&sync_lock);
1402204076Spjd				cv_signal(&sync_cond);
1403204076Spjd			} else {
1404204076Spjd				pjdlog_debug(2,
1405204076Spjd				    "remote_recv: (%p) Moving request to the done queue.",
1406204076Spjd				    hio);
1407204076Spjd				QUEUE_INSERT2(hio, done);
1408204076Spjd			}
1409204076Spjd		}
1410204076Spjd	}
1411204076Spjd	/* NOTREACHED */
1412204076Spjd	return (NULL);
1413204076Spjd}
1414204076Spjd
1415204076Spjd/*
1416204076Spjd * Thread sends answer to the kernel.
1417204076Spjd */
1418204076Spjdstatic void *
1419204076Spjdggate_send_thread(void *arg)
1420204076Spjd{
1421204076Spjd	struct hast_resource *res = arg;
1422204076Spjd	struct g_gate_ctl_io *ggio;
1423204076Spjd	struct hio *hio;
1424204076Spjd	unsigned int ii, ncomp, ncomps;
1425204076Spjd
1426204076Spjd	ncomps = HAST_NCOMPONENTS;
1427204076Spjd
1428204076Spjd	for (;;) {
1429204076Spjd		pjdlog_debug(2, "ggate_send: Taking request.");
1430204076Spjd		QUEUE_TAKE2(hio, done);
1431204076Spjd		pjdlog_debug(2, "ggate_send: (%p) Got request.", hio);
1432204076Spjd		ggio = &hio->hio_ggio;
1433204076Spjd		for (ii = 0; ii < ncomps; ii++) {
1434204076Spjd			if (hio->hio_errors[ii] == 0) {
1435204076Spjd				/*
1436204076Spjd				 * One successful request is enough to declare
1437204076Spjd				 * success.
1438204076Spjd				 */
1439204076Spjd				ggio->gctl_error = 0;
1440204076Spjd				break;
1441204076Spjd			}
1442204076Spjd		}
1443204076Spjd		if (ii == ncomps) {
1444204076Spjd			/*
1445204076Spjd			 * None of the requests were successful.
1446204076Spjd			 * Use first error.
1447204076Spjd			 */
1448204076Spjd			ggio->gctl_error = hio->hio_errors[0];
1449204076Spjd		}
1450204076Spjd		if (ggio->gctl_error == 0 && ggio->gctl_cmd == BIO_WRITE) {
1451204076Spjd			mtx_lock(&res->hr_amp_lock);
1452204076Spjd			activemap_write_complete(res->hr_amp,
1453204076Spjd			    ggio->gctl_offset, ggio->gctl_length);
1454204076Spjd			mtx_unlock(&res->hr_amp_lock);
1455204076Spjd		}
1456204076Spjd		if (ggio->gctl_cmd == BIO_WRITE) {
1457204076Spjd			/*
1458204076Spjd			 * Unlock range we locked.
1459204076Spjd			 */
1460204076Spjd			mtx_lock(&range_lock);
1461204076Spjd			rangelock_del(range_regular, ggio->gctl_offset,
1462204076Spjd			    ggio->gctl_length);
1463204076Spjd			if (range_sync_wait)
1464204076Spjd				cv_signal(&range_sync_cond);
1465204076Spjd			mtx_unlock(&range_lock);
1466204076Spjd			/*
1467204076Spjd			 * Bump local count if this is first write after
1468204076Spjd			 * connection failure with remote node.
1469204076Spjd			 */
1470204076Spjd			ncomp = 1;
1471204076Spjd			rw_rlock(&hio_remote_lock[ncomp]);
1472204076Spjd			if (!ISCONNECTED(res, ncomp)) {
1473204076Spjd				mtx_lock(&metadata_lock);
1474204076Spjd				if (res->hr_primary_localcnt ==
1475204076Spjd				    res->hr_secondary_remotecnt) {
1476204076Spjd					res->hr_primary_localcnt++;
1477204076Spjd					pjdlog_debug(1,
1478204076Spjd					    "Increasing localcnt to %ju.",
1479204076Spjd					    (uintmax_t)res->hr_primary_localcnt);
1480204076Spjd					(void)metadata_write(res);
1481204076Spjd				}
1482204076Spjd				mtx_unlock(&metadata_lock);
1483204076Spjd			}
1484204076Spjd			rw_unlock(&hio_remote_lock[ncomp]);
1485204076Spjd		}
1486204076Spjd		if (ioctl(res->hr_ggatefd, G_GATE_CMD_DONE, ggio) < 0)
1487204076Spjd			primary_exit(EX_OSERR, "G_GATE_CMD_DONE failed");
1488204076Spjd		pjdlog_debug(2,
1489204076Spjd		    "ggate_send: (%p) Moving request to the free queue.", hio);
1490204076Spjd		QUEUE_INSERT2(hio, free);
1491204076Spjd	}
1492204076Spjd	/* NOTREACHED */
1493204076Spjd	return (NULL);
1494204076Spjd}
1495204076Spjd
1496204076Spjd/*
1497204076Spjd * Thread synchronize local and remote components.
1498204076Spjd */
1499204076Spjdstatic void *
1500204076Spjdsync_thread(void *arg __unused)
1501204076Spjd{
1502204076Spjd	struct hast_resource *res = arg;
1503204076Spjd	struct hio *hio;
1504204076Spjd	struct g_gate_ctl_io *ggio;
1505204076Spjd	unsigned int ii, ncomp, ncomps;
1506204076Spjd	off_t offset, length, synced;
1507204076Spjd	bool dorewind;
1508204076Spjd	int syncext;
1509204076Spjd
1510204076Spjd	ncomps = HAST_NCOMPONENTS;
1511204076Spjd	dorewind = true;
1512211897Spjd	synced = 0;
1513211897Spjd	offset = -1;
1514204076Spjd
1515204076Spjd	for (;;) {
1516204076Spjd		mtx_lock(&sync_lock);
1517211897Spjd		if (offset >= 0 && !sync_inprogress) {
1518211879Spjd			pjdlog_info("Synchronization interrupted. "
1519211879Spjd			    "%jd bytes synchronized so far.",
1520211879Spjd			    (intmax_t)synced);
1521211897Spjd			hook_exec(res->hr_exec, "syncintr", res->hr_name, NULL);
1522211879Spjd		}
1523204076Spjd		while (!sync_inprogress) {
1524204076Spjd			dorewind = true;
1525204076Spjd			synced = 0;
1526204076Spjd			cv_wait(&sync_cond, &sync_lock);
1527204076Spjd		}
1528204076Spjd		mtx_unlock(&sync_lock);
1529204076Spjd		/*
1530204076Spjd		 * Obtain offset at which we should synchronize.
1531204076Spjd		 * Rewind synchronization if needed.
1532204076Spjd		 */
1533204076Spjd		mtx_lock(&res->hr_amp_lock);
1534204076Spjd		if (dorewind)
1535204076Spjd			activemap_sync_rewind(res->hr_amp);
1536204076Spjd		offset = activemap_sync_offset(res->hr_amp, &length, &syncext);
1537204076Spjd		if (syncext != -1) {
1538204076Spjd			/*
1539204076Spjd			 * We synchronized entire syncext extent, we can mark
1540204076Spjd			 * it as clean now.
1541204076Spjd			 */
1542204076Spjd			if (activemap_extent_complete(res->hr_amp, syncext))
1543204076Spjd				(void)hast_activemap_flush(res);
1544204076Spjd		}
1545204076Spjd		mtx_unlock(&res->hr_amp_lock);
1546204076Spjd		if (dorewind) {
1547204076Spjd			dorewind = false;
1548204076Spjd			if (offset < 0)
1549204076Spjd				pjdlog_info("Nodes are in sync.");
1550204076Spjd			else {
1551204076Spjd				pjdlog_info("Synchronization started. %ju bytes to go.",
1552204076Spjd				    (uintmax_t)(res->hr_extentsize *
1553204076Spjd				    activemap_ndirty(res->hr_amp)));
1554211895Spjd				hook_exec(res->hr_exec, "syncstart",
1555211895Spjd				    res->hr_name, NULL);
1556204076Spjd			}
1557204076Spjd		}
1558204076Spjd		if (offset < 0) {
1559211878Spjd			sync_stop();
1560204076Spjd			pjdlog_debug(1, "Nothing to synchronize.");
1561204076Spjd			/*
1562204076Spjd			 * Synchronization complete, make both localcnt and
1563204076Spjd			 * remotecnt equal.
1564204076Spjd			 */
1565204076Spjd			ncomp = 1;
1566204076Spjd			rw_rlock(&hio_remote_lock[ncomp]);
1567204076Spjd			if (ISCONNECTED(res, ncomp)) {
1568204076Spjd				if (synced > 0) {
1569204076Spjd					pjdlog_info("Synchronization complete. "
1570204076Spjd					    "%jd bytes synchronized.",
1571204076Spjd					    (intmax_t)synced);
1572211895Spjd					hook_exec(res->hr_exec, "syncdone",
1573211895Spjd					    res->hr_name, NULL);
1574204076Spjd				}
1575204076Spjd				mtx_lock(&metadata_lock);
1576204076Spjd				res->hr_syncsrc = HAST_SYNCSRC_UNDEF;
1577204076Spjd				res->hr_primary_localcnt =
1578204076Spjd				    res->hr_secondary_localcnt;
1579204076Spjd				res->hr_primary_remotecnt =
1580204076Spjd				    res->hr_secondary_remotecnt;
1581204076Spjd				pjdlog_debug(1,
1582204076Spjd				    "Setting localcnt to %ju and remotecnt to %ju.",
1583204076Spjd				    (uintmax_t)res->hr_primary_localcnt,
1584204076Spjd				    (uintmax_t)res->hr_secondary_localcnt);
1585204076Spjd				(void)metadata_write(res);
1586204076Spjd				mtx_unlock(&metadata_lock);
1587204076Spjd			}
1588204076Spjd			rw_unlock(&hio_remote_lock[ncomp]);
1589204076Spjd			continue;
1590204076Spjd		}
1591204076Spjd		pjdlog_debug(2, "sync: Taking free request.");
1592204076Spjd		QUEUE_TAKE2(hio, free);
1593204076Spjd		pjdlog_debug(2, "sync: (%p) Got free request.", hio);
1594204076Spjd		/*
1595204076Spjd		 * Lock the range we are going to synchronize. We don't want
1596204076Spjd		 * race where someone writes between our read and write.
1597204076Spjd		 */
1598204076Spjd		for (;;) {
1599204076Spjd			mtx_lock(&range_lock);
1600204076Spjd			if (rangelock_islocked(range_regular, offset, length)) {
1601204076Spjd				pjdlog_debug(2,
1602204076Spjd				    "sync: Range offset=%jd length=%jd locked.",
1603204076Spjd				    (intmax_t)offset, (intmax_t)length);
1604204076Spjd				range_sync_wait = true;
1605204076Spjd				cv_wait(&range_sync_cond, &range_lock);
1606204076Spjd				range_sync_wait = false;
1607204076Spjd				mtx_unlock(&range_lock);
1608204076Spjd				continue;
1609204076Spjd			}
1610204076Spjd			if (rangelock_add(range_sync, offset, length) < 0) {
1611204076Spjd				mtx_unlock(&range_lock);
1612204076Spjd				pjdlog_debug(2,
1613204076Spjd				    "sync: Range offset=%jd length=%jd is already locked, waiting.",
1614204076Spjd				    (intmax_t)offset, (intmax_t)length);
1615204076Spjd				sleep(1);
1616204076Spjd				continue;
1617204076Spjd			}
1618204076Spjd			mtx_unlock(&range_lock);
1619204076Spjd			break;
1620204076Spjd		}
1621204076Spjd		/*
1622204076Spjd		 * First read the data from synchronization source.
1623204076Spjd		 */
1624204076Spjd		SYNCREQ(hio);
1625204076Spjd		ggio = &hio->hio_ggio;
1626204076Spjd		ggio->gctl_cmd = BIO_READ;
1627204076Spjd		ggio->gctl_offset = offset;
1628204076Spjd		ggio->gctl_length = length;
1629204076Spjd		ggio->gctl_error = 0;
1630204076Spjd		for (ii = 0; ii < ncomps; ii++)
1631204076Spjd			hio->hio_errors[ii] = EINVAL;
1632204076Spjd		reqlog(LOG_DEBUG, 2, ggio, "sync: (%p) Sending sync request: ",
1633204076Spjd		    hio);
1634204076Spjd		pjdlog_debug(2, "sync: (%p) Moving request to the send queue.",
1635204076Spjd		    hio);
1636204076Spjd		mtx_lock(&metadata_lock);
1637204076Spjd		if (res->hr_syncsrc == HAST_SYNCSRC_PRIMARY) {
1638204076Spjd			/*
1639204076Spjd			 * This range is up-to-date on local component,
1640204076Spjd			 * so handle request locally.
1641204076Spjd			 */
1642204076Spjd			 /* Local component is 0 for now. */
1643204076Spjd			ncomp = 0;
1644204076Spjd		} else /* if (res->hr_syncsrc == HAST_SYNCSRC_SECONDARY) */ {
1645204076Spjd			assert(res->hr_syncsrc == HAST_SYNCSRC_SECONDARY);
1646204076Spjd			/*
1647204076Spjd			 * This range is out-of-date on local component,
1648204076Spjd			 * so send request to the remote node.
1649204076Spjd			 */
1650204076Spjd			 /* Remote component is 1 for now. */
1651204076Spjd			ncomp = 1;
1652204076Spjd		}
1653204076Spjd		mtx_unlock(&metadata_lock);
1654204076Spjd		refcount_init(&hio->hio_countdown, 1);
1655204076Spjd		QUEUE_INSERT1(hio, send, ncomp);
1656204076Spjd
1657204076Spjd		/*
1658204076Spjd		 * Let's wait for READ to finish.
1659204076Spjd		 */
1660204076Spjd		mtx_lock(&sync_lock);
1661204076Spjd		while (!ISSYNCREQDONE(hio))
1662204076Spjd			cv_wait(&sync_cond, &sync_lock);
1663204076Spjd		mtx_unlock(&sync_lock);
1664204076Spjd
1665204076Spjd		if (hio->hio_errors[ncomp] != 0) {
1666204076Spjd			pjdlog_error("Unable to read synchronization data: %s.",
1667204076Spjd			    strerror(hio->hio_errors[ncomp]));
1668204076Spjd			goto free_queue;
1669204076Spjd		}
1670204076Spjd
1671204076Spjd		/*
1672204076Spjd		 * We read the data from synchronization source, now write it
1673204076Spjd		 * to synchronization target.
1674204076Spjd		 */
1675204076Spjd		SYNCREQ(hio);
1676204076Spjd		ggio->gctl_cmd = BIO_WRITE;
1677204076Spjd		for (ii = 0; ii < ncomps; ii++)
1678204076Spjd			hio->hio_errors[ii] = EINVAL;
1679204076Spjd		reqlog(LOG_DEBUG, 2, ggio, "sync: (%p) Sending sync request: ",
1680204076Spjd		    hio);
1681204076Spjd		pjdlog_debug(2, "sync: (%p) Moving request to the send queue.",
1682204076Spjd		    hio);
1683204076Spjd		mtx_lock(&metadata_lock);
1684204076Spjd		if (res->hr_syncsrc == HAST_SYNCSRC_PRIMARY) {
1685204076Spjd			/*
1686204076Spjd			 * This range is up-to-date on local component,
1687204076Spjd			 * so we update remote component.
1688204076Spjd			 */
1689204076Spjd			 /* Remote component is 1 for now. */
1690204076Spjd			ncomp = 1;
1691204076Spjd		} else /* if (res->hr_syncsrc == HAST_SYNCSRC_SECONDARY) */ {
1692204076Spjd			assert(res->hr_syncsrc == HAST_SYNCSRC_SECONDARY);
1693204076Spjd			/*
1694204076Spjd			 * This range is out-of-date on local component,
1695204076Spjd			 * so we update it.
1696204076Spjd			 */
1697204076Spjd			 /* Local component is 0 for now. */
1698204076Spjd			ncomp = 0;
1699204076Spjd		}
1700204076Spjd		mtx_unlock(&metadata_lock);
1701204076Spjd
1702204076Spjd		pjdlog_debug(2, "sync: (%p) Moving request to the send queues.",
1703204076Spjd		    hio);
1704204076Spjd		refcount_init(&hio->hio_countdown, 1);
1705204076Spjd		QUEUE_INSERT1(hio, send, ncomp);
1706204076Spjd
1707204076Spjd		/*
1708204076Spjd		 * Let's wait for WRITE to finish.
1709204076Spjd		 */
1710204076Spjd		mtx_lock(&sync_lock);
1711204076Spjd		while (!ISSYNCREQDONE(hio))
1712204076Spjd			cv_wait(&sync_cond, &sync_lock);
1713204076Spjd		mtx_unlock(&sync_lock);
1714204076Spjd
1715204076Spjd		if (hio->hio_errors[ncomp] != 0) {
1716204076Spjd			pjdlog_error("Unable to write synchronization data: %s.",
1717204076Spjd			    strerror(hio->hio_errors[ncomp]));
1718204076Spjd			goto free_queue;
1719204076Spjd		}
1720211880Spjd
1721211880Spjd		synced += length;
1722204076Spjdfree_queue:
1723204076Spjd		mtx_lock(&range_lock);
1724204076Spjd		rangelock_del(range_sync, offset, length);
1725204076Spjd		if (range_regular_wait)
1726204076Spjd			cv_signal(&range_regular_cond);
1727204076Spjd		mtx_unlock(&range_lock);
1728204076Spjd		pjdlog_debug(2, "sync: (%p) Moving request to the free queue.",
1729204076Spjd		    hio);
1730204076Spjd		QUEUE_INSERT2(hio, free);
1731204076Spjd	}
1732204076Spjd	/* NOTREACHED */
1733204076Spjd	return (NULL);
1734204076Spjd}
1735204076Spjd
1736204076Spjdstatic void
1737204076Spjdsighandler(int sig)
1738204076Spjd{
1739204076Spjd	bool unlock;
1740204076Spjd
1741204076Spjd	switch (sig) {
1742204076Spjd	case SIGINT:
1743204076Spjd	case SIGTERM:
1744204076Spjd		sigexit_received = true;
1745204076Spjd		break;
1746210886Spjd	case SIGHUP:
1747210886Spjd		sighup_received = true;
1748210886Spjd		break;
1749211886Spjd	case SIGCHLD:
1750211886Spjd		sigchld_received = true;
1751211886Spjd		break;
1752204076Spjd	default:
1753204076Spjd		assert(!"invalid condition");
1754204076Spjd	}
1755204076Spjd	/*
1756211882Spjd	 * Racy, but if we cannot obtain hio_guard_lock here, we don't
1757204076Spjd	 * want to risk deadlock.
1758204076Spjd	 */
1759204076Spjd	unlock = mtx_trylock(&hio_guard_lock);
1760204076Spjd	cv_signal(&hio_guard_cond);
1761204076Spjd	if (unlock)
1762204076Spjd		mtx_unlock(&hio_guard_lock);
1763204076Spjd}
1764204076Spjd
1765210886Spjdstatic void
1766210886Spjdconfig_reload(void)
1767210886Spjd{
1768210886Spjd	struct hastd_config *newcfg;
1769210886Spjd	struct hast_resource *res;
1770210886Spjd	unsigned int ii, ncomps;
1771210886Spjd	int modified;
1772210886Spjd
1773210886Spjd	pjdlog_info("Reloading configuration...");
1774210886Spjd
1775210886Spjd	ncomps = HAST_NCOMPONENTS;
1776210886Spjd
1777210886Spjd	newcfg = yy_config_parse(cfgpath, false);
1778210886Spjd	if (newcfg == NULL)
1779210886Spjd		goto failed;
1780210886Spjd
1781210886Spjd	TAILQ_FOREACH(res, &newcfg->hc_resources, hr_next) {
1782210886Spjd		if (strcmp(res->hr_name, gres->hr_name) == 0)
1783210886Spjd			break;
1784210886Spjd	}
1785210886Spjd	/*
1786210886Spjd	 * If resource was removed from the configuration file, resource
1787210886Spjd	 * name, provider name or path to local component was modified we
1788210886Spjd	 * shouldn't be here. This means that someone modified configuration
1789210886Spjd	 * file and send SIGHUP to us instead of main hastd process.
1790210886Spjd	 * Log advice and ignore the signal.
1791210886Spjd	 */
1792210886Spjd	if (res == NULL || strcmp(gres->hr_name, res->hr_name) != 0 ||
1793210886Spjd	    strcmp(gres->hr_provname, res->hr_provname) != 0 ||
1794210886Spjd	    strcmp(gres->hr_localpath, res->hr_localpath) != 0) {
1795210886Spjd		pjdlog_warning("To reload configuration send SIGHUP to the main hastd process (pid %u).",
1796210886Spjd		    (unsigned int)getppid());
1797210886Spjd		goto failed;
1798210886Spjd	}
1799210886Spjd
1800210886Spjd#define MODIFIED_REMOTEADDR	0x1
1801210886Spjd#define MODIFIED_REPLICATION	0x2
1802210886Spjd#define MODIFIED_TIMEOUT	0x4
1803211886Spjd#define MODIFIED_EXEC		0x8
1804210886Spjd	modified = 0;
1805210886Spjd	if (strcmp(gres->hr_remoteaddr, res->hr_remoteaddr) != 0) {
1806210886Spjd		/*
1807210886Spjd		 * Don't copy res->hr_remoteaddr to gres just yet.
1808210886Spjd		 * We want remote_close() to log disconnect from the old
1809210886Spjd		 * addresses, not from the new ones.
1810210886Spjd		 */
1811210886Spjd		modified |= MODIFIED_REMOTEADDR;
1812210886Spjd	}
1813210886Spjd	if (gres->hr_replication != res->hr_replication) {
1814210886Spjd		gres->hr_replication = res->hr_replication;
1815210886Spjd		modified |= MODIFIED_REPLICATION;
1816210886Spjd	}
1817210886Spjd	if (gres->hr_timeout != res->hr_timeout) {
1818210886Spjd		gres->hr_timeout = res->hr_timeout;
1819210886Spjd		modified |= MODIFIED_TIMEOUT;
1820210886Spjd	}
1821211886Spjd	if (strcmp(gres->hr_exec, res->hr_exec) != 0) {
1822211886Spjd		strlcpy(gres->hr_exec, res->hr_exec, sizeof(gres->hr_exec));
1823211886Spjd		modified |= MODIFIED_EXEC;
1824211886Spjd	}
1825210886Spjd	/*
1826210886Spjd	 * If only timeout was modified we only need to change it without
1827210886Spjd	 * reconnecting.
1828210886Spjd	 */
1829210886Spjd	if (modified == MODIFIED_TIMEOUT) {
1830210886Spjd		for (ii = 0; ii < ncomps; ii++) {
1831210886Spjd			if (!ISREMOTE(ii))
1832210886Spjd				continue;
1833210886Spjd			rw_rlock(&hio_remote_lock[ii]);
1834210886Spjd			if (!ISCONNECTED(gres, ii)) {
1835210886Spjd				rw_unlock(&hio_remote_lock[ii]);
1836210886Spjd				continue;
1837210886Spjd			}
1838210886Spjd			rw_unlock(&hio_remote_lock[ii]);
1839210886Spjd			if (proto_timeout(gres->hr_remotein,
1840210886Spjd			    gres->hr_timeout) < 0) {
1841210886Spjd				pjdlog_errno(LOG_WARNING,
1842210886Spjd				    "Unable to set connection timeout");
1843210886Spjd			}
1844210886Spjd			if (proto_timeout(gres->hr_remoteout,
1845210886Spjd			    gres->hr_timeout) < 0) {
1846210886Spjd				pjdlog_errno(LOG_WARNING,
1847210886Spjd				    "Unable to set connection timeout");
1848210886Spjd			}
1849210886Spjd		}
1850211886Spjd	} else if ((modified &
1851211886Spjd	    (MODIFIED_REMOTEADDR | MODIFIED_REPLICATION)) != 0) {
1852210886Spjd		for (ii = 0; ii < ncomps; ii++) {
1853210886Spjd			if (!ISREMOTE(ii))
1854210886Spjd				continue;
1855210886Spjd			remote_close(gres, ii);
1856210886Spjd		}
1857210886Spjd		if (modified & MODIFIED_REMOTEADDR) {
1858210886Spjd			strlcpy(gres->hr_remoteaddr, res->hr_remoteaddr,
1859210886Spjd			    sizeof(gres->hr_remoteaddr));
1860210886Spjd		}
1861210886Spjd	}
1862210886Spjd#undef	MODIFIED_REMOTEADDR
1863210886Spjd#undef	MODIFIED_REPLICATION
1864210886Spjd#undef	MODIFIED_TIMEOUT
1865211886Spjd#undef	MODIFIED_EXEC
1866210886Spjd
1867210886Spjd	pjdlog_info("Configuration reloaded successfully.");
1868210886Spjd	return;
1869210886Spjdfailed:
1870210886Spjd	if (newcfg != NULL) {
1871210886Spjd		if (newcfg->hc_controlconn != NULL)
1872210886Spjd			proto_close(newcfg->hc_controlconn);
1873210886Spjd		if (newcfg->hc_listenconn != NULL)
1874210886Spjd			proto_close(newcfg->hc_listenconn);
1875210886Spjd		yy_config_free(newcfg);
1876210886Spjd	}
1877210886Spjd	pjdlog_warning("Configuration not reloaded.");
1878210886Spjd}
1879210886Spjd
1880211882Spjdstatic void
1881211882Spjdkeepalive_send(struct hast_resource *res, unsigned int ncomp)
1882211882Spjd{
1883211882Spjd	struct nv *nv;
1884211882Spjd
1885211882Spjd	nv = nv_alloc();
1886211882Spjd	nv_add_uint8(nv, HIO_KEEPALIVE, "cmd");
1887211882Spjd	if (nv_error(nv) != 0) {
1888211882Spjd		nv_free(nv);
1889211882Spjd		pjdlog_debug(1,
1890211882Spjd		    "keepalive_send: Unable to prepare header to send.");
1891211882Spjd		return;
1892211882Spjd	}
1893211882Spjd	if (hast_proto_send(res, res->hr_remoteout, nv, NULL, 0) < 0) {
1894211882Spjd		pjdlog_common(LOG_DEBUG, 1, errno,
1895211882Spjd		    "keepalive_send: Unable to send request");
1896211882Spjd		nv_free(nv);
1897211882Spjd		rw_unlock(&hio_remote_lock[ncomp]);
1898211882Spjd		remote_close(res, ncomp);
1899211882Spjd		rw_rlock(&hio_remote_lock[ncomp]);
1900211882Spjd		return;
1901211882Spjd	}
1902211882Spjd	nv_free(nv);
1903211882Spjd	pjdlog_debug(2, "keepalive_send: Request sent.");
1904211882Spjd}
1905211882Spjd
1906204076Spjd/*
1907204076Spjd * Thread guards remote connections and reconnects when needed, handles
1908204076Spjd * signals, etc.
1909204076Spjd */
1910204076Spjdstatic void *
1911204076Spjdguard_thread(void *arg)
1912204076Spjd{
1913204076Spjd	struct hast_resource *res = arg;
1914205738Spjd	struct proto_conn *in, *out;
1915204076Spjd	unsigned int ii, ncomps;
1916204076Spjd	int timeout;
1917204076Spjd
1918204076Spjd	ncomps = HAST_NCOMPONENTS;
1919204076Spjd
1920204076Spjd	for (;;) {
1921204076Spjd		if (sigexit_received) {
1922204076Spjd			primary_exitx(EX_OK,
1923204076Spjd			    "Termination signal received, exiting.");
1924204076Spjd		}
1925210886Spjd		if (sighup_received) {
1926210886Spjd			sighup_received = false;
1927210886Spjd			config_reload();
1928210886Spjd		}
1929211886Spjd		hook_check(sigchld_received);
1930211886Spjd		if (sigchld_received)
1931211886Spjd			sigchld_received = false;
1932211882Spjd
1933211882Spjd		timeout = KEEPALIVE_SLEEP;
1934204076Spjd		pjdlog_debug(2, "remote_guard: Checking connections.");
1935204076Spjd		mtx_lock(&hio_guard_lock);
1936204076Spjd		for (ii = 0; ii < ncomps; ii++) {
1937204076Spjd			if (!ISREMOTE(ii))
1938204076Spjd				continue;
1939204076Spjd			rw_rlock(&hio_remote_lock[ii]);
1940204076Spjd			if (ISCONNECTED(res, ii)) {
1941204076Spjd				assert(res->hr_remotein != NULL);
1942204076Spjd				assert(res->hr_remoteout != NULL);
1943211882Spjd				keepalive_send(res, ii);
1944211882Spjd			}
1945211882Spjd			if (ISCONNECTED(res, ii)) {
1946211882Spjd				assert(res->hr_remotein != NULL);
1947211882Spjd				assert(res->hr_remoteout != NULL);
1948204076Spjd				rw_unlock(&hio_remote_lock[ii]);
1949204076Spjd				pjdlog_debug(2,
1950204076Spjd				    "remote_guard: Connection to %s is ok.",
1951204076Spjd				    res->hr_remoteaddr);
1952210881Spjd			} else if (real_remote(res)) {
1953204076Spjd				assert(res->hr_remotein == NULL);
1954204076Spjd				assert(res->hr_remoteout == NULL);
1955204076Spjd				/*
1956204076Spjd				 * Upgrade the lock. It doesn't have to be
1957204076Spjd				 * atomic as no other thread can change
1958204076Spjd				 * connection status from disconnected to
1959204076Spjd				 * connected.
1960204076Spjd				 */
1961204076Spjd				rw_unlock(&hio_remote_lock[ii]);
1962204076Spjd				pjdlog_debug(2,
1963204076Spjd				    "remote_guard: Reconnecting to %s.",
1964204076Spjd				    res->hr_remoteaddr);
1965205738Spjd				in = out = NULL;
1966205738Spjd				if (init_remote(res, &in, &out)) {
1967205738Spjd					rw_wlock(&hio_remote_lock[ii]);
1968205738Spjd					assert(res->hr_remotein == NULL);
1969205738Spjd					assert(res->hr_remoteout == NULL);
1970205738Spjd					assert(in != NULL && out != NULL);
1971205738Spjd					res->hr_remotein = in;
1972205738Spjd					res->hr_remoteout = out;
1973205738Spjd					rw_unlock(&hio_remote_lock[ii]);
1974204076Spjd					pjdlog_info("Successfully reconnected to %s.",
1975204076Spjd					    res->hr_remoteaddr);
1976205738Spjd					sync_start();
1977204076Spjd				} else {
1978204076Spjd					/* Both connections should be NULL. */
1979204076Spjd					assert(res->hr_remotein == NULL);
1980204076Spjd					assert(res->hr_remoteout == NULL);
1981205738Spjd					assert(in == NULL && out == NULL);
1982204076Spjd					pjdlog_debug(2,
1983204076Spjd					    "remote_guard: Reconnect to %s failed.",
1984204076Spjd					    res->hr_remoteaddr);
1985204076Spjd					timeout = RECONNECT_SLEEP;
1986204076Spjd				}
1987210881Spjd			} else {
1988210881Spjd				rw_unlock(&hio_remote_lock[ii]);
1989204076Spjd			}
1990204076Spjd		}
1991211896Spjd		/* Sleep only if a signal wasn't delivered in the meantime. */
1992211896Spjd		if (!sigexit_received && !sighup_received && !sigchld_received)
1993211896Spjd			cv_timedwait(&hio_guard_cond, &hio_guard_lock, timeout);
1994204076Spjd		mtx_unlock(&hio_guard_lock);
1995204076Spjd	}
1996204076Spjd	/* NOTREACHED */
1997204076Spjd	return (NULL);
1998204076Spjd}
1999