primary.c revision 216494
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 216494 2010-12-16 19:48:03Z pjd $");
33204076Spjd
34204076Spjd#include <sys/types.h>
35204076Spjd#include <sys/time.h>
36204076Spjd#include <sys/bio.h>
37204076Spjd#include <sys/disk.h>
38204076Spjd#include <sys/refcount.h>
39204076Spjd#include <sys/stat.h>
40204076Spjd
41204076Spjd#include <geom/gate/g_gate.h>
42204076Spjd
43204076Spjd#include <assert.h>
44204076Spjd#include <err.h>
45204076Spjd#include <errno.h>
46204076Spjd#include <fcntl.h>
47204076Spjd#include <libgeom.h>
48204076Spjd#include <pthread.h>
49211982Spjd#include <signal.h>
50204076Spjd#include <stdint.h>
51204076Spjd#include <stdio.h>
52204076Spjd#include <string.h>
53204076Spjd#include <sysexits.h>
54204076Spjd#include <unistd.h>
55204076Spjd
56204076Spjd#include <activemap.h>
57204076Spjd#include <nv.h>
58204076Spjd#include <rangelock.h>
59204076Spjd
60204076Spjd#include "control.h"
61212038Spjd#include "event.h"
62204076Spjd#include "hast.h"
63204076Spjd#include "hast_proto.h"
64204076Spjd#include "hastd.h"
65211886Spjd#include "hooks.h"
66204076Spjd#include "metadata.h"
67204076Spjd#include "proto.h"
68204076Spjd#include "pjdlog.h"
69204076Spjd#include "subr.h"
70204076Spjd#include "synch.h"
71204076Spjd
72210886Spjd/* The is only one remote component for now. */
73210886Spjd#define	ISREMOTE(no)	((no) == 1)
74210886Spjd
75204076Spjdstruct hio {
76204076Spjd	/*
77204076Spjd	 * Number of components we are still waiting for.
78204076Spjd	 * When this field goes to 0, we can send the request back to the
79204076Spjd	 * kernel. Each component has to decrease this counter by one
80204076Spjd	 * even on failure.
81204076Spjd	 */
82204076Spjd	unsigned int		 hio_countdown;
83204076Spjd	/*
84204076Spjd	 * Each component has a place to store its own error.
85204076Spjd	 * Once the request is handled by all components we can decide if the
86204076Spjd	 * request overall is successful or not.
87204076Spjd	 */
88204076Spjd	int			*hio_errors;
89204076Spjd	/*
90204076Spjd	 * Structure used to comunicate with GEOM Gate class.
91204076Spjd	 */
92204076Spjd	struct g_gate_ctl_io	 hio_ggio;
93204076Spjd	TAILQ_ENTRY(hio)	*hio_next;
94204076Spjd};
95204076Spjd#define	hio_free_next	hio_next[0]
96204076Spjd#define	hio_done_next	hio_next[0]
97204076Spjd
98204076Spjd/*
99204076Spjd * Free list holds unused structures. When free list is empty, we have to wait
100204076Spjd * until some in-progress requests are freed.
101204076Spjd */
102204076Spjdstatic TAILQ_HEAD(, hio) hio_free_list;
103204076Spjdstatic pthread_mutex_t hio_free_list_lock;
104204076Spjdstatic pthread_cond_t hio_free_list_cond;
105204076Spjd/*
106204076Spjd * There is one send list for every component. One requests is placed on all
107204076Spjd * send lists - each component gets the same request, but each component is
108204076Spjd * responsible for managing his own send list.
109204076Spjd */
110204076Spjdstatic TAILQ_HEAD(, hio) *hio_send_list;
111204076Spjdstatic pthread_mutex_t *hio_send_list_lock;
112204076Spjdstatic pthread_cond_t *hio_send_list_cond;
113204076Spjd/*
114204076Spjd * There is one recv list for every component, although local components don't
115204076Spjd * use recv lists as local requests are done synchronously.
116204076Spjd */
117204076Spjdstatic TAILQ_HEAD(, hio) *hio_recv_list;
118204076Spjdstatic pthread_mutex_t *hio_recv_list_lock;
119204076Spjdstatic pthread_cond_t *hio_recv_list_cond;
120204076Spjd/*
121204076Spjd * Request is placed on done list by the slowest component (the one that
122204076Spjd * decreased hio_countdown from 1 to 0).
123204076Spjd */
124204076Spjdstatic TAILQ_HEAD(, hio) hio_done_list;
125204076Spjdstatic pthread_mutex_t hio_done_list_lock;
126204076Spjdstatic pthread_cond_t hio_done_list_cond;
127204076Spjd/*
128204076Spjd * Structure below are for interaction with sync thread.
129204076Spjd */
130204076Spjdstatic bool sync_inprogress;
131204076Spjdstatic pthread_mutex_t sync_lock;
132204076Spjdstatic pthread_cond_t sync_cond;
133204076Spjd/*
134204076Spjd * The lock below allows to synchornize access to remote connections.
135204076Spjd */
136204076Spjdstatic pthread_rwlock_t *hio_remote_lock;
137204076Spjd
138204076Spjd/*
139204076Spjd * Lock to synchronize metadata updates. Also synchronize access to
140204076Spjd * hr_primary_localcnt and hr_primary_remotecnt fields.
141204076Spjd */
142204076Spjdstatic pthread_mutex_t metadata_lock;
143204076Spjd
144204076Spjd/*
145204076Spjd * Maximum number of outstanding I/O requests.
146204076Spjd */
147204076Spjd#define	HAST_HIO_MAX	256
148204076Spjd/*
149204076Spjd * Number of components. At this point there are only two components: local
150204076Spjd * and remote, but in the future it might be possible to use multiple local
151204076Spjd * and remote components.
152204076Spjd */
153204076Spjd#define	HAST_NCOMPONENTS	2
154204076Spjd/*
155211982Spjd * Number of seconds to sleep between reconnect retries or keepalive packets.
156204076Spjd */
157211982Spjd#define	RETRY_SLEEP		10
158204076Spjd
159204076Spjd#define	ISCONNECTED(res, no)	\
160204076Spjd	((res)->hr_remotein != NULL && (res)->hr_remoteout != NULL)
161204076Spjd
162204076Spjd#define	QUEUE_INSERT1(hio, name, ncomp)	do {				\
163204076Spjd	bool _wakeup;							\
164204076Spjd									\
165204076Spjd	mtx_lock(&hio_##name##_list_lock[(ncomp)]);			\
166204076Spjd	_wakeup = TAILQ_EMPTY(&hio_##name##_list[(ncomp)]);		\
167204076Spjd	TAILQ_INSERT_TAIL(&hio_##name##_list[(ncomp)], (hio),		\
168204076Spjd	    hio_next[(ncomp)]);						\
169204076Spjd	mtx_unlock(&hio_##name##_list_lock[ncomp]);			\
170204076Spjd	if (_wakeup)							\
171204076Spjd		cv_signal(&hio_##name##_list_cond[(ncomp)]);		\
172204076Spjd} while (0)
173204076Spjd#define	QUEUE_INSERT2(hio, name)	do {				\
174204076Spjd	bool _wakeup;							\
175204076Spjd									\
176204076Spjd	mtx_lock(&hio_##name##_list_lock);				\
177204076Spjd	_wakeup = TAILQ_EMPTY(&hio_##name##_list);			\
178204076Spjd	TAILQ_INSERT_TAIL(&hio_##name##_list, (hio), hio_##name##_next);\
179204076Spjd	mtx_unlock(&hio_##name##_list_lock);				\
180204076Spjd	if (_wakeup)							\
181204076Spjd		cv_signal(&hio_##name##_list_cond);			\
182204076Spjd} while (0)
183214692Spjd#define	QUEUE_TAKE1(hio, name, ncomp, timeout)	do {			\
184214692Spjd	bool _last;							\
185214692Spjd									\
186204076Spjd	mtx_lock(&hio_##name##_list_lock[(ncomp)]);			\
187214692Spjd	_last = false;							\
188214692Spjd	while (((hio) = TAILQ_FIRST(&hio_##name##_list[(ncomp)])) == NULL && !_last) { \
189214692Spjd		cv_timedwait(&hio_##name##_list_cond[(ncomp)],		\
190214692Spjd		    &hio_##name##_list_lock[(ncomp)], (timeout));	\
191214692Spjd		if ((timeout) != 0) 					\
192214692Spjd			_last = true;					\
193204076Spjd	}								\
194214692Spjd	if (hio != NULL) {						\
195214692Spjd		TAILQ_REMOVE(&hio_##name##_list[(ncomp)], (hio),	\
196214692Spjd		    hio_next[(ncomp)]);					\
197214692Spjd	}								\
198204076Spjd	mtx_unlock(&hio_##name##_list_lock[(ncomp)]);			\
199204076Spjd} while (0)
200204076Spjd#define	QUEUE_TAKE2(hio, name)	do {					\
201204076Spjd	mtx_lock(&hio_##name##_list_lock);				\
202204076Spjd	while (((hio) = TAILQ_FIRST(&hio_##name##_list)) == NULL) {	\
203204076Spjd		cv_wait(&hio_##name##_list_cond,			\
204204076Spjd		    &hio_##name##_list_lock);				\
205204076Spjd	}								\
206204076Spjd	TAILQ_REMOVE(&hio_##name##_list, (hio), hio_##name##_next);	\
207204076Spjd	mtx_unlock(&hio_##name##_list_lock);				\
208204076Spjd} while (0)
209204076Spjd
210209183Spjd#define	SYNCREQ(hio)		do {					\
211209183Spjd	(hio)->hio_ggio.gctl_unit = -1;					\
212209183Spjd	(hio)->hio_ggio.gctl_seq = 1;					\
213209183Spjd} while (0)
214204076Spjd#define	ISSYNCREQ(hio)		((hio)->hio_ggio.gctl_unit == -1)
215204076Spjd#define	SYNCREQDONE(hio)	do { (hio)->hio_ggio.gctl_unit = -2; } while (0)
216204076Spjd#define	ISSYNCREQDONE(hio)	((hio)->hio_ggio.gctl_unit == -2)
217204076Spjd
218204076Spjdstatic struct hast_resource *gres;
219204076Spjd
220204076Spjdstatic pthread_mutex_t range_lock;
221204076Spjdstatic struct rangelocks *range_regular;
222204076Spjdstatic bool range_regular_wait;
223204076Spjdstatic pthread_cond_t range_regular_cond;
224204076Spjdstatic struct rangelocks *range_sync;
225204076Spjdstatic bool range_sync_wait;
226204076Spjdstatic pthread_cond_t range_sync_cond;
227204076Spjd
228204076Spjdstatic void *ggate_recv_thread(void *arg);
229204076Spjdstatic void *local_send_thread(void *arg);
230204076Spjdstatic void *remote_send_thread(void *arg);
231204076Spjdstatic void *remote_recv_thread(void *arg);
232204076Spjdstatic void *ggate_send_thread(void *arg);
233204076Spjdstatic void *sync_thread(void *arg);
234204076Spjdstatic void *guard_thread(void *arg);
235204076Spjd
236211982Spjdstatic void
237204076Spjdcleanup(struct hast_resource *res)
238204076Spjd{
239204076Spjd	int rerrno;
240204076Spjd
241204076Spjd	/* Remember errno. */
242204076Spjd	rerrno = errno;
243204076Spjd
244204076Spjd	/* Destroy ggate provider if we created one. */
245204076Spjd	if (res->hr_ggateunit >= 0) {
246204076Spjd		struct g_gate_ctl_destroy ggiod;
247204076Spjd
248213533Spjd		bzero(&ggiod, sizeof(ggiod));
249204076Spjd		ggiod.gctl_version = G_GATE_VERSION;
250204076Spjd		ggiod.gctl_unit = res->hr_ggateunit;
251204076Spjd		ggiod.gctl_force = 1;
252204076Spjd		if (ioctl(res->hr_ggatefd, G_GATE_CMD_DESTROY, &ggiod) < 0) {
253213531Spjd			pjdlog_errno(LOG_WARNING,
254213531Spjd			    "Unable to destroy hast/%s device",
255204076Spjd			    res->hr_provname);
256204076Spjd		}
257204076Spjd		res->hr_ggateunit = -1;
258204076Spjd	}
259204076Spjd
260204076Spjd	/* Restore errno. */
261204076Spjd	errno = rerrno;
262204076Spjd}
263204076Spjd
264212899Spjdstatic __dead2 void
265204076Spjdprimary_exit(int exitcode, const char *fmt, ...)
266204076Spjd{
267204076Spjd	va_list ap;
268204076Spjd
269204076Spjd	assert(exitcode != EX_OK);
270204076Spjd	va_start(ap, fmt);
271204076Spjd	pjdlogv_errno(LOG_ERR, fmt, ap);
272204076Spjd	va_end(ap);
273204076Spjd	cleanup(gres);
274204076Spjd	exit(exitcode);
275204076Spjd}
276204076Spjd
277212899Spjdstatic __dead2 void
278204076Spjdprimary_exitx(int exitcode, const char *fmt, ...)
279204076Spjd{
280204076Spjd	va_list ap;
281204076Spjd
282204076Spjd	va_start(ap, fmt);
283204076Spjd	pjdlogv(exitcode == EX_OK ? LOG_INFO : LOG_ERR, fmt, ap);
284204076Spjd	va_end(ap);
285204076Spjd	cleanup(gres);
286204076Spjd	exit(exitcode);
287204076Spjd}
288204076Spjd
289204076Spjdstatic int
290204076Spjdhast_activemap_flush(struct hast_resource *res)
291204076Spjd{
292204076Spjd	const unsigned char *buf;
293204076Spjd	size_t size;
294204076Spjd
295204076Spjd	buf = activemap_bitmap(res->hr_amp, &size);
296204076Spjd	assert(buf != NULL);
297204076Spjd	assert((size % res->hr_local_sectorsize) == 0);
298204076Spjd	if (pwrite(res->hr_localfd, buf, size, METADATA_SIZE) !=
299204076Spjd	    (ssize_t)size) {
300204076Spjd		KEEP_ERRNO(pjdlog_errno(LOG_ERR,
301204076Spjd		    "Unable to flush activemap to disk"));
302204076Spjd		return (-1);
303204076Spjd	}
304204076Spjd	return (0);
305204076Spjd}
306204076Spjd
307210881Spjdstatic bool
308210881Spjdreal_remote(const struct hast_resource *res)
309210881Spjd{
310210881Spjd
311210881Spjd	return (strcmp(res->hr_remoteaddr, "none") != 0);
312210881Spjd}
313210881Spjd
314204076Spjdstatic void
315204076Spjdinit_environment(struct hast_resource *res __unused)
316204076Spjd{
317204076Spjd	struct hio *hio;
318204076Spjd	unsigned int ii, ncomps;
319204076Spjd
320204076Spjd	/*
321204076Spjd	 * In the future it might be per-resource value.
322204076Spjd	 */
323204076Spjd	ncomps = HAST_NCOMPONENTS;
324204076Spjd
325204076Spjd	/*
326204076Spjd	 * Allocate memory needed by lists.
327204076Spjd	 */
328204076Spjd	hio_send_list = malloc(sizeof(hio_send_list[0]) * ncomps);
329204076Spjd	if (hio_send_list == NULL) {
330204076Spjd		primary_exitx(EX_TEMPFAIL,
331204076Spjd		    "Unable to allocate %zu bytes of memory for send lists.",
332204076Spjd		    sizeof(hio_send_list[0]) * ncomps);
333204076Spjd	}
334204076Spjd	hio_send_list_lock = malloc(sizeof(hio_send_list_lock[0]) * ncomps);
335204076Spjd	if (hio_send_list_lock == NULL) {
336204076Spjd		primary_exitx(EX_TEMPFAIL,
337204076Spjd		    "Unable to allocate %zu bytes of memory for send list locks.",
338204076Spjd		    sizeof(hio_send_list_lock[0]) * ncomps);
339204076Spjd	}
340204076Spjd	hio_send_list_cond = malloc(sizeof(hio_send_list_cond[0]) * ncomps);
341204076Spjd	if (hio_send_list_cond == NULL) {
342204076Spjd		primary_exitx(EX_TEMPFAIL,
343204076Spjd		    "Unable to allocate %zu bytes of memory for send list condition variables.",
344204076Spjd		    sizeof(hio_send_list_cond[0]) * ncomps);
345204076Spjd	}
346204076Spjd	hio_recv_list = malloc(sizeof(hio_recv_list[0]) * ncomps);
347204076Spjd	if (hio_recv_list == NULL) {
348204076Spjd		primary_exitx(EX_TEMPFAIL,
349204076Spjd		    "Unable to allocate %zu bytes of memory for recv lists.",
350204076Spjd		    sizeof(hio_recv_list[0]) * ncomps);
351204076Spjd	}
352204076Spjd	hio_recv_list_lock = malloc(sizeof(hio_recv_list_lock[0]) * ncomps);
353204076Spjd	if (hio_recv_list_lock == NULL) {
354204076Spjd		primary_exitx(EX_TEMPFAIL,
355204076Spjd		    "Unable to allocate %zu bytes of memory for recv list locks.",
356204076Spjd		    sizeof(hio_recv_list_lock[0]) * ncomps);
357204076Spjd	}
358204076Spjd	hio_recv_list_cond = malloc(sizeof(hio_recv_list_cond[0]) * ncomps);
359204076Spjd	if (hio_recv_list_cond == NULL) {
360204076Spjd		primary_exitx(EX_TEMPFAIL,
361204076Spjd		    "Unable to allocate %zu bytes of memory for recv list condition variables.",
362204076Spjd		    sizeof(hio_recv_list_cond[0]) * ncomps);
363204076Spjd	}
364204076Spjd	hio_remote_lock = malloc(sizeof(hio_remote_lock[0]) * ncomps);
365204076Spjd	if (hio_remote_lock == NULL) {
366204076Spjd		primary_exitx(EX_TEMPFAIL,
367204076Spjd		    "Unable to allocate %zu bytes of memory for remote connections locks.",
368204076Spjd		    sizeof(hio_remote_lock[0]) * ncomps);
369204076Spjd	}
370204076Spjd
371204076Spjd	/*
372204076Spjd	 * Initialize lists, their locks and theirs condition variables.
373204076Spjd	 */
374204076Spjd	TAILQ_INIT(&hio_free_list);
375204076Spjd	mtx_init(&hio_free_list_lock);
376204076Spjd	cv_init(&hio_free_list_cond);
377204076Spjd	for (ii = 0; ii < HAST_NCOMPONENTS; ii++) {
378204076Spjd		TAILQ_INIT(&hio_send_list[ii]);
379204076Spjd		mtx_init(&hio_send_list_lock[ii]);
380204076Spjd		cv_init(&hio_send_list_cond[ii]);
381204076Spjd		TAILQ_INIT(&hio_recv_list[ii]);
382204076Spjd		mtx_init(&hio_recv_list_lock[ii]);
383204076Spjd		cv_init(&hio_recv_list_cond[ii]);
384204076Spjd		rw_init(&hio_remote_lock[ii]);
385204076Spjd	}
386204076Spjd	TAILQ_INIT(&hio_done_list);
387204076Spjd	mtx_init(&hio_done_list_lock);
388204076Spjd	cv_init(&hio_done_list_cond);
389204076Spjd	mtx_init(&metadata_lock);
390204076Spjd
391204076Spjd	/*
392204076Spjd	 * Allocate requests pool and initialize requests.
393204076Spjd	 */
394204076Spjd	for (ii = 0; ii < HAST_HIO_MAX; ii++) {
395204076Spjd		hio = malloc(sizeof(*hio));
396204076Spjd		if (hio == NULL) {
397204076Spjd			primary_exitx(EX_TEMPFAIL,
398204076Spjd			    "Unable to allocate %zu bytes of memory for hio request.",
399204076Spjd			    sizeof(*hio));
400204076Spjd		}
401204076Spjd		hio->hio_countdown = 0;
402204076Spjd		hio->hio_errors = malloc(sizeof(hio->hio_errors[0]) * ncomps);
403204076Spjd		if (hio->hio_errors == NULL) {
404204076Spjd			primary_exitx(EX_TEMPFAIL,
405204076Spjd			    "Unable allocate %zu bytes of memory for hio errors.",
406204076Spjd			    sizeof(hio->hio_errors[0]) * ncomps);
407204076Spjd		}
408204076Spjd		hio->hio_next = malloc(sizeof(hio->hio_next[0]) * ncomps);
409204076Spjd		if (hio->hio_next == NULL) {
410204076Spjd			primary_exitx(EX_TEMPFAIL,
411204076Spjd			    "Unable allocate %zu bytes of memory for hio_next field.",
412204076Spjd			    sizeof(hio->hio_next[0]) * ncomps);
413204076Spjd		}
414204076Spjd		hio->hio_ggio.gctl_version = G_GATE_VERSION;
415204076Spjd		hio->hio_ggio.gctl_data = malloc(MAXPHYS);
416204076Spjd		if (hio->hio_ggio.gctl_data == NULL) {
417204076Spjd			primary_exitx(EX_TEMPFAIL,
418204076Spjd			    "Unable to allocate %zu bytes of memory for gctl_data.",
419204076Spjd			    MAXPHYS);
420204076Spjd		}
421204076Spjd		hio->hio_ggio.gctl_length = MAXPHYS;
422204076Spjd		hio->hio_ggio.gctl_error = 0;
423204076Spjd		TAILQ_INSERT_HEAD(&hio_free_list, hio, hio_free_next);
424204076Spjd	}
425204076Spjd}
426204076Spjd
427214284Spjdstatic bool
428214284Spjdinit_resuid(struct hast_resource *res)
429214284Spjd{
430214284Spjd
431214284Spjd	mtx_lock(&metadata_lock);
432214284Spjd	if (res->hr_resuid != 0) {
433214284Spjd		mtx_unlock(&metadata_lock);
434214284Spjd		return (false);
435214284Spjd	} else {
436214284Spjd		/* Initialize unique resource identifier. */
437214284Spjd		arc4random_buf(&res->hr_resuid, sizeof(res->hr_resuid));
438214284Spjd		mtx_unlock(&metadata_lock);
439214284Spjd		if (metadata_write(res) < 0)
440214284Spjd			exit(EX_NOINPUT);
441214284Spjd		return (true);
442214284Spjd	}
443214284Spjd}
444214284Spjd
445204076Spjdstatic void
446204076Spjdinit_local(struct hast_resource *res)
447204076Spjd{
448204076Spjd	unsigned char *buf;
449204076Spjd	size_t mapsize;
450204076Spjd
451204076Spjd	if (metadata_read(res, true) < 0)
452204076Spjd		exit(EX_NOINPUT);
453204076Spjd	mtx_init(&res->hr_amp_lock);
454204076Spjd	if (activemap_init(&res->hr_amp, res->hr_datasize, res->hr_extentsize,
455204076Spjd	    res->hr_local_sectorsize, res->hr_keepdirty) < 0) {
456204076Spjd		primary_exit(EX_TEMPFAIL, "Unable to create activemap");
457204076Spjd	}
458204076Spjd	mtx_init(&range_lock);
459204076Spjd	cv_init(&range_regular_cond);
460204076Spjd	if (rangelock_init(&range_regular) < 0)
461204076Spjd		primary_exit(EX_TEMPFAIL, "Unable to create regular range lock");
462204076Spjd	cv_init(&range_sync_cond);
463204076Spjd	if (rangelock_init(&range_sync) < 0)
464204076Spjd		primary_exit(EX_TEMPFAIL, "Unable to create sync range lock");
465204076Spjd	mapsize = activemap_ondisk_size(res->hr_amp);
466204076Spjd	buf = calloc(1, mapsize);
467204076Spjd	if (buf == NULL) {
468204076Spjd		primary_exitx(EX_TEMPFAIL,
469204076Spjd		    "Unable to allocate buffer for activemap.");
470204076Spjd	}
471204076Spjd	if (pread(res->hr_localfd, buf, mapsize, METADATA_SIZE) !=
472204076Spjd	    (ssize_t)mapsize) {
473204076Spjd		primary_exit(EX_NOINPUT, "Unable to read activemap");
474204076Spjd	}
475204076Spjd	activemap_copyin(res->hr_amp, buf, mapsize);
476209181Spjd	free(buf);
477204076Spjd	if (res->hr_resuid != 0)
478204076Spjd		return;
479204076Spjd	/*
480214284Spjd	 * We're using provider for the first time. Initialize local and remote
481214284Spjd	 * counters. We don't initialize resuid here, as we want to do it just
482214284Spjd	 * in time. The reason for this is that we want to inform secondary
483214284Spjd	 * that there were no writes yet, so there is no need to synchronize
484214284Spjd	 * anything.
485204076Spjd	 */
486204076Spjd	res->hr_primary_localcnt = 1;
487204076Spjd	res->hr_primary_remotecnt = 0;
488204076Spjd	if (metadata_write(res) < 0)
489204076Spjd		exit(EX_NOINPUT);
490204076Spjd}
491204076Spjd
492205738Spjdstatic bool
493205738Spjdinit_remote(struct hast_resource *res, struct proto_conn **inp,
494205738Spjd    struct proto_conn **outp)
495204076Spjd{
496205738Spjd	struct proto_conn *in, *out;
497204076Spjd	struct nv *nvout, *nvin;
498204076Spjd	const unsigned char *token;
499204076Spjd	unsigned char *map;
500204076Spjd	const char *errmsg;
501204076Spjd	int32_t extentsize;
502204076Spjd	int64_t datasize;
503204076Spjd	uint32_t mapsize;
504204076Spjd	size_t size;
505204076Spjd
506205738Spjd	assert((inp == NULL && outp == NULL) || (inp != NULL && outp != NULL));
507210881Spjd	assert(real_remote(res));
508205738Spjd
509205738Spjd	in = out = NULL;
510211983Spjd	errmsg = NULL;
511205738Spjd
512204076Spjd	/* Prepare outgoing connection with remote node. */
513205738Spjd	if (proto_client(res->hr_remoteaddr, &out) < 0) {
514215331Spjd		primary_exit(EX_TEMPFAIL,
515215331Spjd		    "Unable to create outgoing connection to %s",
516204076Spjd		    res->hr_remoteaddr);
517204076Spjd	}
518204076Spjd	/* Try to connect, but accept failure. */
519205738Spjd	if (proto_connect(out) < 0) {
520204076Spjd		pjdlog_errno(LOG_WARNING, "Unable to connect to %s",
521204076Spjd		    res->hr_remoteaddr);
522204076Spjd		goto close;
523204076Spjd	}
524207371Spjd	/* Error in setting timeout is not critical, but why should it fail? */
525207371Spjd	if (proto_timeout(out, res->hr_timeout) < 0)
526207371Spjd		pjdlog_errno(LOG_WARNING, "Unable to set connection timeout");
527204076Spjd	/*
528204076Spjd	 * First handshake step.
529204076Spjd	 * Setup outgoing connection with remote node.
530204076Spjd	 */
531204076Spjd	nvout = nv_alloc();
532204076Spjd	nv_add_string(nvout, res->hr_name, "resource");
533204076Spjd	if (nv_error(nvout) != 0) {
534204076Spjd		pjdlog_common(LOG_WARNING, 0, nv_error(nvout),
535204076Spjd		    "Unable to allocate header for connection with %s",
536204076Spjd		    res->hr_remoteaddr);
537204076Spjd		nv_free(nvout);
538204076Spjd		goto close;
539204076Spjd	}
540205738Spjd	if (hast_proto_send(res, out, nvout, NULL, 0) < 0) {
541204076Spjd		pjdlog_errno(LOG_WARNING,
542204076Spjd		    "Unable to send handshake header to %s",
543204076Spjd		    res->hr_remoteaddr);
544204076Spjd		nv_free(nvout);
545204076Spjd		goto close;
546204076Spjd	}
547204076Spjd	nv_free(nvout);
548205738Spjd	if (hast_proto_recv_hdr(out, &nvin) < 0) {
549204076Spjd		pjdlog_errno(LOG_WARNING,
550204076Spjd		    "Unable to receive handshake header from %s",
551204076Spjd		    res->hr_remoteaddr);
552204076Spjd		goto close;
553204076Spjd	}
554204076Spjd	errmsg = nv_get_string(nvin, "errmsg");
555204076Spjd	if (errmsg != NULL) {
556204076Spjd		pjdlog_warning("%s", errmsg);
557204076Spjd		nv_free(nvin);
558204076Spjd		goto close;
559204076Spjd	}
560204076Spjd	token = nv_get_uint8_array(nvin, &size, "token");
561204076Spjd	if (token == NULL) {
562204076Spjd		pjdlog_warning("Handshake header from %s has no 'token' field.",
563204076Spjd		    res->hr_remoteaddr);
564204076Spjd		nv_free(nvin);
565204076Spjd		goto close;
566204076Spjd	}
567204076Spjd	if (size != sizeof(res->hr_token)) {
568204076Spjd		pjdlog_warning("Handshake header from %s contains 'token' of wrong size (got %zu, expected %zu).",
569204076Spjd		    res->hr_remoteaddr, size, sizeof(res->hr_token));
570204076Spjd		nv_free(nvin);
571204076Spjd		goto close;
572204076Spjd	}
573204076Spjd	bcopy(token, res->hr_token, sizeof(res->hr_token));
574204076Spjd	nv_free(nvin);
575204076Spjd
576204076Spjd	/*
577204076Spjd	 * Second handshake step.
578204076Spjd	 * Setup incoming connection with remote node.
579204076Spjd	 */
580205738Spjd	if (proto_client(res->hr_remoteaddr, &in) < 0) {
581215331Spjd		primary_exit(EX_TEMPFAIL,
582215331Spjd		    "Unable to create incoming connection to %s",
583204076Spjd		    res->hr_remoteaddr);
584204076Spjd	}
585204076Spjd	/* Try to connect, but accept failure. */
586205738Spjd	if (proto_connect(in) < 0) {
587204076Spjd		pjdlog_errno(LOG_WARNING, "Unable to connect to %s",
588204076Spjd		    res->hr_remoteaddr);
589204076Spjd		goto close;
590204076Spjd	}
591207371Spjd	/* Error in setting timeout is not critical, but why should it fail? */
592207371Spjd	if (proto_timeout(in, res->hr_timeout) < 0)
593207371Spjd		pjdlog_errno(LOG_WARNING, "Unable to set connection timeout");
594204076Spjd	nvout = nv_alloc();
595204076Spjd	nv_add_string(nvout, res->hr_name, "resource");
596204076Spjd	nv_add_uint8_array(nvout, res->hr_token, sizeof(res->hr_token),
597204076Spjd	    "token");
598214284Spjd	if (res->hr_resuid == 0) {
599214284Spjd		/*
600214284Spjd		 * The resuid field was not yet initialized.
601214284Spjd		 * Because we do synchronization inside init_resuid(), it is
602214284Spjd		 * possible that someone already initialized it, the function
603214284Spjd		 * will return false then, but if we successfully initialized
604214284Spjd		 * it, we will get true. True means that there were no writes
605214284Spjd		 * to this resource yet and we want to inform secondary that
606214284Spjd		 * synchronization is not needed by sending "virgin" argument.
607214284Spjd		 */
608214284Spjd		if (init_resuid(res))
609214284Spjd			nv_add_int8(nvout, 1, "virgin");
610214284Spjd	}
611204076Spjd	nv_add_uint64(nvout, res->hr_resuid, "resuid");
612204076Spjd	nv_add_uint64(nvout, res->hr_primary_localcnt, "localcnt");
613204076Spjd	nv_add_uint64(nvout, res->hr_primary_remotecnt, "remotecnt");
614204076Spjd	if (nv_error(nvout) != 0) {
615204076Spjd		pjdlog_common(LOG_WARNING, 0, nv_error(nvout),
616204076Spjd		    "Unable to allocate header for connection with %s",
617204076Spjd		    res->hr_remoteaddr);
618204076Spjd		nv_free(nvout);
619204076Spjd		goto close;
620204076Spjd	}
621205738Spjd	if (hast_proto_send(res, in, nvout, NULL, 0) < 0) {
622204076Spjd		pjdlog_errno(LOG_WARNING,
623204076Spjd		    "Unable to send handshake header to %s",
624204076Spjd		    res->hr_remoteaddr);
625204076Spjd		nv_free(nvout);
626204076Spjd		goto close;
627204076Spjd	}
628204076Spjd	nv_free(nvout);
629205738Spjd	if (hast_proto_recv_hdr(out, &nvin) < 0) {
630204076Spjd		pjdlog_errno(LOG_WARNING,
631204076Spjd		    "Unable to receive handshake header from %s",
632204076Spjd		    res->hr_remoteaddr);
633204076Spjd		goto close;
634204076Spjd	}
635204076Spjd	errmsg = nv_get_string(nvin, "errmsg");
636204076Spjd	if (errmsg != NULL) {
637204076Spjd		pjdlog_warning("%s", errmsg);
638204076Spjd		nv_free(nvin);
639204076Spjd		goto close;
640204076Spjd	}
641204076Spjd	datasize = nv_get_int64(nvin, "datasize");
642204076Spjd	if (datasize != res->hr_datasize) {
643204076Spjd		pjdlog_warning("Data size differs between nodes (local=%jd, remote=%jd).",
644204076Spjd		    (intmax_t)res->hr_datasize, (intmax_t)datasize);
645204076Spjd		nv_free(nvin);
646204076Spjd		goto close;
647204076Spjd	}
648204076Spjd	extentsize = nv_get_int32(nvin, "extentsize");
649204076Spjd	if (extentsize != res->hr_extentsize) {
650204076Spjd		pjdlog_warning("Extent size differs between nodes (local=%zd, remote=%zd).",
651204076Spjd		    (ssize_t)res->hr_extentsize, (ssize_t)extentsize);
652204076Spjd		nv_free(nvin);
653204076Spjd		goto close;
654204076Spjd	}
655204076Spjd	res->hr_secondary_localcnt = nv_get_uint64(nvin, "localcnt");
656204076Spjd	res->hr_secondary_remotecnt = nv_get_uint64(nvin, "remotecnt");
657204076Spjd	res->hr_syncsrc = nv_get_uint8(nvin, "syncsrc");
658204076Spjd	map = NULL;
659204076Spjd	mapsize = nv_get_uint32(nvin, "mapsize");
660204076Spjd	if (mapsize > 0) {
661204076Spjd		map = malloc(mapsize);
662204076Spjd		if (map == NULL) {
663204076Spjd			pjdlog_error("Unable to allocate memory for remote activemap (mapsize=%ju).",
664204076Spjd			    (uintmax_t)mapsize);
665204076Spjd			nv_free(nvin);
666204076Spjd			goto close;
667204076Spjd		}
668204076Spjd		/*
669204076Spjd		 * Remote node have some dirty extents on its own, lets
670204076Spjd		 * download its activemap.
671204076Spjd		 */
672205738Spjd		if (hast_proto_recv_data(res, out, nvin, map,
673204076Spjd		    mapsize) < 0) {
674204076Spjd			pjdlog_errno(LOG_ERR,
675204076Spjd			    "Unable to receive remote activemap");
676204076Spjd			nv_free(nvin);
677204076Spjd			free(map);
678204076Spjd			goto close;
679204076Spjd		}
680204076Spjd		/*
681204076Spjd		 * Merge local and remote bitmaps.
682204076Spjd		 */
683204076Spjd		activemap_merge(res->hr_amp, map, mapsize);
684204076Spjd		free(map);
685204076Spjd		/*
686204076Spjd		 * Now that we merged bitmaps from both nodes, flush it to the
687204076Spjd		 * disk before we start to synchronize.
688204076Spjd		 */
689204076Spjd		(void)hast_activemap_flush(res);
690204076Spjd	}
691214274Spjd	nv_free(nvin);
692204076Spjd	pjdlog_info("Connected to %s.", res->hr_remoteaddr);
693205738Spjd	if (inp != NULL && outp != NULL) {
694205738Spjd		*inp = in;
695205738Spjd		*outp = out;
696205738Spjd	} else {
697205738Spjd		res->hr_remotein = in;
698205738Spjd		res->hr_remoteout = out;
699205738Spjd	}
700212038Spjd	event_send(res, EVENT_CONNECT);
701205738Spjd	return (true);
702205738Spjdclose:
703211983Spjd	if (errmsg != NULL && strcmp(errmsg, "Split-brain condition!") == 0)
704212038Spjd		event_send(res, EVENT_SPLITBRAIN);
705205738Spjd	proto_close(out);
706205738Spjd	if (in != NULL)
707205738Spjd		proto_close(in);
708205738Spjd	return (false);
709205738Spjd}
710205738Spjd
711205738Spjdstatic void
712205738Spjdsync_start(void)
713205738Spjd{
714205738Spjd
715204076Spjd	mtx_lock(&sync_lock);
716204076Spjd	sync_inprogress = true;
717204076Spjd	mtx_unlock(&sync_lock);
718204076Spjd	cv_signal(&sync_cond);
719204076Spjd}
720204076Spjd
721204076Spjdstatic void
722211878Spjdsync_stop(void)
723211878Spjd{
724211878Spjd
725211878Spjd	mtx_lock(&sync_lock);
726211878Spjd	if (sync_inprogress)
727211878Spjd		sync_inprogress = false;
728211878Spjd	mtx_unlock(&sync_lock);
729211878Spjd}
730211878Spjd
731211878Spjdstatic void
732204076Spjdinit_ggate(struct hast_resource *res)
733204076Spjd{
734204076Spjd	struct g_gate_ctl_create ggiocreate;
735204076Spjd	struct g_gate_ctl_cancel ggiocancel;
736204076Spjd
737204076Spjd	/*
738204076Spjd	 * We communicate with ggate via /dev/ggctl. Open it.
739204076Spjd	 */
740204076Spjd	res->hr_ggatefd = open("/dev/" G_GATE_CTL_NAME, O_RDWR);
741204076Spjd	if (res->hr_ggatefd < 0)
742204076Spjd		primary_exit(EX_OSFILE, "Unable to open /dev/" G_GATE_CTL_NAME);
743204076Spjd	/*
744204076Spjd	 * Create provider before trying to connect, as connection failure
745204076Spjd	 * is not critical, but may take some time.
746204076Spjd	 */
747213533Spjd	bzero(&ggiocreate, sizeof(ggiocreate));
748204076Spjd	ggiocreate.gctl_version = G_GATE_VERSION;
749204076Spjd	ggiocreate.gctl_mediasize = res->hr_datasize;
750204076Spjd	ggiocreate.gctl_sectorsize = res->hr_local_sectorsize;
751204076Spjd	ggiocreate.gctl_flags = 0;
752206669Spjd	ggiocreate.gctl_maxcount = G_GATE_MAX_QUEUE_SIZE;
753204076Spjd	ggiocreate.gctl_timeout = 0;
754204076Spjd	ggiocreate.gctl_unit = G_GATE_NAME_GIVEN;
755204076Spjd	snprintf(ggiocreate.gctl_name, sizeof(ggiocreate.gctl_name), "hast/%s",
756204076Spjd	    res->hr_provname);
757204076Spjd	if (ioctl(res->hr_ggatefd, G_GATE_CMD_CREATE, &ggiocreate) == 0) {
758204076Spjd		pjdlog_info("Device hast/%s created.", res->hr_provname);
759204076Spjd		res->hr_ggateunit = ggiocreate.gctl_unit;
760204076Spjd		return;
761204076Spjd	}
762204076Spjd	if (errno != EEXIST) {
763204076Spjd		primary_exit(EX_OSERR, "Unable to create hast/%s device",
764204076Spjd		    res->hr_provname);
765204076Spjd	}
766204076Spjd	pjdlog_debug(1,
767204076Spjd	    "Device hast/%s already exists, we will try to take it over.",
768204076Spjd	    res->hr_provname);
769204076Spjd	/*
770204076Spjd	 * If we received EEXIST, we assume that the process who created the
771204076Spjd	 * provider died and didn't clean up. In that case we will start from
772204076Spjd	 * where he left of.
773204076Spjd	 */
774213533Spjd	bzero(&ggiocancel, sizeof(ggiocancel));
775204076Spjd	ggiocancel.gctl_version = G_GATE_VERSION;
776204076Spjd	ggiocancel.gctl_unit = G_GATE_NAME_GIVEN;
777204076Spjd	snprintf(ggiocancel.gctl_name, sizeof(ggiocancel.gctl_name), "hast/%s",
778204076Spjd	    res->hr_provname);
779204076Spjd	if (ioctl(res->hr_ggatefd, G_GATE_CMD_CANCEL, &ggiocancel) == 0) {
780204076Spjd		pjdlog_info("Device hast/%s recovered.", res->hr_provname);
781204076Spjd		res->hr_ggateunit = ggiocancel.gctl_unit;
782204076Spjd		return;
783204076Spjd	}
784204076Spjd	primary_exit(EX_OSERR, "Unable to take over hast/%s device",
785204076Spjd	    res->hr_provname);
786204076Spjd}
787204076Spjd
788204076Spjdvoid
789204076Spjdhastd_primary(struct hast_resource *res)
790204076Spjd{
791204076Spjd	pthread_t td;
792204076Spjd	pid_t pid;
793204076Spjd	int error;
794204076Spjd
795204076Spjd	/*
796204076Spjd	 * Create communication channel between parent and child.
797204076Spjd	 */
798204076Spjd	if (proto_client("socketpair://", &res->hr_ctrl) < 0) {
799204076Spjd		KEEP_ERRNO((void)pidfile_remove(pfh));
800212034Spjd		pjdlog_exit(EX_OSERR,
801204076Spjd		    "Unable to create control sockets between parent and child");
802204076Spjd	}
803212038Spjd	/*
804212038Spjd	 * Create communication channel between child and parent.
805212038Spjd	 */
806212038Spjd	if (proto_client("socketpair://", &res->hr_event) < 0) {
807212038Spjd		KEEP_ERRNO((void)pidfile_remove(pfh));
808212038Spjd		pjdlog_exit(EX_OSERR,
809212038Spjd		    "Unable to create event sockets between child and parent");
810212038Spjd	}
811204076Spjd
812204076Spjd	pid = fork();
813204076Spjd	if (pid < 0) {
814204076Spjd		KEEP_ERRNO((void)pidfile_remove(pfh));
815212034Spjd		pjdlog_exit(EX_TEMPFAIL, "Unable to fork");
816204076Spjd	}
817204076Spjd
818204076Spjd	if (pid > 0) {
819204076Spjd		/* This is parent. */
820212038Spjd		/* Declare that we are receiver. */
821212038Spjd		proto_recv(res->hr_event, NULL, 0);
822204076Spjd		res->hr_workerpid = pid;
823204076Spjd		return;
824204076Spjd	}
825211977Spjd
826211984Spjd	gres = res;
827211984Spjd
828204076Spjd	(void)pidfile_close(pfh);
829211977Spjd	hook_fini();
830204076Spjd
831204076Spjd	setproctitle("%s (primary)", res->hr_name);
832204076Spjd
833212038Spjd	/* Declare that we are sender. */
834212038Spjd	proto_send(res->hr_event, NULL, 0);
835212038Spjd
836204076Spjd	init_local(res);
837213007Spjd	init_ggate(res);
838213007Spjd	init_environment(res);
839213007Spjd	/*
840213530Spjd	 * Create the guard thread first, so we can handle signals from the
841213530Spjd	 * very begining.
842213530Spjd	 */
843213530Spjd	error = pthread_create(&td, NULL, guard_thread, res);
844213530Spjd	assert(error == 0);
845213530Spjd	/*
846213007Spjd	 * Create the control thread before sending any event to the parent,
847213007Spjd	 * as we can deadlock when parent sends control request to worker,
848213007Spjd	 * but worker has no control thread started yet, so parent waits.
849213007Spjd	 * In the meantime worker sends an event to the parent, but parent
850213007Spjd	 * is unable to handle the event, because it waits for control
851213007Spjd	 * request response.
852213007Spjd	 */
853213007Spjd	error = pthread_create(&td, NULL, ctrl_thread, res);
854213007Spjd	assert(error == 0);
855210881Spjd	if (real_remote(res) && init_remote(res, NULL, NULL))
856205738Spjd		sync_start();
857204076Spjd	error = pthread_create(&td, NULL, ggate_recv_thread, res);
858204076Spjd	assert(error == 0);
859204076Spjd	error = pthread_create(&td, NULL, local_send_thread, res);
860204076Spjd	assert(error == 0);
861204076Spjd	error = pthread_create(&td, NULL, remote_send_thread, res);
862204076Spjd	assert(error == 0);
863204076Spjd	error = pthread_create(&td, NULL, remote_recv_thread, res);
864204076Spjd	assert(error == 0);
865204076Spjd	error = pthread_create(&td, NULL, ggate_send_thread, res);
866204076Spjd	assert(error == 0);
867213530Spjd	(void)sync_thread(res);
868204076Spjd}
869204076Spjd
870204076Spjdstatic void
871204076Spjdreqlog(int loglevel, int debuglevel, struct g_gate_ctl_io *ggio, const char *fmt, ...)
872204076Spjd{
873204076Spjd	char msg[1024];
874204076Spjd	va_list ap;
875204076Spjd	int len;
876204076Spjd
877204076Spjd	va_start(ap, fmt);
878204076Spjd	len = vsnprintf(msg, sizeof(msg), fmt, ap);
879204076Spjd	va_end(ap);
880204076Spjd	if ((size_t)len < sizeof(msg)) {
881204076Spjd		switch (ggio->gctl_cmd) {
882204076Spjd		case BIO_READ:
883204076Spjd			(void)snprintf(msg + len, sizeof(msg) - len,
884204076Spjd			    "READ(%ju, %ju).", (uintmax_t)ggio->gctl_offset,
885204076Spjd			    (uintmax_t)ggio->gctl_length);
886204076Spjd			break;
887204076Spjd		case BIO_DELETE:
888204076Spjd			(void)snprintf(msg + len, sizeof(msg) - len,
889204076Spjd			    "DELETE(%ju, %ju).", (uintmax_t)ggio->gctl_offset,
890204076Spjd			    (uintmax_t)ggio->gctl_length);
891204076Spjd			break;
892204076Spjd		case BIO_FLUSH:
893204076Spjd			(void)snprintf(msg + len, sizeof(msg) - len, "FLUSH.");
894204076Spjd			break;
895204076Spjd		case BIO_WRITE:
896204076Spjd			(void)snprintf(msg + len, sizeof(msg) - len,
897204076Spjd			    "WRITE(%ju, %ju).", (uintmax_t)ggio->gctl_offset,
898204076Spjd			    (uintmax_t)ggio->gctl_length);
899204076Spjd			break;
900204076Spjd		default:
901204076Spjd			(void)snprintf(msg + len, sizeof(msg) - len,
902204076Spjd			    "UNKNOWN(%u).", (unsigned int)ggio->gctl_cmd);
903204076Spjd			break;
904204076Spjd		}
905204076Spjd	}
906204076Spjd	pjdlog_common(loglevel, debuglevel, -1, "%s", msg);
907204076Spjd}
908204076Spjd
909204076Spjdstatic void
910204076Spjdremote_close(struct hast_resource *res, int ncomp)
911204076Spjd{
912204076Spjd
913204076Spjd	rw_wlock(&hio_remote_lock[ncomp]);
914204076Spjd	/*
915204076Spjd	 * A race is possible between dropping rlock and acquiring wlock -
916204076Spjd	 * another thread can close connection in-between.
917204076Spjd	 */
918204076Spjd	if (!ISCONNECTED(res, ncomp)) {
919204076Spjd		assert(res->hr_remotein == NULL);
920204076Spjd		assert(res->hr_remoteout == NULL);
921204076Spjd		rw_unlock(&hio_remote_lock[ncomp]);
922204076Spjd		return;
923204076Spjd	}
924204076Spjd
925204076Spjd	assert(res->hr_remotein != NULL);
926204076Spjd	assert(res->hr_remoteout != NULL);
927204076Spjd
928211881Spjd	pjdlog_debug(2, "Closing incoming connection to %s.",
929204076Spjd	    res->hr_remoteaddr);
930204076Spjd	proto_close(res->hr_remotein);
931204076Spjd	res->hr_remotein = NULL;
932211881Spjd	pjdlog_debug(2, "Closing outgoing connection to %s.",
933204076Spjd	    res->hr_remoteaddr);
934204076Spjd	proto_close(res->hr_remoteout);
935204076Spjd	res->hr_remoteout = NULL;
936204076Spjd
937204076Spjd	rw_unlock(&hio_remote_lock[ncomp]);
938204076Spjd
939211881Spjd	pjdlog_warning("Disconnected from %s.", res->hr_remoteaddr);
940211881Spjd
941204076Spjd	/*
942204076Spjd	 * Stop synchronization if in-progress.
943204076Spjd	 */
944211878Spjd	sync_stop();
945211984Spjd
946212038Spjd	event_send(res, EVENT_DISCONNECT);
947204076Spjd}
948204076Spjd
949204076Spjd/*
950204076Spjd * Thread receives ggate I/O requests from the kernel and passes them to
951204076Spjd * appropriate threads:
952204076Spjd * WRITE - always goes to both local_send and remote_send threads
953204076Spjd * READ (when the block is up-to-date on local component) -
954204076Spjd *	only local_send thread
955204076Spjd * READ (when the block isn't up-to-date on local component) -
956204076Spjd *	only remote_send thread
957204076Spjd * DELETE - always goes to both local_send and remote_send threads
958204076Spjd * FLUSH - always goes to both local_send and remote_send threads
959204076Spjd */
960204076Spjdstatic void *
961204076Spjdggate_recv_thread(void *arg)
962204076Spjd{
963204076Spjd	struct hast_resource *res = arg;
964204076Spjd	struct g_gate_ctl_io *ggio;
965204076Spjd	struct hio *hio;
966204076Spjd	unsigned int ii, ncomp, ncomps;
967204076Spjd	int error;
968204076Spjd
969204076Spjd	ncomps = HAST_NCOMPONENTS;
970204076Spjd
971204076Spjd	for (;;) {
972204076Spjd		pjdlog_debug(2, "ggate_recv: Taking free request.");
973204076Spjd		QUEUE_TAKE2(hio, free);
974204076Spjd		pjdlog_debug(2, "ggate_recv: (%p) Got free request.", hio);
975204076Spjd		ggio = &hio->hio_ggio;
976204076Spjd		ggio->gctl_unit = res->hr_ggateunit;
977204076Spjd		ggio->gctl_length = MAXPHYS;
978204076Spjd		ggio->gctl_error = 0;
979204076Spjd		pjdlog_debug(2,
980204076Spjd		    "ggate_recv: (%p) Waiting for request from the kernel.",
981204076Spjd		    hio);
982204076Spjd		if (ioctl(res->hr_ggatefd, G_GATE_CMD_START, ggio) < 0) {
983204076Spjd			if (sigexit_received)
984204076Spjd				pthread_exit(NULL);
985204076Spjd			primary_exit(EX_OSERR, "G_GATE_CMD_START failed");
986204076Spjd		}
987204076Spjd		error = ggio->gctl_error;
988204076Spjd		switch (error) {
989204076Spjd		case 0:
990204076Spjd			break;
991204076Spjd		case ECANCELED:
992204076Spjd			/* Exit gracefully. */
993204076Spjd			if (!sigexit_received) {
994204076Spjd				pjdlog_debug(2,
995204076Spjd				    "ggate_recv: (%p) Received cancel from the kernel.",
996204076Spjd				    hio);
997204076Spjd				pjdlog_info("Received cancel from the kernel, exiting.");
998204076Spjd			}
999204076Spjd			pthread_exit(NULL);
1000204076Spjd		case ENOMEM:
1001204076Spjd			/*
1002204076Spjd			 * Buffer too small? Impossible, we allocate MAXPHYS
1003204076Spjd			 * bytes - request can't be bigger than that.
1004204076Spjd			 */
1005204076Spjd			/* FALLTHROUGH */
1006204076Spjd		case ENXIO:
1007204076Spjd		default:
1008204076Spjd			primary_exitx(EX_OSERR, "G_GATE_CMD_START failed: %s.",
1009204076Spjd			    strerror(error));
1010204076Spjd		}
1011204076Spjd		for (ii = 0; ii < ncomps; ii++)
1012204076Spjd			hio->hio_errors[ii] = EINVAL;
1013204076Spjd		reqlog(LOG_DEBUG, 2, ggio,
1014204076Spjd		    "ggate_recv: (%p) Request received from the kernel: ",
1015204076Spjd		    hio);
1016204076Spjd		/*
1017204076Spjd		 * Inform all components about new write request.
1018204076Spjd		 * For read request prefer local component unless the given
1019204076Spjd		 * range is out-of-date, then use remote component.
1020204076Spjd		 */
1021204076Spjd		switch (ggio->gctl_cmd) {
1022204076Spjd		case BIO_READ:
1023204076Spjd			pjdlog_debug(2,
1024204076Spjd			    "ggate_recv: (%p) Moving request to the send queue.",
1025204076Spjd			    hio);
1026204076Spjd			refcount_init(&hio->hio_countdown, 1);
1027204076Spjd			mtx_lock(&metadata_lock);
1028204076Spjd			if (res->hr_syncsrc == HAST_SYNCSRC_UNDEF ||
1029204076Spjd			    res->hr_syncsrc == HAST_SYNCSRC_PRIMARY) {
1030204076Spjd				/*
1031204076Spjd				 * This range is up-to-date on local component,
1032204076Spjd				 * so handle request locally.
1033204076Spjd				 */
1034204076Spjd				 /* Local component is 0 for now. */
1035204076Spjd				ncomp = 0;
1036204076Spjd			} else /* if (res->hr_syncsrc ==
1037204076Spjd			    HAST_SYNCSRC_SECONDARY) */ {
1038204076Spjd				assert(res->hr_syncsrc ==
1039204076Spjd				    HAST_SYNCSRC_SECONDARY);
1040204076Spjd				/*
1041204076Spjd				 * This range is out-of-date on local component,
1042204076Spjd				 * so send request to the remote node.
1043204076Spjd				 */
1044204076Spjd				 /* Remote component is 1 for now. */
1045204076Spjd				ncomp = 1;
1046204076Spjd			}
1047204076Spjd			mtx_unlock(&metadata_lock);
1048204076Spjd			QUEUE_INSERT1(hio, send, ncomp);
1049204076Spjd			break;
1050204076Spjd		case BIO_WRITE:
1051214284Spjd			if (res->hr_resuid == 0) {
1052214284Spjd				/* This is first write, initialize resuid. */
1053214284Spjd				(void)init_resuid(res);
1054214284Spjd			}
1055204076Spjd			for (;;) {
1056204076Spjd				mtx_lock(&range_lock);
1057204076Spjd				if (rangelock_islocked(range_sync,
1058204076Spjd				    ggio->gctl_offset, ggio->gctl_length)) {
1059204076Spjd					pjdlog_debug(2,
1060204076Spjd					    "regular: Range offset=%jd length=%zu locked.",
1061204076Spjd					    (intmax_t)ggio->gctl_offset,
1062204076Spjd					    (size_t)ggio->gctl_length);
1063204076Spjd					range_regular_wait = true;
1064204076Spjd					cv_wait(&range_regular_cond, &range_lock);
1065204076Spjd					range_regular_wait = false;
1066204076Spjd					mtx_unlock(&range_lock);
1067204076Spjd					continue;
1068204076Spjd				}
1069204076Spjd				if (rangelock_add(range_regular,
1070204076Spjd				    ggio->gctl_offset, ggio->gctl_length) < 0) {
1071204076Spjd					mtx_unlock(&range_lock);
1072204076Spjd					pjdlog_debug(2,
1073204076Spjd					    "regular: Range offset=%jd length=%zu is already locked, waiting.",
1074204076Spjd					    (intmax_t)ggio->gctl_offset,
1075204076Spjd					    (size_t)ggio->gctl_length);
1076204076Spjd					sleep(1);
1077204076Spjd					continue;
1078204076Spjd				}
1079204076Spjd				mtx_unlock(&range_lock);
1080204076Spjd				break;
1081204076Spjd			}
1082204076Spjd			mtx_lock(&res->hr_amp_lock);
1083204076Spjd			if (activemap_write_start(res->hr_amp,
1084204076Spjd			    ggio->gctl_offset, ggio->gctl_length)) {
1085204076Spjd				(void)hast_activemap_flush(res);
1086204076Spjd			}
1087204076Spjd			mtx_unlock(&res->hr_amp_lock);
1088204076Spjd			/* FALLTHROUGH */
1089204076Spjd		case BIO_DELETE:
1090204076Spjd		case BIO_FLUSH:
1091204076Spjd			pjdlog_debug(2,
1092204076Spjd			    "ggate_recv: (%p) Moving request to the send queues.",
1093204076Spjd			    hio);
1094204076Spjd			refcount_init(&hio->hio_countdown, ncomps);
1095204076Spjd			for (ii = 0; ii < ncomps; ii++)
1096204076Spjd				QUEUE_INSERT1(hio, send, ii);
1097204076Spjd			break;
1098204076Spjd		}
1099204076Spjd	}
1100204076Spjd	/* NOTREACHED */
1101204076Spjd	return (NULL);
1102204076Spjd}
1103204076Spjd
1104204076Spjd/*
1105204076Spjd * Thread reads from or writes to local component.
1106204076Spjd * If local read fails, it redirects it to remote_send thread.
1107204076Spjd */
1108204076Spjdstatic void *
1109204076Spjdlocal_send_thread(void *arg)
1110204076Spjd{
1111204076Spjd	struct hast_resource *res = arg;
1112204076Spjd	struct g_gate_ctl_io *ggio;
1113204076Spjd	struct hio *hio;
1114204076Spjd	unsigned int ncomp, rncomp;
1115204076Spjd	ssize_t ret;
1116204076Spjd
1117204076Spjd	/* Local component is 0 for now. */
1118204076Spjd	ncomp = 0;
1119204076Spjd	/* Remote component is 1 for now. */
1120204076Spjd	rncomp = 1;
1121204076Spjd
1122204076Spjd	for (;;) {
1123204076Spjd		pjdlog_debug(2, "local_send: Taking request.");
1124214692Spjd		QUEUE_TAKE1(hio, send, ncomp, 0);
1125204076Spjd		pjdlog_debug(2, "local_send: (%p) Got request.", hio);
1126204076Spjd		ggio = &hio->hio_ggio;
1127204076Spjd		switch (ggio->gctl_cmd) {
1128204076Spjd		case BIO_READ:
1129204076Spjd			ret = pread(res->hr_localfd, ggio->gctl_data,
1130204076Spjd			    ggio->gctl_length,
1131204076Spjd			    ggio->gctl_offset + res->hr_localoff);
1132204076Spjd			if (ret == ggio->gctl_length)
1133204076Spjd				hio->hio_errors[ncomp] = 0;
1134204076Spjd			else {
1135204076Spjd				/*
1136204076Spjd				 * If READ failed, try to read from remote node.
1137204076Spjd				 */
1138216479Spjd				if (ret < 0) {
1139216479Spjd					reqlog(LOG_WARNING, 0, ggio,
1140216479Spjd					    "Local request failed (%s), trying remote node. ",
1141216479Spjd					    strerror(errno));
1142216479Spjd				} else if (ret != ggio->gctl_length) {
1143216479Spjd					reqlog(LOG_WARNING, 0, ggio,
1144216479Spjd					    "Local request failed (%zd != %jd), trying remote node. ",
1145216494Spjd					    ret, (intmax_t)ggio->gctl_length);
1146216479Spjd				}
1147204076Spjd				QUEUE_INSERT1(hio, send, rncomp);
1148204076Spjd				continue;
1149204076Spjd			}
1150204076Spjd			break;
1151204076Spjd		case BIO_WRITE:
1152204076Spjd			ret = pwrite(res->hr_localfd, ggio->gctl_data,
1153204076Spjd			    ggio->gctl_length,
1154204076Spjd			    ggio->gctl_offset + res->hr_localoff);
1155216479Spjd			if (ret < 0) {
1156204076Spjd				hio->hio_errors[ncomp] = errno;
1157216479Spjd				reqlog(LOG_WARNING, 0, ggio,
1158216479Spjd				    "Local request failed (%s): ",
1159216479Spjd				    strerror(errno));
1160216479Spjd			} else if (ret != ggio->gctl_length) {
1161204076Spjd				hio->hio_errors[ncomp] = EIO;
1162216479Spjd				reqlog(LOG_WARNING, 0, ggio,
1163216479Spjd				    "Local request failed (%zd != %jd): ",
1164216494Spjd				    ret, (intmax_t)ggio->gctl_length);
1165216479Spjd			} else {
1166204076Spjd				hio->hio_errors[ncomp] = 0;
1167216479Spjd			}
1168204076Spjd			break;
1169204076Spjd		case BIO_DELETE:
1170204076Spjd			ret = g_delete(res->hr_localfd,
1171204076Spjd			    ggio->gctl_offset + res->hr_localoff,
1172204076Spjd			    ggio->gctl_length);
1173216479Spjd			if (ret < 0) {
1174204076Spjd				hio->hio_errors[ncomp] = errno;
1175216479Spjd				reqlog(LOG_WARNING, 0, ggio,
1176216479Spjd				    "Local request failed (%s): ",
1177216479Spjd				    strerror(errno));
1178216479Spjd			} else {
1179204076Spjd				hio->hio_errors[ncomp] = 0;
1180216479Spjd			}
1181204076Spjd			break;
1182204076Spjd		case BIO_FLUSH:
1183204076Spjd			ret = g_flush(res->hr_localfd);
1184216479Spjd			if (ret < 0) {
1185204076Spjd				hio->hio_errors[ncomp] = errno;
1186216479Spjd				reqlog(LOG_WARNING, 0, ggio,
1187216479Spjd				    "Local request failed (%s): ",
1188216479Spjd				    strerror(errno));
1189216479Spjd			} else {
1190204076Spjd				hio->hio_errors[ncomp] = 0;
1191216479Spjd			}
1192204076Spjd			break;
1193204076Spjd		}
1194204076Spjd		if (refcount_release(&hio->hio_countdown)) {
1195204076Spjd			if (ISSYNCREQ(hio)) {
1196204076Spjd				mtx_lock(&sync_lock);
1197204076Spjd				SYNCREQDONE(hio);
1198204076Spjd				mtx_unlock(&sync_lock);
1199204076Spjd				cv_signal(&sync_cond);
1200204076Spjd			} else {
1201204076Spjd				pjdlog_debug(2,
1202204076Spjd				    "local_send: (%p) Moving request to the done queue.",
1203204076Spjd				    hio);
1204204076Spjd				QUEUE_INSERT2(hio, done);
1205204076Spjd			}
1206204076Spjd		}
1207204076Spjd	}
1208204076Spjd	/* NOTREACHED */
1209204076Spjd	return (NULL);
1210204076Spjd}
1211204076Spjd
1212214692Spjdstatic void
1213214692Spjdkeepalive_send(struct hast_resource *res, unsigned int ncomp)
1214214692Spjd{
1215214692Spjd	struct nv *nv;
1216214692Spjd
1217214692Spjd	if (!ISCONNECTED(res, ncomp))
1218214692Spjd		return;
1219214692Spjd
1220214692Spjd	assert(res->hr_remotein != NULL);
1221214692Spjd	assert(res->hr_remoteout != NULL);
1222214692Spjd
1223214692Spjd	nv = nv_alloc();
1224214692Spjd	nv_add_uint8(nv, HIO_KEEPALIVE, "cmd");
1225214692Spjd	if (nv_error(nv) != 0) {
1226214692Spjd		nv_free(nv);
1227214692Spjd		pjdlog_debug(1,
1228214692Spjd		    "keepalive_send: Unable to prepare header to send.");
1229214692Spjd		return;
1230214692Spjd	}
1231214692Spjd	if (hast_proto_send(res, res->hr_remoteout, nv, NULL, 0) < 0) {
1232214692Spjd		pjdlog_common(LOG_DEBUG, 1, errno,
1233214692Spjd		    "keepalive_send: Unable to send request");
1234214692Spjd		nv_free(nv);
1235214692Spjd		rw_unlock(&hio_remote_lock[ncomp]);
1236214692Spjd		remote_close(res, ncomp);
1237214692Spjd		rw_rlock(&hio_remote_lock[ncomp]);
1238214692Spjd		return;
1239214692Spjd	}
1240214692Spjd	nv_free(nv);
1241214692Spjd	pjdlog_debug(2, "keepalive_send: Request sent.");
1242214692Spjd}
1243214692Spjd
1244204076Spjd/*
1245204076Spjd * Thread sends request to secondary node.
1246204076Spjd */
1247204076Spjdstatic void *
1248204076Spjdremote_send_thread(void *arg)
1249204076Spjd{
1250204076Spjd	struct hast_resource *res = arg;
1251204076Spjd	struct g_gate_ctl_io *ggio;
1252214692Spjd	time_t lastcheck, now;
1253204076Spjd	struct hio *hio;
1254204076Spjd	struct nv *nv;
1255204076Spjd	unsigned int ncomp;
1256204076Spjd	bool wakeup;
1257204076Spjd	uint64_t offset, length;
1258204076Spjd	uint8_t cmd;
1259204076Spjd	void *data;
1260204076Spjd
1261204076Spjd	/* Remote component is 1 for now. */
1262204076Spjd	ncomp = 1;
1263214692Spjd	lastcheck = time(NULL);
1264204076Spjd
1265204076Spjd	for (;;) {
1266204076Spjd		pjdlog_debug(2, "remote_send: Taking request.");
1267214692Spjd		QUEUE_TAKE1(hio, send, ncomp, RETRY_SLEEP);
1268214692Spjd		if (hio == NULL) {
1269214692Spjd			now = time(NULL);
1270214692Spjd			if (lastcheck + RETRY_SLEEP <= now) {
1271214692Spjd				keepalive_send(res, ncomp);
1272214692Spjd				lastcheck = now;
1273214692Spjd			}
1274214692Spjd			continue;
1275214692Spjd		}
1276204076Spjd		pjdlog_debug(2, "remote_send: (%p) Got request.", hio);
1277204076Spjd		ggio = &hio->hio_ggio;
1278204076Spjd		switch (ggio->gctl_cmd) {
1279204076Spjd		case BIO_READ:
1280204076Spjd			cmd = HIO_READ;
1281204076Spjd			data = NULL;
1282204076Spjd			offset = ggio->gctl_offset;
1283204076Spjd			length = ggio->gctl_length;
1284204076Spjd			break;
1285204076Spjd		case BIO_WRITE:
1286204076Spjd			cmd = HIO_WRITE;
1287204076Spjd			data = ggio->gctl_data;
1288204076Spjd			offset = ggio->gctl_offset;
1289204076Spjd			length = ggio->gctl_length;
1290204076Spjd			break;
1291204076Spjd		case BIO_DELETE:
1292204076Spjd			cmd = HIO_DELETE;
1293204076Spjd			data = NULL;
1294204076Spjd			offset = ggio->gctl_offset;
1295204076Spjd			length = ggio->gctl_length;
1296204076Spjd			break;
1297204076Spjd		case BIO_FLUSH:
1298204076Spjd			cmd = HIO_FLUSH;
1299204076Spjd			data = NULL;
1300204076Spjd			offset = 0;
1301204076Spjd			length = 0;
1302204076Spjd			break;
1303204076Spjd		default:
1304204076Spjd			assert(!"invalid condition");
1305204076Spjd			abort();
1306204076Spjd		}
1307204076Spjd		nv = nv_alloc();
1308204076Spjd		nv_add_uint8(nv, cmd, "cmd");
1309204076Spjd		nv_add_uint64(nv, (uint64_t)ggio->gctl_seq, "seq");
1310204076Spjd		nv_add_uint64(nv, offset, "offset");
1311204076Spjd		nv_add_uint64(nv, length, "length");
1312204076Spjd		if (nv_error(nv) != 0) {
1313204076Spjd			hio->hio_errors[ncomp] = nv_error(nv);
1314204076Spjd			pjdlog_debug(2,
1315204076Spjd			    "remote_send: (%p) Unable to prepare header to send.",
1316204076Spjd			    hio);
1317204076Spjd			reqlog(LOG_ERR, 0, ggio,
1318204076Spjd			    "Unable to prepare header to send (%s): ",
1319204076Spjd			    strerror(nv_error(nv)));
1320204076Spjd			/* Move failed request immediately to the done queue. */
1321204076Spjd			goto done_queue;
1322204076Spjd		}
1323204076Spjd		pjdlog_debug(2,
1324204076Spjd		    "remote_send: (%p) Moving request to the recv queue.",
1325204076Spjd		    hio);
1326204076Spjd		/*
1327204076Spjd		 * Protect connection from disappearing.
1328204076Spjd		 */
1329204076Spjd		rw_rlock(&hio_remote_lock[ncomp]);
1330204076Spjd		if (!ISCONNECTED(res, ncomp)) {
1331204076Spjd			rw_unlock(&hio_remote_lock[ncomp]);
1332204076Spjd			hio->hio_errors[ncomp] = ENOTCONN;
1333204076Spjd			goto done_queue;
1334204076Spjd		}
1335204076Spjd		/*
1336204076Spjd		 * Move the request to recv queue before sending it, because
1337204076Spjd		 * in different order we can get reply before we move request
1338204076Spjd		 * to recv queue.
1339204076Spjd		 */
1340204076Spjd		mtx_lock(&hio_recv_list_lock[ncomp]);
1341204076Spjd		wakeup = TAILQ_EMPTY(&hio_recv_list[ncomp]);
1342204076Spjd		TAILQ_INSERT_TAIL(&hio_recv_list[ncomp], hio, hio_next[ncomp]);
1343204076Spjd		mtx_unlock(&hio_recv_list_lock[ncomp]);
1344204076Spjd		if (hast_proto_send(res, res->hr_remoteout, nv, data,
1345204076Spjd		    data != NULL ? length : 0) < 0) {
1346204076Spjd			hio->hio_errors[ncomp] = errno;
1347204076Spjd			rw_unlock(&hio_remote_lock[ncomp]);
1348204076Spjd			pjdlog_debug(2,
1349204076Spjd			    "remote_send: (%p) Unable to send request.", hio);
1350204076Spjd			reqlog(LOG_ERR, 0, ggio,
1351204076Spjd			    "Unable to send request (%s): ",
1352204076Spjd			    strerror(hio->hio_errors[ncomp]));
1353211979Spjd			remote_close(res, ncomp);
1354204076Spjd			/*
1355204076Spjd			 * Take request back from the receive queue and move
1356204076Spjd			 * it immediately to the done queue.
1357204076Spjd			 */
1358204076Spjd			mtx_lock(&hio_recv_list_lock[ncomp]);
1359204076Spjd			TAILQ_REMOVE(&hio_recv_list[ncomp], hio, hio_next[ncomp]);
1360204076Spjd			mtx_unlock(&hio_recv_list_lock[ncomp]);
1361204076Spjd			goto done_queue;
1362204076Spjd		}
1363204076Spjd		rw_unlock(&hio_remote_lock[ncomp]);
1364204076Spjd		nv_free(nv);
1365204076Spjd		if (wakeup)
1366204076Spjd			cv_signal(&hio_recv_list_cond[ncomp]);
1367204076Spjd		continue;
1368204076Spjddone_queue:
1369204076Spjd		nv_free(nv);
1370204076Spjd		if (ISSYNCREQ(hio)) {
1371204076Spjd			if (!refcount_release(&hio->hio_countdown))
1372204076Spjd				continue;
1373204076Spjd			mtx_lock(&sync_lock);
1374204076Spjd			SYNCREQDONE(hio);
1375204076Spjd			mtx_unlock(&sync_lock);
1376204076Spjd			cv_signal(&sync_cond);
1377204076Spjd			continue;
1378204076Spjd		}
1379204076Spjd		if (ggio->gctl_cmd == BIO_WRITE) {
1380204076Spjd			mtx_lock(&res->hr_amp_lock);
1381204076Spjd			if (activemap_need_sync(res->hr_amp, ggio->gctl_offset,
1382204076Spjd			    ggio->gctl_length)) {
1383204076Spjd				(void)hast_activemap_flush(res);
1384204076Spjd			}
1385204076Spjd			mtx_unlock(&res->hr_amp_lock);
1386204076Spjd		}
1387204076Spjd		if (!refcount_release(&hio->hio_countdown))
1388204076Spjd			continue;
1389204076Spjd		pjdlog_debug(2,
1390204076Spjd		    "remote_send: (%p) Moving request to the done queue.",
1391204076Spjd		    hio);
1392204076Spjd		QUEUE_INSERT2(hio, done);
1393204076Spjd	}
1394204076Spjd	/* NOTREACHED */
1395204076Spjd	return (NULL);
1396204076Spjd}
1397204076Spjd
1398204076Spjd/*
1399204076Spjd * Thread receives answer from secondary node and passes it to ggate_send
1400204076Spjd * thread.
1401204076Spjd */
1402204076Spjdstatic void *
1403204076Spjdremote_recv_thread(void *arg)
1404204076Spjd{
1405204076Spjd	struct hast_resource *res = arg;
1406204076Spjd	struct g_gate_ctl_io *ggio;
1407204076Spjd	struct hio *hio;
1408204076Spjd	struct nv *nv;
1409204076Spjd	unsigned int ncomp;
1410204076Spjd	uint64_t seq;
1411204076Spjd	int error;
1412204076Spjd
1413204076Spjd	/* Remote component is 1 for now. */
1414204076Spjd	ncomp = 1;
1415204076Spjd
1416204076Spjd	for (;;) {
1417204076Spjd		/* Wait until there is anything to receive. */
1418204076Spjd		mtx_lock(&hio_recv_list_lock[ncomp]);
1419204076Spjd		while (TAILQ_EMPTY(&hio_recv_list[ncomp])) {
1420204076Spjd			pjdlog_debug(2, "remote_recv: No requests, waiting.");
1421204076Spjd			cv_wait(&hio_recv_list_cond[ncomp],
1422204076Spjd			    &hio_recv_list_lock[ncomp]);
1423204076Spjd		}
1424204076Spjd		mtx_unlock(&hio_recv_list_lock[ncomp]);
1425204076Spjd		rw_rlock(&hio_remote_lock[ncomp]);
1426204076Spjd		if (!ISCONNECTED(res, ncomp)) {
1427204076Spjd			rw_unlock(&hio_remote_lock[ncomp]);
1428204076Spjd			/*
1429204076Spjd			 * Connection is dead, so move all pending requests to
1430204076Spjd			 * the done queue (one-by-one).
1431204076Spjd			 */
1432204076Spjd			mtx_lock(&hio_recv_list_lock[ncomp]);
1433204076Spjd			hio = TAILQ_FIRST(&hio_recv_list[ncomp]);
1434204076Spjd			assert(hio != NULL);
1435204076Spjd			TAILQ_REMOVE(&hio_recv_list[ncomp], hio,
1436204076Spjd			    hio_next[ncomp]);
1437204076Spjd			mtx_unlock(&hio_recv_list_lock[ncomp]);
1438204076Spjd			goto done_queue;
1439204076Spjd		}
1440204076Spjd		if (hast_proto_recv_hdr(res->hr_remotein, &nv) < 0) {
1441204076Spjd			pjdlog_errno(LOG_ERR,
1442204076Spjd			    "Unable to receive reply header");
1443204076Spjd			rw_unlock(&hio_remote_lock[ncomp]);
1444204076Spjd			remote_close(res, ncomp);
1445204076Spjd			continue;
1446204076Spjd		}
1447204076Spjd		rw_unlock(&hio_remote_lock[ncomp]);
1448204076Spjd		seq = nv_get_uint64(nv, "seq");
1449204076Spjd		if (seq == 0) {
1450204076Spjd			pjdlog_error("Header contains no 'seq' field.");
1451204076Spjd			nv_free(nv);
1452204076Spjd			continue;
1453204076Spjd		}
1454204076Spjd		mtx_lock(&hio_recv_list_lock[ncomp]);
1455204076Spjd		TAILQ_FOREACH(hio, &hio_recv_list[ncomp], hio_next[ncomp]) {
1456204076Spjd			if (hio->hio_ggio.gctl_seq == seq) {
1457204076Spjd				TAILQ_REMOVE(&hio_recv_list[ncomp], hio,
1458204076Spjd				    hio_next[ncomp]);
1459204076Spjd				break;
1460204076Spjd			}
1461204076Spjd		}
1462204076Spjd		mtx_unlock(&hio_recv_list_lock[ncomp]);
1463204076Spjd		if (hio == NULL) {
1464204076Spjd			pjdlog_error("Found no request matching received 'seq' field (%ju).",
1465204076Spjd			    (uintmax_t)seq);
1466204076Spjd			nv_free(nv);
1467204076Spjd			continue;
1468204076Spjd		}
1469204076Spjd		error = nv_get_int16(nv, "error");
1470204076Spjd		if (error != 0) {
1471204076Spjd			/* Request failed on remote side. */
1472216478Spjd			hio->hio_errors[ncomp] = error;
1473216479Spjd			reqlog(LOG_WARNING, 0, &hio->hio_ggio,
1474216479Spjd			    "Remote request failed (%s): ", strerror(error));
1475204076Spjd			nv_free(nv);
1476204076Spjd			goto done_queue;
1477204076Spjd		}
1478204076Spjd		ggio = &hio->hio_ggio;
1479204076Spjd		switch (ggio->gctl_cmd) {
1480204076Spjd		case BIO_READ:
1481204076Spjd			rw_rlock(&hio_remote_lock[ncomp]);
1482204076Spjd			if (!ISCONNECTED(res, ncomp)) {
1483204076Spjd				rw_unlock(&hio_remote_lock[ncomp]);
1484204076Spjd				nv_free(nv);
1485204076Spjd				goto done_queue;
1486204076Spjd			}
1487204076Spjd			if (hast_proto_recv_data(res, res->hr_remotein, nv,
1488204076Spjd			    ggio->gctl_data, ggio->gctl_length) < 0) {
1489204076Spjd				hio->hio_errors[ncomp] = errno;
1490204076Spjd				pjdlog_errno(LOG_ERR,
1491204076Spjd				    "Unable to receive reply data");
1492204076Spjd				rw_unlock(&hio_remote_lock[ncomp]);
1493204076Spjd				nv_free(nv);
1494204076Spjd				remote_close(res, ncomp);
1495204076Spjd				goto done_queue;
1496204076Spjd			}
1497204076Spjd			rw_unlock(&hio_remote_lock[ncomp]);
1498204076Spjd			break;
1499204076Spjd		case BIO_WRITE:
1500204076Spjd		case BIO_DELETE:
1501204076Spjd		case BIO_FLUSH:
1502204076Spjd			break;
1503204076Spjd		default:
1504204076Spjd			assert(!"invalid condition");
1505204076Spjd			abort();
1506204076Spjd		}
1507204076Spjd		hio->hio_errors[ncomp] = 0;
1508204076Spjd		nv_free(nv);
1509204076Spjddone_queue:
1510204076Spjd		if (refcount_release(&hio->hio_countdown)) {
1511204076Spjd			if (ISSYNCREQ(hio)) {
1512204076Spjd				mtx_lock(&sync_lock);
1513204076Spjd				SYNCREQDONE(hio);
1514204076Spjd				mtx_unlock(&sync_lock);
1515204076Spjd				cv_signal(&sync_cond);
1516204076Spjd			} else {
1517204076Spjd				pjdlog_debug(2,
1518204076Spjd				    "remote_recv: (%p) Moving request to the done queue.",
1519204076Spjd				    hio);
1520204076Spjd				QUEUE_INSERT2(hio, done);
1521204076Spjd			}
1522204076Spjd		}
1523204076Spjd	}
1524204076Spjd	/* NOTREACHED */
1525204076Spjd	return (NULL);
1526204076Spjd}
1527204076Spjd
1528204076Spjd/*
1529204076Spjd * Thread sends answer to the kernel.
1530204076Spjd */
1531204076Spjdstatic void *
1532204076Spjdggate_send_thread(void *arg)
1533204076Spjd{
1534204076Spjd	struct hast_resource *res = arg;
1535204076Spjd	struct g_gate_ctl_io *ggio;
1536204076Spjd	struct hio *hio;
1537204076Spjd	unsigned int ii, ncomp, ncomps;
1538204076Spjd
1539204076Spjd	ncomps = HAST_NCOMPONENTS;
1540204076Spjd
1541204076Spjd	for (;;) {
1542204076Spjd		pjdlog_debug(2, "ggate_send: Taking request.");
1543204076Spjd		QUEUE_TAKE2(hio, done);
1544204076Spjd		pjdlog_debug(2, "ggate_send: (%p) Got request.", hio);
1545204076Spjd		ggio = &hio->hio_ggio;
1546204076Spjd		for (ii = 0; ii < ncomps; ii++) {
1547204076Spjd			if (hio->hio_errors[ii] == 0) {
1548204076Spjd				/*
1549204076Spjd				 * One successful request is enough to declare
1550204076Spjd				 * success.
1551204076Spjd				 */
1552204076Spjd				ggio->gctl_error = 0;
1553204076Spjd				break;
1554204076Spjd			}
1555204076Spjd		}
1556204076Spjd		if (ii == ncomps) {
1557204076Spjd			/*
1558204076Spjd			 * None of the requests were successful.
1559204076Spjd			 * Use first error.
1560204076Spjd			 */
1561204076Spjd			ggio->gctl_error = hio->hio_errors[0];
1562204076Spjd		}
1563204076Spjd		if (ggio->gctl_error == 0 && ggio->gctl_cmd == BIO_WRITE) {
1564204076Spjd			mtx_lock(&res->hr_amp_lock);
1565204076Spjd			activemap_write_complete(res->hr_amp,
1566204076Spjd			    ggio->gctl_offset, ggio->gctl_length);
1567204076Spjd			mtx_unlock(&res->hr_amp_lock);
1568204076Spjd		}
1569204076Spjd		if (ggio->gctl_cmd == BIO_WRITE) {
1570204076Spjd			/*
1571204076Spjd			 * Unlock range we locked.
1572204076Spjd			 */
1573204076Spjd			mtx_lock(&range_lock);
1574204076Spjd			rangelock_del(range_regular, ggio->gctl_offset,
1575204076Spjd			    ggio->gctl_length);
1576204076Spjd			if (range_sync_wait)
1577204076Spjd				cv_signal(&range_sync_cond);
1578204076Spjd			mtx_unlock(&range_lock);
1579204076Spjd			/*
1580204076Spjd			 * Bump local count if this is first write after
1581204076Spjd			 * connection failure with remote node.
1582204076Spjd			 */
1583204076Spjd			ncomp = 1;
1584204076Spjd			rw_rlock(&hio_remote_lock[ncomp]);
1585204076Spjd			if (!ISCONNECTED(res, ncomp)) {
1586204076Spjd				mtx_lock(&metadata_lock);
1587204076Spjd				if (res->hr_primary_localcnt ==
1588204076Spjd				    res->hr_secondary_remotecnt) {
1589204076Spjd					res->hr_primary_localcnt++;
1590204076Spjd					pjdlog_debug(1,
1591204076Spjd					    "Increasing localcnt to %ju.",
1592204076Spjd					    (uintmax_t)res->hr_primary_localcnt);
1593204076Spjd					(void)metadata_write(res);
1594204076Spjd				}
1595204076Spjd				mtx_unlock(&metadata_lock);
1596204076Spjd			}
1597204076Spjd			rw_unlock(&hio_remote_lock[ncomp]);
1598204076Spjd		}
1599204076Spjd		if (ioctl(res->hr_ggatefd, G_GATE_CMD_DONE, ggio) < 0)
1600204076Spjd			primary_exit(EX_OSERR, "G_GATE_CMD_DONE failed");
1601204076Spjd		pjdlog_debug(2,
1602204076Spjd		    "ggate_send: (%p) Moving request to the free queue.", hio);
1603204076Spjd		QUEUE_INSERT2(hio, free);
1604204076Spjd	}
1605204076Spjd	/* NOTREACHED */
1606204076Spjd	return (NULL);
1607204076Spjd}
1608204076Spjd
1609204076Spjd/*
1610204076Spjd * Thread synchronize local and remote components.
1611204076Spjd */
1612204076Spjdstatic void *
1613204076Spjdsync_thread(void *arg __unused)
1614204076Spjd{
1615204076Spjd	struct hast_resource *res = arg;
1616204076Spjd	struct hio *hio;
1617204076Spjd	struct g_gate_ctl_io *ggio;
1618204076Spjd	unsigned int ii, ncomp, ncomps;
1619204076Spjd	off_t offset, length, synced;
1620204076Spjd	bool dorewind;
1621204076Spjd	int syncext;
1622204076Spjd
1623204076Spjd	ncomps = HAST_NCOMPONENTS;
1624204076Spjd	dorewind = true;
1625211897Spjd	synced = 0;
1626211897Spjd	offset = -1;
1627204076Spjd
1628204076Spjd	for (;;) {
1629204076Spjd		mtx_lock(&sync_lock);
1630211897Spjd		if (offset >= 0 && !sync_inprogress) {
1631211879Spjd			pjdlog_info("Synchronization interrupted. "
1632211879Spjd			    "%jd bytes synchronized so far.",
1633211879Spjd			    (intmax_t)synced);
1634212038Spjd			event_send(res, EVENT_SYNCINTR);
1635211879Spjd		}
1636204076Spjd		while (!sync_inprogress) {
1637204076Spjd			dorewind = true;
1638204076Spjd			synced = 0;
1639204076Spjd			cv_wait(&sync_cond, &sync_lock);
1640204076Spjd		}
1641204076Spjd		mtx_unlock(&sync_lock);
1642204076Spjd		/*
1643204076Spjd		 * Obtain offset at which we should synchronize.
1644204076Spjd		 * Rewind synchronization if needed.
1645204076Spjd		 */
1646204076Spjd		mtx_lock(&res->hr_amp_lock);
1647204076Spjd		if (dorewind)
1648204076Spjd			activemap_sync_rewind(res->hr_amp);
1649204076Spjd		offset = activemap_sync_offset(res->hr_amp, &length, &syncext);
1650204076Spjd		if (syncext != -1) {
1651204076Spjd			/*
1652204076Spjd			 * We synchronized entire syncext extent, we can mark
1653204076Spjd			 * it as clean now.
1654204076Spjd			 */
1655204076Spjd			if (activemap_extent_complete(res->hr_amp, syncext))
1656204076Spjd				(void)hast_activemap_flush(res);
1657204076Spjd		}
1658204076Spjd		mtx_unlock(&res->hr_amp_lock);
1659204076Spjd		if (dorewind) {
1660204076Spjd			dorewind = false;
1661204076Spjd			if (offset < 0)
1662204076Spjd				pjdlog_info("Nodes are in sync.");
1663204076Spjd			else {
1664204076Spjd				pjdlog_info("Synchronization started. %ju bytes to go.",
1665204076Spjd				    (uintmax_t)(res->hr_extentsize *
1666204076Spjd				    activemap_ndirty(res->hr_amp)));
1667212038Spjd				event_send(res, EVENT_SYNCSTART);
1668204076Spjd			}
1669204076Spjd		}
1670204076Spjd		if (offset < 0) {
1671211878Spjd			sync_stop();
1672204076Spjd			pjdlog_debug(1, "Nothing to synchronize.");
1673204076Spjd			/*
1674204076Spjd			 * Synchronization complete, make both localcnt and
1675204076Spjd			 * remotecnt equal.
1676204076Spjd			 */
1677204076Spjd			ncomp = 1;
1678204076Spjd			rw_rlock(&hio_remote_lock[ncomp]);
1679204076Spjd			if (ISCONNECTED(res, ncomp)) {
1680204076Spjd				if (synced > 0) {
1681204076Spjd					pjdlog_info("Synchronization complete. "
1682204076Spjd					    "%jd bytes synchronized.",
1683204076Spjd					    (intmax_t)synced);
1684212038Spjd					event_send(res, EVENT_SYNCDONE);
1685204076Spjd				}
1686204076Spjd				mtx_lock(&metadata_lock);
1687204076Spjd				res->hr_syncsrc = HAST_SYNCSRC_UNDEF;
1688204076Spjd				res->hr_primary_localcnt =
1689204076Spjd				    res->hr_secondary_localcnt;
1690204076Spjd				res->hr_primary_remotecnt =
1691204076Spjd				    res->hr_secondary_remotecnt;
1692204076Spjd				pjdlog_debug(1,
1693204076Spjd				    "Setting localcnt to %ju and remotecnt to %ju.",
1694204076Spjd				    (uintmax_t)res->hr_primary_localcnt,
1695204076Spjd				    (uintmax_t)res->hr_secondary_localcnt);
1696204076Spjd				(void)metadata_write(res);
1697204076Spjd				mtx_unlock(&metadata_lock);
1698204076Spjd			}
1699204076Spjd			rw_unlock(&hio_remote_lock[ncomp]);
1700204076Spjd			continue;
1701204076Spjd		}
1702204076Spjd		pjdlog_debug(2, "sync: Taking free request.");
1703204076Spjd		QUEUE_TAKE2(hio, free);
1704204076Spjd		pjdlog_debug(2, "sync: (%p) Got free request.", hio);
1705204076Spjd		/*
1706204076Spjd		 * Lock the range we are going to synchronize. We don't want
1707204076Spjd		 * race where someone writes between our read and write.
1708204076Spjd		 */
1709204076Spjd		for (;;) {
1710204076Spjd			mtx_lock(&range_lock);
1711204076Spjd			if (rangelock_islocked(range_regular, offset, length)) {
1712204076Spjd				pjdlog_debug(2,
1713204076Spjd				    "sync: Range offset=%jd length=%jd locked.",
1714204076Spjd				    (intmax_t)offset, (intmax_t)length);
1715204076Spjd				range_sync_wait = true;
1716204076Spjd				cv_wait(&range_sync_cond, &range_lock);
1717204076Spjd				range_sync_wait = false;
1718204076Spjd				mtx_unlock(&range_lock);
1719204076Spjd				continue;
1720204076Spjd			}
1721204076Spjd			if (rangelock_add(range_sync, offset, length) < 0) {
1722204076Spjd				mtx_unlock(&range_lock);
1723204076Spjd				pjdlog_debug(2,
1724204076Spjd				    "sync: Range offset=%jd length=%jd is already locked, waiting.",
1725204076Spjd				    (intmax_t)offset, (intmax_t)length);
1726204076Spjd				sleep(1);
1727204076Spjd				continue;
1728204076Spjd			}
1729204076Spjd			mtx_unlock(&range_lock);
1730204076Spjd			break;
1731204076Spjd		}
1732204076Spjd		/*
1733204076Spjd		 * First read the data from synchronization source.
1734204076Spjd		 */
1735204076Spjd		SYNCREQ(hio);
1736204076Spjd		ggio = &hio->hio_ggio;
1737204076Spjd		ggio->gctl_cmd = BIO_READ;
1738204076Spjd		ggio->gctl_offset = offset;
1739204076Spjd		ggio->gctl_length = length;
1740204076Spjd		ggio->gctl_error = 0;
1741204076Spjd		for (ii = 0; ii < ncomps; ii++)
1742204076Spjd			hio->hio_errors[ii] = EINVAL;
1743204076Spjd		reqlog(LOG_DEBUG, 2, ggio, "sync: (%p) Sending sync request: ",
1744204076Spjd		    hio);
1745204076Spjd		pjdlog_debug(2, "sync: (%p) Moving request to the send queue.",
1746204076Spjd		    hio);
1747204076Spjd		mtx_lock(&metadata_lock);
1748204076Spjd		if (res->hr_syncsrc == HAST_SYNCSRC_PRIMARY) {
1749204076Spjd			/*
1750204076Spjd			 * This range is up-to-date on local component,
1751204076Spjd			 * so handle request locally.
1752204076Spjd			 */
1753204076Spjd			 /* Local component is 0 for now. */
1754204076Spjd			ncomp = 0;
1755204076Spjd		} else /* if (res->hr_syncsrc == HAST_SYNCSRC_SECONDARY) */ {
1756204076Spjd			assert(res->hr_syncsrc == HAST_SYNCSRC_SECONDARY);
1757204076Spjd			/*
1758204076Spjd			 * This range is out-of-date on local component,
1759204076Spjd			 * so send request to the remote node.
1760204076Spjd			 */
1761204076Spjd			 /* Remote component is 1 for now. */
1762204076Spjd			ncomp = 1;
1763204076Spjd		}
1764204076Spjd		mtx_unlock(&metadata_lock);
1765204076Spjd		refcount_init(&hio->hio_countdown, 1);
1766204076Spjd		QUEUE_INSERT1(hio, send, ncomp);
1767204076Spjd
1768204076Spjd		/*
1769204076Spjd		 * Let's wait for READ to finish.
1770204076Spjd		 */
1771204076Spjd		mtx_lock(&sync_lock);
1772204076Spjd		while (!ISSYNCREQDONE(hio))
1773204076Spjd			cv_wait(&sync_cond, &sync_lock);
1774204076Spjd		mtx_unlock(&sync_lock);
1775204076Spjd
1776204076Spjd		if (hio->hio_errors[ncomp] != 0) {
1777204076Spjd			pjdlog_error("Unable to read synchronization data: %s.",
1778204076Spjd			    strerror(hio->hio_errors[ncomp]));
1779204076Spjd			goto free_queue;
1780204076Spjd		}
1781204076Spjd
1782204076Spjd		/*
1783204076Spjd		 * We read the data from synchronization source, now write it
1784204076Spjd		 * to synchronization target.
1785204076Spjd		 */
1786204076Spjd		SYNCREQ(hio);
1787204076Spjd		ggio->gctl_cmd = BIO_WRITE;
1788204076Spjd		for (ii = 0; ii < ncomps; ii++)
1789204076Spjd			hio->hio_errors[ii] = EINVAL;
1790204076Spjd		reqlog(LOG_DEBUG, 2, ggio, "sync: (%p) Sending sync request: ",
1791204076Spjd		    hio);
1792204076Spjd		pjdlog_debug(2, "sync: (%p) Moving request to the send queue.",
1793204076Spjd		    hio);
1794204076Spjd		mtx_lock(&metadata_lock);
1795204076Spjd		if (res->hr_syncsrc == HAST_SYNCSRC_PRIMARY) {
1796204076Spjd			/*
1797204076Spjd			 * This range is up-to-date on local component,
1798204076Spjd			 * so we update remote component.
1799204076Spjd			 */
1800204076Spjd			 /* Remote component is 1 for now. */
1801204076Spjd			ncomp = 1;
1802204076Spjd		} else /* if (res->hr_syncsrc == HAST_SYNCSRC_SECONDARY) */ {
1803204076Spjd			assert(res->hr_syncsrc == HAST_SYNCSRC_SECONDARY);
1804204076Spjd			/*
1805204076Spjd			 * This range is out-of-date on local component,
1806204076Spjd			 * so we update it.
1807204076Spjd			 */
1808204076Spjd			 /* Local component is 0 for now. */
1809204076Spjd			ncomp = 0;
1810204076Spjd		}
1811204076Spjd		mtx_unlock(&metadata_lock);
1812204076Spjd
1813204076Spjd		pjdlog_debug(2, "sync: (%p) Moving request to the send queues.",
1814204076Spjd		    hio);
1815204076Spjd		refcount_init(&hio->hio_countdown, 1);
1816204076Spjd		QUEUE_INSERT1(hio, send, ncomp);
1817204076Spjd
1818204076Spjd		/*
1819204076Spjd		 * Let's wait for WRITE to finish.
1820204076Spjd		 */
1821204076Spjd		mtx_lock(&sync_lock);
1822204076Spjd		while (!ISSYNCREQDONE(hio))
1823204076Spjd			cv_wait(&sync_cond, &sync_lock);
1824204076Spjd		mtx_unlock(&sync_lock);
1825204076Spjd
1826204076Spjd		if (hio->hio_errors[ncomp] != 0) {
1827204076Spjd			pjdlog_error("Unable to write synchronization data: %s.",
1828204076Spjd			    strerror(hio->hio_errors[ncomp]));
1829204076Spjd			goto free_queue;
1830204076Spjd		}
1831211880Spjd
1832211880Spjd		synced += length;
1833204076Spjdfree_queue:
1834204076Spjd		mtx_lock(&range_lock);
1835204076Spjd		rangelock_del(range_sync, offset, length);
1836204076Spjd		if (range_regular_wait)
1837204076Spjd			cv_signal(&range_regular_cond);
1838204076Spjd		mtx_unlock(&range_lock);
1839204076Spjd		pjdlog_debug(2, "sync: (%p) Moving request to the free queue.",
1840204076Spjd		    hio);
1841204076Spjd		QUEUE_INSERT2(hio, free);
1842204076Spjd	}
1843204076Spjd	/* NOTREACHED */
1844204076Spjd	return (NULL);
1845204076Spjd}
1846204076Spjd
1847204076Spjdstatic void
1848210886Spjdconfig_reload(void)
1849210886Spjd{
1850210886Spjd	struct hastd_config *newcfg;
1851210886Spjd	struct hast_resource *res;
1852210886Spjd	unsigned int ii, ncomps;
1853210886Spjd	int modified;
1854210886Spjd
1855210886Spjd	pjdlog_info("Reloading configuration...");
1856210886Spjd
1857210886Spjd	ncomps = HAST_NCOMPONENTS;
1858210886Spjd
1859210886Spjd	newcfg = yy_config_parse(cfgpath, false);
1860210886Spjd	if (newcfg == NULL)
1861210886Spjd		goto failed;
1862210886Spjd
1863210886Spjd	TAILQ_FOREACH(res, &newcfg->hc_resources, hr_next) {
1864210886Spjd		if (strcmp(res->hr_name, gres->hr_name) == 0)
1865210886Spjd			break;
1866210886Spjd	}
1867210886Spjd	/*
1868210886Spjd	 * If resource was removed from the configuration file, resource
1869210886Spjd	 * name, provider name or path to local component was modified we
1870210886Spjd	 * shouldn't be here. This means that someone modified configuration
1871210886Spjd	 * file and send SIGHUP to us instead of main hastd process.
1872210886Spjd	 * Log advice and ignore the signal.
1873210886Spjd	 */
1874210886Spjd	if (res == NULL || strcmp(gres->hr_name, res->hr_name) != 0 ||
1875210886Spjd	    strcmp(gres->hr_provname, res->hr_provname) != 0 ||
1876210886Spjd	    strcmp(gres->hr_localpath, res->hr_localpath) != 0) {
1877210886Spjd		pjdlog_warning("To reload configuration send SIGHUP to the main hastd process (pid %u).",
1878210886Spjd		    (unsigned int)getppid());
1879210886Spjd		goto failed;
1880210886Spjd	}
1881210886Spjd
1882210886Spjd#define MODIFIED_REMOTEADDR	0x1
1883210886Spjd#define MODIFIED_REPLICATION	0x2
1884210886Spjd#define MODIFIED_TIMEOUT	0x4
1885211886Spjd#define MODIFIED_EXEC		0x8
1886210886Spjd	modified = 0;
1887210886Spjd	if (strcmp(gres->hr_remoteaddr, res->hr_remoteaddr) != 0) {
1888210886Spjd		/*
1889210886Spjd		 * Don't copy res->hr_remoteaddr to gres just yet.
1890210886Spjd		 * We want remote_close() to log disconnect from the old
1891210886Spjd		 * addresses, not from the new ones.
1892210886Spjd		 */
1893210886Spjd		modified |= MODIFIED_REMOTEADDR;
1894210886Spjd	}
1895210886Spjd	if (gres->hr_replication != res->hr_replication) {
1896210886Spjd		gres->hr_replication = res->hr_replication;
1897210886Spjd		modified |= MODIFIED_REPLICATION;
1898210886Spjd	}
1899210886Spjd	if (gres->hr_timeout != res->hr_timeout) {
1900210886Spjd		gres->hr_timeout = res->hr_timeout;
1901210886Spjd		modified |= MODIFIED_TIMEOUT;
1902210886Spjd	}
1903211886Spjd	if (strcmp(gres->hr_exec, res->hr_exec) != 0) {
1904211886Spjd		strlcpy(gres->hr_exec, res->hr_exec, sizeof(gres->hr_exec));
1905211886Spjd		modified |= MODIFIED_EXEC;
1906211886Spjd	}
1907210886Spjd	/*
1908210886Spjd	 * If only timeout was modified we only need to change it without
1909210886Spjd	 * reconnecting.
1910210886Spjd	 */
1911210886Spjd	if (modified == MODIFIED_TIMEOUT) {
1912210886Spjd		for (ii = 0; ii < ncomps; ii++) {
1913210886Spjd			if (!ISREMOTE(ii))
1914210886Spjd				continue;
1915210886Spjd			rw_rlock(&hio_remote_lock[ii]);
1916210886Spjd			if (!ISCONNECTED(gres, ii)) {
1917210886Spjd				rw_unlock(&hio_remote_lock[ii]);
1918210886Spjd				continue;
1919210886Spjd			}
1920210886Spjd			rw_unlock(&hio_remote_lock[ii]);
1921210886Spjd			if (proto_timeout(gres->hr_remotein,
1922210886Spjd			    gres->hr_timeout) < 0) {
1923210886Spjd				pjdlog_errno(LOG_WARNING,
1924210886Spjd				    "Unable to set connection timeout");
1925210886Spjd			}
1926210886Spjd			if (proto_timeout(gres->hr_remoteout,
1927210886Spjd			    gres->hr_timeout) < 0) {
1928210886Spjd				pjdlog_errno(LOG_WARNING,
1929210886Spjd				    "Unable to set connection timeout");
1930210886Spjd			}
1931210886Spjd		}
1932211886Spjd	} else if ((modified &
1933211886Spjd	    (MODIFIED_REMOTEADDR | MODIFIED_REPLICATION)) != 0) {
1934210886Spjd		for (ii = 0; ii < ncomps; ii++) {
1935210886Spjd			if (!ISREMOTE(ii))
1936210886Spjd				continue;
1937210886Spjd			remote_close(gres, ii);
1938210886Spjd		}
1939210886Spjd		if (modified & MODIFIED_REMOTEADDR) {
1940210886Spjd			strlcpy(gres->hr_remoteaddr, res->hr_remoteaddr,
1941210886Spjd			    sizeof(gres->hr_remoteaddr));
1942210886Spjd		}
1943210886Spjd	}
1944210886Spjd#undef	MODIFIED_REMOTEADDR
1945210886Spjd#undef	MODIFIED_REPLICATION
1946210886Spjd#undef	MODIFIED_TIMEOUT
1947211886Spjd#undef	MODIFIED_EXEC
1948210886Spjd
1949210886Spjd	pjdlog_info("Configuration reloaded successfully.");
1950210886Spjd	return;
1951210886Spjdfailed:
1952210886Spjd	if (newcfg != NULL) {
1953210886Spjd		if (newcfg->hc_controlconn != NULL)
1954210886Spjd			proto_close(newcfg->hc_controlconn);
1955210886Spjd		if (newcfg->hc_listenconn != NULL)
1956210886Spjd			proto_close(newcfg->hc_listenconn);
1957210886Spjd		yy_config_free(newcfg);
1958210886Spjd	}
1959210886Spjd	pjdlog_warning("Configuration not reloaded.");
1960210886Spjd}
1961210886Spjd
1962211882Spjdstatic void
1963211981Spjdguard_one(struct hast_resource *res, unsigned int ncomp)
1964211981Spjd{
1965211981Spjd	struct proto_conn *in, *out;
1966211981Spjd
1967211981Spjd	if (!ISREMOTE(ncomp))
1968211981Spjd		return;
1969211981Spjd
1970211981Spjd	rw_rlock(&hio_remote_lock[ncomp]);
1971211981Spjd
1972211981Spjd	if (!real_remote(res)) {
1973211981Spjd		rw_unlock(&hio_remote_lock[ncomp]);
1974211981Spjd		return;
1975211981Spjd	}
1976211981Spjd
1977211981Spjd	if (ISCONNECTED(res, ncomp)) {
1978211981Spjd		assert(res->hr_remotein != NULL);
1979211981Spjd		assert(res->hr_remoteout != NULL);
1980211981Spjd		rw_unlock(&hio_remote_lock[ncomp]);
1981211981Spjd		pjdlog_debug(2, "remote_guard: Connection to %s is ok.",
1982211981Spjd		    res->hr_remoteaddr);
1983211981Spjd		return;
1984211981Spjd	}
1985211981Spjd
1986211981Spjd	assert(res->hr_remotein == NULL);
1987211981Spjd	assert(res->hr_remoteout == NULL);
1988211981Spjd	/*
1989211981Spjd	 * Upgrade the lock. It doesn't have to be atomic as no other thread
1990211981Spjd	 * can change connection status from disconnected to connected.
1991211981Spjd	 */
1992211981Spjd	rw_unlock(&hio_remote_lock[ncomp]);
1993211981Spjd	pjdlog_debug(2, "remote_guard: Reconnecting to %s.",
1994211981Spjd	    res->hr_remoteaddr);
1995211981Spjd	in = out = NULL;
1996211981Spjd	if (init_remote(res, &in, &out)) {
1997211981Spjd		rw_wlock(&hio_remote_lock[ncomp]);
1998211981Spjd		assert(res->hr_remotein == NULL);
1999211981Spjd		assert(res->hr_remoteout == NULL);
2000211981Spjd		assert(in != NULL && out != NULL);
2001211981Spjd		res->hr_remotein = in;
2002211981Spjd		res->hr_remoteout = out;
2003211981Spjd		rw_unlock(&hio_remote_lock[ncomp]);
2004211981Spjd		pjdlog_info("Successfully reconnected to %s.",
2005211981Spjd		    res->hr_remoteaddr);
2006211981Spjd		sync_start();
2007211981Spjd	} else {
2008211981Spjd		/* Both connections should be NULL. */
2009211981Spjd		assert(res->hr_remotein == NULL);
2010211981Spjd		assert(res->hr_remoteout == NULL);
2011211981Spjd		assert(in == NULL && out == NULL);
2012211981Spjd		pjdlog_debug(2, "remote_guard: Reconnect to %s failed.",
2013211981Spjd		    res->hr_remoteaddr);
2014211981Spjd	}
2015211981Spjd}
2016211981Spjd
2017204076Spjd/*
2018204076Spjd * Thread guards remote connections and reconnects when needed, handles
2019204076Spjd * signals, etc.
2020204076Spjd */
2021204076Spjdstatic void *
2022204076Spjdguard_thread(void *arg)
2023204076Spjd{
2024204076Spjd	struct hast_resource *res = arg;
2025204076Spjd	unsigned int ii, ncomps;
2026211982Spjd	struct timespec timeout;
2027211981Spjd	time_t lastcheck, now;
2028211982Spjd	sigset_t mask;
2029211982Spjd	int signo;
2030204076Spjd
2031204076Spjd	ncomps = HAST_NCOMPONENTS;
2032211981Spjd	lastcheck = time(NULL);
2033204076Spjd
2034211982Spjd	PJDLOG_VERIFY(sigemptyset(&mask) == 0);
2035211982Spjd	PJDLOG_VERIFY(sigaddset(&mask, SIGHUP) == 0);
2036211982Spjd	PJDLOG_VERIFY(sigaddset(&mask, SIGINT) == 0);
2037211982Spjd	PJDLOG_VERIFY(sigaddset(&mask, SIGTERM) == 0);
2038211982Spjd
2039215332Spjd	timeout.tv_sec = RETRY_SLEEP;
2040211982Spjd	timeout.tv_nsec = 0;
2041211982Spjd	signo = -1;
2042211982Spjd
2043204076Spjd	for (;;) {
2044211982Spjd		switch (signo) {
2045211982Spjd		case SIGHUP:
2046211982Spjd			config_reload();
2047211982Spjd			break;
2048211982Spjd		case SIGINT:
2049211982Spjd		case SIGTERM:
2050211982Spjd			sigexit_received = true;
2051204076Spjd			primary_exitx(EX_OK,
2052204076Spjd			    "Termination signal received, exiting.");
2053211982Spjd			break;
2054211982Spjd		default:
2055211982Spjd			break;
2056204076Spjd		}
2057211882Spjd
2058204076Spjd		pjdlog_debug(2, "remote_guard: Checking connections.");
2059211981Spjd		now = time(NULL);
2060211982Spjd		if (lastcheck + RETRY_SLEEP <= now) {
2061211982Spjd			for (ii = 0; ii < ncomps; ii++)
2062211981Spjd				guard_one(res, ii);
2063211981Spjd			lastcheck = now;
2064204076Spjd		}
2065211982Spjd		signo = sigtimedwait(&mask, NULL, &timeout);
2066204076Spjd	}
2067204076Spjd	/* NOTREACHED */
2068204076Spjd	return (NULL);
2069204076Spjd}
2070