primary.c revision 212034
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 212034 2010-08-30 22:28:04Z pjd $");
33204076Spjd
34204076Spjd#include <sys/types.h>
35204076Spjd#include <sys/time.h>
36204076Spjd#include <sys/bio.h>
37204076Spjd#include <sys/disk.h>
38204076Spjd#include <sys/refcount.h>
39204076Spjd#include <sys/stat.h>
40204076Spjd
41204076Spjd#include <geom/gate/g_gate.h>
42204076Spjd
43204076Spjd#include <assert.h>
44204076Spjd#include <err.h>
45204076Spjd#include <errno.h>
46204076Spjd#include <fcntl.h>
47204076Spjd#include <libgeom.h>
48204076Spjd#include <pthread.h>
49211982Spjd#include <signal.h>
50204076Spjd#include <stdint.h>
51204076Spjd#include <stdio.h>
52204076Spjd#include <string.h>
53204076Spjd#include <sysexits.h>
54204076Spjd#include <unistd.h>
55204076Spjd
56204076Spjd#include <activemap.h>
57204076Spjd#include <nv.h>
58204076Spjd#include <rangelock.h>
59204076Spjd
60204076Spjd#include "control.h"
61204076Spjd#include "hast.h"
62204076Spjd#include "hast_proto.h"
63204076Spjd#include "hastd.h"
64211886Spjd#include "hooks.h"
65204076Spjd#include "metadata.h"
66204076Spjd#include "proto.h"
67204076Spjd#include "pjdlog.h"
68204076Spjd#include "subr.h"
69204076Spjd#include "synch.h"
70204076Spjd
71210886Spjd/* The is only one remote component for now. */
72210886Spjd#define	ISREMOTE(no)	((no) == 1)
73210886Spjd
74204076Spjdstruct hio {
75204076Spjd	/*
76204076Spjd	 * Number of components we are still waiting for.
77204076Spjd	 * When this field goes to 0, we can send the request back to the
78204076Spjd	 * kernel. Each component has to decrease this counter by one
79204076Spjd	 * even on failure.
80204076Spjd	 */
81204076Spjd	unsigned int		 hio_countdown;
82204076Spjd	/*
83204076Spjd	 * Each component has a place to store its own error.
84204076Spjd	 * Once the request is handled by all components we can decide if the
85204076Spjd	 * request overall is successful or not.
86204076Spjd	 */
87204076Spjd	int			*hio_errors;
88204076Spjd	/*
89204076Spjd	 * Structure used to comunicate with GEOM Gate class.
90204076Spjd	 */
91204076Spjd	struct g_gate_ctl_io	 hio_ggio;
92204076Spjd	TAILQ_ENTRY(hio)	*hio_next;
93204076Spjd};
94204076Spjd#define	hio_free_next	hio_next[0]
95204076Spjd#define	hio_done_next	hio_next[0]
96204076Spjd
97204076Spjd/*
98204076Spjd * Free list holds unused structures. When free list is empty, we have to wait
99204076Spjd * until some in-progress requests are freed.
100204076Spjd */
101204076Spjdstatic TAILQ_HEAD(, hio) hio_free_list;
102204076Spjdstatic pthread_mutex_t hio_free_list_lock;
103204076Spjdstatic pthread_cond_t hio_free_list_cond;
104204076Spjd/*
105204076Spjd * There is one send list for every component. One requests is placed on all
106204076Spjd * send lists - each component gets the same request, but each component is
107204076Spjd * responsible for managing his own send list.
108204076Spjd */
109204076Spjdstatic TAILQ_HEAD(, hio) *hio_send_list;
110204076Spjdstatic pthread_mutex_t *hio_send_list_lock;
111204076Spjdstatic pthread_cond_t *hio_send_list_cond;
112204076Spjd/*
113204076Spjd * There is one recv list for every component, although local components don't
114204076Spjd * use recv lists as local requests are done synchronously.
115204076Spjd */
116204076Spjdstatic TAILQ_HEAD(, hio) *hio_recv_list;
117204076Spjdstatic pthread_mutex_t *hio_recv_list_lock;
118204076Spjdstatic pthread_cond_t *hio_recv_list_cond;
119204076Spjd/*
120204076Spjd * Request is placed on done list by the slowest component (the one that
121204076Spjd * decreased hio_countdown from 1 to 0).
122204076Spjd */
123204076Spjdstatic TAILQ_HEAD(, hio) hio_done_list;
124204076Spjdstatic pthread_mutex_t hio_done_list_lock;
125204076Spjdstatic pthread_cond_t hio_done_list_cond;
126204076Spjd/*
127204076Spjd * Structure below are for interaction with sync thread.
128204076Spjd */
129204076Spjdstatic bool sync_inprogress;
130204076Spjdstatic pthread_mutex_t sync_lock;
131204076Spjdstatic pthread_cond_t sync_cond;
132204076Spjd/*
133204076Spjd * The lock below allows to synchornize access to remote connections.
134204076Spjd */
135204076Spjdstatic pthread_rwlock_t *hio_remote_lock;
136204076Spjd
137204076Spjd/*
138204076Spjd * Lock to synchronize metadata updates. Also synchronize access to
139204076Spjd * hr_primary_localcnt and hr_primary_remotecnt fields.
140204076Spjd */
141204076Spjdstatic pthread_mutex_t metadata_lock;
142204076Spjd
143204076Spjd/*
144204076Spjd * Maximum number of outstanding I/O requests.
145204076Spjd */
146204076Spjd#define	HAST_HIO_MAX	256
147204076Spjd/*
148204076Spjd * Number of components. At this point there are only two components: local
149204076Spjd * and remote, but in the future it might be possible to use multiple local
150204076Spjd * and remote components.
151204076Spjd */
152204076Spjd#define	HAST_NCOMPONENTS	2
153204076Spjd/*
154211982Spjd * Number of seconds to sleep between reconnect retries or keepalive packets.
155204076Spjd */
156211982Spjd#define	RETRY_SLEEP		10
157204076Spjd
158204076Spjd#define	ISCONNECTED(res, no)	\
159204076Spjd	((res)->hr_remotein != NULL && (res)->hr_remoteout != NULL)
160204076Spjd
161204076Spjd#define	QUEUE_INSERT1(hio, name, ncomp)	do {				\
162204076Spjd	bool _wakeup;							\
163204076Spjd									\
164204076Spjd	mtx_lock(&hio_##name##_list_lock[(ncomp)]);			\
165204076Spjd	_wakeup = TAILQ_EMPTY(&hio_##name##_list[(ncomp)]);		\
166204076Spjd	TAILQ_INSERT_TAIL(&hio_##name##_list[(ncomp)], (hio),		\
167204076Spjd	    hio_next[(ncomp)]);						\
168204076Spjd	mtx_unlock(&hio_##name##_list_lock[ncomp]);			\
169204076Spjd	if (_wakeup)							\
170204076Spjd		cv_signal(&hio_##name##_list_cond[(ncomp)]);		\
171204076Spjd} while (0)
172204076Spjd#define	QUEUE_INSERT2(hio, name)	do {				\
173204076Spjd	bool _wakeup;							\
174204076Spjd									\
175204076Spjd	mtx_lock(&hio_##name##_list_lock);				\
176204076Spjd	_wakeup = TAILQ_EMPTY(&hio_##name##_list);			\
177204076Spjd	TAILQ_INSERT_TAIL(&hio_##name##_list, (hio), hio_##name##_next);\
178204076Spjd	mtx_unlock(&hio_##name##_list_lock);				\
179204076Spjd	if (_wakeup)							\
180204076Spjd		cv_signal(&hio_##name##_list_cond);			\
181204076Spjd} while (0)
182204076Spjd#define	QUEUE_TAKE1(hio, name, ncomp)	do {				\
183204076Spjd	mtx_lock(&hio_##name##_list_lock[(ncomp)]);			\
184204076Spjd	while (((hio) = TAILQ_FIRST(&hio_##name##_list[(ncomp)])) == NULL) { \
185204076Spjd		cv_wait(&hio_##name##_list_cond[(ncomp)],		\
186204076Spjd		    &hio_##name##_list_lock[(ncomp)]);			\
187204076Spjd	}								\
188204076Spjd	TAILQ_REMOVE(&hio_##name##_list[(ncomp)], (hio),		\
189204076Spjd	    hio_next[(ncomp)]);						\
190204076Spjd	mtx_unlock(&hio_##name##_list_lock[(ncomp)]);			\
191204076Spjd} while (0)
192204076Spjd#define	QUEUE_TAKE2(hio, name)	do {					\
193204076Spjd	mtx_lock(&hio_##name##_list_lock);				\
194204076Spjd	while (((hio) = TAILQ_FIRST(&hio_##name##_list)) == NULL) {	\
195204076Spjd		cv_wait(&hio_##name##_list_cond,			\
196204076Spjd		    &hio_##name##_list_lock);				\
197204076Spjd	}								\
198204076Spjd	TAILQ_REMOVE(&hio_##name##_list, (hio), hio_##name##_next);	\
199204076Spjd	mtx_unlock(&hio_##name##_list_lock);				\
200204076Spjd} while (0)
201204076Spjd
202209183Spjd#define	SYNCREQ(hio)		do {					\
203209183Spjd	(hio)->hio_ggio.gctl_unit = -1;					\
204209183Spjd	(hio)->hio_ggio.gctl_seq = 1;					\
205209183Spjd} while (0)
206204076Spjd#define	ISSYNCREQ(hio)		((hio)->hio_ggio.gctl_unit == -1)
207204076Spjd#define	SYNCREQDONE(hio)	do { (hio)->hio_ggio.gctl_unit = -2; } while (0)
208204076Spjd#define	ISSYNCREQDONE(hio)	((hio)->hio_ggio.gctl_unit == -2)
209204076Spjd
210204076Spjdstatic struct hast_resource *gres;
211204076Spjd
212204076Spjdstatic pthread_mutex_t range_lock;
213204076Spjdstatic struct rangelocks *range_regular;
214204076Spjdstatic bool range_regular_wait;
215204076Spjdstatic pthread_cond_t range_regular_cond;
216204076Spjdstatic struct rangelocks *range_sync;
217204076Spjdstatic bool range_sync_wait;
218204076Spjdstatic pthread_cond_t range_sync_cond;
219204076Spjd
220204076Spjdstatic void *ggate_recv_thread(void *arg);
221204076Spjdstatic void *local_send_thread(void *arg);
222204076Spjdstatic void *remote_send_thread(void *arg);
223204076Spjdstatic void *remote_recv_thread(void *arg);
224204076Spjdstatic void *ggate_send_thread(void *arg);
225204076Spjdstatic void *sync_thread(void *arg);
226204076Spjdstatic void *guard_thread(void *arg);
227204076Spjd
228211982Spjdstatic void
229211982Spjddummy_sighandler(int sig __unused)
230211982Spjd{
231211982Spjd	/* Nothing to do. */
232211982Spjd}
233204076Spjd
234204076Spjdstatic void
235204076Spjdcleanup(struct hast_resource *res)
236204076Spjd{
237204076Spjd	int rerrno;
238204076Spjd
239204076Spjd	/* Remember errno. */
240204076Spjd	rerrno = errno;
241204076Spjd
242204076Spjd	/*
243204076Spjd	 * Close descriptor to /dev/hast/<name>
244204076Spjd	 * to work-around race in the kernel.
245204076Spjd	 */
246204076Spjd	close(res->hr_localfd);
247204076Spjd
248204076Spjd	/* Destroy ggate provider if we created one. */
249204076Spjd	if (res->hr_ggateunit >= 0) {
250204076Spjd		struct g_gate_ctl_destroy ggiod;
251204076Spjd
252204076Spjd		ggiod.gctl_version = G_GATE_VERSION;
253204076Spjd		ggiod.gctl_unit = res->hr_ggateunit;
254204076Spjd		ggiod.gctl_force = 1;
255204076Spjd		if (ioctl(res->hr_ggatefd, G_GATE_CMD_DESTROY, &ggiod) < 0) {
256204076Spjd			pjdlog_warning("Unable to destroy hast/%s device",
257204076Spjd			    res->hr_provname);
258204076Spjd		}
259204076Spjd		res->hr_ggateunit = -1;
260204076Spjd	}
261204076Spjd
262204076Spjd	/* Restore errno. */
263204076Spjd	errno = rerrno;
264204076Spjd}
265204076Spjd
266204076Spjdstatic void
267204076Spjdprimary_exit(int exitcode, const char *fmt, ...)
268204076Spjd{
269204076Spjd	va_list ap;
270204076Spjd
271204076Spjd	assert(exitcode != EX_OK);
272204076Spjd	va_start(ap, fmt);
273204076Spjd	pjdlogv_errno(LOG_ERR, fmt, ap);
274204076Spjd	va_end(ap);
275204076Spjd	cleanup(gres);
276204076Spjd	exit(exitcode);
277204076Spjd}
278204076Spjd
279204076Spjdstatic void
280204076Spjdprimary_exitx(int exitcode, const char *fmt, ...)
281204076Spjd{
282204076Spjd	va_list ap;
283204076Spjd
284204076Spjd	va_start(ap, fmt);
285204076Spjd	pjdlogv(exitcode == EX_OK ? LOG_INFO : LOG_ERR, fmt, ap);
286204076Spjd	va_end(ap);
287204076Spjd	cleanup(gres);
288204076Spjd	exit(exitcode);
289204076Spjd}
290204076Spjd
291204076Spjdstatic int
292204076Spjdhast_activemap_flush(struct hast_resource *res)
293204076Spjd{
294204076Spjd	const unsigned char *buf;
295204076Spjd	size_t size;
296204076Spjd
297204076Spjd	buf = activemap_bitmap(res->hr_amp, &size);
298204076Spjd	assert(buf != NULL);
299204076Spjd	assert((size % res->hr_local_sectorsize) == 0);
300204076Spjd	if (pwrite(res->hr_localfd, buf, size, METADATA_SIZE) !=
301204076Spjd	    (ssize_t)size) {
302204076Spjd		KEEP_ERRNO(pjdlog_errno(LOG_ERR,
303204076Spjd		    "Unable to flush activemap to disk"));
304204076Spjd		return (-1);
305204076Spjd	}
306204076Spjd	return (0);
307204076Spjd}
308204076Spjd
309210881Spjdstatic bool
310210881Spjdreal_remote(const struct hast_resource *res)
311210881Spjd{
312210881Spjd
313210881Spjd	return (strcmp(res->hr_remoteaddr, "none") != 0);
314210881Spjd}
315210881Spjd
316204076Spjdstatic void
317204076Spjdinit_environment(struct hast_resource *res __unused)
318204076Spjd{
319204076Spjd	struct hio *hio;
320204076Spjd	unsigned int ii, ncomps;
321211982Spjd	sigset_t mask;
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(&metadata_lock);
393204076Spjd
394204076Spjd	/*
395204076Spjd	 * Allocate requests pool and initialize requests.
396204076Spjd	 */
397204076Spjd	for (ii = 0; ii < HAST_HIO_MAX; ii++) {
398204076Spjd		hio = malloc(sizeof(*hio));
399204076Spjd		if (hio == NULL) {
400204076Spjd			primary_exitx(EX_TEMPFAIL,
401204076Spjd			    "Unable to allocate %zu bytes of memory for hio request.",
402204076Spjd			    sizeof(*hio));
403204076Spjd		}
404204076Spjd		hio->hio_countdown = 0;
405204076Spjd		hio->hio_errors = malloc(sizeof(hio->hio_errors[0]) * ncomps);
406204076Spjd		if (hio->hio_errors == NULL) {
407204076Spjd			primary_exitx(EX_TEMPFAIL,
408204076Spjd			    "Unable allocate %zu bytes of memory for hio errors.",
409204076Spjd			    sizeof(hio->hio_errors[0]) * ncomps);
410204076Spjd		}
411204076Spjd		hio->hio_next = malloc(sizeof(hio->hio_next[0]) * ncomps);
412204076Spjd		if (hio->hio_next == NULL) {
413204076Spjd			primary_exitx(EX_TEMPFAIL,
414204076Spjd			    "Unable allocate %zu bytes of memory for hio_next field.",
415204076Spjd			    sizeof(hio->hio_next[0]) * ncomps);
416204076Spjd		}
417204076Spjd		hio->hio_ggio.gctl_version = G_GATE_VERSION;
418204076Spjd		hio->hio_ggio.gctl_data = malloc(MAXPHYS);
419204076Spjd		if (hio->hio_ggio.gctl_data == NULL) {
420204076Spjd			primary_exitx(EX_TEMPFAIL,
421204076Spjd			    "Unable to allocate %zu bytes of memory for gctl_data.",
422204076Spjd			    MAXPHYS);
423204076Spjd		}
424204076Spjd		hio->hio_ggio.gctl_length = MAXPHYS;
425204076Spjd		hio->hio_ggio.gctl_error = 0;
426204076Spjd		TAILQ_INSERT_HEAD(&hio_free_list, hio, hio_free_next);
427204076Spjd	}
428204076Spjd
429204076Spjd	/*
430204076Spjd	 * Turn on signals handling.
431204076Spjd	 */
432211982Spjd	/* Because SIGCHLD is ignored by default, setup dummy handler for it. */
433211982Spjd	PJDLOG_VERIFY(signal(SIGCHLD, dummy_sighandler) != SIG_ERR);
434211982Spjd	PJDLOG_VERIFY(sigfillset(&mask) == 0);
435211982Spjd	PJDLOG_VERIFY(sigprocmask(SIG_SETMASK, &mask, NULL) == 0);
436204076Spjd}
437204076Spjd
438204076Spjdstatic void
439204076Spjdinit_local(struct hast_resource *res)
440204076Spjd{
441204076Spjd	unsigned char *buf;
442204076Spjd	size_t mapsize;
443204076Spjd
444204076Spjd	if (metadata_read(res, true) < 0)
445204076Spjd		exit(EX_NOINPUT);
446204076Spjd	mtx_init(&res->hr_amp_lock);
447204076Spjd	if (activemap_init(&res->hr_amp, res->hr_datasize, res->hr_extentsize,
448204076Spjd	    res->hr_local_sectorsize, res->hr_keepdirty) < 0) {
449204076Spjd		primary_exit(EX_TEMPFAIL, "Unable to create activemap");
450204076Spjd	}
451204076Spjd	mtx_init(&range_lock);
452204076Spjd	cv_init(&range_regular_cond);
453204076Spjd	if (rangelock_init(&range_regular) < 0)
454204076Spjd		primary_exit(EX_TEMPFAIL, "Unable to create regular range lock");
455204076Spjd	cv_init(&range_sync_cond);
456204076Spjd	if (rangelock_init(&range_sync) < 0)
457204076Spjd		primary_exit(EX_TEMPFAIL, "Unable to create sync range lock");
458204076Spjd	mapsize = activemap_ondisk_size(res->hr_amp);
459204076Spjd	buf = calloc(1, mapsize);
460204076Spjd	if (buf == NULL) {
461204076Spjd		primary_exitx(EX_TEMPFAIL,
462204076Spjd		    "Unable to allocate buffer for activemap.");
463204076Spjd	}
464204076Spjd	if (pread(res->hr_localfd, buf, mapsize, METADATA_SIZE) !=
465204076Spjd	    (ssize_t)mapsize) {
466204076Spjd		primary_exit(EX_NOINPUT, "Unable to read activemap");
467204076Spjd	}
468204076Spjd	activemap_copyin(res->hr_amp, buf, mapsize);
469209181Spjd	free(buf);
470204076Spjd	if (res->hr_resuid != 0)
471204076Spjd		return;
472204076Spjd	/*
473204076Spjd	 * We're using provider for the first time, so we have to generate
474204076Spjd	 * resource unique identifier and initialize local and remote counts.
475204076Spjd	 */
476204076Spjd	arc4random_buf(&res->hr_resuid, sizeof(res->hr_resuid));
477204076Spjd	res->hr_primary_localcnt = 1;
478204076Spjd	res->hr_primary_remotecnt = 0;
479204076Spjd	if (metadata_write(res) < 0)
480204076Spjd		exit(EX_NOINPUT);
481204076Spjd}
482204076Spjd
483205738Spjdstatic bool
484205738Spjdinit_remote(struct hast_resource *res, struct proto_conn **inp,
485205738Spjd    struct proto_conn **outp)
486204076Spjd{
487205738Spjd	struct proto_conn *in, *out;
488204076Spjd	struct nv *nvout, *nvin;
489204076Spjd	const unsigned char *token;
490204076Spjd	unsigned char *map;
491204076Spjd	const char *errmsg;
492204076Spjd	int32_t extentsize;
493204076Spjd	int64_t datasize;
494204076Spjd	uint32_t mapsize;
495204076Spjd	size_t size;
496204076Spjd
497205738Spjd	assert((inp == NULL && outp == NULL) || (inp != NULL && outp != NULL));
498210881Spjd	assert(real_remote(res));
499205738Spjd
500205738Spjd	in = out = NULL;
501211983Spjd	errmsg = NULL;
502205738Spjd
503204076Spjd	/* Prepare outgoing connection with remote node. */
504205738Spjd	if (proto_client(res->hr_remoteaddr, &out) < 0) {
505207347Spjd		primary_exit(EX_TEMPFAIL, "Unable to create connection to %s",
506204076Spjd		    res->hr_remoteaddr);
507204076Spjd	}
508204076Spjd	/* Try to connect, but accept failure. */
509205738Spjd	if (proto_connect(out) < 0) {
510204076Spjd		pjdlog_errno(LOG_WARNING, "Unable to connect to %s",
511204076Spjd		    res->hr_remoteaddr);
512204076Spjd		goto close;
513204076Spjd	}
514207371Spjd	/* Error in setting timeout is not critical, but why should it fail? */
515207371Spjd	if (proto_timeout(out, res->hr_timeout) < 0)
516207371Spjd		pjdlog_errno(LOG_WARNING, "Unable to set connection timeout");
517204076Spjd	/*
518204076Spjd	 * First handshake step.
519204076Spjd	 * Setup outgoing connection with remote node.
520204076Spjd	 */
521204076Spjd	nvout = nv_alloc();
522204076Spjd	nv_add_string(nvout, res->hr_name, "resource");
523204076Spjd	if (nv_error(nvout) != 0) {
524204076Spjd		pjdlog_common(LOG_WARNING, 0, nv_error(nvout),
525204076Spjd		    "Unable to allocate header for connection with %s",
526204076Spjd		    res->hr_remoteaddr);
527204076Spjd		nv_free(nvout);
528204076Spjd		goto close;
529204076Spjd	}
530205738Spjd	if (hast_proto_send(res, out, nvout, NULL, 0) < 0) {
531204076Spjd		pjdlog_errno(LOG_WARNING,
532204076Spjd		    "Unable to send handshake header to %s",
533204076Spjd		    res->hr_remoteaddr);
534204076Spjd		nv_free(nvout);
535204076Spjd		goto close;
536204076Spjd	}
537204076Spjd	nv_free(nvout);
538205738Spjd	if (hast_proto_recv_hdr(out, &nvin) < 0) {
539204076Spjd		pjdlog_errno(LOG_WARNING,
540204076Spjd		    "Unable to receive handshake header from %s",
541204076Spjd		    res->hr_remoteaddr);
542204076Spjd		goto close;
543204076Spjd	}
544204076Spjd	errmsg = nv_get_string(nvin, "errmsg");
545204076Spjd	if (errmsg != NULL) {
546204076Spjd		pjdlog_warning("%s", errmsg);
547204076Spjd		nv_free(nvin);
548204076Spjd		goto close;
549204076Spjd	}
550204076Spjd	token = nv_get_uint8_array(nvin, &size, "token");
551204076Spjd	if (token == NULL) {
552204076Spjd		pjdlog_warning("Handshake header from %s has no 'token' field.",
553204076Spjd		    res->hr_remoteaddr);
554204076Spjd		nv_free(nvin);
555204076Spjd		goto close;
556204076Spjd	}
557204076Spjd	if (size != sizeof(res->hr_token)) {
558204076Spjd		pjdlog_warning("Handshake header from %s contains 'token' of wrong size (got %zu, expected %zu).",
559204076Spjd		    res->hr_remoteaddr, size, sizeof(res->hr_token));
560204076Spjd		nv_free(nvin);
561204076Spjd		goto close;
562204076Spjd	}
563204076Spjd	bcopy(token, res->hr_token, sizeof(res->hr_token));
564204076Spjd	nv_free(nvin);
565204076Spjd
566204076Spjd	/*
567204076Spjd	 * Second handshake step.
568204076Spjd	 * Setup incoming connection with remote node.
569204076Spjd	 */
570205738Spjd	if (proto_client(res->hr_remoteaddr, &in) < 0) {
571204076Spjd		pjdlog_errno(LOG_WARNING, "Unable to create connection to %s",
572204076Spjd		    res->hr_remoteaddr);
573204076Spjd	}
574204076Spjd	/* Try to connect, but accept failure. */
575205738Spjd	if (proto_connect(in) < 0) {
576204076Spjd		pjdlog_errno(LOG_WARNING, "Unable to connect to %s",
577204076Spjd		    res->hr_remoteaddr);
578204076Spjd		goto close;
579204076Spjd	}
580207371Spjd	/* Error in setting timeout is not critical, but why should it fail? */
581207371Spjd	if (proto_timeout(in, res->hr_timeout) < 0)
582207371Spjd		pjdlog_errno(LOG_WARNING, "Unable to set connection timeout");
583204076Spjd	nvout = nv_alloc();
584204076Spjd	nv_add_string(nvout, res->hr_name, "resource");
585204076Spjd	nv_add_uint8_array(nvout, res->hr_token, sizeof(res->hr_token),
586204076Spjd	    "token");
587204076Spjd	nv_add_uint64(nvout, res->hr_resuid, "resuid");
588204076Spjd	nv_add_uint64(nvout, res->hr_primary_localcnt, "localcnt");
589204076Spjd	nv_add_uint64(nvout, res->hr_primary_remotecnt, "remotecnt");
590204076Spjd	if (nv_error(nvout) != 0) {
591204076Spjd		pjdlog_common(LOG_WARNING, 0, nv_error(nvout),
592204076Spjd		    "Unable to allocate header for connection with %s",
593204076Spjd		    res->hr_remoteaddr);
594204076Spjd		nv_free(nvout);
595204076Spjd		goto close;
596204076Spjd	}
597205738Spjd	if (hast_proto_send(res, in, nvout, NULL, 0) < 0) {
598204076Spjd		pjdlog_errno(LOG_WARNING,
599204076Spjd		    "Unable to send handshake header to %s",
600204076Spjd		    res->hr_remoteaddr);
601204076Spjd		nv_free(nvout);
602204076Spjd		goto close;
603204076Spjd	}
604204076Spjd	nv_free(nvout);
605205738Spjd	if (hast_proto_recv_hdr(out, &nvin) < 0) {
606204076Spjd		pjdlog_errno(LOG_WARNING,
607204076Spjd		    "Unable to receive handshake header from %s",
608204076Spjd		    res->hr_remoteaddr);
609204076Spjd		goto close;
610204076Spjd	}
611204076Spjd	errmsg = nv_get_string(nvin, "errmsg");
612204076Spjd	if (errmsg != NULL) {
613204076Spjd		pjdlog_warning("%s", errmsg);
614204076Spjd		nv_free(nvin);
615204076Spjd		goto close;
616204076Spjd	}
617204076Spjd	datasize = nv_get_int64(nvin, "datasize");
618204076Spjd	if (datasize != res->hr_datasize) {
619204076Spjd		pjdlog_warning("Data size differs between nodes (local=%jd, remote=%jd).",
620204076Spjd		    (intmax_t)res->hr_datasize, (intmax_t)datasize);
621204076Spjd		nv_free(nvin);
622204076Spjd		goto close;
623204076Spjd	}
624204076Spjd	extentsize = nv_get_int32(nvin, "extentsize");
625204076Spjd	if (extentsize != res->hr_extentsize) {
626204076Spjd		pjdlog_warning("Extent size differs between nodes (local=%zd, remote=%zd).",
627204076Spjd		    (ssize_t)res->hr_extentsize, (ssize_t)extentsize);
628204076Spjd		nv_free(nvin);
629204076Spjd		goto close;
630204076Spjd	}
631204076Spjd	res->hr_secondary_localcnt = nv_get_uint64(nvin, "localcnt");
632204076Spjd	res->hr_secondary_remotecnt = nv_get_uint64(nvin, "remotecnt");
633204076Spjd	res->hr_syncsrc = nv_get_uint8(nvin, "syncsrc");
634204076Spjd	map = NULL;
635204076Spjd	mapsize = nv_get_uint32(nvin, "mapsize");
636204076Spjd	if (mapsize > 0) {
637204076Spjd		map = malloc(mapsize);
638204076Spjd		if (map == NULL) {
639204076Spjd			pjdlog_error("Unable to allocate memory for remote activemap (mapsize=%ju).",
640204076Spjd			    (uintmax_t)mapsize);
641204076Spjd			nv_free(nvin);
642204076Spjd			goto close;
643204076Spjd		}
644204076Spjd		/*
645204076Spjd		 * Remote node have some dirty extents on its own, lets
646204076Spjd		 * download its activemap.
647204076Spjd		 */
648205738Spjd		if (hast_proto_recv_data(res, out, nvin, map,
649204076Spjd		    mapsize) < 0) {
650204076Spjd			pjdlog_errno(LOG_ERR,
651204076Spjd			    "Unable to receive remote activemap");
652204076Spjd			nv_free(nvin);
653204076Spjd			free(map);
654204076Spjd			goto close;
655204076Spjd		}
656204076Spjd		/*
657204076Spjd		 * Merge local and remote bitmaps.
658204076Spjd		 */
659204076Spjd		activemap_merge(res->hr_amp, map, mapsize);
660204076Spjd		free(map);
661204076Spjd		/*
662204076Spjd		 * Now that we merged bitmaps from both nodes, flush it to the
663204076Spjd		 * disk before we start to synchronize.
664204076Spjd		 */
665204076Spjd		(void)hast_activemap_flush(res);
666204076Spjd	}
667204076Spjd	pjdlog_info("Connected to %s.", res->hr_remoteaddr);
668205738Spjd	if (inp != NULL && outp != NULL) {
669205738Spjd		*inp = in;
670205738Spjd		*outp = out;
671205738Spjd	} else {
672205738Spjd		res->hr_remotein = in;
673205738Spjd		res->hr_remoteout = out;
674205738Spjd	}
675211984Spjd	hook_exec(res->hr_exec, "connect", res->hr_name, NULL);
676205738Spjd	return (true);
677205738Spjdclose:
678211983Spjd	if (errmsg != NULL && strcmp(errmsg, "Split-brain condition!") == 0)
679211983Spjd		hook_exec(res->hr_exec, "split-brain", res->hr_name, NULL);
680205738Spjd	proto_close(out);
681205738Spjd	if (in != NULL)
682205738Spjd		proto_close(in);
683205738Spjd	return (false);
684205738Spjd}
685205738Spjd
686205738Spjdstatic void
687205738Spjdsync_start(void)
688205738Spjd{
689205738Spjd
690204076Spjd	mtx_lock(&sync_lock);
691204076Spjd	sync_inprogress = true;
692204076Spjd	mtx_unlock(&sync_lock);
693204076Spjd	cv_signal(&sync_cond);
694204076Spjd}
695204076Spjd
696204076Spjdstatic void
697211878Spjdsync_stop(void)
698211878Spjd{
699211878Spjd
700211878Spjd	mtx_lock(&sync_lock);
701211878Spjd	if (sync_inprogress)
702211878Spjd		sync_inprogress = false;
703211878Spjd	mtx_unlock(&sync_lock);
704211878Spjd}
705211878Spjd
706211878Spjdstatic void
707204076Spjdinit_ggate(struct hast_resource *res)
708204076Spjd{
709204076Spjd	struct g_gate_ctl_create ggiocreate;
710204076Spjd	struct g_gate_ctl_cancel ggiocancel;
711204076Spjd
712204076Spjd	/*
713204076Spjd	 * We communicate with ggate via /dev/ggctl. Open it.
714204076Spjd	 */
715204076Spjd	res->hr_ggatefd = open("/dev/" G_GATE_CTL_NAME, O_RDWR);
716204076Spjd	if (res->hr_ggatefd < 0)
717204076Spjd		primary_exit(EX_OSFILE, "Unable to open /dev/" G_GATE_CTL_NAME);
718204076Spjd	/*
719204076Spjd	 * Create provider before trying to connect, as connection failure
720204076Spjd	 * is not critical, but may take some time.
721204076Spjd	 */
722204076Spjd	ggiocreate.gctl_version = G_GATE_VERSION;
723204076Spjd	ggiocreate.gctl_mediasize = res->hr_datasize;
724204076Spjd	ggiocreate.gctl_sectorsize = res->hr_local_sectorsize;
725204076Spjd	ggiocreate.gctl_flags = 0;
726206669Spjd	ggiocreate.gctl_maxcount = G_GATE_MAX_QUEUE_SIZE;
727204076Spjd	ggiocreate.gctl_timeout = 0;
728204076Spjd	ggiocreate.gctl_unit = G_GATE_NAME_GIVEN;
729204076Spjd	snprintf(ggiocreate.gctl_name, sizeof(ggiocreate.gctl_name), "hast/%s",
730204076Spjd	    res->hr_provname);
731204076Spjd	bzero(ggiocreate.gctl_info, sizeof(ggiocreate.gctl_info));
732204076Spjd	if (ioctl(res->hr_ggatefd, G_GATE_CMD_CREATE, &ggiocreate) == 0) {
733204076Spjd		pjdlog_info("Device hast/%s created.", res->hr_provname);
734204076Spjd		res->hr_ggateunit = ggiocreate.gctl_unit;
735204076Spjd		return;
736204076Spjd	}
737204076Spjd	if (errno != EEXIST) {
738204076Spjd		primary_exit(EX_OSERR, "Unable to create hast/%s device",
739204076Spjd		    res->hr_provname);
740204076Spjd	}
741204076Spjd	pjdlog_debug(1,
742204076Spjd	    "Device hast/%s already exists, we will try to take it over.",
743204076Spjd	    res->hr_provname);
744204076Spjd	/*
745204076Spjd	 * If we received EEXIST, we assume that the process who created the
746204076Spjd	 * provider died and didn't clean up. In that case we will start from
747204076Spjd	 * where he left of.
748204076Spjd	 */
749204076Spjd	ggiocancel.gctl_version = G_GATE_VERSION;
750204076Spjd	ggiocancel.gctl_unit = G_GATE_NAME_GIVEN;
751204076Spjd	snprintf(ggiocancel.gctl_name, sizeof(ggiocancel.gctl_name), "hast/%s",
752204076Spjd	    res->hr_provname);
753204076Spjd	if (ioctl(res->hr_ggatefd, G_GATE_CMD_CANCEL, &ggiocancel) == 0) {
754204076Spjd		pjdlog_info("Device hast/%s recovered.", res->hr_provname);
755204076Spjd		res->hr_ggateunit = ggiocancel.gctl_unit;
756204076Spjd		return;
757204076Spjd	}
758204076Spjd	primary_exit(EX_OSERR, "Unable to take over hast/%s device",
759204076Spjd	    res->hr_provname);
760204076Spjd}
761204076Spjd
762204076Spjdvoid
763204076Spjdhastd_primary(struct hast_resource *res)
764204076Spjd{
765204076Spjd	pthread_t td;
766204076Spjd	pid_t pid;
767204076Spjd	int error;
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));
774212034Spjd		pjdlog_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));
781212034Spjd		pjdlog_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
790211984Spjd	gres = res;
791211984Spjd
792204076Spjd	(void)pidfile_close(pfh);
793211977Spjd	hook_fini();
794204076Spjd
795204076Spjd	setproctitle("%s (primary)", res->hr_name);
796204076Spjd
797210880Spjd	signal(SIGHUP, SIG_DFL);
798210880Spjd	signal(SIGCHLD, SIG_DFL);
799210880Spjd
800211886Spjd	hook_init();
801204076Spjd	init_local(res);
802210881Spjd	if (real_remote(res) && init_remote(res, NULL, NULL))
803205738Spjd		sync_start();
804204076Spjd	init_ggate(res);
805204076Spjd	init_environment(res);
806204076Spjd	error = pthread_create(&td, NULL, ggate_recv_thread, res);
807204076Spjd	assert(error == 0);
808204076Spjd	error = pthread_create(&td, NULL, local_send_thread, res);
809204076Spjd	assert(error == 0);
810204076Spjd	error = pthread_create(&td, NULL, remote_send_thread, res);
811204076Spjd	assert(error == 0);
812204076Spjd	error = pthread_create(&td, NULL, remote_recv_thread, res);
813204076Spjd	assert(error == 0);
814204076Spjd	error = pthread_create(&td, NULL, ggate_send_thread, res);
815204076Spjd	assert(error == 0);
816204076Spjd	error = pthread_create(&td, NULL, sync_thread, res);
817204076Spjd	assert(error == 0);
818204076Spjd	error = pthread_create(&td, NULL, ctrl_thread, res);
819204076Spjd	assert(error == 0);
820204076Spjd	(void)guard_thread(res);
821204076Spjd}
822204076Spjd
823204076Spjdstatic void
824204076Spjdreqlog(int loglevel, int debuglevel, struct g_gate_ctl_io *ggio, const char *fmt, ...)
825204076Spjd{
826204076Spjd	char msg[1024];
827204076Spjd	va_list ap;
828204076Spjd	int len;
829204076Spjd
830204076Spjd	va_start(ap, fmt);
831204076Spjd	len = vsnprintf(msg, sizeof(msg), fmt, ap);
832204076Spjd	va_end(ap);
833204076Spjd	if ((size_t)len < sizeof(msg)) {
834204076Spjd		switch (ggio->gctl_cmd) {
835204076Spjd		case BIO_READ:
836204076Spjd			(void)snprintf(msg + len, sizeof(msg) - len,
837204076Spjd			    "READ(%ju, %ju).", (uintmax_t)ggio->gctl_offset,
838204076Spjd			    (uintmax_t)ggio->gctl_length);
839204076Spjd			break;
840204076Spjd		case BIO_DELETE:
841204076Spjd			(void)snprintf(msg + len, sizeof(msg) - len,
842204076Spjd			    "DELETE(%ju, %ju).", (uintmax_t)ggio->gctl_offset,
843204076Spjd			    (uintmax_t)ggio->gctl_length);
844204076Spjd			break;
845204076Spjd		case BIO_FLUSH:
846204076Spjd			(void)snprintf(msg + len, sizeof(msg) - len, "FLUSH.");
847204076Spjd			break;
848204076Spjd		case BIO_WRITE:
849204076Spjd			(void)snprintf(msg + len, sizeof(msg) - len,
850204076Spjd			    "WRITE(%ju, %ju).", (uintmax_t)ggio->gctl_offset,
851204076Spjd			    (uintmax_t)ggio->gctl_length);
852204076Spjd			break;
853204076Spjd		default:
854204076Spjd			(void)snprintf(msg + len, sizeof(msg) - len,
855204076Spjd			    "UNKNOWN(%u).", (unsigned int)ggio->gctl_cmd);
856204076Spjd			break;
857204076Spjd		}
858204076Spjd	}
859204076Spjd	pjdlog_common(loglevel, debuglevel, -1, "%s", msg);
860204076Spjd}
861204076Spjd
862204076Spjdstatic void
863204076Spjdremote_close(struct hast_resource *res, int ncomp)
864204076Spjd{
865204076Spjd
866204076Spjd	rw_wlock(&hio_remote_lock[ncomp]);
867204076Spjd	/*
868204076Spjd	 * A race is possible between dropping rlock and acquiring wlock -
869204076Spjd	 * another thread can close connection in-between.
870204076Spjd	 */
871204076Spjd	if (!ISCONNECTED(res, ncomp)) {
872204076Spjd		assert(res->hr_remotein == NULL);
873204076Spjd		assert(res->hr_remoteout == NULL);
874204076Spjd		rw_unlock(&hio_remote_lock[ncomp]);
875204076Spjd		return;
876204076Spjd	}
877204076Spjd
878204076Spjd	assert(res->hr_remotein != NULL);
879204076Spjd	assert(res->hr_remoteout != NULL);
880204076Spjd
881211881Spjd	pjdlog_debug(2, "Closing incoming connection to %s.",
882204076Spjd	    res->hr_remoteaddr);
883204076Spjd	proto_close(res->hr_remotein);
884204076Spjd	res->hr_remotein = NULL;
885211881Spjd	pjdlog_debug(2, "Closing outgoing connection to %s.",
886204076Spjd	    res->hr_remoteaddr);
887204076Spjd	proto_close(res->hr_remoteout);
888204076Spjd	res->hr_remoteout = NULL;
889204076Spjd
890204076Spjd	rw_unlock(&hio_remote_lock[ncomp]);
891204076Spjd
892211881Spjd	pjdlog_warning("Disconnected from %s.", res->hr_remoteaddr);
893211881Spjd
894204076Spjd	/*
895204076Spjd	 * Stop synchronization if in-progress.
896204076Spjd	 */
897211878Spjd	sync_stop();
898211984Spjd
899211984Spjd	hook_exec(res->hr_exec, "disconnect", res->hr_name, NULL);
900204076Spjd}
901204076Spjd
902204076Spjd/*
903204076Spjd * Thread receives ggate I/O requests from the kernel and passes them to
904204076Spjd * appropriate threads:
905204076Spjd * WRITE - always goes to both local_send and remote_send threads
906204076Spjd * READ (when the block is up-to-date on local component) -
907204076Spjd *	only local_send thread
908204076Spjd * READ (when the block isn't up-to-date on local component) -
909204076Spjd *	only remote_send thread
910204076Spjd * DELETE - always goes to both local_send and remote_send threads
911204076Spjd * FLUSH - always goes to both local_send and remote_send threads
912204076Spjd */
913204076Spjdstatic void *
914204076Spjdggate_recv_thread(void *arg)
915204076Spjd{
916204076Spjd	struct hast_resource *res = arg;
917204076Spjd	struct g_gate_ctl_io *ggio;
918204076Spjd	struct hio *hio;
919204076Spjd	unsigned int ii, ncomp, ncomps;
920204076Spjd	int error;
921204076Spjd
922204076Spjd	ncomps = HAST_NCOMPONENTS;
923204076Spjd
924204076Spjd	for (;;) {
925204076Spjd		pjdlog_debug(2, "ggate_recv: Taking free request.");
926204076Spjd		QUEUE_TAKE2(hio, free);
927204076Spjd		pjdlog_debug(2, "ggate_recv: (%p) Got free request.", hio);
928204076Spjd		ggio = &hio->hio_ggio;
929204076Spjd		ggio->gctl_unit = res->hr_ggateunit;
930204076Spjd		ggio->gctl_length = MAXPHYS;
931204076Spjd		ggio->gctl_error = 0;
932204076Spjd		pjdlog_debug(2,
933204076Spjd		    "ggate_recv: (%p) Waiting for request from the kernel.",
934204076Spjd		    hio);
935204076Spjd		if (ioctl(res->hr_ggatefd, G_GATE_CMD_START, ggio) < 0) {
936204076Spjd			if (sigexit_received)
937204076Spjd				pthread_exit(NULL);
938204076Spjd			primary_exit(EX_OSERR, "G_GATE_CMD_START failed");
939204076Spjd		}
940204076Spjd		error = ggio->gctl_error;
941204076Spjd		switch (error) {
942204076Spjd		case 0:
943204076Spjd			break;
944204076Spjd		case ECANCELED:
945204076Spjd			/* Exit gracefully. */
946204076Spjd			if (!sigexit_received) {
947204076Spjd				pjdlog_debug(2,
948204076Spjd				    "ggate_recv: (%p) Received cancel from the kernel.",
949204076Spjd				    hio);
950204076Spjd				pjdlog_info("Received cancel from the kernel, exiting.");
951204076Spjd			}
952204076Spjd			pthread_exit(NULL);
953204076Spjd		case ENOMEM:
954204076Spjd			/*
955204076Spjd			 * Buffer too small? Impossible, we allocate MAXPHYS
956204076Spjd			 * bytes - request can't be bigger than that.
957204076Spjd			 */
958204076Spjd			/* FALLTHROUGH */
959204076Spjd		case ENXIO:
960204076Spjd		default:
961204076Spjd			primary_exitx(EX_OSERR, "G_GATE_CMD_START failed: %s.",
962204076Spjd			    strerror(error));
963204076Spjd		}
964204076Spjd		for (ii = 0; ii < ncomps; ii++)
965204076Spjd			hio->hio_errors[ii] = EINVAL;
966204076Spjd		reqlog(LOG_DEBUG, 2, ggio,
967204076Spjd		    "ggate_recv: (%p) Request received from the kernel: ",
968204076Spjd		    hio);
969204076Spjd		/*
970204076Spjd		 * Inform all components about new write request.
971204076Spjd		 * For read request prefer local component unless the given
972204076Spjd		 * range is out-of-date, then use remote component.
973204076Spjd		 */
974204076Spjd		switch (ggio->gctl_cmd) {
975204076Spjd		case BIO_READ:
976204076Spjd			pjdlog_debug(2,
977204076Spjd			    "ggate_recv: (%p) Moving request to the send queue.",
978204076Spjd			    hio);
979204076Spjd			refcount_init(&hio->hio_countdown, 1);
980204076Spjd			mtx_lock(&metadata_lock);
981204076Spjd			if (res->hr_syncsrc == HAST_SYNCSRC_UNDEF ||
982204076Spjd			    res->hr_syncsrc == HAST_SYNCSRC_PRIMARY) {
983204076Spjd				/*
984204076Spjd				 * This range is up-to-date on local component,
985204076Spjd				 * so handle request locally.
986204076Spjd				 */
987204076Spjd				 /* Local component is 0 for now. */
988204076Spjd				ncomp = 0;
989204076Spjd			} else /* if (res->hr_syncsrc ==
990204076Spjd			    HAST_SYNCSRC_SECONDARY) */ {
991204076Spjd				assert(res->hr_syncsrc ==
992204076Spjd				    HAST_SYNCSRC_SECONDARY);
993204076Spjd				/*
994204076Spjd				 * This range is out-of-date on local component,
995204076Spjd				 * so send request to the remote node.
996204076Spjd				 */
997204076Spjd				 /* Remote component is 1 for now. */
998204076Spjd				ncomp = 1;
999204076Spjd			}
1000204076Spjd			mtx_unlock(&metadata_lock);
1001204076Spjd			QUEUE_INSERT1(hio, send, ncomp);
1002204076Spjd			break;
1003204076Spjd		case BIO_WRITE:
1004204076Spjd			for (;;) {
1005204076Spjd				mtx_lock(&range_lock);
1006204076Spjd				if (rangelock_islocked(range_sync,
1007204076Spjd				    ggio->gctl_offset, ggio->gctl_length)) {
1008204076Spjd					pjdlog_debug(2,
1009204076Spjd					    "regular: Range offset=%jd length=%zu locked.",
1010204076Spjd					    (intmax_t)ggio->gctl_offset,
1011204076Spjd					    (size_t)ggio->gctl_length);
1012204076Spjd					range_regular_wait = true;
1013204076Spjd					cv_wait(&range_regular_cond, &range_lock);
1014204076Spjd					range_regular_wait = false;
1015204076Spjd					mtx_unlock(&range_lock);
1016204076Spjd					continue;
1017204076Spjd				}
1018204076Spjd				if (rangelock_add(range_regular,
1019204076Spjd				    ggio->gctl_offset, ggio->gctl_length) < 0) {
1020204076Spjd					mtx_unlock(&range_lock);
1021204076Spjd					pjdlog_debug(2,
1022204076Spjd					    "regular: Range offset=%jd length=%zu is already locked, waiting.",
1023204076Spjd					    (intmax_t)ggio->gctl_offset,
1024204076Spjd					    (size_t)ggio->gctl_length);
1025204076Spjd					sleep(1);
1026204076Spjd					continue;
1027204076Spjd				}
1028204076Spjd				mtx_unlock(&range_lock);
1029204076Spjd				break;
1030204076Spjd			}
1031204076Spjd			mtx_lock(&res->hr_amp_lock);
1032204076Spjd			if (activemap_write_start(res->hr_amp,
1033204076Spjd			    ggio->gctl_offset, ggio->gctl_length)) {
1034204076Spjd				(void)hast_activemap_flush(res);
1035204076Spjd			}
1036204076Spjd			mtx_unlock(&res->hr_amp_lock);
1037204076Spjd			/* FALLTHROUGH */
1038204076Spjd		case BIO_DELETE:
1039204076Spjd		case BIO_FLUSH:
1040204076Spjd			pjdlog_debug(2,
1041204076Spjd			    "ggate_recv: (%p) Moving request to the send queues.",
1042204076Spjd			    hio);
1043204076Spjd			refcount_init(&hio->hio_countdown, ncomps);
1044204076Spjd			for (ii = 0; ii < ncomps; ii++)
1045204076Spjd				QUEUE_INSERT1(hio, send, ii);
1046204076Spjd			break;
1047204076Spjd		}
1048204076Spjd	}
1049204076Spjd	/* NOTREACHED */
1050204076Spjd	return (NULL);
1051204076Spjd}
1052204076Spjd
1053204076Spjd/*
1054204076Spjd * Thread reads from or writes to local component.
1055204076Spjd * If local read fails, it redirects it to remote_send thread.
1056204076Spjd */
1057204076Spjdstatic void *
1058204076Spjdlocal_send_thread(void *arg)
1059204076Spjd{
1060204076Spjd	struct hast_resource *res = arg;
1061204076Spjd	struct g_gate_ctl_io *ggio;
1062204076Spjd	struct hio *hio;
1063204076Spjd	unsigned int ncomp, rncomp;
1064204076Spjd	ssize_t ret;
1065204076Spjd
1066204076Spjd	/* Local component is 0 for now. */
1067204076Spjd	ncomp = 0;
1068204076Spjd	/* Remote component is 1 for now. */
1069204076Spjd	rncomp = 1;
1070204076Spjd
1071204076Spjd	for (;;) {
1072204076Spjd		pjdlog_debug(2, "local_send: Taking request.");
1073204076Spjd		QUEUE_TAKE1(hio, send, ncomp);
1074204076Spjd		pjdlog_debug(2, "local_send: (%p) Got request.", hio);
1075204076Spjd		ggio = &hio->hio_ggio;
1076204076Spjd		switch (ggio->gctl_cmd) {
1077204076Spjd		case BIO_READ:
1078204076Spjd			ret = pread(res->hr_localfd, ggio->gctl_data,
1079204076Spjd			    ggio->gctl_length,
1080204076Spjd			    ggio->gctl_offset + res->hr_localoff);
1081204076Spjd			if (ret == ggio->gctl_length)
1082204076Spjd				hio->hio_errors[ncomp] = 0;
1083204076Spjd			else {
1084204076Spjd				/*
1085204076Spjd				 * If READ failed, try to read from remote node.
1086204076Spjd				 */
1087204076Spjd				QUEUE_INSERT1(hio, send, rncomp);
1088204076Spjd				continue;
1089204076Spjd			}
1090204076Spjd			break;
1091204076Spjd		case BIO_WRITE:
1092204076Spjd			ret = pwrite(res->hr_localfd, ggio->gctl_data,
1093204076Spjd			    ggio->gctl_length,
1094204076Spjd			    ggio->gctl_offset + res->hr_localoff);
1095204076Spjd			if (ret < 0)
1096204076Spjd				hio->hio_errors[ncomp] = errno;
1097204076Spjd			else if (ret != ggio->gctl_length)
1098204076Spjd				hio->hio_errors[ncomp] = EIO;
1099204076Spjd			else
1100204076Spjd				hio->hio_errors[ncomp] = 0;
1101204076Spjd			break;
1102204076Spjd		case BIO_DELETE:
1103204076Spjd			ret = g_delete(res->hr_localfd,
1104204076Spjd			    ggio->gctl_offset + res->hr_localoff,
1105204076Spjd			    ggio->gctl_length);
1106204076Spjd			if (ret < 0)
1107204076Spjd				hio->hio_errors[ncomp] = errno;
1108204076Spjd			else
1109204076Spjd				hio->hio_errors[ncomp] = 0;
1110204076Spjd			break;
1111204076Spjd		case BIO_FLUSH:
1112204076Spjd			ret = g_flush(res->hr_localfd);
1113204076Spjd			if (ret < 0)
1114204076Spjd				hio->hio_errors[ncomp] = errno;
1115204076Spjd			else
1116204076Spjd				hio->hio_errors[ncomp] = 0;
1117204076Spjd			break;
1118204076Spjd		}
1119204076Spjd		if (refcount_release(&hio->hio_countdown)) {
1120204076Spjd			if (ISSYNCREQ(hio)) {
1121204076Spjd				mtx_lock(&sync_lock);
1122204076Spjd				SYNCREQDONE(hio);
1123204076Spjd				mtx_unlock(&sync_lock);
1124204076Spjd				cv_signal(&sync_cond);
1125204076Spjd			} else {
1126204076Spjd				pjdlog_debug(2,
1127204076Spjd				    "local_send: (%p) Moving request to the done queue.",
1128204076Spjd				    hio);
1129204076Spjd				QUEUE_INSERT2(hio, done);
1130204076Spjd			}
1131204076Spjd		}
1132204076Spjd	}
1133204076Spjd	/* NOTREACHED */
1134204076Spjd	return (NULL);
1135204076Spjd}
1136204076Spjd
1137204076Spjd/*
1138204076Spjd * Thread sends request to secondary node.
1139204076Spjd */
1140204076Spjdstatic void *
1141204076Spjdremote_send_thread(void *arg)
1142204076Spjd{
1143204076Spjd	struct hast_resource *res = arg;
1144204076Spjd	struct g_gate_ctl_io *ggio;
1145204076Spjd	struct hio *hio;
1146204076Spjd	struct nv *nv;
1147204076Spjd	unsigned int ncomp;
1148204076Spjd	bool wakeup;
1149204076Spjd	uint64_t offset, length;
1150204076Spjd	uint8_t cmd;
1151204076Spjd	void *data;
1152204076Spjd
1153204076Spjd	/* Remote component is 1 for now. */
1154204076Spjd	ncomp = 1;
1155204076Spjd
1156204076Spjd	for (;;) {
1157204076Spjd		pjdlog_debug(2, "remote_send: Taking request.");
1158204076Spjd		QUEUE_TAKE1(hio, send, ncomp);
1159204076Spjd		pjdlog_debug(2, "remote_send: (%p) Got request.", hio);
1160204076Spjd		ggio = &hio->hio_ggio;
1161204076Spjd		switch (ggio->gctl_cmd) {
1162204076Spjd		case BIO_READ:
1163204076Spjd			cmd = HIO_READ;
1164204076Spjd			data = NULL;
1165204076Spjd			offset = ggio->gctl_offset;
1166204076Spjd			length = ggio->gctl_length;
1167204076Spjd			break;
1168204076Spjd		case BIO_WRITE:
1169204076Spjd			cmd = HIO_WRITE;
1170204076Spjd			data = ggio->gctl_data;
1171204076Spjd			offset = ggio->gctl_offset;
1172204076Spjd			length = ggio->gctl_length;
1173204076Spjd			break;
1174204076Spjd		case BIO_DELETE:
1175204076Spjd			cmd = HIO_DELETE;
1176204076Spjd			data = NULL;
1177204076Spjd			offset = ggio->gctl_offset;
1178204076Spjd			length = ggio->gctl_length;
1179204076Spjd			break;
1180204076Spjd		case BIO_FLUSH:
1181204076Spjd			cmd = HIO_FLUSH;
1182204076Spjd			data = NULL;
1183204076Spjd			offset = 0;
1184204076Spjd			length = 0;
1185204076Spjd			break;
1186204076Spjd		default:
1187204076Spjd			assert(!"invalid condition");
1188204076Spjd			abort();
1189204076Spjd		}
1190204076Spjd		nv = nv_alloc();
1191204076Spjd		nv_add_uint8(nv, cmd, "cmd");
1192204076Spjd		nv_add_uint64(nv, (uint64_t)ggio->gctl_seq, "seq");
1193204076Spjd		nv_add_uint64(nv, offset, "offset");
1194204076Spjd		nv_add_uint64(nv, length, "length");
1195204076Spjd		if (nv_error(nv) != 0) {
1196204076Spjd			hio->hio_errors[ncomp] = nv_error(nv);
1197204076Spjd			pjdlog_debug(2,
1198204076Spjd			    "remote_send: (%p) Unable to prepare header to send.",
1199204076Spjd			    hio);
1200204076Spjd			reqlog(LOG_ERR, 0, ggio,
1201204076Spjd			    "Unable to prepare header to send (%s): ",
1202204076Spjd			    strerror(nv_error(nv)));
1203204076Spjd			/* Move failed request immediately to the done queue. */
1204204076Spjd			goto done_queue;
1205204076Spjd		}
1206204076Spjd		pjdlog_debug(2,
1207204076Spjd		    "remote_send: (%p) Moving request to the recv queue.",
1208204076Spjd		    hio);
1209204076Spjd		/*
1210204076Spjd		 * Protect connection from disappearing.
1211204076Spjd		 */
1212204076Spjd		rw_rlock(&hio_remote_lock[ncomp]);
1213204076Spjd		if (!ISCONNECTED(res, ncomp)) {
1214204076Spjd			rw_unlock(&hio_remote_lock[ncomp]);
1215204076Spjd			hio->hio_errors[ncomp] = ENOTCONN;
1216204076Spjd			goto done_queue;
1217204076Spjd		}
1218204076Spjd		/*
1219204076Spjd		 * Move the request to recv queue before sending it, because
1220204076Spjd		 * in different order we can get reply before we move request
1221204076Spjd		 * to recv queue.
1222204076Spjd		 */
1223204076Spjd		mtx_lock(&hio_recv_list_lock[ncomp]);
1224204076Spjd		wakeup = TAILQ_EMPTY(&hio_recv_list[ncomp]);
1225204076Spjd		TAILQ_INSERT_TAIL(&hio_recv_list[ncomp], hio, hio_next[ncomp]);
1226204076Spjd		mtx_unlock(&hio_recv_list_lock[ncomp]);
1227204076Spjd		if (hast_proto_send(res, res->hr_remoteout, nv, data,
1228204076Spjd		    data != NULL ? length : 0) < 0) {
1229204076Spjd			hio->hio_errors[ncomp] = errno;
1230204076Spjd			rw_unlock(&hio_remote_lock[ncomp]);
1231204076Spjd			pjdlog_debug(2,
1232204076Spjd			    "remote_send: (%p) Unable to send request.", hio);
1233204076Spjd			reqlog(LOG_ERR, 0, ggio,
1234204076Spjd			    "Unable to send request (%s): ",
1235204076Spjd			    strerror(hio->hio_errors[ncomp]));
1236211979Spjd			remote_close(res, ncomp);
1237204076Spjd			/*
1238204076Spjd			 * Take request back from the receive queue and move
1239204076Spjd			 * it immediately to the done queue.
1240204076Spjd			 */
1241204076Spjd			mtx_lock(&hio_recv_list_lock[ncomp]);
1242204076Spjd			TAILQ_REMOVE(&hio_recv_list[ncomp], hio, hio_next[ncomp]);
1243204076Spjd			mtx_unlock(&hio_recv_list_lock[ncomp]);
1244204076Spjd			goto done_queue;
1245204076Spjd		}
1246204076Spjd		rw_unlock(&hio_remote_lock[ncomp]);
1247204076Spjd		nv_free(nv);
1248204076Spjd		if (wakeup)
1249204076Spjd			cv_signal(&hio_recv_list_cond[ncomp]);
1250204076Spjd		continue;
1251204076Spjddone_queue:
1252204076Spjd		nv_free(nv);
1253204076Spjd		if (ISSYNCREQ(hio)) {
1254204076Spjd			if (!refcount_release(&hio->hio_countdown))
1255204076Spjd				continue;
1256204076Spjd			mtx_lock(&sync_lock);
1257204076Spjd			SYNCREQDONE(hio);
1258204076Spjd			mtx_unlock(&sync_lock);
1259204076Spjd			cv_signal(&sync_cond);
1260204076Spjd			continue;
1261204076Spjd		}
1262204076Spjd		if (ggio->gctl_cmd == BIO_WRITE) {
1263204076Spjd			mtx_lock(&res->hr_amp_lock);
1264204076Spjd			if (activemap_need_sync(res->hr_amp, ggio->gctl_offset,
1265204076Spjd			    ggio->gctl_length)) {
1266204076Spjd				(void)hast_activemap_flush(res);
1267204076Spjd			}
1268204076Spjd			mtx_unlock(&res->hr_amp_lock);
1269204076Spjd		}
1270204076Spjd		if (!refcount_release(&hio->hio_countdown))
1271204076Spjd			continue;
1272204076Spjd		pjdlog_debug(2,
1273204076Spjd		    "remote_send: (%p) Moving request to the done queue.",
1274204076Spjd		    hio);
1275204076Spjd		QUEUE_INSERT2(hio, done);
1276204076Spjd	}
1277204076Spjd	/* NOTREACHED */
1278204076Spjd	return (NULL);
1279204076Spjd}
1280204076Spjd
1281204076Spjd/*
1282204076Spjd * Thread receives answer from secondary node and passes it to ggate_send
1283204076Spjd * thread.
1284204076Spjd */
1285204076Spjdstatic void *
1286204076Spjdremote_recv_thread(void *arg)
1287204076Spjd{
1288204076Spjd	struct hast_resource *res = arg;
1289204076Spjd	struct g_gate_ctl_io *ggio;
1290204076Spjd	struct hio *hio;
1291204076Spjd	struct nv *nv;
1292204076Spjd	unsigned int ncomp;
1293204076Spjd	uint64_t seq;
1294204076Spjd	int error;
1295204076Spjd
1296204076Spjd	/* Remote component is 1 for now. */
1297204076Spjd	ncomp = 1;
1298204076Spjd
1299204076Spjd	for (;;) {
1300204076Spjd		/* Wait until there is anything to receive. */
1301204076Spjd		mtx_lock(&hio_recv_list_lock[ncomp]);
1302204076Spjd		while (TAILQ_EMPTY(&hio_recv_list[ncomp])) {
1303204076Spjd			pjdlog_debug(2, "remote_recv: No requests, waiting.");
1304204076Spjd			cv_wait(&hio_recv_list_cond[ncomp],
1305204076Spjd			    &hio_recv_list_lock[ncomp]);
1306204076Spjd		}
1307204076Spjd		mtx_unlock(&hio_recv_list_lock[ncomp]);
1308204076Spjd		rw_rlock(&hio_remote_lock[ncomp]);
1309204076Spjd		if (!ISCONNECTED(res, ncomp)) {
1310204076Spjd			rw_unlock(&hio_remote_lock[ncomp]);
1311204076Spjd			/*
1312204076Spjd			 * Connection is dead, so move all pending requests to
1313204076Spjd			 * the done queue (one-by-one).
1314204076Spjd			 */
1315204076Spjd			mtx_lock(&hio_recv_list_lock[ncomp]);
1316204076Spjd			hio = TAILQ_FIRST(&hio_recv_list[ncomp]);
1317204076Spjd			assert(hio != NULL);
1318204076Spjd			TAILQ_REMOVE(&hio_recv_list[ncomp], hio,
1319204076Spjd			    hio_next[ncomp]);
1320204076Spjd			mtx_unlock(&hio_recv_list_lock[ncomp]);
1321204076Spjd			goto done_queue;
1322204076Spjd		}
1323204076Spjd		if (hast_proto_recv_hdr(res->hr_remotein, &nv) < 0) {
1324204076Spjd			pjdlog_errno(LOG_ERR,
1325204076Spjd			    "Unable to receive reply header");
1326204076Spjd			rw_unlock(&hio_remote_lock[ncomp]);
1327204076Spjd			remote_close(res, ncomp);
1328204076Spjd			continue;
1329204076Spjd		}
1330204076Spjd		rw_unlock(&hio_remote_lock[ncomp]);
1331204076Spjd		seq = nv_get_uint64(nv, "seq");
1332204076Spjd		if (seq == 0) {
1333204076Spjd			pjdlog_error("Header contains no 'seq' field.");
1334204076Spjd			nv_free(nv);
1335204076Spjd			continue;
1336204076Spjd		}
1337204076Spjd		mtx_lock(&hio_recv_list_lock[ncomp]);
1338204076Spjd		TAILQ_FOREACH(hio, &hio_recv_list[ncomp], hio_next[ncomp]) {
1339204076Spjd			if (hio->hio_ggio.gctl_seq == seq) {
1340204076Spjd				TAILQ_REMOVE(&hio_recv_list[ncomp], hio,
1341204076Spjd				    hio_next[ncomp]);
1342204076Spjd				break;
1343204076Spjd			}
1344204076Spjd		}
1345204076Spjd		mtx_unlock(&hio_recv_list_lock[ncomp]);
1346204076Spjd		if (hio == NULL) {
1347204076Spjd			pjdlog_error("Found no request matching received 'seq' field (%ju).",
1348204076Spjd			    (uintmax_t)seq);
1349204076Spjd			nv_free(nv);
1350204076Spjd			continue;
1351204076Spjd		}
1352204076Spjd		error = nv_get_int16(nv, "error");
1353204076Spjd		if (error != 0) {
1354204076Spjd			/* Request failed on remote side. */
1355204076Spjd			hio->hio_errors[ncomp] = 0;
1356204076Spjd			nv_free(nv);
1357204076Spjd			goto done_queue;
1358204076Spjd		}
1359204076Spjd		ggio = &hio->hio_ggio;
1360204076Spjd		switch (ggio->gctl_cmd) {
1361204076Spjd		case BIO_READ:
1362204076Spjd			rw_rlock(&hio_remote_lock[ncomp]);
1363204076Spjd			if (!ISCONNECTED(res, ncomp)) {
1364204076Spjd				rw_unlock(&hio_remote_lock[ncomp]);
1365204076Spjd				nv_free(nv);
1366204076Spjd				goto done_queue;
1367204076Spjd			}
1368204076Spjd			if (hast_proto_recv_data(res, res->hr_remotein, nv,
1369204076Spjd			    ggio->gctl_data, ggio->gctl_length) < 0) {
1370204076Spjd				hio->hio_errors[ncomp] = errno;
1371204076Spjd				pjdlog_errno(LOG_ERR,
1372204076Spjd				    "Unable to receive reply data");
1373204076Spjd				rw_unlock(&hio_remote_lock[ncomp]);
1374204076Spjd				nv_free(nv);
1375204076Spjd				remote_close(res, ncomp);
1376204076Spjd				goto done_queue;
1377204076Spjd			}
1378204076Spjd			rw_unlock(&hio_remote_lock[ncomp]);
1379204076Spjd			break;
1380204076Spjd		case BIO_WRITE:
1381204076Spjd		case BIO_DELETE:
1382204076Spjd		case BIO_FLUSH:
1383204076Spjd			break;
1384204076Spjd		default:
1385204076Spjd			assert(!"invalid condition");
1386204076Spjd			abort();
1387204076Spjd		}
1388204076Spjd		hio->hio_errors[ncomp] = 0;
1389204076Spjd		nv_free(nv);
1390204076Spjddone_queue:
1391204076Spjd		if (refcount_release(&hio->hio_countdown)) {
1392204076Spjd			if (ISSYNCREQ(hio)) {
1393204076Spjd				mtx_lock(&sync_lock);
1394204076Spjd				SYNCREQDONE(hio);
1395204076Spjd				mtx_unlock(&sync_lock);
1396204076Spjd				cv_signal(&sync_cond);
1397204076Spjd			} else {
1398204076Spjd				pjdlog_debug(2,
1399204076Spjd				    "remote_recv: (%p) Moving request to the done queue.",
1400204076Spjd				    hio);
1401204076Spjd				QUEUE_INSERT2(hio, done);
1402204076Spjd			}
1403204076Spjd		}
1404204076Spjd	}
1405204076Spjd	/* NOTREACHED */
1406204076Spjd	return (NULL);
1407204076Spjd}
1408204076Spjd
1409204076Spjd/*
1410204076Spjd * Thread sends answer to the kernel.
1411204076Spjd */
1412204076Spjdstatic void *
1413204076Spjdggate_send_thread(void *arg)
1414204076Spjd{
1415204076Spjd	struct hast_resource *res = arg;
1416204076Spjd	struct g_gate_ctl_io *ggio;
1417204076Spjd	struct hio *hio;
1418204076Spjd	unsigned int ii, ncomp, ncomps;
1419204076Spjd
1420204076Spjd	ncomps = HAST_NCOMPONENTS;
1421204076Spjd
1422204076Spjd	for (;;) {
1423204076Spjd		pjdlog_debug(2, "ggate_send: Taking request.");
1424204076Spjd		QUEUE_TAKE2(hio, done);
1425204076Spjd		pjdlog_debug(2, "ggate_send: (%p) Got request.", hio);
1426204076Spjd		ggio = &hio->hio_ggio;
1427204076Spjd		for (ii = 0; ii < ncomps; ii++) {
1428204076Spjd			if (hio->hio_errors[ii] == 0) {
1429204076Spjd				/*
1430204076Spjd				 * One successful request is enough to declare
1431204076Spjd				 * success.
1432204076Spjd				 */
1433204076Spjd				ggio->gctl_error = 0;
1434204076Spjd				break;
1435204076Spjd			}
1436204076Spjd		}
1437204076Spjd		if (ii == ncomps) {
1438204076Spjd			/*
1439204076Spjd			 * None of the requests were successful.
1440204076Spjd			 * Use first error.
1441204076Spjd			 */
1442204076Spjd			ggio->gctl_error = hio->hio_errors[0];
1443204076Spjd		}
1444204076Spjd		if (ggio->gctl_error == 0 && ggio->gctl_cmd == BIO_WRITE) {
1445204076Spjd			mtx_lock(&res->hr_amp_lock);
1446204076Spjd			activemap_write_complete(res->hr_amp,
1447204076Spjd			    ggio->gctl_offset, ggio->gctl_length);
1448204076Spjd			mtx_unlock(&res->hr_amp_lock);
1449204076Spjd		}
1450204076Spjd		if (ggio->gctl_cmd == BIO_WRITE) {
1451204076Spjd			/*
1452204076Spjd			 * Unlock range we locked.
1453204076Spjd			 */
1454204076Spjd			mtx_lock(&range_lock);
1455204076Spjd			rangelock_del(range_regular, ggio->gctl_offset,
1456204076Spjd			    ggio->gctl_length);
1457204076Spjd			if (range_sync_wait)
1458204076Spjd				cv_signal(&range_sync_cond);
1459204076Spjd			mtx_unlock(&range_lock);
1460204076Spjd			/*
1461204076Spjd			 * Bump local count if this is first write after
1462204076Spjd			 * connection failure with remote node.
1463204076Spjd			 */
1464204076Spjd			ncomp = 1;
1465204076Spjd			rw_rlock(&hio_remote_lock[ncomp]);
1466204076Spjd			if (!ISCONNECTED(res, ncomp)) {
1467204076Spjd				mtx_lock(&metadata_lock);
1468204076Spjd				if (res->hr_primary_localcnt ==
1469204076Spjd				    res->hr_secondary_remotecnt) {
1470204076Spjd					res->hr_primary_localcnt++;
1471204076Spjd					pjdlog_debug(1,
1472204076Spjd					    "Increasing localcnt to %ju.",
1473204076Spjd					    (uintmax_t)res->hr_primary_localcnt);
1474204076Spjd					(void)metadata_write(res);
1475204076Spjd				}
1476204076Spjd				mtx_unlock(&metadata_lock);
1477204076Spjd			}
1478204076Spjd			rw_unlock(&hio_remote_lock[ncomp]);
1479204076Spjd		}
1480204076Spjd		if (ioctl(res->hr_ggatefd, G_GATE_CMD_DONE, ggio) < 0)
1481204076Spjd			primary_exit(EX_OSERR, "G_GATE_CMD_DONE failed");
1482204076Spjd		pjdlog_debug(2,
1483204076Spjd		    "ggate_send: (%p) Moving request to the free queue.", hio);
1484204076Spjd		QUEUE_INSERT2(hio, free);
1485204076Spjd	}
1486204076Spjd	/* NOTREACHED */
1487204076Spjd	return (NULL);
1488204076Spjd}
1489204076Spjd
1490204076Spjd/*
1491204076Spjd * Thread synchronize local and remote components.
1492204076Spjd */
1493204076Spjdstatic void *
1494204076Spjdsync_thread(void *arg __unused)
1495204076Spjd{
1496204076Spjd	struct hast_resource *res = arg;
1497204076Spjd	struct hio *hio;
1498204076Spjd	struct g_gate_ctl_io *ggio;
1499204076Spjd	unsigned int ii, ncomp, ncomps;
1500204076Spjd	off_t offset, length, synced;
1501204076Spjd	bool dorewind;
1502204076Spjd	int syncext;
1503204076Spjd
1504204076Spjd	ncomps = HAST_NCOMPONENTS;
1505204076Spjd	dorewind = true;
1506211897Spjd	synced = 0;
1507211897Spjd	offset = -1;
1508204076Spjd
1509204076Spjd	for (;;) {
1510204076Spjd		mtx_lock(&sync_lock);
1511211897Spjd		if (offset >= 0 && !sync_inprogress) {
1512211879Spjd			pjdlog_info("Synchronization interrupted. "
1513211879Spjd			    "%jd bytes synchronized so far.",
1514211879Spjd			    (intmax_t)synced);
1515211897Spjd			hook_exec(res->hr_exec, "syncintr", res->hr_name, NULL);
1516211879Spjd		}
1517204076Spjd		while (!sync_inprogress) {
1518204076Spjd			dorewind = true;
1519204076Spjd			synced = 0;
1520204076Spjd			cv_wait(&sync_cond, &sync_lock);
1521204076Spjd		}
1522204076Spjd		mtx_unlock(&sync_lock);
1523204076Spjd		/*
1524204076Spjd		 * Obtain offset at which we should synchronize.
1525204076Spjd		 * Rewind synchronization if needed.
1526204076Spjd		 */
1527204076Spjd		mtx_lock(&res->hr_amp_lock);
1528204076Spjd		if (dorewind)
1529204076Spjd			activemap_sync_rewind(res->hr_amp);
1530204076Spjd		offset = activemap_sync_offset(res->hr_amp, &length, &syncext);
1531204076Spjd		if (syncext != -1) {
1532204076Spjd			/*
1533204076Spjd			 * We synchronized entire syncext extent, we can mark
1534204076Spjd			 * it as clean now.
1535204076Spjd			 */
1536204076Spjd			if (activemap_extent_complete(res->hr_amp, syncext))
1537204076Spjd				(void)hast_activemap_flush(res);
1538204076Spjd		}
1539204076Spjd		mtx_unlock(&res->hr_amp_lock);
1540204076Spjd		if (dorewind) {
1541204076Spjd			dorewind = false;
1542204076Spjd			if (offset < 0)
1543204076Spjd				pjdlog_info("Nodes are in sync.");
1544204076Spjd			else {
1545204076Spjd				pjdlog_info("Synchronization started. %ju bytes to go.",
1546204076Spjd				    (uintmax_t)(res->hr_extentsize *
1547204076Spjd				    activemap_ndirty(res->hr_amp)));
1548211895Spjd				hook_exec(res->hr_exec, "syncstart",
1549211895Spjd				    res->hr_name, NULL);
1550204076Spjd			}
1551204076Spjd		}
1552204076Spjd		if (offset < 0) {
1553211878Spjd			sync_stop();
1554204076Spjd			pjdlog_debug(1, "Nothing to synchronize.");
1555204076Spjd			/*
1556204076Spjd			 * Synchronization complete, make both localcnt and
1557204076Spjd			 * remotecnt equal.
1558204076Spjd			 */
1559204076Spjd			ncomp = 1;
1560204076Spjd			rw_rlock(&hio_remote_lock[ncomp]);
1561204076Spjd			if (ISCONNECTED(res, ncomp)) {
1562204076Spjd				if (synced > 0) {
1563204076Spjd					pjdlog_info("Synchronization complete. "
1564204076Spjd					    "%jd bytes synchronized.",
1565204076Spjd					    (intmax_t)synced);
1566211895Spjd					hook_exec(res->hr_exec, "syncdone",
1567211895Spjd					    res->hr_name, NULL);
1568204076Spjd				}
1569204076Spjd				mtx_lock(&metadata_lock);
1570204076Spjd				res->hr_syncsrc = HAST_SYNCSRC_UNDEF;
1571204076Spjd				res->hr_primary_localcnt =
1572204076Spjd				    res->hr_secondary_localcnt;
1573204076Spjd				res->hr_primary_remotecnt =
1574204076Spjd				    res->hr_secondary_remotecnt;
1575204076Spjd				pjdlog_debug(1,
1576204076Spjd				    "Setting localcnt to %ju and remotecnt to %ju.",
1577204076Spjd				    (uintmax_t)res->hr_primary_localcnt,
1578204076Spjd				    (uintmax_t)res->hr_secondary_localcnt);
1579204076Spjd				(void)metadata_write(res);
1580204076Spjd				mtx_unlock(&metadata_lock);
1581204076Spjd			}
1582204076Spjd			rw_unlock(&hio_remote_lock[ncomp]);
1583204076Spjd			continue;
1584204076Spjd		}
1585204076Spjd		pjdlog_debug(2, "sync: Taking free request.");
1586204076Spjd		QUEUE_TAKE2(hio, free);
1587204076Spjd		pjdlog_debug(2, "sync: (%p) Got free request.", hio);
1588204076Spjd		/*
1589204076Spjd		 * Lock the range we are going to synchronize. We don't want
1590204076Spjd		 * race where someone writes between our read and write.
1591204076Spjd		 */
1592204076Spjd		for (;;) {
1593204076Spjd			mtx_lock(&range_lock);
1594204076Spjd			if (rangelock_islocked(range_regular, offset, length)) {
1595204076Spjd				pjdlog_debug(2,
1596204076Spjd				    "sync: Range offset=%jd length=%jd locked.",
1597204076Spjd				    (intmax_t)offset, (intmax_t)length);
1598204076Spjd				range_sync_wait = true;
1599204076Spjd				cv_wait(&range_sync_cond, &range_lock);
1600204076Spjd				range_sync_wait = false;
1601204076Spjd				mtx_unlock(&range_lock);
1602204076Spjd				continue;
1603204076Spjd			}
1604204076Spjd			if (rangelock_add(range_sync, offset, length) < 0) {
1605204076Spjd				mtx_unlock(&range_lock);
1606204076Spjd				pjdlog_debug(2,
1607204076Spjd				    "sync: Range offset=%jd length=%jd is already locked, waiting.",
1608204076Spjd				    (intmax_t)offset, (intmax_t)length);
1609204076Spjd				sleep(1);
1610204076Spjd				continue;
1611204076Spjd			}
1612204076Spjd			mtx_unlock(&range_lock);
1613204076Spjd			break;
1614204076Spjd		}
1615204076Spjd		/*
1616204076Spjd		 * First read the data from synchronization source.
1617204076Spjd		 */
1618204076Spjd		SYNCREQ(hio);
1619204076Spjd		ggio = &hio->hio_ggio;
1620204076Spjd		ggio->gctl_cmd = BIO_READ;
1621204076Spjd		ggio->gctl_offset = offset;
1622204076Spjd		ggio->gctl_length = length;
1623204076Spjd		ggio->gctl_error = 0;
1624204076Spjd		for (ii = 0; ii < ncomps; ii++)
1625204076Spjd			hio->hio_errors[ii] = EINVAL;
1626204076Spjd		reqlog(LOG_DEBUG, 2, ggio, "sync: (%p) Sending sync request: ",
1627204076Spjd		    hio);
1628204076Spjd		pjdlog_debug(2, "sync: (%p) Moving request to the send queue.",
1629204076Spjd		    hio);
1630204076Spjd		mtx_lock(&metadata_lock);
1631204076Spjd		if (res->hr_syncsrc == HAST_SYNCSRC_PRIMARY) {
1632204076Spjd			/*
1633204076Spjd			 * This range is up-to-date on local component,
1634204076Spjd			 * so handle request locally.
1635204076Spjd			 */
1636204076Spjd			 /* Local component is 0 for now. */
1637204076Spjd			ncomp = 0;
1638204076Spjd		} else /* if (res->hr_syncsrc == HAST_SYNCSRC_SECONDARY) */ {
1639204076Spjd			assert(res->hr_syncsrc == HAST_SYNCSRC_SECONDARY);
1640204076Spjd			/*
1641204076Spjd			 * This range is out-of-date on local component,
1642204076Spjd			 * so send request to the remote node.
1643204076Spjd			 */
1644204076Spjd			 /* Remote component is 1 for now. */
1645204076Spjd			ncomp = 1;
1646204076Spjd		}
1647204076Spjd		mtx_unlock(&metadata_lock);
1648204076Spjd		refcount_init(&hio->hio_countdown, 1);
1649204076Spjd		QUEUE_INSERT1(hio, send, ncomp);
1650204076Spjd
1651204076Spjd		/*
1652204076Spjd		 * Let's wait for READ to finish.
1653204076Spjd		 */
1654204076Spjd		mtx_lock(&sync_lock);
1655204076Spjd		while (!ISSYNCREQDONE(hio))
1656204076Spjd			cv_wait(&sync_cond, &sync_lock);
1657204076Spjd		mtx_unlock(&sync_lock);
1658204076Spjd
1659204076Spjd		if (hio->hio_errors[ncomp] != 0) {
1660204076Spjd			pjdlog_error("Unable to read synchronization data: %s.",
1661204076Spjd			    strerror(hio->hio_errors[ncomp]));
1662204076Spjd			goto free_queue;
1663204076Spjd		}
1664204076Spjd
1665204076Spjd		/*
1666204076Spjd		 * We read the data from synchronization source, now write it
1667204076Spjd		 * to synchronization target.
1668204076Spjd		 */
1669204076Spjd		SYNCREQ(hio);
1670204076Spjd		ggio->gctl_cmd = BIO_WRITE;
1671204076Spjd		for (ii = 0; ii < ncomps; ii++)
1672204076Spjd			hio->hio_errors[ii] = EINVAL;
1673204076Spjd		reqlog(LOG_DEBUG, 2, ggio, "sync: (%p) Sending sync request: ",
1674204076Spjd		    hio);
1675204076Spjd		pjdlog_debug(2, "sync: (%p) Moving request to the send queue.",
1676204076Spjd		    hio);
1677204076Spjd		mtx_lock(&metadata_lock);
1678204076Spjd		if (res->hr_syncsrc == HAST_SYNCSRC_PRIMARY) {
1679204076Spjd			/*
1680204076Spjd			 * This range is up-to-date on local component,
1681204076Spjd			 * so we update remote component.
1682204076Spjd			 */
1683204076Spjd			 /* Remote component is 1 for now. */
1684204076Spjd			ncomp = 1;
1685204076Spjd		} else /* if (res->hr_syncsrc == HAST_SYNCSRC_SECONDARY) */ {
1686204076Spjd			assert(res->hr_syncsrc == HAST_SYNCSRC_SECONDARY);
1687204076Spjd			/*
1688204076Spjd			 * This range is out-of-date on local component,
1689204076Spjd			 * so we update it.
1690204076Spjd			 */
1691204076Spjd			 /* Local component is 0 for now. */
1692204076Spjd			ncomp = 0;
1693204076Spjd		}
1694204076Spjd		mtx_unlock(&metadata_lock);
1695204076Spjd
1696204076Spjd		pjdlog_debug(2, "sync: (%p) Moving request to the send queues.",
1697204076Spjd		    hio);
1698204076Spjd		refcount_init(&hio->hio_countdown, 1);
1699204076Spjd		QUEUE_INSERT1(hio, send, ncomp);
1700204076Spjd
1701204076Spjd		/*
1702204076Spjd		 * Let's wait for WRITE to finish.
1703204076Spjd		 */
1704204076Spjd		mtx_lock(&sync_lock);
1705204076Spjd		while (!ISSYNCREQDONE(hio))
1706204076Spjd			cv_wait(&sync_cond, &sync_lock);
1707204076Spjd		mtx_unlock(&sync_lock);
1708204076Spjd
1709204076Spjd		if (hio->hio_errors[ncomp] != 0) {
1710204076Spjd			pjdlog_error("Unable to write synchronization data: %s.",
1711204076Spjd			    strerror(hio->hio_errors[ncomp]));
1712204076Spjd			goto free_queue;
1713204076Spjd		}
1714211880Spjd
1715211880Spjd		synced += length;
1716204076Spjdfree_queue:
1717204076Spjd		mtx_lock(&range_lock);
1718204076Spjd		rangelock_del(range_sync, offset, length);
1719204076Spjd		if (range_regular_wait)
1720204076Spjd			cv_signal(&range_regular_cond);
1721204076Spjd		mtx_unlock(&range_lock);
1722204076Spjd		pjdlog_debug(2, "sync: (%p) Moving request to the free queue.",
1723204076Spjd		    hio);
1724204076Spjd		QUEUE_INSERT2(hio, free);
1725204076Spjd	}
1726204076Spjd	/* NOTREACHED */
1727204076Spjd	return (NULL);
1728204076Spjd}
1729204076Spjd
1730204076Spjdstatic void
1731210886Spjdconfig_reload(void)
1732210886Spjd{
1733210886Spjd	struct hastd_config *newcfg;
1734210886Spjd	struct hast_resource *res;
1735210886Spjd	unsigned int ii, ncomps;
1736210886Spjd	int modified;
1737210886Spjd
1738210886Spjd	pjdlog_info("Reloading configuration...");
1739210886Spjd
1740210886Spjd	ncomps = HAST_NCOMPONENTS;
1741210886Spjd
1742210886Spjd	newcfg = yy_config_parse(cfgpath, false);
1743210886Spjd	if (newcfg == NULL)
1744210886Spjd		goto failed;
1745210886Spjd
1746210886Spjd	TAILQ_FOREACH(res, &newcfg->hc_resources, hr_next) {
1747210886Spjd		if (strcmp(res->hr_name, gres->hr_name) == 0)
1748210886Spjd			break;
1749210886Spjd	}
1750210886Spjd	/*
1751210886Spjd	 * If resource was removed from the configuration file, resource
1752210886Spjd	 * name, provider name or path to local component was modified we
1753210886Spjd	 * shouldn't be here. This means that someone modified configuration
1754210886Spjd	 * file and send SIGHUP to us instead of main hastd process.
1755210886Spjd	 * Log advice and ignore the signal.
1756210886Spjd	 */
1757210886Spjd	if (res == NULL || strcmp(gres->hr_name, res->hr_name) != 0 ||
1758210886Spjd	    strcmp(gres->hr_provname, res->hr_provname) != 0 ||
1759210886Spjd	    strcmp(gres->hr_localpath, res->hr_localpath) != 0) {
1760210886Spjd		pjdlog_warning("To reload configuration send SIGHUP to the main hastd process (pid %u).",
1761210886Spjd		    (unsigned int)getppid());
1762210886Spjd		goto failed;
1763210886Spjd	}
1764210886Spjd
1765210886Spjd#define MODIFIED_REMOTEADDR	0x1
1766210886Spjd#define MODIFIED_REPLICATION	0x2
1767210886Spjd#define MODIFIED_TIMEOUT	0x4
1768211886Spjd#define MODIFIED_EXEC		0x8
1769210886Spjd	modified = 0;
1770210886Spjd	if (strcmp(gres->hr_remoteaddr, res->hr_remoteaddr) != 0) {
1771210886Spjd		/*
1772210886Spjd		 * Don't copy res->hr_remoteaddr to gres just yet.
1773210886Spjd		 * We want remote_close() to log disconnect from the old
1774210886Spjd		 * addresses, not from the new ones.
1775210886Spjd		 */
1776210886Spjd		modified |= MODIFIED_REMOTEADDR;
1777210886Spjd	}
1778210886Spjd	if (gres->hr_replication != res->hr_replication) {
1779210886Spjd		gres->hr_replication = res->hr_replication;
1780210886Spjd		modified |= MODIFIED_REPLICATION;
1781210886Spjd	}
1782210886Spjd	if (gres->hr_timeout != res->hr_timeout) {
1783210886Spjd		gres->hr_timeout = res->hr_timeout;
1784210886Spjd		modified |= MODIFIED_TIMEOUT;
1785210886Spjd	}
1786211886Spjd	if (strcmp(gres->hr_exec, res->hr_exec) != 0) {
1787211886Spjd		strlcpy(gres->hr_exec, res->hr_exec, sizeof(gres->hr_exec));
1788211886Spjd		modified |= MODIFIED_EXEC;
1789211886Spjd	}
1790210886Spjd	/*
1791210886Spjd	 * If only timeout was modified we only need to change it without
1792210886Spjd	 * reconnecting.
1793210886Spjd	 */
1794210886Spjd	if (modified == MODIFIED_TIMEOUT) {
1795210886Spjd		for (ii = 0; ii < ncomps; ii++) {
1796210886Spjd			if (!ISREMOTE(ii))
1797210886Spjd				continue;
1798210886Spjd			rw_rlock(&hio_remote_lock[ii]);
1799210886Spjd			if (!ISCONNECTED(gres, ii)) {
1800210886Spjd				rw_unlock(&hio_remote_lock[ii]);
1801210886Spjd				continue;
1802210886Spjd			}
1803210886Spjd			rw_unlock(&hio_remote_lock[ii]);
1804210886Spjd			if (proto_timeout(gres->hr_remotein,
1805210886Spjd			    gres->hr_timeout) < 0) {
1806210886Spjd				pjdlog_errno(LOG_WARNING,
1807210886Spjd				    "Unable to set connection timeout");
1808210886Spjd			}
1809210886Spjd			if (proto_timeout(gres->hr_remoteout,
1810210886Spjd			    gres->hr_timeout) < 0) {
1811210886Spjd				pjdlog_errno(LOG_WARNING,
1812210886Spjd				    "Unable to set connection timeout");
1813210886Spjd			}
1814210886Spjd		}
1815211886Spjd	} else if ((modified &
1816211886Spjd	    (MODIFIED_REMOTEADDR | MODIFIED_REPLICATION)) != 0) {
1817210886Spjd		for (ii = 0; ii < ncomps; ii++) {
1818210886Spjd			if (!ISREMOTE(ii))
1819210886Spjd				continue;
1820210886Spjd			remote_close(gres, ii);
1821210886Spjd		}
1822210886Spjd		if (modified & MODIFIED_REMOTEADDR) {
1823210886Spjd			strlcpy(gres->hr_remoteaddr, res->hr_remoteaddr,
1824210886Spjd			    sizeof(gres->hr_remoteaddr));
1825210886Spjd		}
1826210886Spjd	}
1827210886Spjd#undef	MODIFIED_REMOTEADDR
1828210886Spjd#undef	MODIFIED_REPLICATION
1829210886Spjd#undef	MODIFIED_TIMEOUT
1830211886Spjd#undef	MODIFIED_EXEC
1831210886Spjd
1832210886Spjd	pjdlog_info("Configuration reloaded successfully.");
1833210886Spjd	return;
1834210886Spjdfailed:
1835210886Spjd	if (newcfg != NULL) {
1836210886Spjd		if (newcfg->hc_controlconn != NULL)
1837210886Spjd			proto_close(newcfg->hc_controlconn);
1838210886Spjd		if (newcfg->hc_listenconn != NULL)
1839210886Spjd			proto_close(newcfg->hc_listenconn);
1840210886Spjd		yy_config_free(newcfg);
1841210886Spjd	}
1842210886Spjd	pjdlog_warning("Configuration not reloaded.");
1843210886Spjd}
1844210886Spjd
1845211882Spjdstatic void
1846211882Spjdkeepalive_send(struct hast_resource *res, unsigned int ncomp)
1847211882Spjd{
1848211882Spjd	struct nv *nv;
1849211882Spjd
1850211882Spjd	nv = nv_alloc();
1851211882Spjd	nv_add_uint8(nv, HIO_KEEPALIVE, "cmd");
1852211882Spjd	if (nv_error(nv) != 0) {
1853211882Spjd		nv_free(nv);
1854211882Spjd		pjdlog_debug(1,
1855211882Spjd		    "keepalive_send: Unable to prepare header to send.");
1856211882Spjd		return;
1857211882Spjd	}
1858211882Spjd	if (hast_proto_send(res, res->hr_remoteout, nv, NULL, 0) < 0) {
1859211882Spjd		pjdlog_common(LOG_DEBUG, 1, errno,
1860211882Spjd		    "keepalive_send: Unable to send request");
1861211882Spjd		nv_free(nv);
1862211882Spjd		rw_unlock(&hio_remote_lock[ncomp]);
1863211882Spjd		remote_close(res, ncomp);
1864211882Spjd		rw_rlock(&hio_remote_lock[ncomp]);
1865211882Spjd		return;
1866211882Spjd	}
1867211882Spjd	nv_free(nv);
1868211882Spjd	pjdlog_debug(2, "keepalive_send: Request sent.");
1869211882Spjd}
1870211882Spjd
1871211981Spjdstatic void
1872211981Spjdguard_one(struct hast_resource *res, unsigned int ncomp)
1873211981Spjd{
1874211981Spjd	struct proto_conn *in, *out;
1875211981Spjd
1876211981Spjd	if (!ISREMOTE(ncomp))
1877211981Spjd		return;
1878211981Spjd
1879211981Spjd	rw_rlock(&hio_remote_lock[ncomp]);
1880211981Spjd
1881211981Spjd	if (!real_remote(res)) {
1882211981Spjd		rw_unlock(&hio_remote_lock[ncomp]);
1883211981Spjd		return;
1884211981Spjd	}
1885211981Spjd
1886211981Spjd	if (ISCONNECTED(res, ncomp)) {
1887211981Spjd		assert(res->hr_remotein != NULL);
1888211981Spjd		assert(res->hr_remoteout != NULL);
1889211981Spjd		keepalive_send(res, ncomp);
1890211981Spjd	}
1891211981Spjd
1892211981Spjd	if (ISCONNECTED(res, ncomp)) {
1893211981Spjd		assert(res->hr_remotein != NULL);
1894211981Spjd		assert(res->hr_remoteout != NULL);
1895211981Spjd		rw_unlock(&hio_remote_lock[ncomp]);
1896211981Spjd		pjdlog_debug(2, "remote_guard: Connection to %s is ok.",
1897211981Spjd		    res->hr_remoteaddr);
1898211981Spjd		return;
1899211981Spjd	}
1900211981Spjd
1901211981Spjd	assert(res->hr_remotein == NULL);
1902211981Spjd	assert(res->hr_remoteout == NULL);
1903211981Spjd	/*
1904211981Spjd	 * Upgrade the lock. It doesn't have to be atomic as no other thread
1905211981Spjd	 * can change connection status from disconnected to connected.
1906211981Spjd	 */
1907211981Spjd	rw_unlock(&hio_remote_lock[ncomp]);
1908211981Spjd	pjdlog_debug(2, "remote_guard: Reconnecting to %s.",
1909211981Spjd	    res->hr_remoteaddr);
1910211981Spjd	in = out = NULL;
1911211981Spjd	if (init_remote(res, &in, &out)) {
1912211981Spjd		rw_wlock(&hio_remote_lock[ncomp]);
1913211981Spjd		assert(res->hr_remotein == NULL);
1914211981Spjd		assert(res->hr_remoteout == NULL);
1915211981Spjd		assert(in != NULL && out != NULL);
1916211981Spjd		res->hr_remotein = in;
1917211981Spjd		res->hr_remoteout = out;
1918211981Spjd		rw_unlock(&hio_remote_lock[ncomp]);
1919211981Spjd		pjdlog_info("Successfully reconnected to %s.",
1920211981Spjd		    res->hr_remoteaddr);
1921211981Spjd		sync_start();
1922211981Spjd	} else {
1923211981Spjd		/* Both connections should be NULL. */
1924211981Spjd		assert(res->hr_remotein == NULL);
1925211981Spjd		assert(res->hr_remoteout == NULL);
1926211981Spjd		assert(in == NULL && out == NULL);
1927211981Spjd		pjdlog_debug(2, "remote_guard: Reconnect to %s failed.",
1928211981Spjd		    res->hr_remoteaddr);
1929211981Spjd	}
1930211981Spjd}
1931211981Spjd
1932204076Spjd/*
1933204076Spjd * Thread guards remote connections and reconnects when needed, handles
1934204076Spjd * signals, etc.
1935204076Spjd */
1936204076Spjdstatic void *
1937204076Spjdguard_thread(void *arg)
1938204076Spjd{
1939204076Spjd	struct hast_resource *res = arg;
1940204076Spjd	unsigned int ii, ncomps;
1941211982Spjd	struct timespec timeout;
1942211981Spjd	time_t lastcheck, now;
1943211982Spjd	sigset_t mask;
1944211982Spjd	int signo;
1945204076Spjd
1946204076Spjd	ncomps = HAST_NCOMPONENTS;
1947211981Spjd	lastcheck = time(NULL);
1948204076Spjd
1949211982Spjd	PJDLOG_VERIFY(sigemptyset(&mask) == 0);
1950211982Spjd	PJDLOG_VERIFY(sigaddset(&mask, SIGHUP) == 0);
1951211982Spjd	PJDLOG_VERIFY(sigaddset(&mask, SIGINT) == 0);
1952211982Spjd	PJDLOG_VERIFY(sigaddset(&mask, SIGTERM) == 0);
1953211982Spjd	PJDLOG_VERIFY(sigaddset(&mask, SIGCHLD) == 0);
1954211982Spjd
1955211982Spjd	timeout.tv_nsec = 0;
1956211982Spjd	signo = -1;
1957211982Spjd
1958204076Spjd	for (;;) {
1959211982Spjd		switch (signo) {
1960211982Spjd		case SIGHUP:
1961211982Spjd			config_reload();
1962211982Spjd			break;
1963211982Spjd		case SIGINT:
1964211982Spjd		case SIGTERM:
1965211982Spjd			sigexit_received = true;
1966204076Spjd			primary_exitx(EX_OK,
1967204076Spjd			    "Termination signal received, exiting.");
1968211982Spjd			break;
1969211982Spjd		default:
1970211982Spjd			break;
1971204076Spjd		}
1972211982Spjd		hook_check(signo == SIGCHLD);
1973211882Spjd
1974204076Spjd		pjdlog_debug(2, "remote_guard: Checking connections.");
1975211981Spjd		now = time(NULL);
1976211982Spjd		if (lastcheck + RETRY_SLEEP <= now) {
1977211982Spjd			for (ii = 0; ii < ncomps; ii++)
1978211981Spjd				guard_one(res, ii);
1979211981Spjd			lastcheck = now;
1980204076Spjd		}
1981211982Spjd		timeout.tv_sec = RETRY_SLEEP;
1982211982Spjd		signo = sigtimedwait(&mask, NULL, &timeout);
1983204076Spjd	}
1984204076Spjd	/* NOTREACHED */
1985204076Spjd	return (NULL);
1986204076Spjd}
1987