primary.c revision 218214
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 218214 2011-02-03 10:37:44Z 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 <err.h>
44204076Spjd#include <errno.h>
45204076Spjd#include <fcntl.h>
46204076Spjd#include <libgeom.h>
47204076Spjd#include <pthread.h>
48211982Spjd#include <signal.h>
49204076Spjd#include <stdint.h>
50204076Spjd#include <stdio.h>
51204076Spjd#include <string.h>
52204076Spjd#include <sysexits.h>
53204076Spjd#include <unistd.h>
54204076Spjd
55204076Spjd#include <activemap.h>
56204076Spjd#include <nv.h>
57204076Spjd#include <rangelock.h>
58204076Spjd
59204076Spjd#include "control.h"
60212038Spjd#include "event.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)
182214692Spjd#define	QUEUE_TAKE1(hio, name, ncomp, timeout)	do {			\
183214692Spjd	bool _last;							\
184214692Spjd									\
185204076Spjd	mtx_lock(&hio_##name##_list_lock[(ncomp)]);			\
186214692Spjd	_last = false;							\
187214692Spjd	while (((hio) = TAILQ_FIRST(&hio_##name##_list[(ncomp)])) == NULL && !_last) { \
188214692Spjd		cv_timedwait(&hio_##name##_list_cond[(ncomp)],		\
189214692Spjd		    &hio_##name##_list_lock[(ncomp)], (timeout));	\
190214692Spjd		if ((timeout) != 0) 					\
191214692Spjd			_last = true;					\
192204076Spjd	}								\
193214692Spjd	if (hio != NULL) {						\
194214692Spjd		TAILQ_REMOVE(&hio_##name##_list[(ncomp)], (hio),	\
195214692Spjd		    hio_next[(ncomp)]);					\
196214692Spjd	}								\
197204076Spjd	mtx_unlock(&hio_##name##_list_lock[(ncomp)]);			\
198204076Spjd} while (0)
199204076Spjd#define	QUEUE_TAKE2(hio, name)	do {					\
200204076Spjd	mtx_lock(&hio_##name##_list_lock);				\
201204076Spjd	while (((hio) = TAILQ_FIRST(&hio_##name##_list)) == NULL) {	\
202204076Spjd		cv_wait(&hio_##name##_list_cond,			\
203204076Spjd		    &hio_##name##_list_lock);				\
204204076Spjd	}								\
205204076Spjd	TAILQ_REMOVE(&hio_##name##_list, (hio), hio_##name##_next);	\
206204076Spjd	mtx_unlock(&hio_##name##_list_lock);				\
207204076Spjd} while (0)
208204076Spjd
209209183Spjd#define	SYNCREQ(hio)		do {					\
210209183Spjd	(hio)->hio_ggio.gctl_unit = -1;					\
211209183Spjd	(hio)->hio_ggio.gctl_seq = 1;					\
212209183Spjd} while (0)
213204076Spjd#define	ISSYNCREQ(hio)		((hio)->hio_ggio.gctl_unit == -1)
214204076Spjd#define	SYNCREQDONE(hio)	do { (hio)->hio_ggio.gctl_unit = -2; } while (0)
215204076Spjd#define	ISSYNCREQDONE(hio)	((hio)->hio_ggio.gctl_unit == -2)
216204076Spjd
217204076Spjdstatic struct hast_resource *gres;
218204076Spjd
219204076Spjdstatic pthread_mutex_t range_lock;
220204076Spjdstatic struct rangelocks *range_regular;
221204076Spjdstatic bool range_regular_wait;
222204076Spjdstatic pthread_cond_t range_regular_cond;
223204076Spjdstatic struct rangelocks *range_sync;
224204076Spjdstatic bool range_sync_wait;
225204076Spjdstatic pthread_cond_t range_sync_cond;
226204076Spjd
227204076Spjdstatic void *ggate_recv_thread(void *arg);
228204076Spjdstatic void *local_send_thread(void *arg);
229204076Spjdstatic void *remote_send_thread(void *arg);
230204076Spjdstatic void *remote_recv_thread(void *arg);
231204076Spjdstatic void *ggate_send_thread(void *arg);
232204076Spjdstatic void *sync_thread(void *arg);
233204076Spjdstatic void *guard_thread(void *arg);
234204076Spjd
235211982Spjdstatic void
236204076Spjdcleanup(struct hast_resource *res)
237204076Spjd{
238204076Spjd	int rerrno;
239204076Spjd
240204076Spjd	/* Remember errno. */
241204076Spjd	rerrno = errno;
242204076Spjd
243204076Spjd	/* Destroy ggate provider if we created one. */
244204076Spjd	if (res->hr_ggateunit >= 0) {
245204076Spjd		struct g_gate_ctl_destroy ggiod;
246204076Spjd
247213533Spjd		bzero(&ggiod, sizeof(ggiod));
248204076Spjd		ggiod.gctl_version = G_GATE_VERSION;
249204076Spjd		ggiod.gctl_unit = res->hr_ggateunit;
250204076Spjd		ggiod.gctl_force = 1;
251204076Spjd		if (ioctl(res->hr_ggatefd, G_GATE_CMD_DESTROY, &ggiod) < 0) {
252213531Spjd			pjdlog_errno(LOG_WARNING,
253213531Spjd			    "Unable to destroy hast/%s device",
254204076Spjd			    res->hr_provname);
255204076Spjd		}
256204076Spjd		res->hr_ggateunit = -1;
257204076Spjd	}
258204076Spjd
259204076Spjd	/* Restore errno. */
260204076Spjd	errno = rerrno;
261204076Spjd}
262204076Spjd
263212899Spjdstatic __dead2 void
264204076Spjdprimary_exit(int exitcode, const char *fmt, ...)
265204076Spjd{
266204076Spjd	va_list ap;
267204076Spjd
268218138Spjd	PJDLOG_ASSERT(exitcode != EX_OK);
269204076Spjd	va_start(ap, fmt);
270204076Spjd	pjdlogv_errno(LOG_ERR, fmt, ap);
271204076Spjd	va_end(ap);
272204076Spjd	cleanup(gres);
273204076Spjd	exit(exitcode);
274204076Spjd}
275204076Spjd
276212899Spjdstatic __dead2 void
277204076Spjdprimary_exitx(int exitcode, const char *fmt, ...)
278204076Spjd{
279204076Spjd	va_list ap;
280204076Spjd
281204076Spjd	va_start(ap, fmt);
282204076Spjd	pjdlogv(exitcode == EX_OK ? LOG_INFO : LOG_ERR, fmt, ap);
283204076Spjd	va_end(ap);
284204076Spjd	cleanup(gres);
285204076Spjd	exit(exitcode);
286204076Spjd}
287204076Spjd
288204076Spjdstatic int
289204076Spjdhast_activemap_flush(struct hast_resource *res)
290204076Spjd{
291204076Spjd	const unsigned char *buf;
292204076Spjd	size_t size;
293204076Spjd
294204076Spjd	buf = activemap_bitmap(res->hr_amp, &size);
295218138Spjd	PJDLOG_ASSERT(buf != NULL);
296218138Spjd	PJDLOG_ASSERT((size % res->hr_local_sectorsize) == 0);
297204076Spjd	if (pwrite(res->hr_localfd, buf, size, METADATA_SIZE) !=
298204076Spjd	    (ssize_t)size) {
299204076Spjd		KEEP_ERRNO(pjdlog_errno(LOG_ERR,
300204076Spjd		    "Unable to flush activemap to disk"));
301204076Spjd		return (-1);
302204076Spjd	}
303204076Spjd	return (0);
304204076Spjd}
305204076Spjd
306210881Spjdstatic bool
307210881Spjdreal_remote(const struct hast_resource *res)
308210881Spjd{
309210881Spjd
310210881Spjd	return (strcmp(res->hr_remoteaddr, "none") != 0);
311210881Spjd}
312210881Spjd
313204076Spjdstatic void
314204076Spjdinit_environment(struct hast_resource *res __unused)
315204076Spjd{
316204076Spjd	struct hio *hio;
317204076Spjd	unsigned int ii, ncomps;
318204076Spjd
319204076Spjd	/*
320204076Spjd	 * In the future it might be per-resource value.
321204076Spjd	 */
322204076Spjd	ncomps = HAST_NCOMPONENTS;
323204076Spjd
324204076Spjd	/*
325204076Spjd	 * Allocate memory needed by lists.
326204076Spjd	 */
327204076Spjd	hio_send_list = malloc(sizeof(hio_send_list[0]) * ncomps);
328204076Spjd	if (hio_send_list == NULL) {
329204076Spjd		primary_exitx(EX_TEMPFAIL,
330204076Spjd		    "Unable to allocate %zu bytes of memory for send lists.",
331204076Spjd		    sizeof(hio_send_list[0]) * ncomps);
332204076Spjd	}
333204076Spjd	hio_send_list_lock = malloc(sizeof(hio_send_list_lock[0]) * ncomps);
334204076Spjd	if (hio_send_list_lock == NULL) {
335204076Spjd		primary_exitx(EX_TEMPFAIL,
336204076Spjd		    "Unable to allocate %zu bytes of memory for send list locks.",
337204076Spjd		    sizeof(hio_send_list_lock[0]) * ncomps);
338204076Spjd	}
339204076Spjd	hio_send_list_cond = malloc(sizeof(hio_send_list_cond[0]) * ncomps);
340204076Spjd	if (hio_send_list_cond == NULL) {
341204076Spjd		primary_exitx(EX_TEMPFAIL,
342204076Spjd		    "Unable to allocate %zu bytes of memory for send list condition variables.",
343204076Spjd		    sizeof(hio_send_list_cond[0]) * ncomps);
344204076Spjd	}
345204076Spjd	hio_recv_list = malloc(sizeof(hio_recv_list[0]) * ncomps);
346204076Spjd	if (hio_recv_list == NULL) {
347204076Spjd		primary_exitx(EX_TEMPFAIL,
348204076Spjd		    "Unable to allocate %zu bytes of memory for recv lists.",
349204076Spjd		    sizeof(hio_recv_list[0]) * ncomps);
350204076Spjd	}
351204076Spjd	hio_recv_list_lock = malloc(sizeof(hio_recv_list_lock[0]) * ncomps);
352204076Spjd	if (hio_recv_list_lock == NULL) {
353204076Spjd		primary_exitx(EX_TEMPFAIL,
354204076Spjd		    "Unable to allocate %zu bytes of memory for recv list locks.",
355204076Spjd		    sizeof(hio_recv_list_lock[0]) * ncomps);
356204076Spjd	}
357204076Spjd	hio_recv_list_cond = malloc(sizeof(hio_recv_list_cond[0]) * ncomps);
358204076Spjd	if (hio_recv_list_cond == NULL) {
359204076Spjd		primary_exitx(EX_TEMPFAIL,
360204076Spjd		    "Unable to allocate %zu bytes of memory for recv list condition variables.",
361204076Spjd		    sizeof(hio_recv_list_cond[0]) * ncomps);
362204076Spjd	}
363204076Spjd	hio_remote_lock = malloc(sizeof(hio_remote_lock[0]) * ncomps);
364204076Spjd	if (hio_remote_lock == NULL) {
365204076Spjd		primary_exitx(EX_TEMPFAIL,
366204076Spjd		    "Unable to allocate %zu bytes of memory for remote connections locks.",
367204076Spjd		    sizeof(hio_remote_lock[0]) * ncomps);
368204076Spjd	}
369204076Spjd
370204076Spjd	/*
371204076Spjd	 * Initialize lists, their locks and theirs condition variables.
372204076Spjd	 */
373204076Spjd	TAILQ_INIT(&hio_free_list);
374204076Spjd	mtx_init(&hio_free_list_lock);
375204076Spjd	cv_init(&hio_free_list_cond);
376204076Spjd	for (ii = 0; ii < HAST_NCOMPONENTS; ii++) {
377204076Spjd		TAILQ_INIT(&hio_send_list[ii]);
378204076Spjd		mtx_init(&hio_send_list_lock[ii]);
379204076Spjd		cv_init(&hio_send_list_cond[ii]);
380204076Spjd		TAILQ_INIT(&hio_recv_list[ii]);
381204076Spjd		mtx_init(&hio_recv_list_lock[ii]);
382204076Spjd		cv_init(&hio_recv_list_cond[ii]);
383204076Spjd		rw_init(&hio_remote_lock[ii]);
384204076Spjd	}
385204076Spjd	TAILQ_INIT(&hio_done_list);
386204076Spjd	mtx_init(&hio_done_list_lock);
387204076Spjd	cv_init(&hio_done_list_cond);
388204076Spjd	mtx_init(&metadata_lock);
389204076Spjd
390204076Spjd	/*
391204076Spjd	 * Allocate requests pool and initialize requests.
392204076Spjd	 */
393204076Spjd	for (ii = 0; ii < HAST_HIO_MAX; ii++) {
394204076Spjd		hio = malloc(sizeof(*hio));
395204076Spjd		if (hio == NULL) {
396204076Spjd			primary_exitx(EX_TEMPFAIL,
397204076Spjd			    "Unable to allocate %zu bytes of memory for hio request.",
398204076Spjd			    sizeof(*hio));
399204076Spjd		}
400204076Spjd		hio->hio_countdown = 0;
401204076Spjd		hio->hio_errors = malloc(sizeof(hio->hio_errors[0]) * ncomps);
402204076Spjd		if (hio->hio_errors == NULL) {
403204076Spjd			primary_exitx(EX_TEMPFAIL,
404204076Spjd			    "Unable allocate %zu bytes of memory for hio errors.",
405204076Spjd			    sizeof(hio->hio_errors[0]) * ncomps);
406204076Spjd		}
407204076Spjd		hio->hio_next = malloc(sizeof(hio->hio_next[0]) * ncomps);
408204076Spjd		if (hio->hio_next == NULL) {
409204076Spjd			primary_exitx(EX_TEMPFAIL,
410204076Spjd			    "Unable allocate %zu bytes of memory for hio_next field.",
411204076Spjd			    sizeof(hio->hio_next[0]) * ncomps);
412204076Spjd		}
413204076Spjd		hio->hio_ggio.gctl_version = G_GATE_VERSION;
414204076Spjd		hio->hio_ggio.gctl_data = malloc(MAXPHYS);
415204076Spjd		if (hio->hio_ggio.gctl_data == NULL) {
416204076Spjd			primary_exitx(EX_TEMPFAIL,
417204076Spjd			    "Unable to allocate %zu bytes of memory for gctl_data.",
418204076Spjd			    MAXPHYS);
419204076Spjd		}
420204076Spjd		hio->hio_ggio.gctl_length = MAXPHYS;
421204076Spjd		hio->hio_ggio.gctl_error = 0;
422204076Spjd		TAILQ_INSERT_HEAD(&hio_free_list, hio, hio_free_next);
423204076Spjd	}
424204076Spjd}
425204076Spjd
426214284Spjdstatic bool
427214284Spjdinit_resuid(struct hast_resource *res)
428214284Spjd{
429214284Spjd
430214284Spjd	mtx_lock(&metadata_lock);
431214284Spjd	if (res->hr_resuid != 0) {
432214284Spjd		mtx_unlock(&metadata_lock);
433214284Spjd		return (false);
434214284Spjd	} else {
435214284Spjd		/* Initialize unique resource identifier. */
436214284Spjd		arc4random_buf(&res->hr_resuid, sizeof(res->hr_resuid));
437214284Spjd		mtx_unlock(&metadata_lock);
438214284Spjd		if (metadata_write(res) < 0)
439214284Spjd			exit(EX_NOINPUT);
440214284Spjd		return (true);
441214284Spjd	}
442214284Spjd}
443214284Spjd
444204076Spjdstatic void
445204076Spjdinit_local(struct hast_resource *res)
446204076Spjd{
447204076Spjd	unsigned char *buf;
448204076Spjd	size_t mapsize;
449204076Spjd
450204076Spjd	if (metadata_read(res, true) < 0)
451204076Spjd		exit(EX_NOINPUT);
452204076Spjd	mtx_init(&res->hr_amp_lock);
453204076Spjd	if (activemap_init(&res->hr_amp, res->hr_datasize, res->hr_extentsize,
454204076Spjd	    res->hr_local_sectorsize, res->hr_keepdirty) < 0) {
455204076Spjd		primary_exit(EX_TEMPFAIL, "Unable to create activemap");
456204076Spjd	}
457204076Spjd	mtx_init(&range_lock);
458204076Spjd	cv_init(&range_regular_cond);
459204076Spjd	if (rangelock_init(&range_regular) < 0)
460204076Spjd		primary_exit(EX_TEMPFAIL, "Unable to create regular range lock");
461204076Spjd	cv_init(&range_sync_cond);
462204076Spjd	if (rangelock_init(&range_sync) < 0)
463204076Spjd		primary_exit(EX_TEMPFAIL, "Unable to create sync range lock");
464204076Spjd	mapsize = activemap_ondisk_size(res->hr_amp);
465204076Spjd	buf = calloc(1, mapsize);
466204076Spjd	if (buf == NULL) {
467204076Spjd		primary_exitx(EX_TEMPFAIL,
468204076Spjd		    "Unable to allocate buffer for activemap.");
469204076Spjd	}
470204076Spjd	if (pread(res->hr_localfd, buf, mapsize, METADATA_SIZE) !=
471204076Spjd	    (ssize_t)mapsize) {
472204076Spjd		primary_exit(EX_NOINPUT, "Unable to read activemap");
473204076Spjd	}
474204076Spjd	activemap_copyin(res->hr_amp, buf, mapsize);
475209181Spjd	free(buf);
476204076Spjd	if (res->hr_resuid != 0)
477204076Spjd		return;
478204076Spjd	/*
479214284Spjd	 * We're using provider for the first time. Initialize local and remote
480214284Spjd	 * counters. We don't initialize resuid here, as we want to do it just
481214284Spjd	 * in time. The reason for this is that we want to inform secondary
482214284Spjd	 * that there were no writes yet, so there is no need to synchronize
483214284Spjd	 * anything.
484204076Spjd	 */
485204076Spjd	res->hr_primary_localcnt = 1;
486204076Spjd	res->hr_primary_remotecnt = 0;
487204076Spjd	if (metadata_write(res) < 0)
488204076Spjd		exit(EX_NOINPUT);
489204076Spjd}
490204076Spjd
491205738Spjdstatic bool
492205738Spjdinit_remote(struct hast_resource *res, struct proto_conn **inp,
493205738Spjd    struct proto_conn **outp)
494204076Spjd{
495205738Spjd	struct proto_conn *in, *out;
496204076Spjd	struct nv *nvout, *nvin;
497204076Spjd	const unsigned char *token;
498204076Spjd	unsigned char *map;
499204076Spjd	const char *errmsg;
500204076Spjd	int32_t extentsize;
501204076Spjd	int64_t datasize;
502204076Spjd	uint32_t mapsize;
503204076Spjd	size_t size;
504204076Spjd
505218138Spjd	PJDLOG_ASSERT((inp == NULL && outp == NULL) || (inp != NULL && outp != NULL));
506218138Spjd	PJDLOG_ASSERT(real_remote(res));
507205738Spjd
508205738Spjd	in = out = NULL;
509211983Spjd	errmsg = NULL;
510205738Spjd
511204076Spjd	/* Prepare outgoing connection with remote node. */
512205738Spjd	if (proto_client(res->hr_remoteaddr, &out) < 0) {
513215331Spjd		primary_exit(EX_TEMPFAIL,
514215331Spjd		    "Unable to create outgoing connection to %s",
515204076Spjd		    res->hr_remoteaddr);
516204076Spjd	}
517204076Spjd	/* Try to connect, but accept failure. */
518218192Spjd	if (proto_connect(out, HAST_TIMEOUT) < 0) {
519204076Spjd		pjdlog_errno(LOG_WARNING, "Unable to connect to %s",
520204076Spjd		    res->hr_remoteaddr);
521204076Spjd		goto close;
522204076Spjd	}
523207371Spjd	/* Error in setting timeout is not critical, but why should it fail? */
524207371Spjd	if (proto_timeout(out, res->hr_timeout) < 0)
525207371Spjd		pjdlog_errno(LOG_WARNING, "Unable to set connection timeout");
526204076Spjd	/*
527204076Spjd	 * First handshake step.
528204076Spjd	 * Setup outgoing connection with remote node.
529204076Spjd	 */
530204076Spjd	nvout = nv_alloc();
531204076Spjd	nv_add_string(nvout, res->hr_name, "resource");
532204076Spjd	if (nv_error(nvout) != 0) {
533204076Spjd		pjdlog_common(LOG_WARNING, 0, nv_error(nvout),
534204076Spjd		    "Unable to allocate header for connection with %s",
535204076Spjd		    res->hr_remoteaddr);
536204076Spjd		nv_free(nvout);
537204076Spjd		goto close;
538204076Spjd	}
539205738Spjd	if (hast_proto_send(res, out, nvout, NULL, 0) < 0) {
540204076Spjd		pjdlog_errno(LOG_WARNING,
541204076Spjd		    "Unable to send handshake header to %s",
542204076Spjd		    res->hr_remoteaddr);
543204076Spjd		nv_free(nvout);
544204076Spjd		goto close;
545204076Spjd	}
546204076Spjd	nv_free(nvout);
547205738Spjd	if (hast_proto_recv_hdr(out, &nvin) < 0) {
548204076Spjd		pjdlog_errno(LOG_WARNING,
549204076Spjd		    "Unable to receive handshake header from %s",
550204076Spjd		    res->hr_remoteaddr);
551204076Spjd		goto close;
552204076Spjd	}
553204076Spjd	errmsg = nv_get_string(nvin, "errmsg");
554204076Spjd	if (errmsg != NULL) {
555204076Spjd		pjdlog_warning("%s", errmsg);
556204076Spjd		nv_free(nvin);
557204076Spjd		goto close;
558204076Spjd	}
559204076Spjd	token = nv_get_uint8_array(nvin, &size, "token");
560204076Spjd	if (token == NULL) {
561204076Spjd		pjdlog_warning("Handshake header from %s has no 'token' field.",
562204076Spjd		    res->hr_remoteaddr);
563204076Spjd		nv_free(nvin);
564204076Spjd		goto close;
565204076Spjd	}
566204076Spjd	if (size != sizeof(res->hr_token)) {
567204076Spjd		pjdlog_warning("Handshake header from %s contains 'token' of wrong size (got %zu, expected %zu).",
568204076Spjd		    res->hr_remoteaddr, size, sizeof(res->hr_token));
569204076Spjd		nv_free(nvin);
570204076Spjd		goto close;
571204076Spjd	}
572204076Spjd	bcopy(token, res->hr_token, sizeof(res->hr_token));
573204076Spjd	nv_free(nvin);
574204076Spjd
575204076Spjd	/*
576204076Spjd	 * Second handshake step.
577204076Spjd	 * Setup incoming connection with remote node.
578204076Spjd	 */
579205738Spjd	if (proto_client(res->hr_remoteaddr, &in) < 0) {
580215331Spjd		primary_exit(EX_TEMPFAIL,
581215331Spjd		    "Unable to create incoming connection to %s",
582204076Spjd		    res->hr_remoteaddr);
583204076Spjd	}
584204076Spjd	/* Try to connect, but accept failure. */
585218192Spjd	if (proto_connect(in, HAST_TIMEOUT) < 0) {
586204076Spjd		pjdlog_errno(LOG_WARNING, "Unable to connect to %s",
587204076Spjd		    res->hr_remoteaddr);
588204076Spjd		goto close;
589204076Spjd	}
590207371Spjd	/* Error in setting timeout is not critical, but why should it fail? */
591207371Spjd	if (proto_timeout(in, res->hr_timeout) < 0)
592207371Spjd		pjdlog_errno(LOG_WARNING, "Unable to set connection timeout");
593204076Spjd	nvout = nv_alloc();
594204076Spjd	nv_add_string(nvout, res->hr_name, "resource");
595204076Spjd	nv_add_uint8_array(nvout, res->hr_token, sizeof(res->hr_token),
596204076Spjd	    "token");
597214284Spjd	if (res->hr_resuid == 0) {
598214284Spjd		/*
599214284Spjd		 * The resuid field was not yet initialized.
600214284Spjd		 * Because we do synchronization inside init_resuid(), it is
601214284Spjd		 * possible that someone already initialized it, the function
602214284Spjd		 * will return false then, but if we successfully initialized
603214284Spjd		 * it, we will get true. True means that there were no writes
604214284Spjd		 * to this resource yet and we want to inform secondary that
605214284Spjd		 * synchronization is not needed by sending "virgin" argument.
606214284Spjd		 */
607214284Spjd		if (init_resuid(res))
608214284Spjd			nv_add_int8(nvout, 1, "virgin");
609214284Spjd	}
610204076Spjd	nv_add_uint64(nvout, res->hr_resuid, "resuid");
611204076Spjd	nv_add_uint64(nvout, res->hr_primary_localcnt, "localcnt");
612204076Spjd	nv_add_uint64(nvout, res->hr_primary_remotecnt, "remotecnt");
613204076Spjd	if (nv_error(nvout) != 0) {
614204076Spjd		pjdlog_common(LOG_WARNING, 0, nv_error(nvout),
615204076Spjd		    "Unable to allocate header for connection with %s",
616204076Spjd		    res->hr_remoteaddr);
617204076Spjd		nv_free(nvout);
618204076Spjd		goto close;
619204076Spjd	}
620205738Spjd	if (hast_proto_send(res, in, nvout, NULL, 0) < 0) {
621204076Spjd		pjdlog_errno(LOG_WARNING,
622204076Spjd		    "Unable to send handshake header to %s",
623204076Spjd		    res->hr_remoteaddr);
624204076Spjd		nv_free(nvout);
625204076Spjd		goto close;
626204076Spjd	}
627204076Spjd	nv_free(nvout);
628205738Spjd	if (hast_proto_recv_hdr(out, &nvin) < 0) {
629204076Spjd		pjdlog_errno(LOG_WARNING,
630204076Spjd		    "Unable to receive handshake header from %s",
631204076Spjd		    res->hr_remoteaddr);
632204076Spjd		goto close;
633204076Spjd	}
634204076Spjd	errmsg = nv_get_string(nvin, "errmsg");
635204076Spjd	if (errmsg != NULL) {
636204076Spjd		pjdlog_warning("%s", errmsg);
637204076Spjd		nv_free(nvin);
638204076Spjd		goto close;
639204076Spjd	}
640204076Spjd	datasize = nv_get_int64(nvin, "datasize");
641204076Spjd	if (datasize != res->hr_datasize) {
642204076Spjd		pjdlog_warning("Data size differs between nodes (local=%jd, remote=%jd).",
643204076Spjd		    (intmax_t)res->hr_datasize, (intmax_t)datasize);
644204076Spjd		nv_free(nvin);
645204076Spjd		goto close;
646204076Spjd	}
647204076Spjd	extentsize = nv_get_int32(nvin, "extentsize");
648204076Spjd	if (extentsize != res->hr_extentsize) {
649204076Spjd		pjdlog_warning("Extent size differs between nodes (local=%zd, remote=%zd).",
650204076Spjd		    (ssize_t)res->hr_extentsize, (ssize_t)extentsize);
651204076Spjd		nv_free(nvin);
652204076Spjd		goto close;
653204076Spjd	}
654204076Spjd	res->hr_secondary_localcnt = nv_get_uint64(nvin, "localcnt");
655204076Spjd	res->hr_secondary_remotecnt = nv_get_uint64(nvin, "remotecnt");
656204076Spjd	res->hr_syncsrc = nv_get_uint8(nvin, "syncsrc");
657204076Spjd	map = NULL;
658204076Spjd	mapsize = nv_get_uint32(nvin, "mapsize");
659204076Spjd	if (mapsize > 0) {
660204076Spjd		map = malloc(mapsize);
661204076Spjd		if (map == NULL) {
662204076Spjd			pjdlog_error("Unable to allocate memory for remote activemap (mapsize=%ju).",
663204076Spjd			    (uintmax_t)mapsize);
664204076Spjd			nv_free(nvin);
665204076Spjd			goto close;
666204076Spjd		}
667204076Spjd		/*
668204076Spjd		 * Remote node have some dirty extents on its own, lets
669204076Spjd		 * download its activemap.
670204076Spjd		 */
671205738Spjd		if (hast_proto_recv_data(res, out, nvin, map,
672204076Spjd		    mapsize) < 0) {
673204076Spjd			pjdlog_errno(LOG_ERR,
674204076Spjd			    "Unable to receive remote activemap");
675204076Spjd			nv_free(nvin);
676204076Spjd			free(map);
677204076Spjd			goto close;
678204076Spjd		}
679204076Spjd		/*
680204076Spjd		 * Merge local and remote bitmaps.
681204076Spjd		 */
682204076Spjd		activemap_merge(res->hr_amp, map, mapsize);
683204076Spjd		free(map);
684204076Spjd		/*
685204076Spjd		 * Now that we merged bitmaps from both nodes, flush it to the
686204076Spjd		 * disk before we start to synchronize.
687204076Spjd		 */
688204076Spjd		(void)hast_activemap_flush(res);
689204076Spjd	}
690214274Spjd	nv_free(nvin);
691204076Spjd	pjdlog_info("Connected to %s.", res->hr_remoteaddr);
692205738Spjd	if (inp != NULL && outp != NULL) {
693205738Spjd		*inp = in;
694205738Spjd		*outp = out;
695205738Spjd	} else {
696205738Spjd		res->hr_remotein = in;
697205738Spjd		res->hr_remoteout = out;
698205738Spjd	}
699212038Spjd	event_send(res, EVENT_CONNECT);
700205738Spjd	return (true);
701205738Spjdclose:
702211983Spjd	if (errmsg != NULL && strcmp(errmsg, "Split-brain condition!") == 0)
703212038Spjd		event_send(res, EVENT_SPLITBRAIN);
704205738Spjd	proto_close(out);
705205738Spjd	if (in != NULL)
706205738Spjd		proto_close(in);
707205738Spjd	return (false);
708205738Spjd}
709205738Spjd
710205738Spjdstatic void
711205738Spjdsync_start(void)
712205738Spjd{
713205738Spjd
714204076Spjd	mtx_lock(&sync_lock);
715204076Spjd	sync_inprogress = true;
716204076Spjd	mtx_unlock(&sync_lock);
717204076Spjd	cv_signal(&sync_cond);
718204076Spjd}
719204076Spjd
720204076Spjdstatic void
721211878Spjdsync_stop(void)
722211878Spjd{
723211878Spjd
724211878Spjd	mtx_lock(&sync_lock);
725211878Spjd	if (sync_inprogress)
726211878Spjd		sync_inprogress = false;
727211878Spjd	mtx_unlock(&sync_lock);
728211878Spjd}
729211878Spjd
730211878Spjdstatic void
731204076Spjdinit_ggate(struct hast_resource *res)
732204076Spjd{
733204076Spjd	struct g_gate_ctl_create ggiocreate;
734204076Spjd	struct g_gate_ctl_cancel ggiocancel;
735204076Spjd
736204076Spjd	/*
737204076Spjd	 * We communicate with ggate via /dev/ggctl. Open it.
738204076Spjd	 */
739204076Spjd	res->hr_ggatefd = open("/dev/" G_GATE_CTL_NAME, O_RDWR);
740204076Spjd	if (res->hr_ggatefd < 0)
741204076Spjd		primary_exit(EX_OSFILE, "Unable to open /dev/" G_GATE_CTL_NAME);
742204076Spjd	/*
743204076Spjd	 * Create provider before trying to connect, as connection failure
744204076Spjd	 * is not critical, but may take some time.
745204076Spjd	 */
746213533Spjd	bzero(&ggiocreate, sizeof(ggiocreate));
747204076Spjd	ggiocreate.gctl_version = G_GATE_VERSION;
748204076Spjd	ggiocreate.gctl_mediasize = res->hr_datasize;
749204076Spjd	ggiocreate.gctl_sectorsize = res->hr_local_sectorsize;
750204076Spjd	ggiocreate.gctl_flags = 0;
751206669Spjd	ggiocreate.gctl_maxcount = G_GATE_MAX_QUEUE_SIZE;
752204076Spjd	ggiocreate.gctl_timeout = 0;
753204076Spjd	ggiocreate.gctl_unit = G_GATE_NAME_GIVEN;
754204076Spjd	snprintf(ggiocreate.gctl_name, sizeof(ggiocreate.gctl_name), "hast/%s",
755204076Spjd	    res->hr_provname);
756204076Spjd	if (ioctl(res->hr_ggatefd, G_GATE_CMD_CREATE, &ggiocreate) == 0) {
757204076Spjd		pjdlog_info("Device hast/%s created.", res->hr_provname);
758204076Spjd		res->hr_ggateunit = ggiocreate.gctl_unit;
759204076Spjd		return;
760204076Spjd	}
761204076Spjd	if (errno != EEXIST) {
762204076Spjd		primary_exit(EX_OSERR, "Unable to create hast/%s device",
763204076Spjd		    res->hr_provname);
764204076Spjd	}
765204076Spjd	pjdlog_debug(1,
766204076Spjd	    "Device hast/%s already exists, we will try to take it over.",
767204076Spjd	    res->hr_provname);
768204076Spjd	/*
769204076Spjd	 * If we received EEXIST, we assume that the process who created the
770204076Spjd	 * provider died and didn't clean up. In that case we will start from
771204076Spjd	 * where he left of.
772204076Spjd	 */
773213533Spjd	bzero(&ggiocancel, sizeof(ggiocancel));
774204076Spjd	ggiocancel.gctl_version = G_GATE_VERSION;
775204076Spjd	ggiocancel.gctl_unit = G_GATE_NAME_GIVEN;
776204076Spjd	snprintf(ggiocancel.gctl_name, sizeof(ggiocancel.gctl_name), "hast/%s",
777204076Spjd	    res->hr_provname);
778204076Spjd	if (ioctl(res->hr_ggatefd, G_GATE_CMD_CANCEL, &ggiocancel) == 0) {
779204076Spjd		pjdlog_info("Device hast/%s recovered.", res->hr_provname);
780204076Spjd		res->hr_ggateunit = ggiocancel.gctl_unit;
781204076Spjd		return;
782204076Spjd	}
783204076Spjd	primary_exit(EX_OSERR, "Unable to take over hast/%s device",
784204076Spjd	    res->hr_provname);
785204076Spjd}
786204076Spjd
787204076Spjdvoid
788204076Spjdhastd_primary(struct hast_resource *res)
789204076Spjd{
790204076Spjd	pthread_t td;
791204076Spjd	pid_t pid;
792218043Spjd	int error, mode;
793204076Spjd
794204076Spjd	/*
795204076Spjd	 * Create communication channel between parent and child.
796204076Spjd	 */
797204076Spjd	if (proto_client("socketpair://", &res->hr_ctrl) < 0) {
798218042Spjd		/* TODO: There's no need for this to be fatal error. */
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) {
807218042Spjd		/* TODO: There's no need for this to be fatal error. */
808212038Spjd		KEEP_ERRNO((void)pidfile_remove(pfh));
809212038Spjd		pjdlog_exit(EX_OSERR,
810212038Spjd		    "Unable to create event sockets between child and parent");
811212038Spjd	}
812204076Spjd
813204076Spjd	pid = fork();
814204076Spjd	if (pid < 0) {
815218042Spjd		/* TODO: There's no need for this to be fatal error. */
816204076Spjd		KEEP_ERRNO((void)pidfile_remove(pfh));
817212034Spjd		pjdlog_exit(EX_TEMPFAIL, "Unable to fork");
818204076Spjd	}
819204076Spjd
820204076Spjd	if (pid > 0) {
821204076Spjd		/* This is parent. */
822212038Spjd		/* Declare that we are receiver. */
823212038Spjd		proto_recv(res->hr_event, NULL, 0);
824218043Spjd		/* Declare that we are sender. */
825218043Spjd		proto_send(res->hr_ctrl, NULL, 0);
826204076Spjd		res->hr_workerpid = pid;
827204076Spjd		return;
828204076Spjd	}
829211977Spjd
830211984Spjd	gres = res;
831218043Spjd	mode = pjdlog_mode_get();
832211984Spjd
833218043Spjd	/* Declare that we are sender. */
834218043Spjd	proto_send(res->hr_event, NULL, 0);
835218043Spjd	/* Declare that we are receiver. */
836218043Spjd	proto_recv(res->hr_ctrl, NULL, 0);
837218043Spjd	descriptors_cleanup(res);
838204076Spjd
839218045Spjd	descriptors_assert(res, mode);
840218045Spjd
841218043Spjd	pjdlog_init(mode);
842218043Spjd	pjdlog_prefix_set("[%s] (%s) ", res->hr_name, role2str(res->hr_role));
843204076Spjd	setproctitle("%s (primary)", res->hr_name);
844204076Spjd
845204076Spjd	init_local(res);
846213007Spjd	init_ggate(res);
847213007Spjd	init_environment(res);
848217784Spjd
849218049Spjd	if (drop_privs() != 0) {
850218049Spjd		cleanup(res);
851218049Spjd		exit(EX_CONFIG);
852218049Spjd	}
853218214Spjd	pjdlog_info("Privileges successfully dropped.");
854218049Spjd
855213007Spjd	/*
856213530Spjd	 * Create the guard thread first, so we can handle signals from the
857213530Spjd	 * very begining.
858213530Spjd	 */
859213530Spjd	error = pthread_create(&td, NULL, guard_thread, res);
860218138Spjd	PJDLOG_ASSERT(error == 0);
861213530Spjd	/*
862213007Spjd	 * Create the control thread before sending any event to the parent,
863213007Spjd	 * as we can deadlock when parent sends control request to worker,
864213007Spjd	 * but worker has no control thread started yet, so parent waits.
865213007Spjd	 * In the meantime worker sends an event to the parent, but parent
866213007Spjd	 * is unable to handle the event, because it waits for control
867213007Spjd	 * request response.
868213007Spjd	 */
869213007Spjd	error = pthread_create(&td, NULL, ctrl_thread, res);
870218138Spjd	PJDLOG_ASSERT(error == 0);
871210881Spjd	if (real_remote(res) && init_remote(res, NULL, NULL))
872205738Spjd		sync_start();
873204076Spjd	error = pthread_create(&td, NULL, ggate_recv_thread, res);
874218138Spjd	PJDLOG_ASSERT(error == 0);
875204076Spjd	error = pthread_create(&td, NULL, local_send_thread, res);
876218138Spjd	PJDLOG_ASSERT(error == 0);
877204076Spjd	error = pthread_create(&td, NULL, remote_send_thread, res);
878218138Spjd	PJDLOG_ASSERT(error == 0);
879204076Spjd	error = pthread_create(&td, NULL, remote_recv_thread, res);
880218138Spjd	PJDLOG_ASSERT(error == 0);
881204076Spjd	error = pthread_create(&td, NULL, ggate_send_thread, res);
882218138Spjd	PJDLOG_ASSERT(error == 0);
883213530Spjd	(void)sync_thread(res);
884204076Spjd}
885204076Spjd
886204076Spjdstatic void
887204076Spjdreqlog(int loglevel, int debuglevel, struct g_gate_ctl_io *ggio, const char *fmt, ...)
888204076Spjd{
889204076Spjd	char msg[1024];
890204076Spjd	va_list ap;
891204076Spjd	int len;
892204076Spjd
893204076Spjd	va_start(ap, fmt);
894204076Spjd	len = vsnprintf(msg, sizeof(msg), fmt, ap);
895204076Spjd	va_end(ap);
896204076Spjd	if ((size_t)len < sizeof(msg)) {
897204076Spjd		switch (ggio->gctl_cmd) {
898204076Spjd		case BIO_READ:
899204076Spjd			(void)snprintf(msg + len, sizeof(msg) - len,
900204076Spjd			    "READ(%ju, %ju).", (uintmax_t)ggio->gctl_offset,
901204076Spjd			    (uintmax_t)ggio->gctl_length);
902204076Spjd			break;
903204076Spjd		case BIO_DELETE:
904204076Spjd			(void)snprintf(msg + len, sizeof(msg) - len,
905204076Spjd			    "DELETE(%ju, %ju).", (uintmax_t)ggio->gctl_offset,
906204076Spjd			    (uintmax_t)ggio->gctl_length);
907204076Spjd			break;
908204076Spjd		case BIO_FLUSH:
909204076Spjd			(void)snprintf(msg + len, sizeof(msg) - len, "FLUSH.");
910204076Spjd			break;
911204076Spjd		case BIO_WRITE:
912204076Spjd			(void)snprintf(msg + len, sizeof(msg) - len,
913204076Spjd			    "WRITE(%ju, %ju).", (uintmax_t)ggio->gctl_offset,
914204076Spjd			    (uintmax_t)ggio->gctl_length);
915204076Spjd			break;
916204076Spjd		default:
917204076Spjd			(void)snprintf(msg + len, sizeof(msg) - len,
918204076Spjd			    "UNKNOWN(%u).", (unsigned int)ggio->gctl_cmd);
919204076Spjd			break;
920204076Spjd		}
921204076Spjd	}
922204076Spjd	pjdlog_common(loglevel, debuglevel, -1, "%s", msg);
923204076Spjd}
924204076Spjd
925204076Spjdstatic void
926204076Spjdremote_close(struct hast_resource *res, int ncomp)
927204076Spjd{
928204076Spjd
929204076Spjd	rw_wlock(&hio_remote_lock[ncomp]);
930204076Spjd	/*
931204076Spjd	 * A race is possible between dropping rlock and acquiring wlock -
932204076Spjd	 * another thread can close connection in-between.
933204076Spjd	 */
934204076Spjd	if (!ISCONNECTED(res, ncomp)) {
935218138Spjd		PJDLOG_ASSERT(res->hr_remotein == NULL);
936218138Spjd		PJDLOG_ASSERT(res->hr_remoteout == NULL);
937204076Spjd		rw_unlock(&hio_remote_lock[ncomp]);
938204076Spjd		return;
939204076Spjd	}
940204076Spjd
941218138Spjd	PJDLOG_ASSERT(res->hr_remotein != NULL);
942218138Spjd	PJDLOG_ASSERT(res->hr_remoteout != NULL);
943204076Spjd
944211881Spjd	pjdlog_debug(2, "Closing incoming connection to %s.",
945204076Spjd	    res->hr_remoteaddr);
946204076Spjd	proto_close(res->hr_remotein);
947204076Spjd	res->hr_remotein = NULL;
948211881Spjd	pjdlog_debug(2, "Closing outgoing connection to %s.",
949204076Spjd	    res->hr_remoteaddr);
950204076Spjd	proto_close(res->hr_remoteout);
951204076Spjd	res->hr_remoteout = NULL;
952204076Spjd
953204076Spjd	rw_unlock(&hio_remote_lock[ncomp]);
954204076Spjd
955211881Spjd	pjdlog_warning("Disconnected from %s.", res->hr_remoteaddr);
956211881Spjd
957204076Spjd	/*
958204076Spjd	 * Stop synchronization if in-progress.
959204076Spjd	 */
960211878Spjd	sync_stop();
961211984Spjd
962212038Spjd	event_send(res, EVENT_DISCONNECT);
963204076Spjd}
964204076Spjd
965204076Spjd/*
966204076Spjd * Thread receives ggate I/O requests from the kernel and passes them to
967204076Spjd * appropriate threads:
968204076Spjd * WRITE - always goes to both local_send and remote_send threads
969204076Spjd * READ (when the block is up-to-date on local component) -
970204076Spjd *	only local_send thread
971204076Spjd * READ (when the block isn't up-to-date on local component) -
972204076Spjd *	only remote_send thread
973204076Spjd * DELETE - always goes to both local_send and remote_send threads
974204076Spjd * FLUSH - always goes to both local_send and remote_send threads
975204076Spjd */
976204076Spjdstatic void *
977204076Spjdggate_recv_thread(void *arg)
978204076Spjd{
979204076Spjd	struct hast_resource *res = arg;
980204076Spjd	struct g_gate_ctl_io *ggio;
981204076Spjd	struct hio *hio;
982204076Spjd	unsigned int ii, ncomp, ncomps;
983204076Spjd	int error;
984204076Spjd
985204076Spjd	ncomps = HAST_NCOMPONENTS;
986204076Spjd
987204076Spjd	for (;;) {
988204076Spjd		pjdlog_debug(2, "ggate_recv: Taking free request.");
989204076Spjd		QUEUE_TAKE2(hio, free);
990204076Spjd		pjdlog_debug(2, "ggate_recv: (%p) Got free request.", hio);
991204076Spjd		ggio = &hio->hio_ggio;
992204076Spjd		ggio->gctl_unit = res->hr_ggateunit;
993204076Spjd		ggio->gctl_length = MAXPHYS;
994204076Spjd		ggio->gctl_error = 0;
995204076Spjd		pjdlog_debug(2,
996204076Spjd		    "ggate_recv: (%p) Waiting for request from the kernel.",
997204076Spjd		    hio);
998204076Spjd		if (ioctl(res->hr_ggatefd, G_GATE_CMD_START, ggio) < 0) {
999204076Spjd			if (sigexit_received)
1000204076Spjd				pthread_exit(NULL);
1001204076Spjd			primary_exit(EX_OSERR, "G_GATE_CMD_START failed");
1002204076Spjd		}
1003204076Spjd		error = ggio->gctl_error;
1004204076Spjd		switch (error) {
1005204076Spjd		case 0:
1006204076Spjd			break;
1007204076Spjd		case ECANCELED:
1008204076Spjd			/* Exit gracefully. */
1009204076Spjd			if (!sigexit_received) {
1010204076Spjd				pjdlog_debug(2,
1011204076Spjd				    "ggate_recv: (%p) Received cancel from the kernel.",
1012204076Spjd				    hio);
1013204076Spjd				pjdlog_info("Received cancel from the kernel, exiting.");
1014204076Spjd			}
1015204076Spjd			pthread_exit(NULL);
1016204076Spjd		case ENOMEM:
1017204076Spjd			/*
1018204076Spjd			 * Buffer too small? Impossible, we allocate MAXPHYS
1019204076Spjd			 * bytes - request can't be bigger than that.
1020204076Spjd			 */
1021204076Spjd			/* FALLTHROUGH */
1022204076Spjd		case ENXIO:
1023204076Spjd		default:
1024204076Spjd			primary_exitx(EX_OSERR, "G_GATE_CMD_START failed: %s.",
1025204076Spjd			    strerror(error));
1026204076Spjd		}
1027204076Spjd		for (ii = 0; ii < ncomps; ii++)
1028204076Spjd			hio->hio_errors[ii] = EINVAL;
1029204076Spjd		reqlog(LOG_DEBUG, 2, ggio,
1030204076Spjd		    "ggate_recv: (%p) Request received from the kernel: ",
1031204076Spjd		    hio);
1032204076Spjd		/*
1033204076Spjd		 * Inform all components about new write request.
1034204076Spjd		 * For read request prefer local component unless the given
1035204076Spjd		 * range is out-of-date, then use remote component.
1036204076Spjd		 */
1037204076Spjd		switch (ggio->gctl_cmd) {
1038204076Spjd		case BIO_READ:
1039204076Spjd			pjdlog_debug(2,
1040204076Spjd			    "ggate_recv: (%p) Moving request to the send queue.",
1041204076Spjd			    hio);
1042204076Spjd			refcount_init(&hio->hio_countdown, 1);
1043204076Spjd			mtx_lock(&metadata_lock);
1044204076Spjd			if (res->hr_syncsrc == HAST_SYNCSRC_UNDEF ||
1045204076Spjd			    res->hr_syncsrc == HAST_SYNCSRC_PRIMARY) {
1046204076Spjd				/*
1047204076Spjd				 * This range is up-to-date on local component,
1048204076Spjd				 * so handle request locally.
1049204076Spjd				 */
1050204076Spjd				 /* Local component is 0 for now. */
1051204076Spjd				ncomp = 0;
1052204076Spjd			} else /* if (res->hr_syncsrc ==
1053204076Spjd			    HAST_SYNCSRC_SECONDARY) */ {
1054218138Spjd				PJDLOG_ASSERT(res->hr_syncsrc ==
1055204076Spjd				    HAST_SYNCSRC_SECONDARY);
1056204076Spjd				/*
1057204076Spjd				 * This range is out-of-date on local component,
1058204076Spjd				 * so send request to the remote node.
1059204076Spjd				 */
1060204076Spjd				 /* Remote component is 1 for now. */
1061204076Spjd				ncomp = 1;
1062204076Spjd			}
1063204076Spjd			mtx_unlock(&metadata_lock);
1064204076Spjd			QUEUE_INSERT1(hio, send, ncomp);
1065204076Spjd			break;
1066204076Spjd		case BIO_WRITE:
1067214284Spjd			if (res->hr_resuid == 0) {
1068214284Spjd				/* This is first write, initialize resuid. */
1069214284Spjd				(void)init_resuid(res);
1070214284Spjd			}
1071204076Spjd			for (;;) {
1072204076Spjd				mtx_lock(&range_lock);
1073204076Spjd				if (rangelock_islocked(range_sync,
1074204076Spjd				    ggio->gctl_offset, ggio->gctl_length)) {
1075204076Spjd					pjdlog_debug(2,
1076204076Spjd					    "regular: Range offset=%jd length=%zu locked.",
1077204076Spjd					    (intmax_t)ggio->gctl_offset,
1078204076Spjd					    (size_t)ggio->gctl_length);
1079204076Spjd					range_regular_wait = true;
1080204076Spjd					cv_wait(&range_regular_cond, &range_lock);
1081204076Spjd					range_regular_wait = false;
1082204076Spjd					mtx_unlock(&range_lock);
1083204076Spjd					continue;
1084204076Spjd				}
1085204076Spjd				if (rangelock_add(range_regular,
1086204076Spjd				    ggio->gctl_offset, ggio->gctl_length) < 0) {
1087204076Spjd					mtx_unlock(&range_lock);
1088204076Spjd					pjdlog_debug(2,
1089204076Spjd					    "regular: Range offset=%jd length=%zu is already locked, waiting.",
1090204076Spjd					    (intmax_t)ggio->gctl_offset,
1091204076Spjd					    (size_t)ggio->gctl_length);
1092204076Spjd					sleep(1);
1093204076Spjd					continue;
1094204076Spjd				}
1095204076Spjd				mtx_unlock(&range_lock);
1096204076Spjd				break;
1097204076Spjd			}
1098204076Spjd			mtx_lock(&res->hr_amp_lock);
1099204076Spjd			if (activemap_write_start(res->hr_amp,
1100204076Spjd			    ggio->gctl_offset, ggio->gctl_length)) {
1101204076Spjd				(void)hast_activemap_flush(res);
1102204076Spjd			}
1103204076Spjd			mtx_unlock(&res->hr_amp_lock);
1104204076Spjd			/* FALLTHROUGH */
1105204076Spjd		case BIO_DELETE:
1106204076Spjd		case BIO_FLUSH:
1107204076Spjd			pjdlog_debug(2,
1108204076Spjd			    "ggate_recv: (%p) Moving request to the send queues.",
1109204076Spjd			    hio);
1110204076Spjd			refcount_init(&hio->hio_countdown, ncomps);
1111204076Spjd			for (ii = 0; ii < ncomps; ii++)
1112204076Spjd				QUEUE_INSERT1(hio, send, ii);
1113204076Spjd			break;
1114204076Spjd		}
1115204076Spjd	}
1116204076Spjd	/* NOTREACHED */
1117204076Spjd	return (NULL);
1118204076Spjd}
1119204076Spjd
1120204076Spjd/*
1121204076Spjd * Thread reads from or writes to local component.
1122204076Spjd * If local read fails, it redirects it to remote_send thread.
1123204076Spjd */
1124204076Spjdstatic void *
1125204076Spjdlocal_send_thread(void *arg)
1126204076Spjd{
1127204076Spjd	struct hast_resource *res = arg;
1128204076Spjd	struct g_gate_ctl_io *ggio;
1129204076Spjd	struct hio *hio;
1130204076Spjd	unsigned int ncomp, rncomp;
1131204076Spjd	ssize_t ret;
1132204076Spjd
1133204076Spjd	/* Local component is 0 for now. */
1134204076Spjd	ncomp = 0;
1135204076Spjd	/* Remote component is 1 for now. */
1136204076Spjd	rncomp = 1;
1137204076Spjd
1138204076Spjd	for (;;) {
1139204076Spjd		pjdlog_debug(2, "local_send: Taking request.");
1140214692Spjd		QUEUE_TAKE1(hio, send, ncomp, 0);
1141204076Spjd		pjdlog_debug(2, "local_send: (%p) Got request.", hio);
1142204076Spjd		ggio = &hio->hio_ggio;
1143204076Spjd		switch (ggio->gctl_cmd) {
1144204076Spjd		case BIO_READ:
1145204076Spjd			ret = pread(res->hr_localfd, ggio->gctl_data,
1146204076Spjd			    ggio->gctl_length,
1147204076Spjd			    ggio->gctl_offset + res->hr_localoff);
1148204076Spjd			if (ret == ggio->gctl_length)
1149204076Spjd				hio->hio_errors[ncomp] = 0;
1150204076Spjd			else {
1151204076Spjd				/*
1152204076Spjd				 * If READ failed, try to read from remote node.
1153204076Spjd				 */
1154216479Spjd				if (ret < 0) {
1155216479Spjd					reqlog(LOG_WARNING, 0, ggio,
1156216479Spjd					    "Local request failed (%s), trying remote node. ",
1157216479Spjd					    strerror(errno));
1158216479Spjd				} else if (ret != ggio->gctl_length) {
1159216479Spjd					reqlog(LOG_WARNING, 0, ggio,
1160216479Spjd					    "Local request failed (%zd != %jd), trying remote node. ",
1161216494Spjd					    ret, (intmax_t)ggio->gctl_length);
1162216479Spjd				}
1163204076Spjd				QUEUE_INSERT1(hio, send, rncomp);
1164204076Spjd				continue;
1165204076Spjd			}
1166204076Spjd			break;
1167204076Spjd		case BIO_WRITE:
1168204076Spjd			ret = pwrite(res->hr_localfd, ggio->gctl_data,
1169204076Spjd			    ggio->gctl_length,
1170204076Spjd			    ggio->gctl_offset + res->hr_localoff);
1171216479Spjd			if (ret < 0) {
1172204076Spjd				hio->hio_errors[ncomp] = errno;
1173216479Spjd				reqlog(LOG_WARNING, 0, ggio,
1174216479Spjd				    "Local request failed (%s): ",
1175216479Spjd				    strerror(errno));
1176216479Spjd			} else if (ret != ggio->gctl_length) {
1177204076Spjd				hio->hio_errors[ncomp] = EIO;
1178216479Spjd				reqlog(LOG_WARNING, 0, ggio,
1179216479Spjd				    "Local request failed (%zd != %jd): ",
1180216494Spjd				    ret, (intmax_t)ggio->gctl_length);
1181216479Spjd			} else {
1182204076Spjd				hio->hio_errors[ncomp] = 0;
1183216479Spjd			}
1184204076Spjd			break;
1185204076Spjd		case BIO_DELETE:
1186204076Spjd			ret = g_delete(res->hr_localfd,
1187204076Spjd			    ggio->gctl_offset + res->hr_localoff,
1188204076Spjd			    ggio->gctl_length);
1189216479Spjd			if (ret < 0) {
1190204076Spjd				hio->hio_errors[ncomp] = errno;
1191216479Spjd				reqlog(LOG_WARNING, 0, ggio,
1192216479Spjd				    "Local request failed (%s): ",
1193216479Spjd				    strerror(errno));
1194216479Spjd			} else {
1195204076Spjd				hio->hio_errors[ncomp] = 0;
1196216479Spjd			}
1197204076Spjd			break;
1198204076Spjd		case BIO_FLUSH:
1199204076Spjd			ret = g_flush(res->hr_localfd);
1200216479Spjd			if (ret < 0) {
1201204076Spjd				hio->hio_errors[ncomp] = errno;
1202216479Spjd				reqlog(LOG_WARNING, 0, ggio,
1203216479Spjd				    "Local request failed (%s): ",
1204216479Spjd				    strerror(errno));
1205216479Spjd			} else {
1206204076Spjd				hio->hio_errors[ncomp] = 0;
1207216479Spjd			}
1208204076Spjd			break;
1209204076Spjd		}
1210204076Spjd		if (refcount_release(&hio->hio_countdown)) {
1211204076Spjd			if (ISSYNCREQ(hio)) {
1212204076Spjd				mtx_lock(&sync_lock);
1213204076Spjd				SYNCREQDONE(hio);
1214204076Spjd				mtx_unlock(&sync_lock);
1215204076Spjd				cv_signal(&sync_cond);
1216204076Spjd			} else {
1217204076Spjd				pjdlog_debug(2,
1218204076Spjd				    "local_send: (%p) Moving request to the done queue.",
1219204076Spjd				    hio);
1220204076Spjd				QUEUE_INSERT2(hio, done);
1221204076Spjd			}
1222204076Spjd		}
1223204076Spjd	}
1224204076Spjd	/* NOTREACHED */
1225204076Spjd	return (NULL);
1226204076Spjd}
1227204076Spjd
1228214692Spjdstatic void
1229214692Spjdkeepalive_send(struct hast_resource *res, unsigned int ncomp)
1230214692Spjd{
1231214692Spjd	struct nv *nv;
1232214692Spjd
1233214692Spjd	if (!ISCONNECTED(res, ncomp))
1234214692Spjd		return;
1235214692Spjd
1236218138Spjd	PJDLOG_ASSERT(res->hr_remotein != NULL);
1237218138Spjd	PJDLOG_ASSERT(res->hr_remoteout != NULL);
1238214692Spjd
1239214692Spjd	nv = nv_alloc();
1240214692Spjd	nv_add_uint8(nv, HIO_KEEPALIVE, "cmd");
1241214692Spjd	if (nv_error(nv) != 0) {
1242214692Spjd		nv_free(nv);
1243214692Spjd		pjdlog_debug(1,
1244214692Spjd		    "keepalive_send: Unable to prepare header to send.");
1245214692Spjd		return;
1246214692Spjd	}
1247214692Spjd	if (hast_proto_send(res, res->hr_remoteout, nv, NULL, 0) < 0) {
1248214692Spjd		pjdlog_common(LOG_DEBUG, 1, errno,
1249214692Spjd		    "keepalive_send: Unable to send request");
1250214692Spjd		nv_free(nv);
1251214692Spjd		rw_unlock(&hio_remote_lock[ncomp]);
1252214692Spjd		remote_close(res, ncomp);
1253214692Spjd		rw_rlock(&hio_remote_lock[ncomp]);
1254214692Spjd		return;
1255214692Spjd	}
1256214692Spjd	nv_free(nv);
1257214692Spjd	pjdlog_debug(2, "keepalive_send: Request sent.");
1258214692Spjd}
1259214692Spjd
1260204076Spjd/*
1261204076Spjd * Thread sends request to secondary node.
1262204076Spjd */
1263204076Spjdstatic void *
1264204076Spjdremote_send_thread(void *arg)
1265204076Spjd{
1266204076Spjd	struct hast_resource *res = arg;
1267204076Spjd	struct g_gate_ctl_io *ggio;
1268214692Spjd	time_t lastcheck, now;
1269204076Spjd	struct hio *hio;
1270204076Spjd	struct nv *nv;
1271204076Spjd	unsigned int ncomp;
1272204076Spjd	bool wakeup;
1273204076Spjd	uint64_t offset, length;
1274204076Spjd	uint8_t cmd;
1275204076Spjd	void *data;
1276204076Spjd
1277204076Spjd	/* Remote component is 1 for now. */
1278204076Spjd	ncomp = 1;
1279214692Spjd	lastcheck = time(NULL);
1280204076Spjd
1281204076Spjd	for (;;) {
1282204076Spjd		pjdlog_debug(2, "remote_send: Taking request.");
1283214692Spjd		QUEUE_TAKE1(hio, send, ncomp, RETRY_SLEEP);
1284214692Spjd		if (hio == NULL) {
1285214692Spjd			now = time(NULL);
1286214692Spjd			if (lastcheck + RETRY_SLEEP <= now) {
1287214692Spjd				keepalive_send(res, ncomp);
1288214692Spjd				lastcheck = now;
1289214692Spjd			}
1290214692Spjd			continue;
1291214692Spjd		}
1292204076Spjd		pjdlog_debug(2, "remote_send: (%p) Got request.", hio);
1293204076Spjd		ggio = &hio->hio_ggio;
1294204076Spjd		switch (ggio->gctl_cmd) {
1295204076Spjd		case BIO_READ:
1296204076Spjd			cmd = HIO_READ;
1297204076Spjd			data = NULL;
1298204076Spjd			offset = ggio->gctl_offset;
1299204076Spjd			length = ggio->gctl_length;
1300204076Spjd			break;
1301204076Spjd		case BIO_WRITE:
1302204076Spjd			cmd = HIO_WRITE;
1303204076Spjd			data = ggio->gctl_data;
1304204076Spjd			offset = ggio->gctl_offset;
1305204076Spjd			length = ggio->gctl_length;
1306204076Spjd			break;
1307204076Spjd		case BIO_DELETE:
1308204076Spjd			cmd = HIO_DELETE;
1309204076Spjd			data = NULL;
1310204076Spjd			offset = ggio->gctl_offset;
1311204076Spjd			length = ggio->gctl_length;
1312204076Spjd			break;
1313204076Spjd		case BIO_FLUSH:
1314204076Spjd			cmd = HIO_FLUSH;
1315204076Spjd			data = NULL;
1316204076Spjd			offset = 0;
1317204076Spjd			length = 0;
1318204076Spjd			break;
1319204076Spjd		default:
1320218138Spjd			PJDLOG_ASSERT(!"invalid condition");
1321204076Spjd			abort();
1322204076Spjd		}
1323204076Spjd		nv = nv_alloc();
1324204076Spjd		nv_add_uint8(nv, cmd, "cmd");
1325204076Spjd		nv_add_uint64(nv, (uint64_t)ggio->gctl_seq, "seq");
1326204076Spjd		nv_add_uint64(nv, offset, "offset");
1327204076Spjd		nv_add_uint64(nv, length, "length");
1328204076Spjd		if (nv_error(nv) != 0) {
1329204076Spjd			hio->hio_errors[ncomp] = nv_error(nv);
1330204076Spjd			pjdlog_debug(2,
1331204076Spjd			    "remote_send: (%p) Unable to prepare header to send.",
1332204076Spjd			    hio);
1333204076Spjd			reqlog(LOG_ERR, 0, ggio,
1334204076Spjd			    "Unable to prepare header to send (%s): ",
1335204076Spjd			    strerror(nv_error(nv)));
1336204076Spjd			/* Move failed request immediately to the done queue. */
1337204076Spjd			goto done_queue;
1338204076Spjd		}
1339204076Spjd		pjdlog_debug(2,
1340204076Spjd		    "remote_send: (%p) Moving request to the recv queue.",
1341204076Spjd		    hio);
1342204076Spjd		/*
1343204076Spjd		 * Protect connection from disappearing.
1344204076Spjd		 */
1345204076Spjd		rw_rlock(&hio_remote_lock[ncomp]);
1346204076Spjd		if (!ISCONNECTED(res, ncomp)) {
1347204076Spjd			rw_unlock(&hio_remote_lock[ncomp]);
1348204076Spjd			hio->hio_errors[ncomp] = ENOTCONN;
1349204076Spjd			goto done_queue;
1350204076Spjd		}
1351204076Spjd		/*
1352204076Spjd		 * Move the request to recv queue before sending it, because
1353204076Spjd		 * in different order we can get reply before we move request
1354204076Spjd		 * to recv queue.
1355204076Spjd		 */
1356204076Spjd		mtx_lock(&hio_recv_list_lock[ncomp]);
1357204076Spjd		wakeup = TAILQ_EMPTY(&hio_recv_list[ncomp]);
1358204076Spjd		TAILQ_INSERT_TAIL(&hio_recv_list[ncomp], hio, hio_next[ncomp]);
1359204076Spjd		mtx_unlock(&hio_recv_list_lock[ncomp]);
1360204076Spjd		if (hast_proto_send(res, res->hr_remoteout, nv, data,
1361204076Spjd		    data != NULL ? length : 0) < 0) {
1362204076Spjd			hio->hio_errors[ncomp] = errno;
1363204076Spjd			rw_unlock(&hio_remote_lock[ncomp]);
1364204076Spjd			pjdlog_debug(2,
1365204076Spjd			    "remote_send: (%p) Unable to send request.", hio);
1366204076Spjd			reqlog(LOG_ERR, 0, ggio,
1367204076Spjd			    "Unable to send request (%s): ",
1368204076Spjd			    strerror(hio->hio_errors[ncomp]));
1369211979Spjd			remote_close(res, ncomp);
1370204076Spjd			/*
1371204076Spjd			 * Take request back from the receive queue and move
1372204076Spjd			 * it immediately to the done queue.
1373204076Spjd			 */
1374204076Spjd			mtx_lock(&hio_recv_list_lock[ncomp]);
1375204076Spjd			TAILQ_REMOVE(&hio_recv_list[ncomp], hio, hio_next[ncomp]);
1376204076Spjd			mtx_unlock(&hio_recv_list_lock[ncomp]);
1377204076Spjd			goto done_queue;
1378204076Spjd		}
1379204076Spjd		rw_unlock(&hio_remote_lock[ncomp]);
1380204076Spjd		nv_free(nv);
1381204076Spjd		if (wakeup)
1382204076Spjd			cv_signal(&hio_recv_list_cond[ncomp]);
1383204076Spjd		continue;
1384204076Spjddone_queue:
1385204076Spjd		nv_free(nv);
1386204076Spjd		if (ISSYNCREQ(hio)) {
1387204076Spjd			if (!refcount_release(&hio->hio_countdown))
1388204076Spjd				continue;
1389204076Spjd			mtx_lock(&sync_lock);
1390204076Spjd			SYNCREQDONE(hio);
1391204076Spjd			mtx_unlock(&sync_lock);
1392204076Spjd			cv_signal(&sync_cond);
1393204076Spjd			continue;
1394204076Spjd		}
1395204076Spjd		if (ggio->gctl_cmd == BIO_WRITE) {
1396204076Spjd			mtx_lock(&res->hr_amp_lock);
1397204076Spjd			if (activemap_need_sync(res->hr_amp, ggio->gctl_offset,
1398204076Spjd			    ggio->gctl_length)) {
1399204076Spjd				(void)hast_activemap_flush(res);
1400204076Spjd			}
1401204076Spjd			mtx_unlock(&res->hr_amp_lock);
1402204076Spjd		}
1403204076Spjd		if (!refcount_release(&hio->hio_countdown))
1404204076Spjd			continue;
1405204076Spjd		pjdlog_debug(2,
1406204076Spjd		    "remote_send: (%p) Moving request to the done queue.",
1407204076Spjd		    hio);
1408204076Spjd		QUEUE_INSERT2(hio, done);
1409204076Spjd	}
1410204076Spjd	/* NOTREACHED */
1411204076Spjd	return (NULL);
1412204076Spjd}
1413204076Spjd
1414204076Spjd/*
1415204076Spjd * Thread receives answer from secondary node and passes it to ggate_send
1416204076Spjd * thread.
1417204076Spjd */
1418204076Spjdstatic void *
1419204076Spjdremote_recv_thread(void *arg)
1420204076Spjd{
1421204076Spjd	struct hast_resource *res = arg;
1422204076Spjd	struct g_gate_ctl_io *ggio;
1423204076Spjd	struct hio *hio;
1424204076Spjd	struct nv *nv;
1425204076Spjd	unsigned int ncomp;
1426204076Spjd	uint64_t seq;
1427204076Spjd	int error;
1428204076Spjd
1429204076Spjd	/* Remote component is 1 for now. */
1430204076Spjd	ncomp = 1;
1431204076Spjd
1432204076Spjd	for (;;) {
1433204076Spjd		/* Wait until there is anything to receive. */
1434204076Spjd		mtx_lock(&hio_recv_list_lock[ncomp]);
1435204076Spjd		while (TAILQ_EMPTY(&hio_recv_list[ncomp])) {
1436204076Spjd			pjdlog_debug(2, "remote_recv: No requests, waiting.");
1437204076Spjd			cv_wait(&hio_recv_list_cond[ncomp],
1438204076Spjd			    &hio_recv_list_lock[ncomp]);
1439204076Spjd		}
1440204076Spjd		mtx_unlock(&hio_recv_list_lock[ncomp]);
1441204076Spjd		rw_rlock(&hio_remote_lock[ncomp]);
1442204076Spjd		if (!ISCONNECTED(res, ncomp)) {
1443204076Spjd			rw_unlock(&hio_remote_lock[ncomp]);
1444204076Spjd			/*
1445204076Spjd			 * Connection is dead, so move all pending requests to
1446204076Spjd			 * the done queue (one-by-one).
1447204076Spjd			 */
1448204076Spjd			mtx_lock(&hio_recv_list_lock[ncomp]);
1449204076Spjd			hio = TAILQ_FIRST(&hio_recv_list[ncomp]);
1450218138Spjd			PJDLOG_ASSERT(hio != NULL);
1451204076Spjd			TAILQ_REMOVE(&hio_recv_list[ncomp], hio,
1452204076Spjd			    hio_next[ncomp]);
1453204076Spjd			mtx_unlock(&hio_recv_list_lock[ncomp]);
1454204076Spjd			goto done_queue;
1455204076Spjd		}
1456204076Spjd		if (hast_proto_recv_hdr(res->hr_remotein, &nv) < 0) {
1457204076Spjd			pjdlog_errno(LOG_ERR,
1458204076Spjd			    "Unable to receive reply header");
1459204076Spjd			rw_unlock(&hio_remote_lock[ncomp]);
1460204076Spjd			remote_close(res, ncomp);
1461204076Spjd			continue;
1462204076Spjd		}
1463204076Spjd		rw_unlock(&hio_remote_lock[ncomp]);
1464204076Spjd		seq = nv_get_uint64(nv, "seq");
1465204076Spjd		if (seq == 0) {
1466204076Spjd			pjdlog_error("Header contains no 'seq' field.");
1467204076Spjd			nv_free(nv);
1468204076Spjd			continue;
1469204076Spjd		}
1470204076Spjd		mtx_lock(&hio_recv_list_lock[ncomp]);
1471204076Spjd		TAILQ_FOREACH(hio, &hio_recv_list[ncomp], hio_next[ncomp]) {
1472204076Spjd			if (hio->hio_ggio.gctl_seq == seq) {
1473204076Spjd				TAILQ_REMOVE(&hio_recv_list[ncomp], hio,
1474204076Spjd				    hio_next[ncomp]);
1475204076Spjd				break;
1476204076Spjd			}
1477204076Spjd		}
1478204076Spjd		mtx_unlock(&hio_recv_list_lock[ncomp]);
1479204076Spjd		if (hio == NULL) {
1480204076Spjd			pjdlog_error("Found no request matching received 'seq' field (%ju).",
1481204076Spjd			    (uintmax_t)seq);
1482204076Spjd			nv_free(nv);
1483204076Spjd			continue;
1484204076Spjd		}
1485204076Spjd		error = nv_get_int16(nv, "error");
1486204076Spjd		if (error != 0) {
1487204076Spjd			/* Request failed on remote side. */
1488216478Spjd			hio->hio_errors[ncomp] = error;
1489216479Spjd			reqlog(LOG_WARNING, 0, &hio->hio_ggio,
1490216479Spjd			    "Remote request failed (%s): ", strerror(error));
1491204076Spjd			nv_free(nv);
1492204076Spjd			goto done_queue;
1493204076Spjd		}
1494204076Spjd		ggio = &hio->hio_ggio;
1495204076Spjd		switch (ggio->gctl_cmd) {
1496204076Spjd		case BIO_READ:
1497204076Spjd			rw_rlock(&hio_remote_lock[ncomp]);
1498204076Spjd			if (!ISCONNECTED(res, ncomp)) {
1499204076Spjd				rw_unlock(&hio_remote_lock[ncomp]);
1500204076Spjd				nv_free(nv);
1501204076Spjd				goto done_queue;
1502204076Spjd			}
1503204076Spjd			if (hast_proto_recv_data(res, res->hr_remotein, nv,
1504204076Spjd			    ggio->gctl_data, ggio->gctl_length) < 0) {
1505204076Spjd				hio->hio_errors[ncomp] = errno;
1506204076Spjd				pjdlog_errno(LOG_ERR,
1507204076Spjd				    "Unable to receive reply data");
1508204076Spjd				rw_unlock(&hio_remote_lock[ncomp]);
1509204076Spjd				nv_free(nv);
1510204076Spjd				remote_close(res, ncomp);
1511204076Spjd				goto done_queue;
1512204076Spjd			}
1513204076Spjd			rw_unlock(&hio_remote_lock[ncomp]);
1514204076Spjd			break;
1515204076Spjd		case BIO_WRITE:
1516204076Spjd		case BIO_DELETE:
1517204076Spjd		case BIO_FLUSH:
1518204076Spjd			break;
1519204076Spjd		default:
1520218138Spjd			PJDLOG_ASSERT(!"invalid condition");
1521204076Spjd			abort();
1522204076Spjd		}
1523204076Spjd		hio->hio_errors[ncomp] = 0;
1524204076Spjd		nv_free(nv);
1525204076Spjddone_queue:
1526204076Spjd		if (refcount_release(&hio->hio_countdown)) {
1527204076Spjd			if (ISSYNCREQ(hio)) {
1528204076Spjd				mtx_lock(&sync_lock);
1529204076Spjd				SYNCREQDONE(hio);
1530204076Spjd				mtx_unlock(&sync_lock);
1531204076Spjd				cv_signal(&sync_cond);
1532204076Spjd			} else {
1533204076Spjd				pjdlog_debug(2,
1534204076Spjd				    "remote_recv: (%p) Moving request to the done queue.",
1535204076Spjd				    hio);
1536204076Spjd				QUEUE_INSERT2(hio, done);
1537204076Spjd			}
1538204076Spjd		}
1539204076Spjd	}
1540204076Spjd	/* NOTREACHED */
1541204076Spjd	return (NULL);
1542204076Spjd}
1543204076Spjd
1544204076Spjd/*
1545204076Spjd * Thread sends answer to the kernel.
1546204076Spjd */
1547204076Spjdstatic void *
1548204076Spjdggate_send_thread(void *arg)
1549204076Spjd{
1550204076Spjd	struct hast_resource *res = arg;
1551204076Spjd	struct g_gate_ctl_io *ggio;
1552204076Spjd	struct hio *hio;
1553204076Spjd	unsigned int ii, ncomp, ncomps;
1554204076Spjd
1555204076Spjd	ncomps = HAST_NCOMPONENTS;
1556204076Spjd
1557204076Spjd	for (;;) {
1558204076Spjd		pjdlog_debug(2, "ggate_send: Taking request.");
1559204076Spjd		QUEUE_TAKE2(hio, done);
1560204076Spjd		pjdlog_debug(2, "ggate_send: (%p) Got request.", hio);
1561204076Spjd		ggio = &hio->hio_ggio;
1562204076Spjd		for (ii = 0; ii < ncomps; ii++) {
1563204076Spjd			if (hio->hio_errors[ii] == 0) {
1564204076Spjd				/*
1565204076Spjd				 * One successful request is enough to declare
1566204076Spjd				 * success.
1567204076Spjd				 */
1568204076Spjd				ggio->gctl_error = 0;
1569204076Spjd				break;
1570204076Spjd			}
1571204076Spjd		}
1572204076Spjd		if (ii == ncomps) {
1573204076Spjd			/*
1574204076Spjd			 * None of the requests were successful.
1575204076Spjd			 * Use first error.
1576204076Spjd			 */
1577204076Spjd			ggio->gctl_error = hio->hio_errors[0];
1578204076Spjd		}
1579204076Spjd		if (ggio->gctl_error == 0 && ggio->gctl_cmd == BIO_WRITE) {
1580204076Spjd			mtx_lock(&res->hr_amp_lock);
1581204076Spjd			activemap_write_complete(res->hr_amp,
1582204076Spjd			    ggio->gctl_offset, ggio->gctl_length);
1583204076Spjd			mtx_unlock(&res->hr_amp_lock);
1584204076Spjd		}
1585204076Spjd		if (ggio->gctl_cmd == BIO_WRITE) {
1586204076Spjd			/*
1587204076Spjd			 * Unlock range we locked.
1588204076Spjd			 */
1589204076Spjd			mtx_lock(&range_lock);
1590204076Spjd			rangelock_del(range_regular, ggio->gctl_offset,
1591204076Spjd			    ggio->gctl_length);
1592204076Spjd			if (range_sync_wait)
1593204076Spjd				cv_signal(&range_sync_cond);
1594204076Spjd			mtx_unlock(&range_lock);
1595204076Spjd			/*
1596204076Spjd			 * Bump local count if this is first write after
1597204076Spjd			 * connection failure with remote node.
1598204076Spjd			 */
1599204076Spjd			ncomp = 1;
1600204076Spjd			rw_rlock(&hio_remote_lock[ncomp]);
1601204076Spjd			if (!ISCONNECTED(res, ncomp)) {
1602204076Spjd				mtx_lock(&metadata_lock);
1603204076Spjd				if (res->hr_primary_localcnt ==
1604204076Spjd				    res->hr_secondary_remotecnt) {
1605204076Spjd					res->hr_primary_localcnt++;
1606204076Spjd					pjdlog_debug(1,
1607204076Spjd					    "Increasing localcnt to %ju.",
1608204076Spjd					    (uintmax_t)res->hr_primary_localcnt);
1609204076Spjd					(void)metadata_write(res);
1610204076Spjd				}
1611204076Spjd				mtx_unlock(&metadata_lock);
1612204076Spjd			}
1613204076Spjd			rw_unlock(&hio_remote_lock[ncomp]);
1614204076Spjd		}
1615204076Spjd		if (ioctl(res->hr_ggatefd, G_GATE_CMD_DONE, ggio) < 0)
1616204076Spjd			primary_exit(EX_OSERR, "G_GATE_CMD_DONE failed");
1617204076Spjd		pjdlog_debug(2,
1618204076Spjd		    "ggate_send: (%p) Moving request to the free queue.", hio);
1619204076Spjd		QUEUE_INSERT2(hio, free);
1620204076Spjd	}
1621204076Spjd	/* NOTREACHED */
1622204076Spjd	return (NULL);
1623204076Spjd}
1624204076Spjd
1625204076Spjd/*
1626204076Spjd * Thread synchronize local and remote components.
1627204076Spjd */
1628204076Spjdstatic void *
1629204076Spjdsync_thread(void *arg __unused)
1630204076Spjd{
1631204076Spjd	struct hast_resource *res = arg;
1632204076Spjd	struct hio *hio;
1633204076Spjd	struct g_gate_ctl_io *ggio;
1634204076Spjd	unsigned int ii, ncomp, ncomps;
1635204076Spjd	off_t offset, length, synced;
1636204076Spjd	bool dorewind;
1637204076Spjd	int syncext;
1638204076Spjd
1639204076Spjd	ncomps = HAST_NCOMPONENTS;
1640204076Spjd	dorewind = true;
1641211897Spjd	synced = 0;
1642211897Spjd	offset = -1;
1643204076Spjd
1644204076Spjd	for (;;) {
1645204076Spjd		mtx_lock(&sync_lock);
1646211897Spjd		if (offset >= 0 && !sync_inprogress) {
1647211879Spjd			pjdlog_info("Synchronization interrupted. "
1648211879Spjd			    "%jd bytes synchronized so far.",
1649211879Spjd			    (intmax_t)synced);
1650212038Spjd			event_send(res, EVENT_SYNCINTR);
1651211879Spjd		}
1652204076Spjd		while (!sync_inprogress) {
1653204076Spjd			dorewind = true;
1654204076Spjd			synced = 0;
1655204076Spjd			cv_wait(&sync_cond, &sync_lock);
1656204076Spjd		}
1657204076Spjd		mtx_unlock(&sync_lock);
1658204076Spjd		/*
1659204076Spjd		 * Obtain offset at which we should synchronize.
1660204076Spjd		 * Rewind synchronization if needed.
1661204076Spjd		 */
1662204076Spjd		mtx_lock(&res->hr_amp_lock);
1663204076Spjd		if (dorewind)
1664204076Spjd			activemap_sync_rewind(res->hr_amp);
1665204076Spjd		offset = activemap_sync_offset(res->hr_amp, &length, &syncext);
1666204076Spjd		if (syncext != -1) {
1667204076Spjd			/*
1668204076Spjd			 * We synchronized entire syncext extent, we can mark
1669204076Spjd			 * it as clean now.
1670204076Spjd			 */
1671204076Spjd			if (activemap_extent_complete(res->hr_amp, syncext))
1672204076Spjd				(void)hast_activemap_flush(res);
1673204076Spjd		}
1674204076Spjd		mtx_unlock(&res->hr_amp_lock);
1675204076Spjd		if (dorewind) {
1676204076Spjd			dorewind = false;
1677204076Spjd			if (offset < 0)
1678204076Spjd				pjdlog_info("Nodes are in sync.");
1679204076Spjd			else {
1680204076Spjd				pjdlog_info("Synchronization started. %ju bytes to go.",
1681204076Spjd				    (uintmax_t)(res->hr_extentsize *
1682204076Spjd				    activemap_ndirty(res->hr_amp)));
1683212038Spjd				event_send(res, EVENT_SYNCSTART);
1684204076Spjd			}
1685204076Spjd		}
1686204076Spjd		if (offset < 0) {
1687211878Spjd			sync_stop();
1688204076Spjd			pjdlog_debug(1, "Nothing to synchronize.");
1689204076Spjd			/*
1690204076Spjd			 * Synchronization complete, make both localcnt and
1691204076Spjd			 * remotecnt equal.
1692204076Spjd			 */
1693204076Spjd			ncomp = 1;
1694204076Spjd			rw_rlock(&hio_remote_lock[ncomp]);
1695204076Spjd			if (ISCONNECTED(res, ncomp)) {
1696204076Spjd				if (synced > 0) {
1697204076Spjd					pjdlog_info("Synchronization complete. "
1698204076Spjd					    "%jd bytes synchronized.",
1699204076Spjd					    (intmax_t)synced);
1700212038Spjd					event_send(res, EVENT_SYNCDONE);
1701204076Spjd				}
1702204076Spjd				mtx_lock(&metadata_lock);
1703204076Spjd				res->hr_syncsrc = HAST_SYNCSRC_UNDEF;
1704204076Spjd				res->hr_primary_localcnt =
1705204076Spjd				    res->hr_secondary_localcnt;
1706204076Spjd				res->hr_primary_remotecnt =
1707204076Spjd				    res->hr_secondary_remotecnt;
1708204076Spjd				pjdlog_debug(1,
1709204076Spjd				    "Setting localcnt to %ju and remotecnt to %ju.",
1710204076Spjd				    (uintmax_t)res->hr_primary_localcnt,
1711204076Spjd				    (uintmax_t)res->hr_secondary_localcnt);
1712204076Spjd				(void)metadata_write(res);
1713204076Spjd				mtx_unlock(&metadata_lock);
1714204076Spjd			}
1715204076Spjd			rw_unlock(&hio_remote_lock[ncomp]);
1716204076Spjd			continue;
1717204076Spjd		}
1718204076Spjd		pjdlog_debug(2, "sync: Taking free request.");
1719204076Spjd		QUEUE_TAKE2(hio, free);
1720204076Spjd		pjdlog_debug(2, "sync: (%p) Got free request.", hio);
1721204076Spjd		/*
1722204076Spjd		 * Lock the range we are going to synchronize. We don't want
1723204076Spjd		 * race where someone writes between our read and write.
1724204076Spjd		 */
1725204076Spjd		for (;;) {
1726204076Spjd			mtx_lock(&range_lock);
1727204076Spjd			if (rangelock_islocked(range_regular, offset, length)) {
1728204076Spjd				pjdlog_debug(2,
1729204076Spjd				    "sync: Range offset=%jd length=%jd locked.",
1730204076Spjd				    (intmax_t)offset, (intmax_t)length);
1731204076Spjd				range_sync_wait = true;
1732204076Spjd				cv_wait(&range_sync_cond, &range_lock);
1733204076Spjd				range_sync_wait = false;
1734204076Spjd				mtx_unlock(&range_lock);
1735204076Spjd				continue;
1736204076Spjd			}
1737204076Spjd			if (rangelock_add(range_sync, offset, length) < 0) {
1738204076Spjd				mtx_unlock(&range_lock);
1739204076Spjd				pjdlog_debug(2,
1740204076Spjd				    "sync: Range offset=%jd length=%jd is already locked, waiting.",
1741204076Spjd				    (intmax_t)offset, (intmax_t)length);
1742204076Spjd				sleep(1);
1743204076Spjd				continue;
1744204076Spjd			}
1745204076Spjd			mtx_unlock(&range_lock);
1746204076Spjd			break;
1747204076Spjd		}
1748204076Spjd		/*
1749204076Spjd		 * First read the data from synchronization source.
1750204076Spjd		 */
1751204076Spjd		SYNCREQ(hio);
1752204076Spjd		ggio = &hio->hio_ggio;
1753204076Spjd		ggio->gctl_cmd = BIO_READ;
1754204076Spjd		ggio->gctl_offset = offset;
1755204076Spjd		ggio->gctl_length = length;
1756204076Spjd		ggio->gctl_error = 0;
1757204076Spjd		for (ii = 0; ii < ncomps; ii++)
1758204076Spjd			hio->hio_errors[ii] = EINVAL;
1759204076Spjd		reqlog(LOG_DEBUG, 2, ggio, "sync: (%p) Sending sync request: ",
1760204076Spjd		    hio);
1761204076Spjd		pjdlog_debug(2, "sync: (%p) Moving request to the send queue.",
1762204076Spjd		    hio);
1763204076Spjd		mtx_lock(&metadata_lock);
1764204076Spjd		if (res->hr_syncsrc == HAST_SYNCSRC_PRIMARY) {
1765204076Spjd			/*
1766204076Spjd			 * This range is up-to-date on local component,
1767204076Spjd			 * so handle request locally.
1768204076Spjd			 */
1769204076Spjd			 /* Local component is 0 for now. */
1770204076Spjd			ncomp = 0;
1771204076Spjd		} else /* if (res->hr_syncsrc == HAST_SYNCSRC_SECONDARY) */ {
1772218138Spjd			PJDLOG_ASSERT(res->hr_syncsrc == HAST_SYNCSRC_SECONDARY);
1773204076Spjd			/*
1774204076Spjd			 * This range is out-of-date on local component,
1775204076Spjd			 * so send request to the remote node.
1776204076Spjd			 */
1777204076Spjd			 /* Remote component is 1 for now. */
1778204076Spjd			ncomp = 1;
1779204076Spjd		}
1780204076Spjd		mtx_unlock(&metadata_lock);
1781204076Spjd		refcount_init(&hio->hio_countdown, 1);
1782204076Spjd		QUEUE_INSERT1(hio, send, ncomp);
1783204076Spjd
1784204076Spjd		/*
1785204076Spjd		 * Let's wait for READ to finish.
1786204076Spjd		 */
1787204076Spjd		mtx_lock(&sync_lock);
1788204076Spjd		while (!ISSYNCREQDONE(hio))
1789204076Spjd			cv_wait(&sync_cond, &sync_lock);
1790204076Spjd		mtx_unlock(&sync_lock);
1791204076Spjd
1792204076Spjd		if (hio->hio_errors[ncomp] != 0) {
1793204076Spjd			pjdlog_error("Unable to read synchronization data: %s.",
1794204076Spjd			    strerror(hio->hio_errors[ncomp]));
1795204076Spjd			goto free_queue;
1796204076Spjd		}
1797204076Spjd
1798204076Spjd		/*
1799204076Spjd		 * We read the data from synchronization source, now write it
1800204076Spjd		 * to synchronization target.
1801204076Spjd		 */
1802204076Spjd		SYNCREQ(hio);
1803204076Spjd		ggio->gctl_cmd = BIO_WRITE;
1804204076Spjd		for (ii = 0; ii < ncomps; ii++)
1805204076Spjd			hio->hio_errors[ii] = EINVAL;
1806204076Spjd		reqlog(LOG_DEBUG, 2, ggio, "sync: (%p) Sending sync request: ",
1807204076Spjd		    hio);
1808204076Spjd		pjdlog_debug(2, "sync: (%p) Moving request to the send queue.",
1809204076Spjd		    hio);
1810204076Spjd		mtx_lock(&metadata_lock);
1811204076Spjd		if (res->hr_syncsrc == HAST_SYNCSRC_PRIMARY) {
1812204076Spjd			/*
1813204076Spjd			 * This range is up-to-date on local component,
1814204076Spjd			 * so we update remote component.
1815204076Spjd			 */
1816204076Spjd			 /* Remote component is 1 for now. */
1817204076Spjd			ncomp = 1;
1818204076Spjd		} else /* if (res->hr_syncsrc == HAST_SYNCSRC_SECONDARY) */ {
1819218138Spjd			PJDLOG_ASSERT(res->hr_syncsrc == HAST_SYNCSRC_SECONDARY);
1820204076Spjd			/*
1821204076Spjd			 * This range is out-of-date on local component,
1822204076Spjd			 * so we update it.
1823204076Spjd			 */
1824204076Spjd			 /* Local component is 0 for now. */
1825204076Spjd			ncomp = 0;
1826204076Spjd		}
1827204076Spjd		mtx_unlock(&metadata_lock);
1828204076Spjd
1829204076Spjd		pjdlog_debug(2, "sync: (%p) Moving request to the send queues.",
1830204076Spjd		    hio);
1831204076Spjd		refcount_init(&hio->hio_countdown, 1);
1832204076Spjd		QUEUE_INSERT1(hio, send, ncomp);
1833204076Spjd
1834204076Spjd		/*
1835204076Spjd		 * Let's wait for WRITE to finish.
1836204076Spjd		 */
1837204076Spjd		mtx_lock(&sync_lock);
1838204076Spjd		while (!ISSYNCREQDONE(hio))
1839204076Spjd			cv_wait(&sync_cond, &sync_lock);
1840204076Spjd		mtx_unlock(&sync_lock);
1841204076Spjd
1842204076Spjd		if (hio->hio_errors[ncomp] != 0) {
1843204076Spjd			pjdlog_error("Unable to write synchronization data: %s.",
1844204076Spjd			    strerror(hio->hio_errors[ncomp]));
1845204076Spjd			goto free_queue;
1846204076Spjd		}
1847211880Spjd
1848211880Spjd		synced += length;
1849204076Spjdfree_queue:
1850204076Spjd		mtx_lock(&range_lock);
1851204076Spjd		rangelock_del(range_sync, offset, length);
1852204076Spjd		if (range_regular_wait)
1853204076Spjd			cv_signal(&range_regular_cond);
1854204076Spjd		mtx_unlock(&range_lock);
1855204076Spjd		pjdlog_debug(2, "sync: (%p) Moving request to the free queue.",
1856204076Spjd		    hio);
1857204076Spjd		QUEUE_INSERT2(hio, free);
1858204076Spjd	}
1859204076Spjd	/* NOTREACHED */
1860204076Spjd	return (NULL);
1861204076Spjd}
1862204076Spjd
1863217784Spjdvoid
1864217784Spjdprimary_config_reload(struct hast_resource *res, struct nv *nv)
1865210886Spjd{
1866210886Spjd	unsigned int ii, ncomps;
1867217784Spjd	int modified, vint;
1868217784Spjd	const char *vstr;
1869210886Spjd
1870210886Spjd	pjdlog_info("Reloading configuration...");
1871210886Spjd
1872218138Spjd	PJDLOG_ASSERT(res->hr_role == HAST_ROLE_PRIMARY);
1873218138Spjd	PJDLOG_ASSERT(gres == res);
1874217784Spjd	nv_assert(nv, "remoteaddr");
1875217784Spjd	nv_assert(nv, "replication");
1876217784Spjd	nv_assert(nv, "timeout");
1877217784Spjd	nv_assert(nv, "exec");
1878217784Spjd
1879210886Spjd	ncomps = HAST_NCOMPONENTS;
1880210886Spjd
1881210886Spjd#define MODIFIED_REMOTEADDR	0x1
1882210886Spjd#define MODIFIED_REPLICATION	0x2
1883210886Spjd#define MODIFIED_TIMEOUT	0x4
1884211886Spjd#define MODIFIED_EXEC		0x8
1885210886Spjd	modified = 0;
1886217784Spjd
1887217784Spjd	vstr = nv_get_string(nv, "remoteaddr");
1888217784Spjd	if (strcmp(gres->hr_remoteaddr, vstr) != 0) {
1889210886Spjd		/*
1890210886Spjd		 * Don't copy res->hr_remoteaddr to gres just yet.
1891210886Spjd		 * We want remote_close() to log disconnect from the old
1892210886Spjd		 * addresses, not from the new ones.
1893210886Spjd		 */
1894210886Spjd		modified |= MODIFIED_REMOTEADDR;
1895210886Spjd	}
1896217784Spjd	vint = nv_get_int32(nv, "replication");
1897217784Spjd	if (gres->hr_replication != vint) {
1898217784Spjd		gres->hr_replication = vint;
1899210886Spjd		modified |= MODIFIED_REPLICATION;
1900210886Spjd	}
1901217784Spjd	vint = nv_get_int32(nv, "timeout");
1902217784Spjd	if (gres->hr_timeout != vint) {
1903217784Spjd		gres->hr_timeout = vint;
1904210886Spjd		modified |= MODIFIED_TIMEOUT;
1905210886Spjd	}
1906217784Spjd	vstr = nv_get_string(nv, "exec");
1907217784Spjd	if (strcmp(gres->hr_exec, vstr) != 0) {
1908217784Spjd		strlcpy(gres->hr_exec, vstr, sizeof(gres->hr_exec));
1909211886Spjd		modified |= MODIFIED_EXEC;
1910211886Spjd	}
1911217784Spjd
1912210886Spjd	/*
1913210886Spjd	 * If only timeout was modified we only need to change it without
1914210886Spjd	 * reconnecting.
1915210886Spjd	 */
1916210886Spjd	if (modified == MODIFIED_TIMEOUT) {
1917210886Spjd		for (ii = 0; ii < ncomps; ii++) {
1918210886Spjd			if (!ISREMOTE(ii))
1919210886Spjd				continue;
1920210886Spjd			rw_rlock(&hio_remote_lock[ii]);
1921210886Spjd			if (!ISCONNECTED(gres, ii)) {
1922210886Spjd				rw_unlock(&hio_remote_lock[ii]);
1923210886Spjd				continue;
1924210886Spjd			}
1925210886Spjd			rw_unlock(&hio_remote_lock[ii]);
1926210886Spjd			if (proto_timeout(gres->hr_remotein,
1927210886Spjd			    gres->hr_timeout) < 0) {
1928210886Spjd				pjdlog_errno(LOG_WARNING,
1929210886Spjd				    "Unable to set connection timeout");
1930210886Spjd			}
1931210886Spjd			if (proto_timeout(gres->hr_remoteout,
1932210886Spjd			    gres->hr_timeout) < 0) {
1933210886Spjd				pjdlog_errno(LOG_WARNING,
1934210886Spjd				    "Unable to set connection timeout");
1935210886Spjd			}
1936210886Spjd		}
1937211886Spjd	} else if ((modified &
1938211886Spjd	    (MODIFIED_REMOTEADDR | MODIFIED_REPLICATION)) != 0) {
1939210886Spjd		for (ii = 0; ii < ncomps; ii++) {
1940210886Spjd			if (!ISREMOTE(ii))
1941210886Spjd				continue;
1942210886Spjd			remote_close(gres, ii);
1943210886Spjd		}
1944210886Spjd		if (modified & MODIFIED_REMOTEADDR) {
1945217784Spjd			vstr = nv_get_string(nv, "remoteaddr");
1946217784Spjd			strlcpy(gres->hr_remoteaddr, vstr,
1947210886Spjd			    sizeof(gres->hr_remoteaddr));
1948210886Spjd		}
1949210886Spjd	}
1950210886Spjd#undef	MODIFIED_REMOTEADDR
1951210886Spjd#undef	MODIFIED_REPLICATION
1952210886Spjd#undef	MODIFIED_TIMEOUT
1953211886Spjd#undef	MODIFIED_EXEC
1954210886Spjd
1955210886Spjd	pjdlog_info("Configuration reloaded successfully.");
1956210886Spjd}
1957210886Spjd
1958211882Spjdstatic void
1959211981Spjdguard_one(struct hast_resource *res, unsigned int ncomp)
1960211981Spjd{
1961211981Spjd	struct proto_conn *in, *out;
1962211981Spjd
1963211981Spjd	if (!ISREMOTE(ncomp))
1964211981Spjd		return;
1965211981Spjd
1966211981Spjd	rw_rlock(&hio_remote_lock[ncomp]);
1967211981Spjd
1968211981Spjd	if (!real_remote(res)) {
1969211981Spjd		rw_unlock(&hio_remote_lock[ncomp]);
1970211981Spjd		return;
1971211981Spjd	}
1972211981Spjd
1973211981Spjd	if (ISCONNECTED(res, ncomp)) {
1974218138Spjd		PJDLOG_ASSERT(res->hr_remotein != NULL);
1975218138Spjd		PJDLOG_ASSERT(res->hr_remoteout != NULL);
1976211981Spjd		rw_unlock(&hio_remote_lock[ncomp]);
1977211981Spjd		pjdlog_debug(2, "remote_guard: Connection to %s is ok.",
1978211981Spjd		    res->hr_remoteaddr);
1979211981Spjd		return;
1980211981Spjd	}
1981211981Spjd
1982218138Spjd	PJDLOG_ASSERT(res->hr_remotein == NULL);
1983218138Spjd	PJDLOG_ASSERT(res->hr_remoteout == NULL);
1984211981Spjd	/*
1985211981Spjd	 * Upgrade the lock. It doesn't have to be atomic as no other thread
1986211981Spjd	 * can change connection status from disconnected to connected.
1987211981Spjd	 */
1988211981Spjd	rw_unlock(&hio_remote_lock[ncomp]);
1989211981Spjd	pjdlog_debug(2, "remote_guard: Reconnecting to %s.",
1990211981Spjd	    res->hr_remoteaddr);
1991211981Spjd	in = out = NULL;
1992211981Spjd	if (init_remote(res, &in, &out)) {
1993211981Spjd		rw_wlock(&hio_remote_lock[ncomp]);
1994218138Spjd		PJDLOG_ASSERT(res->hr_remotein == NULL);
1995218138Spjd		PJDLOG_ASSERT(res->hr_remoteout == NULL);
1996218138Spjd		PJDLOG_ASSERT(in != NULL && out != NULL);
1997211981Spjd		res->hr_remotein = in;
1998211981Spjd		res->hr_remoteout = out;
1999211981Spjd		rw_unlock(&hio_remote_lock[ncomp]);
2000211981Spjd		pjdlog_info("Successfully reconnected to %s.",
2001211981Spjd		    res->hr_remoteaddr);
2002211981Spjd		sync_start();
2003211981Spjd	} else {
2004211981Spjd		/* Both connections should be NULL. */
2005218138Spjd		PJDLOG_ASSERT(res->hr_remotein == NULL);
2006218138Spjd		PJDLOG_ASSERT(res->hr_remoteout == NULL);
2007218138Spjd		PJDLOG_ASSERT(in == NULL && out == NULL);
2008211981Spjd		pjdlog_debug(2, "remote_guard: Reconnect to %s failed.",
2009211981Spjd		    res->hr_remoteaddr);
2010211981Spjd	}
2011211981Spjd}
2012211981Spjd
2013204076Spjd/*
2014204076Spjd * Thread guards remote connections and reconnects when needed, handles
2015204076Spjd * signals, etc.
2016204076Spjd */
2017204076Spjdstatic void *
2018204076Spjdguard_thread(void *arg)
2019204076Spjd{
2020204076Spjd	struct hast_resource *res = arg;
2021204076Spjd	unsigned int ii, ncomps;
2022211982Spjd	struct timespec timeout;
2023211981Spjd	time_t lastcheck, now;
2024211982Spjd	sigset_t mask;
2025211982Spjd	int signo;
2026204076Spjd
2027204076Spjd	ncomps = HAST_NCOMPONENTS;
2028211981Spjd	lastcheck = time(NULL);
2029204076Spjd
2030211982Spjd	PJDLOG_VERIFY(sigemptyset(&mask) == 0);
2031211982Spjd	PJDLOG_VERIFY(sigaddset(&mask, SIGINT) == 0);
2032211982Spjd	PJDLOG_VERIFY(sigaddset(&mask, SIGTERM) == 0);
2033211982Spjd
2034215332Spjd	timeout.tv_sec = RETRY_SLEEP;
2035211982Spjd	timeout.tv_nsec = 0;
2036211982Spjd	signo = -1;
2037211982Spjd
2038204076Spjd	for (;;) {
2039211982Spjd		switch (signo) {
2040211982Spjd		case SIGINT:
2041211982Spjd		case SIGTERM:
2042211982Spjd			sigexit_received = true;
2043204076Spjd			primary_exitx(EX_OK,
2044204076Spjd			    "Termination signal received, exiting.");
2045211982Spjd			break;
2046211982Spjd		default:
2047211982Spjd			break;
2048204076Spjd		}
2049211882Spjd
2050204076Spjd		pjdlog_debug(2, "remote_guard: Checking connections.");
2051211981Spjd		now = time(NULL);
2052211982Spjd		if (lastcheck + RETRY_SLEEP <= now) {
2053211982Spjd			for (ii = 0; ii < ncomps; ii++)
2054211981Spjd				guard_one(res, ii);
2055211981Spjd			lastcheck = now;
2056204076Spjd		}
2057211982Spjd		signo = sigtimedwait(&mask, NULL, &timeout);
2058204076Spjd	}
2059204076Spjd	/* NOTREACHED */
2060204076Spjd	return (NULL);
2061204076Spjd}
2062