primary.c revision 219879
1204076Spjd/*-
2204076Spjd * Copyright (c) 2009 The FreeBSD Foundation
3219351Spjd * Copyright (c) 2010-2011 Pawel Jakub Dawidek <pawel@dawidek.net>
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 219879 2011-03-22 19:49:27Z trociny $");
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	/*
89219818Spjd	 * Structure used to communicate 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
154204076Spjd#define	ISCONNECTED(res, no)	\
155204076Spjd	((res)->hr_remotein != NULL && (res)->hr_remoteout != NULL)
156204076Spjd
157204076Spjd#define	QUEUE_INSERT1(hio, name, ncomp)	do {				\
158204076Spjd	bool _wakeup;							\
159204076Spjd									\
160204076Spjd	mtx_lock(&hio_##name##_list_lock[(ncomp)]);			\
161204076Spjd	_wakeup = TAILQ_EMPTY(&hio_##name##_list[(ncomp)]);		\
162204076Spjd	TAILQ_INSERT_TAIL(&hio_##name##_list[(ncomp)], (hio),		\
163204076Spjd	    hio_next[(ncomp)]);						\
164204076Spjd	mtx_unlock(&hio_##name##_list_lock[ncomp]);			\
165204076Spjd	if (_wakeup)							\
166204076Spjd		cv_signal(&hio_##name##_list_cond[(ncomp)]);		\
167204076Spjd} while (0)
168204076Spjd#define	QUEUE_INSERT2(hio, name)	do {				\
169204076Spjd	bool _wakeup;							\
170204076Spjd									\
171204076Spjd	mtx_lock(&hio_##name##_list_lock);				\
172204076Spjd	_wakeup = TAILQ_EMPTY(&hio_##name##_list);			\
173204076Spjd	TAILQ_INSERT_TAIL(&hio_##name##_list, (hio), hio_##name##_next);\
174204076Spjd	mtx_unlock(&hio_##name##_list_lock);				\
175204076Spjd	if (_wakeup)							\
176204076Spjd		cv_signal(&hio_##name##_list_cond);			\
177204076Spjd} while (0)
178214692Spjd#define	QUEUE_TAKE1(hio, name, ncomp, timeout)	do {			\
179214692Spjd	bool _last;							\
180214692Spjd									\
181204076Spjd	mtx_lock(&hio_##name##_list_lock[(ncomp)]);			\
182214692Spjd	_last = false;							\
183214692Spjd	while (((hio) = TAILQ_FIRST(&hio_##name##_list[(ncomp)])) == NULL && !_last) { \
184214692Spjd		cv_timedwait(&hio_##name##_list_cond[(ncomp)],		\
185214692Spjd		    &hio_##name##_list_lock[(ncomp)], (timeout));	\
186219864Spjd		if ((timeout) != 0)					\
187214692Spjd			_last = true;					\
188204076Spjd	}								\
189214692Spjd	if (hio != NULL) {						\
190214692Spjd		TAILQ_REMOVE(&hio_##name##_list[(ncomp)], (hio),	\
191214692Spjd		    hio_next[(ncomp)]);					\
192214692Spjd	}								\
193204076Spjd	mtx_unlock(&hio_##name##_list_lock[(ncomp)]);			\
194204076Spjd} while (0)
195204076Spjd#define	QUEUE_TAKE2(hio, name)	do {					\
196204076Spjd	mtx_lock(&hio_##name##_list_lock);				\
197204076Spjd	while (((hio) = TAILQ_FIRST(&hio_##name##_list)) == NULL) {	\
198204076Spjd		cv_wait(&hio_##name##_list_cond,			\
199204076Spjd		    &hio_##name##_list_lock);				\
200204076Spjd	}								\
201204076Spjd	TAILQ_REMOVE(&hio_##name##_list, (hio), hio_##name##_next);	\
202204076Spjd	mtx_unlock(&hio_##name##_list_lock);				\
203204076Spjd} while (0)
204204076Spjd
205209183Spjd#define	SYNCREQ(hio)		do {					\
206209183Spjd	(hio)->hio_ggio.gctl_unit = -1;					\
207209183Spjd	(hio)->hio_ggio.gctl_seq = 1;					\
208209183Spjd} while (0)
209204076Spjd#define	ISSYNCREQ(hio)		((hio)->hio_ggio.gctl_unit == -1)
210204076Spjd#define	SYNCREQDONE(hio)	do { (hio)->hio_ggio.gctl_unit = -2; } while (0)
211204076Spjd#define	ISSYNCREQDONE(hio)	((hio)->hio_ggio.gctl_unit == -2)
212204076Spjd
213204076Spjdstatic struct hast_resource *gres;
214204076Spjd
215204076Spjdstatic pthread_mutex_t range_lock;
216204076Spjdstatic struct rangelocks *range_regular;
217204076Spjdstatic bool range_regular_wait;
218204076Spjdstatic pthread_cond_t range_regular_cond;
219204076Spjdstatic struct rangelocks *range_sync;
220204076Spjdstatic bool range_sync_wait;
221204076Spjdstatic pthread_cond_t range_sync_cond;
222204076Spjd
223204076Spjdstatic void *ggate_recv_thread(void *arg);
224204076Spjdstatic void *local_send_thread(void *arg);
225204076Spjdstatic void *remote_send_thread(void *arg);
226204076Spjdstatic void *remote_recv_thread(void *arg);
227204076Spjdstatic void *ggate_send_thread(void *arg);
228204076Spjdstatic void *sync_thread(void *arg);
229204076Spjdstatic void *guard_thread(void *arg);
230204076Spjd
231211982Spjdstatic void
232204076Spjdcleanup(struct hast_resource *res)
233204076Spjd{
234204076Spjd	int rerrno;
235204076Spjd
236204076Spjd	/* Remember errno. */
237204076Spjd	rerrno = errno;
238204076Spjd
239204076Spjd	/* Destroy ggate provider if we created one. */
240204076Spjd	if (res->hr_ggateunit >= 0) {
241204076Spjd		struct g_gate_ctl_destroy ggiod;
242204076Spjd
243213533Spjd		bzero(&ggiod, sizeof(ggiod));
244204076Spjd		ggiod.gctl_version = G_GATE_VERSION;
245204076Spjd		ggiod.gctl_unit = res->hr_ggateunit;
246204076Spjd		ggiod.gctl_force = 1;
247204076Spjd		if (ioctl(res->hr_ggatefd, G_GATE_CMD_DESTROY, &ggiod) < 0) {
248213531Spjd			pjdlog_errno(LOG_WARNING,
249213531Spjd			    "Unable to destroy hast/%s device",
250204076Spjd			    res->hr_provname);
251204076Spjd		}
252204076Spjd		res->hr_ggateunit = -1;
253204076Spjd	}
254204076Spjd
255204076Spjd	/* Restore errno. */
256204076Spjd	errno = rerrno;
257204076Spjd}
258204076Spjd
259212899Spjdstatic __dead2 void
260204076Spjdprimary_exit(int exitcode, const char *fmt, ...)
261204076Spjd{
262204076Spjd	va_list ap;
263204076Spjd
264218138Spjd	PJDLOG_ASSERT(exitcode != EX_OK);
265204076Spjd	va_start(ap, fmt);
266204076Spjd	pjdlogv_errno(LOG_ERR, fmt, ap);
267204076Spjd	va_end(ap);
268204076Spjd	cleanup(gres);
269204076Spjd	exit(exitcode);
270204076Spjd}
271204076Spjd
272212899Spjdstatic __dead2 void
273204076Spjdprimary_exitx(int exitcode, const char *fmt, ...)
274204076Spjd{
275204076Spjd	va_list ap;
276204076Spjd
277204076Spjd	va_start(ap, fmt);
278204076Spjd	pjdlogv(exitcode == EX_OK ? LOG_INFO : LOG_ERR, fmt, ap);
279204076Spjd	va_end(ap);
280204076Spjd	cleanup(gres);
281204076Spjd	exit(exitcode);
282204076Spjd}
283204076Spjd
284204076Spjdstatic int
285204076Spjdhast_activemap_flush(struct hast_resource *res)
286204076Spjd{
287204076Spjd	const unsigned char *buf;
288204076Spjd	size_t size;
289204076Spjd
290204076Spjd	buf = activemap_bitmap(res->hr_amp, &size);
291218138Spjd	PJDLOG_ASSERT(buf != NULL);
292218138Spjd	PJDLOG_ASSERT((size % res->hr_local_sectorsize) == 0);
293204076Spjd	if (pwrite(res->hr_localfd, buf, size, METADATA_SIZE) !=
294204076Spjd	    (ssize_t)size) {
295204076Spjd		KEEP_ERRNO(pjdlog_errno(LOG_ERR,
296204076Spjd		    "Unable to flush activemap to disk"));
297204076Spjd		return (-1);
298204076Spjd	}
299204076Spjd	return (0);
300204076Spjd}
301204076Spjd
302210881Spjdstatic bool
303210881Spjdreal_remote(const struct hast_resource *res)
304210881Spjd{
305210881Spjd
306210881Spjd	return (strcmp(res->hr_remoteaddr, "none") != 0);
307210881Spjd}
308210881Spjd
309204076Spjdstatic void
310204076Spjdinit_environment(struct hast_resource *res __unused)
311204076Spjd{
312204076Spjd	struct hio *hio;
313204076Spjd	unsigned int ii, ncomps;
314204076Spjd
315204076Spjd	/*
316204076Spjd	 * In the future it might be per-resource value.
317204076Spjd	 */
318204076Spjd	ncomps = HAST_NCOMPONENTS;
319204076Spjd
320204076Spjd	/*
321204076Spjd	 * Allocate memory needed by lists.
322204076Spjd	 */
323204076Spjd	hio_send_list = malloc(sizeof(hio_send_list[0]) * ncomps);
324204076Spjd	if (hio_send_list == NULL) {
325204076Spjd		primary_exitx(EX_TEMPFAIL,
326204076Spjd		    "Unable to allocate %zu bytes of memory for send lists.",
327204076Spjd		    sizeof(hio_send_list[0]) * ncomps);
328204076Spjd	}
329204076Spjd	hio_send_list_lock = malloc(sizeof(hio_send_list_lock[0]) * ncomps);
330204076Spjd	if (hio_send_list_lock == NULL) {
331204076Spjd		primary_exitx(EX_TEMPFAIL,
332204076Spjd		    "Unable to allocate %zu bytes of memory for send list locks.",
333204076Spjd		    sizeof(hio_send_list_lock[0]) * ncomps);
334204076Spjd	}
335204076Spjd	hio_send_list_cond = malloc(sizeof(hio_send_list_cond[0]) * ncomps);
336204076Spjd	if (hio_send_list_cond == NULL) {
337204076Spjd		primary_exitx(EX_TEMPFAIL,
338204076Spjd		    "Unable to allocate %zu bytes of memory for send list condition variables.",
339204076Spjd		    sizeof(hio_send_list_cond[0]) * ncomps);
340204076Spjd	}
341204076Spjd	hio_recv_list = malloc(sizeof(hio_recv_list[0]) * ncomps);
342204076Spjd	if (hio_recv_list == NULL) {
343204076Spjd		primary_exitx(EX_TEMPFAIL,
344204076Spjd		    "Unable to allocate %zu bytes of memory for recv lists.",
345204076Spjd		    sizeof(hio_recv_list[0]) * ncomps);
346204076Spjd	}
347204076Spjd	hio_recv_list_lock = malloc(sizeof(hio_recv_list_lock[0]) * ncomps);
348204076Spjd	if (hio_recv_list_lock == NULL) {
349204076Spjd		primary_exitx(EX_TEMPFAIL,
350204076Spjd		    "Unable to allocate %zu bytes of memory for recv list locks.",
351204076Spjd		    sizeof(hio_recv_list_lock[0]) * ncomps);
352204076Spjd	}
353204076Spjd	hio_recv_list_cond = malloc(sizeof(hio_recv_list_cond[0]) * ncomps);
354204076Spjd	if (hio_recv_list_cond == NULL) {
355204076Spjd		primary_exitx(EX_TEMPFAIL,
356204076Spjd		    "Unable to allocate %zu bytes of memory for recv list condition variables.",
357204076Spjd		    sizeof(hio_recv_list_cond[0]) * ncomps);
358204076Spjd	}
359204076Spjd	hio_remote_lock = malloc(sizeof(hio_remote_lock[0]) * ncomps);
360204076Spjd	if (hio_remote_lock == NULL) {
361204076Spjd		primary_exitx(EX_TEMPFAIL,
362204076Spjd		    "Unable to allocate %zu bytes of memory for remote connections locks.",
363204076Spjd		    sizeof(hio_remote_lock[0]) * ncomps);
364204076Spjd	}
365204076Spjd
366204076Spjd	/*
367204076Spjd	 * Initialize lists, their locks and theirs condition variables.
368204076Spjd	 */
369204076Spjd	TAILQ_INIT(&hio_free_list);
370204076Spjd	mtx_init(&hio_free_list_lock);
371204076Spjd	cv_init(&hio_free_list_cond);
372204076Spjd	for (ii = 0; ii < HAST_NCOMPONENTS; ii++) {
373204076Spjd		TAILQ_INIT(&hio_send_list[ii]);
374204076Spjd		mtx_init(&hio_send_list_lock[ii]);
375204076Spjd		cv_init(&hio_send_list_cond[ii]);
376204076Spjd		TAILQ_INIT(&hio_recv_list[ii]);
377204076Spjd		mtx_init(&hio_recv_list_lock[ii]);
378204076Spjd		cv_init(&hio_recv_list_cond[ii]);
379204076Spjd		rw_init(&hio_remote_lock[ii]);
380204076Spjd	}
381204076Spjd	TAILQ_INIT(&hio_done_list);
382204076Spjd	mtx_init(&hio_done_list_lock);
383204076Spjd	cv_init(&hio_done_list_cond);
384204076Spjd	mtx_init(&metadata_lock);
385204076Spjd
386204076Spjd	/*
387204076Spjd	 * Allocate requests pool and initialize requests.
388204076Spjd	 */
389204076Spjd	for (ii = 0; ii < HAST_HIO_MAX; ii++) {
390204076Spjd		hio = malloc(sizeof(*hio));
391204076Spjd		if (hio == NULL) {
392204076Spjd			primary_exitx(EX_TEMPFAIL,
393204076Spjd			    "Unable to allocate %zu bytes of memory for hio request.",
394204076Spjd			    sizeof(*hio));
395204076Spjd		}
396204076Spjd		hio->hio_countdown = 0;
397204076Spjd		hio->hio_errors = malloc(sizeof(hio->hio_errors[0]) * ncomps);
398204076Spjd		if (hio->hio_errors == NULL) {
399204076Spjd			primary_exitx(EX_TEMPFAIL,
400204076Spjd			    "Unable allocate %zu bytes of memory for hio errors.",
401204076Spjd			    sizeof(hio->hio_errors[0]) * ncomps);
402204076Spjd		}
403204076Spjd		hio->hio_next = malloc(sizeof(hio->hio_next[0]) * ncomps);
404204076Spjd		if (hio->hio_next == NULL) {
405204076Spjd			primary_exitx(EX_TEMPFAIL,
406204076Spjd			    "Unable allocate %zu bytes of memory for hio_next field.",
407204076Spjd			    sizeof(hio->hio_next[0]) * ncomps);
408204076Spjd		}
409204076Spjd		hio->hio_ggio.gctl_version = G_GATE_VERSION;
410204076Spjd		hio->hio_ggio.gctl_data = malloc(MAXPHYS);
411204076Spjd		if (hio->hio_ggio.gctl_data == NULL) {
412204076Spjd			primary_exitx(EX_TEMPFAIL,
413204076Spjd			    "Unable to allocate %zu bytes of memory for gctl_data.",
414204076Spjd			    MAXPHYS);
415204076Spjd		}
416204076Spjd		hio->hio_ggio.gctl_length = MAXPHYS;
417204076Spjd		hio->hio_ggio.gctl_error = 0;
418204076Spjd		TAILQ_INSERT_HEAD(&hio_free_list, hio, hio_free_next);
419204076Spjd	}
420204076Spjd}
421204076Spjd
422214284Spjdstatic bool
423214284Spjdinit_resuid(struct hast_resource *res)
424214284Spjd{
425214284Spjd
426214284Spjd	mtx_lock(&metadata_lock);
427214284Spjd	if (res->hr_resuid != 0) {
428214284Spjd		mtx_unlock(&metadata_lock);
429214284Spjd		return (false);
430214284Spjd	} else {
431214284Spjd		/* Initialize unique resource identifier. */
432214284Spjd		arc4random_buf(&res->hr_resuid, sizeof(res->hr_resuid));
433214284Spjd		mtx_unlock(&metadata_lock);
434214284Spjd		if (metadata_write(res) < 0)
435214284Spjd			exit(EX_NOINPUT);
436214284Spjd		return (true);
437214284Spjd	}
438214284Spjd}
439214284Spjd
440204076Spjdstatic void
441204076Spjdinit_local(struct hast_resource *res)
442204076Spjd{
443204076Spjd	unsigned char *buf;
444204076Spjd	size_t mapsize;
445204076Spjd
446204076Spjd	if (metadata_read(res, true) < 0)
447204076Spjd		exit(EX_NOINPUT);
448204076Spjd	mtx_init(&res->hr_amp_lock);
449204076Spjd	if (activemap_init(&res->hr_amp, res->hr_datasize, res->hr_extentsize,
450204076Spjd	    res->hr_local_sectorsize, res->hr_keepdirty) < 0) {
451204076Spjd		primary_exit(EX_TEMPFAIL, "Unable to create activemap");
452204076Spjd	}
453204076Spjd	mtx_init(&range_lock);
454204076Spjd	cv_init(&range_regular_cond);
455204076Spjd	if (rangelock_init(&range_regular) < 0)
456204076Spjd		primary_exit(EX_TEMPFAIL, "Unable to create regular range lock");
457204076Spjd	cv_init(&range_sync_cond);
458204076Spjd	if (rangelock_init(&range_sync) < 0)
459204076Spjd		primary_exit(EX_TEMPFAIL, "Unable to create sync range lock");
460204076Spjd	mapsize = activemap_ondisk_size(res->hr_amp);
461204076Spjd	buf = calloc(1, mapsize);
462204076Spjd	if (buf == NULL) {
463204076Spjd		primary_exitx(EX_TEMPFAIL,
464204076Spjd		    "Unable to allocate buffer for activemap.");
465204076Spjd	}
466204076Spjd	if (pread(res->hr_localfd, buf, mapsize, METADATA_SIZE) !=
467204076Spjd	    (ssize_t)mapsize) {
468204076Spjd		primary_exit(EX_NOINPUT, "Unable to read activemap");
469204076Spjd	}
470204076Spjd	activemap_copyin(res->hr_amp, buf, mapsize);
471209181Spjd	free(buf);
472204076Spjd	if (res->hr_resuid != 0)
473204076Spjd		return;
474204076Spjd	/*
475214284Spjd	 * We're using provider for the first time. Initialize local and remote
476214284Spjd	 * counters. We don't initialize resuid here, as we want to do it just
477214284Spjd	 * in time. The reason for this is that we want to inform secondary
478214284Spjd	 * that there were no writes yet, so there is no need to synchronize
479214284Spjd	 * anything.
480204076Spjd	 */
481219844Spjd	res->hr_primary_localcnt = 0;
482204076Spjd	res->hr_primary_remotecnt = 0;
483204076Spjd	if (metadata_write(res) < 0)
484204076Spjd		exit(EX_NOINPUT);
485204076Spjd}
486204076Spjd
487218218Spjdstatic int
488218218Spjdprimary_connect(struct hast_resource *res, struct proto_conn **connp)
489218218Spjd{
490218218Spjd	struct proto_conn *conn;
491218218Spjd	int16_t val;
492218218Spjd
493218218Spjd	val = 1;
494218218Spjd	if (proto_send(res->hr_conn, &val, sizeof(val)) < 0) {
495218218Spjd		primary_exit(EX_TEMPFAIL,
496218218Spjd		    "Unable to send connection request to parent");
497218218Spjd	}
498218218Spjd	if (proto_recv(res->hr_conn, &val, sizeof(val)) < 0) {
499218218Spjd		primary_exit(EX_TEMPFAIL,
500218218Spjd		    "Unable to receive reply to connection request from parent");
501218218Spjd	}
502218218Spjd	if (val != 0) {
503218218Spjd		errno = val;
504218218Spjd		pjdlog_errno(LOG_WARNING, "Unable to connect to %s",
505218218Spjd		    res->hr_remoteaddr);
506218218Spjd		return (-1);
507218218Spjd	}
508218218Spjd	if (proto_connection_recv(res->hr_conn, true, &conn) < 0) {
509218218Spjd		primary_exit(EX_TEMPFAIL,
510218218Spjd		    "Unable to receive connection from parent");
511218218Spjd	}
512218218Spjd	if (proto_connect_wait(conn, HAST_TIMEOUT) < 0) {
513218218Spjd		pjdlog_errno(LOG_WARNING, "Unable to connect to %s",
514218218Spjd		    res->hr_remoteaddr);
515218218Spjd		proto_close(conn);
516218218Spjd		return (-1);
517218218Spjd	}
518218218Spjd	/* Error in setting timeout is not critical, but why should it fail? */
519218218Spjd	if (proto_timeout(conn, res->hr_timeout) < 0)
520218218Spjd		pjdlog_errno(LOG_WARNING, "Unable to set connection timeout");
521218218Spjd
522218218Spjd	*connp = conn;
523218218Spjd
524218218Spjd	return (0);
525218218Spjd}
526218218Spjd
527205738Spjdstatic bool
528205738Spjdinit_remote(struct hast_resource *res, struct proto_conn **inp,
529205738Spjd    struct proto_conn **outp)
530204076Spjd{
531205738Spjd	struct proto_conn *in, *out;
532204076Spjd	struct nv *nvout, *nvin;
533204076Spjd	const unsigned char *token;
534204076Spjd	unsigned char *map;
535204076Spjd	const char *errmsg;
536204076Spjd	int32_t extentsize;
537204076Spjd	int64_t datasize;
538204076Spjd	uint32_t mapsize;
539204076Spjd	size_t size;
540204076Spjd
541218138Spjd	PJDLOG_ASSERT((inp == NULL && outp == NULL) || (inp != NULL && outp != NULL));
542218138Spjd	PJDLOG_ASSERT(real_remote(res));
543205738Spjd
544205738Spjd	in = out = NULL;
545211983Spjd	errmsg = NULL;
546205738Spjd
547218218Spjd	if (primary_connect(res, &out) == -1)
548218218Spjd		return (false);
549218218Spjd
550204076Spjd	/*
551204076Spjd	 * First handshake step.
552204076Spjd	 * Setup outgoing connection with remote node.
553204076Spjd	 */
554204076Spjd	nvout = nv_alloc();
555204076Spjd	nv_add_string(nvout, res->hr_name, "resource");
556204076Spjd	if (nv_error(nvout) != 0) {
557204076Spjd		pjdlog_common(LOG_WARNING, 0, nv_error(nvout),
558204076Spjd		    "Unable to allocate header for connection with %s",
559204076Spjd		    res->hr_remoteaddr);
560204076Spjd		nv_free(nvout);
561204076Spjd		goto close;
562204076Spjd	}
563205738Spjd	if (hast_proto_send(res, out, nvout, NULL, 0) < 0) {
564204076Spjd		pjdlog_errno(LOG_WARNING,
565204076Spjd		    "Unable to send handshake header to %s",
566204076Spjd		    res->hr_remoteaddr);
567204076Spjd		nv_free(nvout);
568204076Spjd		goto close;
569204076Spjd	}
570204076Spjd	nv_free(nvout);
571205738Spjd	if (hast_proto_recv_hdr(out, &nvin) < 0) {
572204076Spjd		pjdlog_errno(LOG_WARNING,
573204076Spjd		    "Unable to receive handshake header from %s",
574204076Spjd		    res->hr_remoteaddr);
575204076Spjd		goto close;
576204076Spjd	}
577204076Spjd	errmsg = nv_get_string(nvin, "errmsg");
578204076Spjd	if (errmsg != NULL) {
579204076Spjd		pjdlog_warning("%s", errmsg);
580204076Spjd		nv_free(nvin);
581204076Spjd		goto close;
582204076Spjd	}
583204076Spjd	token = nv_get_uint8_array(nvin, &size, "token");
584204076Spjd	if (token == NULL) {
585204076Spjd		pjdlog_warning("Handshake header from %s has no 'token' field.",
586204076Spjd		    res->hr_remoteaddr);
587204076Spjd		nv_free(nvin);
588204076Spjd		goto close;
589204076Spjd	}
590204076Spjd	if (size != sizeof(res->hr_token)) {
591204076Spjd		pjdlog_warning("Handshake header from %s contains 'token' of wrong size (got %zu, expected %zu).",
592204076Spjd		    res->hr_remoteaddr, size, sizeof(res->hr_token));
593204076Spjd		nv_free(nvin);
594204076Spjd		goto close;
595204076Spjd	}
596204076Spjd	bcopy(token, res->hr_token, sizeof(res->hr_token));
597204076Spjd	nv_free(nvin);
598204076Spjd
599204076Spjd	/*
600204076Spjd	 * Second handshake step.
601204076Spjd	 * Setup incoming connection with remote node.
602204076Spjd	 */
603218218Spjd	if (primary_connect(res, &in) == -1)
604204076Spjd		goto close;
605218218Spjd
606204076Spjd	nvout = nv_alloc();
607204076Spjd	nv_add_string(nvout, res->hr_name, "resource");
608204076Spjd	nv_add_uint8_array(nvout, res->hr_token, sizeof(res->hr_token),
609204076Spjd	    "token");
610214284Spjd	if (res->hr_resuid == 0) {
611214284Spjd		/*
612214284Spjd		 * The resuid field was not yet initialized.
613214284Spjd		 * Because we do synchronization inside init_resuid(), it is
614214284Spjd		 * possible that someone already initialized it, the function
615214284Spjd		 * will return false then, but if we successfully initialized
616214284Spjd		 * it, we will get true. True means that there were no writes
617214284Spjd		 * to this resource yet and we want to inform secondary that
618214284Spjd		 * synchronization is not needed by sending "virgin" argument.
619214284Spjd		 */
620214284Spjd		if (init_resuid(res))
621214284Spjd			nv_add_int8(nvout, 1, "virgin");
622214284Spjd	}
623204076Spjd	nv_add_uint64(nvout, res->hr_resuid, "resuid");
624204076Spjd	nv_add_uint64(nvout, res->hr_primary_localcnt, "localcnt");
625204076Spjd	nv_add_uint64(nvout, res->hr_primary_remotecnt, "remotecnt");
626204076Spjd	if (nv_error(nvout) != 0) {
627204076Spjd		pjdlog_common(LOG_WARNING, 0, nv_error(nvout),
628204076Spjd		    "Unable to allocate header for connection with %s",
629204076Spjd		    res->hr_remoteaddr);
630204076Spjd		nv_free(nvout);
631204076Spjd		goto close;
632204076Spjd	}
633205738Spjd	if (hast_proto_send(res, in, nvout, NULL, 0) < 0) {
634204076Spjd		pjdlog_errno(LOG_WARNING,
635204076Spjd		    "Unable to send handshake header to %s",
636204076Spjd		    res->hr_remoteaddr);
637204076Spjd		nv_free(nvout);
638204076Spjd		goto close;
639204076Spjd	}
640204076Spjd	nv_free(nvout);
641205738Spjd	if (hast_proto_recv_hdr(out, &nvin) < 0) {
642204076Spjd		pjdlog_errno(LOG_WARNING,
643204076Spjd		    "Unable to receive handshake header from %s",
644204076Spjd		    res->hr_remoteaddr);
645204076Spjd		goto close;
646204076Spjd	}
647204076Spjd	errmsg = nv_get_string(nvin, "errmsg");
648204076Spjd	if (errmsg != NULL) {
649204076Spjd		pjdlog_warning("%s", errmsg);
650204076Spjd		nv_free(nvin);
651204076Spjd		goto close;
652204076Spjd	}
653204076Spjd	datasize = nv_get_int64(nvin, "datasize");
654204076Spjd	if (datasize != res->hr_datasize) {
655204076Spjd		pjdlog_warning("Data size differs between nodes (local=%jd, remote=%jd).",
656204076Spjd		    (intmax_t)res->hr_datasize, (intmax_t)datasize);
657204076Spjd		nv_free(nvin);
658204076Spjd		goto close;
659204076Spjd	}
660204076Spjd	extentsize = nv_get_int32(nvin, "extentsize");
661204076Spjd	if (extentsize != res->hr_extentsize) {
662204076Spjd		pjdlog_warning("Extent size differs between nodes (local=%zd, remote=%zd).",
663204076Spjd		    (ssize_t)res->hr_extentsize, (ssize_t)extentsize);
664204076Spjd		nv_free(nvin);
665204076Spjd		goto close;
666204076Spjd	}
667204076Spjd	res->hr_secondary_localcnt = nv_get_uint64(nvin, "localcnt");
668204076Spjd	res->hr_secondary_remotecnt = nv_get_uint64(nvin, "remotecnt");
669204076Spjd	res->hr_syncsrc = nv_get_uint8(nvin, "syncsrc");
670204076Spjd	map = NULL;
671204076Spjd	mapsize = nv_get_uint32(nvin, "mapsize");
672204076Spjd	if (mapsize > 0) {
673204076Spjd		map = malloc(mapsize);
674204076Spjd		if (map == NULL) {
675204076Spjd			pjdlog_error("Unable to allocate memory for remote activemap (mapsize=%ju).",
676204076Spjd			    (uintmax_t)mapsize);
677204076Spjd			nv_free(nvin);
678204076Spjd			goto close;
679204076Spjd		}
680204076Spjd		/*
681204076Spjd		 * Remote node have some dirty extents on its own, lets
682204076Spjd		 * download its activemap.
683204076Spjd		 */
684205738Spjd		if (hast_proto_recv_data(res, out, nvin, map,
685204076Spjd		    mapsize) < 0) {
686204076Spjd			pjdlog_errno(LOG_ERR,
687204076Spjd			    "Unable to receive remote activemap");
688204076Spjd			nv_free(nvin);
689204076Spjd			free(map);
690204076Spjd			goto close;
691204076Spjd		}
692204076Spjd		/*
693204076Spjd		 * Merge local and remote bitmaps.
694204076Spjd		 */
695204076Spjd		activemap_merge(res->hr_amp, map, mapsize);
696204076Spjd		free(map);
697204076Spjd		/*
698204076Spjd		 * Now that we merged bitmaps from both nodes, flush it to the
699204076Spjd		 * disk before we start to synchronize.
700204076Spjd		 */
701204076Spjd		(void)hast_activemap_flush(res);
702204076Spjd	}
703214274Spjd	nv_free(nvin);
704204076Spjd	pjdlog_info("Connected to %s.", res->hr_remoteaddr);
705205738Spjd	if (inp != NULL && outp != NULL) {
706205738Spjd		*inp = in;
707205738Spjd		*outp = out;
708205738Spjd	} else {
709205738Spjd		res->hr_remotein = in;
710205738Spjd		res->hr_remoteout = out;
711205738Spjd	}
712212038Spjd	event_send(res, EVENT_CONNECT);
713205738Spjd	return (true);
714205738Spjdclose:
715211983Spjd	if (errmsg != NULL && strcmp(errmsg, "Split-brain condition!") == 0)
716212038Spjd		event_send(res, EVENT_SPLITBRAIN);
717205738Spjd	proto_close(out);
718205738Spjd	if (in != NULL)
719205738Spjd		proto_close(in);
720205738Spjd	return (false);
721205738Spjd}
722205738Spjd
723205738Spjdstatic void
724205738Spjdsync_start(void)
725205738Spjd{
726205738Spjd
727204076Spjd	mtx_lock(&sync_lock);
728204076Spjd	sync_inprogress = true;
729204076Spjd	mtx_unlock(&sync_lock);
730204076Spjd	cv_signal(&sync_cond);
731204076Spjd}
732204076Spjd
733204076Spjdstatic void
734211878Spjdsync_stop(void)
735211878Spjd{
736211878Spjd
737211878Spjd	mtx_lock(&sync_lock);
738211878Spjd	if (sync_inprogress)
739211878Spjd		sync_inprogress = false;
740211878Spjd	mtx_unlock(&sync_lock);
741211878Spjd}
742211878Spjd
743211878Spjdstatic void
744204076Spjdinit_ggate(struct hast_resource *res)
745204076Spjd{
746204076Spjd	struct g_gate_ctl_create ggiocreate;
747204076Spjd	struct g_gate_ctl_cancel ggiocancel;
748204076Spjd
749204076Spjd	/*
750204076Spjd	 * We communicate with ggate via /dev/ggctl. Open it.
751204076Spjd	 */
752204076Spjd	res->hr_ggatefd = open("/dev/" G_GATE_CTL_NAME, O_RDWR);
753204076Spjd	if (res->hr_ggatefd < 0)
754204076Spjd		primary_exit(EX_OSFILE, "Unable to open /dev/" G_GATE_CTL_NAME);
755204076Spjd	/*
756204076Spjd	 * Create provider before trying to connect, as connection failure
757204076Spjd	 * is not critical, but may take some time.
758204076Spjd	 */
759213533Spjd	bzero(&ggiocreate, sizeof(ggiocreate));
760204076Spjd	ggiocreate.gctl_version = G_GATE_VERSION;
761204076Spjd	ggiocreate.gctl_mediasize = res->hr_datasize;
762204076Spjd	ggiocreate.gctl_sectorsize = res->hr_local_sectorsize;
763204076Spjd	ggiocreate.gctl_flags = 0;
764206669Spjd	ggiocreate.gctl_maxcount = G_GATE_MAX_QUEUE_SIZE;
765204076Spjd	ggiocreate.gctl_timeout = 0;
766204076Spjd	ggiocreate.gctl_unit = G_GATE_NAME_GIVEN;
767204076Spjd	snprintf(ggiocreate.gctl_name, sizeof(ggiocreate.gctl_name), "hast/%s",
768204076Spjd	    res->hr_provname);
769204076Spjd	if (ioctl(res->hr_ggatefd, G_GATE_CMD_CREATE, &ggiocreate) == 0) {
770204076Spjd		pjdlog_info("Device hast/%s created.", res->hr_provname);
771204076Spjd		res->hr_ggateunit = ggiocreate.gctl_unit;
772204076Spjd		return;
773204076Spjd	}
774204076Spjd	if (errno != EEXIST) {
775204076Spjd		primary_exit(EX_OSERR, "Unable to create hast/%s device",
776204076Spjd		    res->hr_provname);
777204076Spjd	}
778204076Spjd	pjdlog_debug(1,
779204076Spjd	    "Device hast/%s already exists, we will try to take it over.",
780204076Spjd	    res->hr_provname);
781204076Spjd	/*
782204076Spjd	 * If we received EEXIST, we assume that the process who created the
783204076Spjd	 * provider died and didn't clean up. In that case we will start from
784204076Spjd	 * where he left of.
785204076Spjd	 */
786213533Spjd	bzero(&ggiocancel, sizeof(ggiocancel));
787204076Spjd	ggiocancel.gctl_version = G_GATE_VERSION;
788204076Spjd	ggiocancel.gctl_unit = G_GATE_NAME_GIVEN;
789204076Spjd	snprintf(ggiocancel.gctl_name, sizeof(ggiocancel.gctl_name), "hast/%s",
790204076Spjd	    res->hr_provname);
791204076Spjd	if (ioctl(res->hr_ggatefd, G_GATE_CMD_CANCEL, &ggiocancel) == 0) {
792204076Spjd		pjdlog_info("Device hast/%s recovered.", res->hr_provname);
793204076Spjd		res->hr_ggateunit = ggiocancel.gctl_unit;
794204076Spjd		return;
795204076Spjd	}
796204076Spjd	primary_exit(EX_OSERR, "Unable to take over hast/%s device",
797204076Spjd	    res->hr_provname);
798204076Spjd}
799204076Spjd
800204076Spjdvoid
801204076Spjdhastd_primary(struct hast_resource *res)
802204076Spjd{
803204076Spjd	pthread_t td;
804204076Spjd	pid_t pid;
805219482Strociny	int error, mode, debuglevel;
806204076Spjd
807204076Spjd	/*
808218218Spjd	 * Create communication channel for sending control commands from
809218218Spjd	 * parent to child.
810204076Spjd	 */
811219818Spjd	if (proto_client(NULL, "socketpair://", &res->hr_ctrl) < 0) {
812218042Spjd		/* TODO: There's no need for this to be fatal error. */
813204076Spjd		KEEP_ERRNO((void)pidfile_remove(pfh));
814212034Spjd		pjdlog_exit(EX_OSERR,
815204076Spjd		    "Unable to create control sockets between parent and child");
816204076Spjd	}
817212038Spjd	/*
818218218Spjd	 * Create communication channel for sending events from child to parent.
819212038Spjd	 */
820219818Spjd	if (proto_client(NULL, "socketpair://", &res->hr_event) < 0) {
821218042Spjd		/* TODO: There's no need for this to be fatal error. */
822212038Spjd		KEEP_ERRNO((void)pidfile_remove(pfh));
823212038Spjd		pjdlog_exit(EX_OSERR,
824212038Spjd		    "Unable to create event sockets between child and parent");
825212038Spjd	}
826218218Spjd	/*
827218218Spjd	 * Create communication channel for sending connection requests from
828218218Spjd	 * child to parent.
829218218Spjd	 */
830219818Spjd	if (proto_client(NULL, "socketpair://", &res->hr_conn) < 0) {
831218218Spjd		/* TODO: There's no need for this to be fatal error. */
832218218Spjd		KEEP_ERRNO((void)pidfile_remove(pfh));
833218218Spjd		pjdlog_exit(EX_OSERR,
834218218Spjd		    "Unable to create connection sockets between child and parent");
835218218Spjd	}
836204076Spjd
837204076Spjd	pid = fork();
838204076Spjd	if (pid < 0) {
839218042Spjd		/* TODO: There's no need for this to be fatal error. */
840204076Spjd		KEEP_ERRNO((void)pidfile_remove(pfh));
841212034Spjd		pjdlog_exit(EX_TEMPFAIL, "Unable to fork");
842204076Spjd	}
843204076Spjd
844204076Spjd	if (pid > 0) {
845204076Spjd		/* This is parent. */
846212038Spjd		/* Declare that we are receiver. */
847212038Spjd		proto_recv(res->hr_event, NULL, 0);
848218218Spjd		proto_recv(res->hr_conn, NULL, 0);
849218043Spjd		/* Declare that we are sender. */
850218043Spjd		proto_send(res->hr_ctrl, NULL, 0);
851204076Spjd		res->hr_workerpid = pid;
852204076Spjd		return;
853204076Spjd	}
854211977Spjd
855211984Spjd	gres = res;
856218043Spjd	mode = pjdlog_mode_get();
857219482Strociny	debuglevel = pjdlog_debug_get();
858211984Spjd
859218043Spjd	/* Declare that we are sender. */
860218043Spjd	proto_send(res->hr_event, NULL, 0);
861218218Spjd	proto_send(res->hr_conn, NULL, 0);
862218043Spjd	/* Declare that we are receiver. */
863218043Spjd	proto_recv(res->hr_ctrl, NULL, 0);
864218043Spjd	descriptors_cleanup(res);
865204076Spjd
866218045Spjd	descriptors_assert(res, mode);
867218045Spjd
868218043Spjd	pjdlog_init(mode);
869219482Strociny	pjdlog_debug_set(debuglevel);
870218043Spjd	pjdlog_prefix_set("[%s] (%s) ", res->hr_name, role2str(res->hr_role));
871204076Spjd	setproctitle("%s (primary)", res->hr_name);
872204076Spjd
873204076Spjd	init_local(res);
874213007Spjd	init_ggate(res);
875213007Spjd	init_environment(res);
876217784Spjd
877219847Spjd	if (drop_privs(true) != 0) {
878218049Spjd		cleanup(res);
879218049Spjd		exit(EX_CONFIG);
880218049Spjd	}
881218214Spjd	pjdlog_info("Privileges successfully dropped.");
882218049Spjd
883213007Spjd	/*
884213530Spjd	 * Create the guard thread first, so we can handle signals from the
885213530Spjd	 * very begining.
886213530Spjd	 */
887213530Spjd	error = pthread_create(&td, NULL, guard_thread, res);
888218138Spjd	PJDLOG_ASSERT(error == 0);
889213530Spjd	/*
890213007Spjd	 * Create the control thread before sending any event to the parent,
891213007Spjd	 * as we can deadlock when parent sends control request to worker,
892213007Spjd	 * but worker has no control thread started yet, so parent waits.
893213007Spjd	 * In the meantime worker sends an event to the parent, but parent
894213007Spjd	 * is unable to handle the event, because it waits for control
895213007Spjd	 * request response.
896213007Spjd	 */
897213007Spjd	error = pthread_create(&td, NULL, ctrl_thread, res);
898218138Spjd	PJDLOG_ASSERT(error == 0);
899210881Spjd	if (real_remote(res) && init_remote(res, NULL, NULL))
900205738Spjd		sync_start();
901204076Spjd	error = pthread_create(&td, NULL, ggate_recv_thread, res);
902218138Spjd	PJDLOG_ASSERT(error == 0);
903204076Spjd	error = pthread_create(&td, NULL, local_send_thread, res);
904218138Spjd	PJDLOG_ASSERT(error == 0);
905204076Spjd	error = pthread_create(&td, NULL, remote_send_thread, res);
906218138Spjd	PJDLOG_ASSERT(error == 0);
907204076Spjd	error = pthread_create(&td, NULL, remote_recv_thread, res);
908218138Spjd	PJDLOG_ASSERT(error == 0);
909204076Spjd	error = pthread_create(&td, NULL, ggate_send_thread, res);
910218138Spjd	PJDLOG_ASSERT(error == 0);
911213530Spjd	(void)sync_thread(res);
912204076Spjd}
913204076Spjd
914204076Spjdstatic void
915204076Spjdreqlog(int loglevel, int debuglevel, struct g_gate_ctl_io *ggio, const char *fmt, ...)
916204076Spjd{
917204076Spjd	char msg[1024];
918204076Spjd	va_list ap;
919204076Spjd	int len;
920204076Spjd
921204076Spjd	va_start(ap, fmt);
922204076Spjd	len = vsnprintf(msg, sizeof(msg), fmt, ap);
923204076Spjd	va_end(ap);
924204076Spjd	if ((size_t)len < sizeof(msg)) {
925204076Spjd		switch (ggio->gctl_cmd) {
926204076Spjd		case BIO_READ:
927204076Spjd			(void)snprintf(msg + len, sizeof(msg) - len,
928204076Spjd			    "READ(%ju, %ju).", (uintmax_t)ggio->gctl_offset,
929204076Spjd			    (uintmax_t)ggio->gctl_length);
930204076Spjd			break;
931204076Spjd		case BIO_DELETE:
932204076Spjd			(void)snprintf(msg + len, sizeof(msg) - len,
933204076Spjd			    "DELETE(%ju, %ju).", (uintmax_t)ggio->gctl_offset,
934204076Spjd			    (uintmax_t)ggio->gctl_length);
935204076Spjd			break;
936204076Spjd		case BIO_FLUSH:
937204076Spjd			(void)snprintf(msg + len, sizeof(msg) - len, "FLUSH.");
938204076Spjd			break;
939204076Spjd		case BIO_WRITE:
940204076Spjd			(void)snprintf(msg + len, sizeof(msg) - len,
941204076Spjd			    "WRITE(%ju, %ju).", (uintmax_t)ggio->gctl_offset,
942204076Spjd			    (uintmax_t)ggio->gctl_length);
943204076Spjd			break;
944204076Spjd		default:
945204076Spjd			(void)snprintf(msg + len, sizeof(msg) - len,
946204076Spjd			    "UNKNOWN(%u).", (unsigned int)ggio->gctl_cmd);
947204076Spjd			break;
948204076Spjd		}
949204076Spjd	}
950204076Spjd	pjdlog_common(loglevel, debuglevel, -1, "%s", msg);
951204076Spjd}
952204076Spjd
953204076Spjdstatic void
954204076Spjdremote_close(struct hast_resource *res, int ncomp)
955204076Spjd{
956204076Spjd
957204076Spjd	rw_wlock(&hio_remote_lock[ncomp]);
958204076Spjd	/*
959204076Spjd	 * A race is possible between dropping rlock and acquiring wlock -
960204076Spjd	 * another thread can close connection in-between.
961204076Spjd	 */
962204076Spjd	if (!ISCONNECTED(res, ncomp)) {
963218138Spjd		PJDLOG_ASSERT(res->hr_remotein == NULL);
964218138Spjd		PJDLOG_ASSERT(res->hr_remoteout == NULL);
965204076Spjd		rw_unlock(&hio_remote_lock[ncomp]);
966204076Spjd		return;
967204076Spjd	}
968204076Spjd
969218138Spjd	PJDLOG_ASSERT(res->hr_remotein != NULL);
970218138Spjd	PJDLOG_ASSERT(res->hr_remoteout != NULL);
971204076Spjd
972211881Spjd	pjdlog_debug(2, "Closing incoming connection to %s.",
973204076Spjd	    res->hr_remoteaddr);
974204076Spjd	proto_close(res->hr_remotein);
975204076Spjd	res->hr_remotein = NULL;
976211881Spjd	pjdlog_debug(2, "Closing outgoing connection to %s.",
977204076Spjd	    res->hr_remoteaddr);
978204076Spjd	proto_close(res->hr_remoteout);
979204076Spjd	res->hr_remoteout = NULL;
980204076Spjd
981204076Spjd	rw_unlock(&hio_remote_lock[ncomp]);
982204076Spjd
983211881Spjd	pjdlog_warning("Disconnected from %s.", res->hr_remoteaddr);
984211881Spjd
985204076Spjd	/*
986204076Spjd	 * Stop synchronization if in-progress.
987204076Spjd	 */
988211878Spjd	sync_stop();
989211984Spjd
990212038Spjd	event_send(res, EVENT_DISCONNECT);
991204076Spjd}
992204076Spjd
993204076Spjd/*
994204076Spjd * Thread receives ggate I/O requests from the kernel and passes them to
995204076Spjd * appropriate threads:
996204076Spjd * WRITE - always goes to both local_send and remote_send threads
997204076Spjd * READ (when the block is up-to-date on local component) -
998204076Spjd *	only local_send thread
999204076Spjd * READ (when the block isn't up-to-date on local component) -
1000204076Spjd *	only remote_send thread
1001204076Spjd * DELETE - always goes to both local_send and remote_send threads
1002204076Spjd * FLUSH - always goes to both local_send and remote_send threads
1003204076Spjd */
1004204076Spjdstatic void *
1005204076Spjdggate_recv_thread(void *arg)
1006204076Spjd{
1007204076Spjd	struct hast_resource *res = arg;
1008204076Spjd	struct g_gate_ctl_io *ggio;
1009204076Spjd	struct hio *hio;
1010204076Spjd	unsigned int ii, ncomp, ncomps;
1011204076Spjd	int error;
1012204076Spjd
1013204076Spjd	ncomps = HAST_NCOMPONENTS;
1014204076Spjd
1015204076Spjd	for (;;) {
1016204076Spjd		pjdlog_debug(2, "ggate_recv: Taking free request.");
1017204076Spjd		QUEUE_TAKE2(hio, free);
1018204076Spjd		pjdlog_debug(2, "ggate_recv: (%p) Got free request.", hio);
1019204076Spjd		ggio = &hio->hio_ggio;
1020204076Spjd		ggio->gctl_unit = res->hr_ggateunit;
1021204076Spjd		ggio->gctl_length = MAXPHYS;
1022204076Spjd		ggio->gctl_error = 0;
1023204076Spjd		pjdlog_debug(2,
1024204076Spjd		    "ggate_recv: (%p) Waiting for request from the kernel.",
1025204076Spjd		    hio);
1026204076Spjd		if (ioctl(res->hr_ggatefd, G_GATE_CMD_START, ggio) < 0) {
1027204076Spjd			if (sigexit_received)
1028204076Spjd				pthread_exit(NULL);
1029204076Spjd			primary_exit(EX_OSERR, "G_GATE_CMD_START failed");
1030204076Spjd		}
1031204076Spjd		error = ggio->gctl_error;
1032204076Spjd		switch (error) {
1033204076Spjd		case 0:
1034204076Spjd			break;
1035204076Spjd		case ECANCELED:
1036204076Spjd			/* Exit gracefully. */
1037204076Spjd			if (!sigexit_received) {
1038204076Spjd				pjdlog_debug(2,
1039204076Spjd				    "ggate_recv: (%p) Received cancel from the kernel.",
1040204076Spjd				    hio);
1041204076Spjd				pjdlog_info("Received cancel from the kernel, exiting.");
1042204076Spjd			}
1043204076Spjd			pthread_exit(NULL);
1044204076Spjd		case ENOMEM:
1045204076Spjd			/*
1046204076Spjd			 * Buffer too small? Impossible, we allocate MAXPHYS
1047204076Spjd			 * bytes - request can't be bigger than that.
1048204076Spjd			 */
1049204076Spjd			/* FALLTHROUGH */
1050204076Spjd		case ENXIO:
1051204076Spjd		default:
1052204076Spjd			primary_exitx(EX_OSERR, "G_GATE_CMD_START failed: %s.",
1053204076Spjd			    strerror(error));
1054204076Spjd		}
1055204076Spjd		for (ii = 0; ii < ncomps; ii++)
1056204076Spjd			hio->hio_errors[ii] = EINVAL;
1057204076Spjd		reqlog(LOG_DEBUG, 2, ggio,
1058204076Spjd		    "ggate_recv: (%p) Request received from the kernel: ",
1059204076Spjd		    hio);
1060204076Spjd		/*
1061204076Spjd		 * Inform all components about new write request.
1062204076Spjd		 * For read request prefer local component unless the given
1063204076Spjd		 * range is out-of-date, then use remote component.
1064204076Spjd		 */
1065204076Spjd		switch (ggio->gctl_cmd) {
1066204076Spjd		case BIO_READ:
1067204076Spjd			pjdlog_debug(2,
1068204076Spjd			    "ggate_recv: (%p) Moving request to the send queue.",
1069204076Spjd			    hio);
1070204076Spjd			refcount_init(&hio->hio_countdown, 1);
1071204076Spjd			mtx_lock(&metadata_lock);
1072204076Spjd			if (res->hr_syncsrc == HAST_SYNCSRC_UNDEF ||
1073204076Spjd			    res->hr_syncsrc == HAST_SYNCSRC_PRIMARY) {
1074204076Spjd				/*
1075204076Spjd				 * This range is up-to-date on local component,
1076204076Spjd				 * so handle request locally.
1077204076Spjd				 */
1078204076Spjd				 /* Local component is 0 for now. */
1079204076Spjd				ncomp = 0;
1080204076Spjd			} else /* if (res->hr_syncsrc ==
1081204076Spjd			    HAST_SYNCSRC_SECONDARY) */ {
1082218138Spjd				PJDLOG_ASSERT(res->hr_syncsrc ==
1083204076Spjd				    HAST_SYNCSRC_SECONDARY);
1084204076Spjd				/*
1085204076Spjd				 * This range is out-of-date on local component,
1086204076Spjd				 * so send request to the remote node.
1087204076Spjd				 */
1088204076Spjd				 /* Remote component is 1 for now. */
1089204076Spjd				ncomp = 1;
1090204076Spjd			}
1091204076Spjd			mtx_unlock(&metadata_lock);
1092204076Spjd			QUEUE_INSERT1(hio, send, ncomp);
1093204076Spjd			break;
1094204076Spjd		case BIO_WRITE:
1095214284Spjd			if (res->hr_resuid == 0) {
1096219844Spjd				/*
1097219844Spjd				 * This is first write, initialize localcnt and
1098219844Spjd				 * resuid.
1099219844Spjd				 */
1100219844Spjd				res->hr_primary_localcnt = 1;
1101214284Spjd				(void)init_resuid(res);
1102214284Spjd			}
1103204076Spjd			for (;;) {
1104204076Spjd				mtx_lock(&range_lock);
1105204076Spjd				if (rangelock_islocked(range_sync,
1106204076Spjd				    ggio->gctl_offset, ggio->gctl_length)) {
1107204076Spjd					pjdlog_debug(2,
1108204076Spjd					    "regular: Range offset=%jd length=%zu locked.",
1109204076Spjd					    (intmax_t)ggio->gctl_offset,
1110204076Spjd					    (size_t)ggio->gctl_length);
1111204076Spjd					range_regular_wait = true;
1112204076Spjd					cv_wait(&range_regular_cond, &range_lock);
1113204076Spjd					range_regular_wait = false;
1114204076Spjd					mtx_unlock(&range_lock);
1115204076Spjd					continue;
1116204076Spjd				}
1117204076Spjd				if (rangelock_add(range_regular,
1118204076Spjd				    ggio->gctl_offset, ggio->gctl_length) < 0) {
1119204076Spjd					mtx_unlock(&range_lock);
1120204076Spjd					pjdlog_debug(2,
1121204076Spjd					    "regular: Range offset=%jd length=%zu is already locked, waiting.",
1122204076Spjd					    (intmax_t)ggio->gctl_offset,
1123204076Spjd					    (size_t)ggio->gctl_length);
1124204076Spjd					sleep(1);
1125204076Spjd					continue;
1126204076Spjd				}
1127204076Spjd				mtx_unlock(&range_lock);
1128204076Spjd				break;
1129204076Spjd			}
1130204076Spjd			mtx_lock(&res->hr_amp_lock);
1131204076Spjd			if (activemap_write_start(res->hr_amp,
1132204076Spjd			    ggio->gctl_offset, ggio->gctl_length)) {
1133204076Spjd				(void)hast_activemap_flush(res);
1134204076Spjd			}
1135204076Spjd			mtx_unlock(&res->hr_amp_lock);
1136204076Spjd			/* FALLTHROUGH */
1137204076Spjd		case BIO_DELETE:
1138204076Spjd		case BIO_FLUSH:
1139204076Spjd			pjdlog_debug(2,
1140204076Spjd			    "ggate_recv: (%p) Moving request to the send queues.",
1141204076Spjd			    hio);
1142204076Spjd			refcount_init(&hio->hio_countdown, ncomps);
1143204076Spjd			for (ii = 0; ii < ncomps; ii++)
1144204076Spjd				QUEUE_INSERT1(hio, send, ii);
1145204076Spjd			break;
1146204076Spjd		}
1147204076Spjd	}
1148204076Spjd	/* NOTREACHED */
1149204076Spjd	return (NULL);
1150204076Spjd}
1151204076Spjd
1152204076Spjd/*
1153204076Spjd * Thread reads from or writes to local component.
1154204076Spjd * If local read fails, it redirects it to remote_send thread.
1155204076Spjd */
1156204076Spjdstatic void *
1157204076Spjdlocal_send_thread(void *arg)
1158204076Spjd{
1159204076Spjd	struct hast_resource *res = arg;
1160204076Spjd	struct g_gate_ctl_io *ggio;
1161204076Spjd	struct hio *hio;
1162204076Spjd	unsigned int ncomp, rncomp;
1163204076Spjd	ssize_t ret;
1164204076Spjd
1165204076Spjd	/* Local component is 0 for now. */
1166204076Spjd	ncomp = 0;
1167204076Spjd	/* Remote component is 1 for now. */
1168204076Spjd	rncomp = 1;
1169204076Spjd
1170204076Spjd	for (;;) {
1171204076Spjd		pjdlog_debug(2, "local_send: Taking request.");
1172214692Spjd		QUEUE_TAKE1(hio, send, ncomp, 0);
1173204076Spjd		pjdlog_debug(2, "local_send: (%p) Got request.", hio);
1174204076Spjd		ggio = &hio->hio_ggio;
1175204076Spjd		switch (ggio->gctl_cmd) {
1176204076Spjd		case BIO_READ:
1177204076Spjd			ret = pread(res->hr_localfd, ggio->gctl_data,
1178204076Spjd			    ggio->gctl_length,
1179204076Spjd			    ggio->gctl_offset + res->hr_localoff);
1180204076Spjd			if (ret == ggio->gctl_length)
1181204076Spjd				hio->hio_errors[ncomp] = 0;
1182204076Spjd			else {
1183204076Spjd				/*
1184204076Spjd				 * If READ failed, try to read from remote node.
1185204076Spjd				 */
1186216479Spjd				if (ret < 0) {
1187216479Spjd					reqlog(LOG_WARNING, 0, ggio,
1188216479Spjd					    "Local request failed (%s), trying remote node. ",
1189216479Spjd					    strerror(errno));
1190216479Spjd				} else if (ret != ggio->gctl_length) {
1191216479Spjd					reqlog(LOG_WARNING, 0, ggio,
1192216479Spjd					    "Local request failed (%zd != %jd), trying remote node. ",
1193216494Spjd					    ret, (intmax_t)ggio->gctl_length);
1194216479Spjd				}
1195204076Spjd				QUEUE_INSERT1(hio, send, rncomp);
1196204076Spjd				continue;
1197204076Spjd			}
1198204076Spjd			break;
1199204076Spjd		case BIO_WRITE:
1200204076Spjd			ret = pwrite(res->hr_localfd, ggio->gctl_data,
1201204076Spjd			    ggio->gctl_length,
1202204076Spjd			    ggio->gctl_offset + res->hr_localoff);
1203216479Spjd			if (ret < 0) {
1204204076Spjd				hio->hio_errors[ncomp] = errno;
1205216479Spjd				reqlog(LOG_WARNING, 0, ggio,
1206216479Spjd				    "Local request failed (%s): ",
1207216479Spjd				    strerror(errno));
1208216479Spjd			} else if (ret != ggio->gctl_length) {
1209204076Spjd				hio->hio_errors[ncomp] = EIO;
1210216479Spjd				reqlog(LOG_WARNING, 0, ggio,
1211216479Spjd				    "Local request failed (%zd != %jd): ",
1212216494Spjd				    ret, (intmax_t)ggio->gctl_length);
1213216479Spjd			} else {
1214204076Spjd				hio->hio_errors[ncomp] = 0;
1215216479Spjd			}
1216204076Spjd			break;
1217204076Spjd		case BIO_DELETE:
1218204076Spjd			ret = g_delete(res->hr_localfd,
1219204076Spjd			    ggio->gctl_offset + res->hr_localoff,
1220204076Spjd			    ggio->gctl_length);
1221216479Spjd			if (ret < 0) {
1222204076Spjd				hio->hio_errors[ncomp] = errno;
1223216479Spjd				reqlog(LOG_WARNING, 0, ggio,
1224216479Spjd				    "Local request failed (%s): ",
1225216479Spjd				    strerror(errno));
1226216479Spjd			} else {
1227204076Spjd				hio->hio_errors[ncomp] = 0;
1228216479Spjd			}
1229204076Spjd			break;
1230204076Spjd		case BIO_FLUSH:
1231204076Spjd			ret = g_flush(res->hr_localfd);
1232216479Spjd			if (ret < 0) {
1233204076Spjd				hio->hio_errors[ncomp] = errno;
1234216479Spjd				reqlog(LOG_WARNING, 0, ggio,
1235216479Spjd				    "Local request failed (%s): ",
1236216479Spjd				    strerror(errno));
1237216479Spjd			} else {
1238204076Spjd				hio->hio_errors[ncomp] = 0;
1239216479Spjd			}
1240204076Spjd			break;
1241204076Spjd		}
1242204076Spjd		if (refcount_release(&hio->hio_countdown)) {
1243204076Spjd			if (ISSYNCREQ(hio)) {
1244204076Spjd				mtx_lock(&sync_lock);
1245204076Spjd				SYNCREQDONE(hio);
1246204076Spjd				mtx_unlock(&sync_lock);
1247204076Spjd				cv_signal(&sync_cond);
1248204076Spjd			} else {
1249204076Spjd				pjdlog_debug(2,
1250204076Spjd				    "local_send: (%p) Moving request to the done queue.",
1251204076Spjd				    hio);
1252204076Spjd				QUEUE_INSERT2(hio, done);
1253204076Spjd			}
1254204076Spjd		}
1255204076Spjd	}
1256204076Spjd	/* NOTREACHED */
1257204076Spjd	return (NULL);
1258204076Spjd}
1259204076Spjd
1260214692Spjdstatic void
1261214692Spjdkeepalive_send(struct hast_resource *res, unsigned int ncomp)
1262214692Spjd{
1263214692Spjd	struct nv *nv;
1264214692Spjd
1265218217Spjd	rw_rlock(&hio_remote_lock[ncomp]);
1266218217Spjd
1267218217Spjd	if (!ISCONNECTED(res, ncomp)) {
1268218217Spjd		rw_unlock(&hio_remote_lock[ncomp]);
1269214692Spjd		return;
1270218217Spjd	}
1271219864Spjd
1272218138Spjd	PJDLOG_ASSERT(res->hr_remotein != NULL);
1273218138Spjd	PJDLOG_ASSERT(res->hr_remoteout != NULL);
1274214692Spjd
1275214692Spjd	nv = nv_alloc();
1276214692Spjd	nv_add_uint8(nv, HIO_KEEPALIVE, "cmd");
1277214692Spjd	if (nv_error(nv) != 0) {
1278218217Spjd		rw_unlock(&hio_remote_lock[ncomp]);
1279214692Spjd		nv_free(nv);
1280214692Spjd		pjdlog_debug(1,
1281214692Spjd		    "keepalive_send: Unable to prepare header to send.");
1282214692Spjd		return;
1283214692Spjd	}
1284214692Spjd	if (hast_proto_send(res, res->hr_remoteout, nv, NULL, 0) < 0) {
1285218217Spjd		rw_unlock(&hio_remote_lock[ncomp]);
1286214692Spjd		pjdlog_common(LOG_DEBUG, 1, errno,
1287214692Spjd		    "keepalive_send: Unable to send request");
1288214692Spjd		nv_free(nv);
1289214692Spjd		remote_close(res, ncomp);
1290214692Spjd		return;
1291214692Spjd	}
1292218217Spjd
1293218217Spjd	rw_unlock(&hio_remote_lock[ncomp]);
1294214692Spjd	nv_free(nv);
1295214692Spjd	pjdlog_debug(2, "keepalive_send: Request sent.");
1296214692Spjd}
1297214692Spjd
1298204076Spjd/*
1299204076Spjd * Thread sends request to secondary node.
1300204076Spjd */
1301204076Spjdstatic void *
1302204076Spjdremote_send_thread(void *arg)
1303204076Spjd{
1304204076Spjd	struct hast_resource *res = arg;
1305204076Spjd	struct g_gate_ctl_io *ggio;
1306214692Spjd	time_t lastcheck, now;
1307204076Spjd	struct hio *hio;
1308204076Spjd	struct nv *nv;
1309204076Spjd	unsigned int ncomp;
1310204076Spjd	bool wakeup;
1311204076Spjd	uint64_t offset, length;
1312204076Spjd	uint8_t cmd;
1313204076Spjd	void *data;
1314204076Spjd
1315204076Spjd	/* Remote component is 1 for now. */
1316204076Spjd	ncomp = 1;
1317219864Spjd	lastcheck = time(NULL);
1318204076Spjd
1319204076Spjd	for (;;) {
1320204076Spjd		pjdlog_debug(2, "remote_send: Taking request.");
1321219721Strociny		QUEUE_TAKE1(hio, send, ncomp, HAST_KEEPALIVE);
1322214692Spjd		if (hio == NULL) {
1323214692Spjd			now = time(NULL);
1324219721Strociny			if (lastcheck + HAST_KEEPALIVE <= now) {
1325214692Spjd				keepalive_send(res, ncomp);
1326214692Spjd				lastcheck = now;
1327214692Spjd			}
1328214692Spjd			continue;
1329214692Spjd		}
1330204076Spjd		pjdlog_debug(2, "remote_send: (%p) Got request.", hio);
1331204076Spjd		ggio = &hio->hio_ggio;
1332204076Spjd		switch (ggio->gctl_cmd) {
1333204076Spjd		case BIO_READ:
1334204076Spjd			cmd = HIO_READ;
1335204076Spjd			data = NULL;
1336204076Spjd			offset = ggio->gctl_offset;
1337204076Spjd			length = ggio->gctl_length;
1338204076Spjd			break;
1339204076Spjd		case BIO_WRITE:
1340204076Spjd			cmd = HIO_WRITE;
1341204076Spjd			data = ggio->gctl_data;
1342204076Spjd			offset = ggio->gctl_offset;
1343204076Spjd			length = ggio->gctl_length;
1344204076Spjd			break;
1345204076Spjd		case BIO_DELETE:
1346204076Spjd			cmd = HIO_DELETE;
1347204076Spjd			data = NULL;
1348204076Spjd			offset = ggio->gctl_offset;
1349204076Spjd			length = ggio->gctl_length;
1350204076Spjd			break;
1351204076Spjd		case BIO_FLUSH:
1352204076Spjd			cmd = HIO_FLUSH;
1353204076Spjd			data = NULL;
1354204076Spjd			offset = 0;
1355204076Spjd			length = 0;
1356204076Spjd			break;
1357204076Spjd		default:
1358218138Spjd			PJDLOG_ASSERT(!"invalid condition");
1359204076Spjd			abort();
1360204076Spjd		}
1361204076Spjd		nv = nv_alloc();
1362204076Spjd		nv_add_uint8(nv, cmd, "cmd");
1363204076Spjd		nv_add_uint64(nv, (uint64_t)ggio->gctl_seq, "seq");
1364204076Spjd		nv_add_uint64(nv, offset, "offset");
1365204076Spjd		nv_add_uint64(nv, length, "length");
1366204076Spjd		if (nv_error(nv) != 0) {
1367204076Spjd			hio->hio_errors[ncomp] = nv_error(nv);
1368204076Spjd			pjdlog_debug(2,
1369204076Spjd			    "remote_send: (%p) Unable to prepare header to send.",
1370204076Spjd			    hio);
1371204076Spjd			reqlog(LOG_ERR, 0, ggio,
1372204076Spjd			    "Unable to prepare header to send (%s): ",
1373204076Spjd			    strerror(nv_error(nv)));
1374204076Spjd			/* Move failed request immediately to the done queue. */
1375204076Spjd			goto done_queue;
1376204076Spjd		}
1377204076Spjd		pjdlog_debug(2,
1378204076Spjd		    "remote_send: (%p) Moving request to the recv queue.",
1379204076Spjd		    hio);
1380204076Spjd		/*
1381204076Spjd		 * Protect connection from disappearing.
1382204076Spjd		 */
1383204076Spjd		rw_rlock(&hio_remote_lock[ncomp]);
1384204076Spjd		if (!ISCONNECTED(res, ncomp)) {
1385204076Spjd			rw_unlock(&hio_remote_lock[ncomp]);
1386204076Spjd			hio->hio_errors[ncomp] = ENOTCONN;
1387204076Spjd			goto done_queue;
1388204076Spjd		}
1389204076Spjd		/*
1390204076Spjd		 * Move the request to recv queue before sending it, because
1391204076Spjd		 * in different order we can get reply before we move request
1392204076Spjd		 * to recv queue.
1393204076Spjd		 */
1394204076Spjd		mtx_lock(&hio_recv_list_lock[ncomp]);
1395204076Spjd		wakeup = TAILQ_EMPTY(&hio_recv_list[ncomp]);
1396204076Spjd		TAILQ_INSERT_TAIL(&hio_recv_list[ncomp], hio, hio_next[ncomp]);
1397204076Spjd		mtx_unlock(&hio_recv_list_lock[ncomp]);
1398204076Spjd		if (hast_proto_send(res, res->hr_remoteout, nv, data,
1399204076Spjd		    data != NULL ? length : 0) < 0) {
1400204076Spjd			hio->hio_errors[ncomp] = errno;
1401204076Spjd			rw_unlock(&hio_remote_lock[ncomp]);
1402204076Spjd			pjdlog_debug(2,
1403204076Spjd			    "remote_send: (%p) Unable to send request.", hio);
1404204076Spjd			reqlog(LOG_ERR, 0, ggio,
1405204076Spjd			    "Unable to send request (%s): ",
1406204076Spjd			    strerror(hio->hio_errors[ncomp]));
1407211979Spjd			remote_close(res, ncomp);
1408204076Spjd			/*
1409204076Spjd			 * Take request back from the receive queue and move
1410204076Spjd			 * it immediately to the done queue.
1411204076Spjd			 */
1412204076Spjd			mtx_lock(&hio_recv_list_lock[ncomp]);
1413204076Spjd			TAILQ_REMOVE(&hio_recv_list[ncomp], hio, hio_next[ncomp]);
1414204076Spjd			mtx_unlock(&hio_recv_list_lock[ncomp]);
1415204076Spjd			goto done_queue;
1416204076Spjd		}
1417204076Spjd		rw_unlock(&hio_remote_lock[ncomp]);
1418204076Spjd		nv_free(nv);
1419204076Spjd		if (wakeup)
1420204076Spjd			cv_signal(&hio_recv_list_cond[ncomp]);
1421204076Spjd		continue;
1422204076Spjddone_queue:
1423204076Spjd		nv_free(nv);
1424204076Spjd		if (ISSYNCREQ(hio)) {
1425204076Spjd			if (!refcount_release(&hio->hio_countdown))
1426204076Spjd				continue;
1427204076Spjd			mtx_lock(&sync_lock);
1428204076Spjd			SYNCREQDONE(hio);
1429204076Spjd			mtx_unlock(&sync_lock);
1430204076Spjd			cv_signal(&sync_cond);
1431204076Spjd			continue;
1432204076Spjd		}
1433204076Spjd		if (ggio->gctl_cmd == BIO_WRITE) {
1434204076Spjd			mtx_lock(&res->hr_amp_lock);
1435204076Spjd			if (activemap_need_sync(res->hr_amp, ggio->gctl_offset,
1436204076Spjd			    ggio->gctl_length)) {
1437204076Spjd				(void)hast_activemap_flush(res);
1438204076Spjd			}
1439204076Spjd			mtx_unlock(&res->hr_amp_lock);
1440204076Spjd		}
1441204076Spjd		if (!refcount_release(&hio->hio_countdown))
1442204076Spjd			continue;
1443204076Spjd		pjdlog_debug(2,
1444204076Spjd		    "remote_send: (%p) Moving request to the done queue.",
1445204076Spjd		    hio);
1446204076Spjd		QUEUE_INSERT2(hio, done);
1447204076Spjd	}
1448204076Spjd	/* NOTREACHED */
1449204076Spjd	return (NULL);
1450204076Spjd}
1451204076Spjd
1452204076Spjd/*
1453204076Spjd * Thread receives answer from secondary node and passes it to ggate_send
1454204076Spjd * thread.
1455204076Spjd */
1456204076Spjdstatic void *
1457204076Spjdremote_recv_thread(void *arg)
1458204076Spjd{
1459204076Spjd	struct hast_resource *res = arg;
1460204076Spjd	struct g_gate_ctl_io *ggio;
1461204076Spjd	struct hio *hio;
1462204076Spjd	struct nv *nv;
1463204076Spjd	unsigned int ncomp;
1464204076Spjd	uint64_t seq;
1465204076Spjd	int error;
1466204076Spjd
1467204076Spjd	/* Remote component is 1 for now. */
1468204076Spjd	ncomp = 1;
1469204076Spjd
1470204076Spjd	for (;;) {
1471204076Spjd		/* Wait until there is anything to receive. */
1472204076Spjd		mtx_lock(&hio_recv_list_lock[ncomp]);
1473204076Spjd		while (TAILQ_EMPTY(&hio_recv_list[ncomp])) {
1474204076Spjd			pjdlog_debug(2, "remote_recv: No requests, waiting.");
1475204076Spjd			cv_wait(&hio_recv_list_cond[ncomp],
1476204076Spjd			    &hio_recv_list_lock[ncomp]);
1477204076Spjd		}
1478204076Spjd		mtx_unlock(&hio_recv_list_lock[ncomp]);
1479204076Spjd		rw_rlock(&hio_remote_lock[ncomp]);
1480204076Spjd		if (!ISCONNECTED(res, ncomp)) {
1481204076Spjd			rw_unlock(&hio_remote_lock[ncomp]);
1482204076Spjd			/*
1483204076Spjd			 * Connection is dead, so move all pending requests to
1484204076Spjd			 * the done queue (one-by-one).
1485204076Spjd			 */
1486204076Spjd			mtx_lock(&hio_recv_list_lock[ncomp]);
1487204076Spjd			hio = TAILQ_FIRST(&hio_recv_list[ncomp]);
1488218138Spjd			PJDLOG_ASSERT(hio != NULL);
1489204076Spjd			TAILQ_REMOVE(&hio_recv_list[ncomp], hio,
1490204076Spjd			    hio_next[ncomp]);
1491204076Spjd			mtx_unlock(&hio_recv_list_lock[ncomp]);
1492204076Spjd			goto done_queue;
1493204076Spjd		}
1494204076Spjd		if (hast_proto_recv_hdr(res->hr_remotein, &nv) < 0) {
1495204076Spjd			pjdlog_errno(LOG_ERR,
1496204076Spjd			    "Unable to receive reply header");
1497204076Spjd			rw_unlock(&hio_remote_lock[ncomp]);
1498204076Spjd			remote_close(res, ncomp);
1499204076Spjd			continue;
1500204076Spjd		}
1501204076Spjd		rw_unlock(&hio_remote_lock[ncomp]);
1502204076Spjd		seq = nv_get_uint64(nv, "seq");
1503204076Spjd		if (seq == 0) {
1504204076Spjd			pjdlog_error("Header contains no 'seq' field.");
1505204076Spjd			nv_free(nv);
1506204076Spjd			continue;
1507204076Spjd		}
1508204076Spjd		mtx_lock(&hio_recv_list_lock[ncomp]);
1509204076Spjd		TAILQ_FOREACH(hio, &hio_recv_list[ncomp], hio_next[ncomp]) {
1510204076Spjd			if (hio->hio_ggio.gctl_seq == seq) {
1511204076Spjd				TAILQ_REMOVE(&hio_recv_list[ncomp], hio,
1512204076Spjd				    hio_next[ncomp]);
1513204076Spjd				break;
1514204076Spjd			}
1515204076Spjd		}
1516204076Spjd		mtx_unlock(&hio_recv_list_lock[ncomp]);
1517204076Spjd		if (hio == NULL) {
1518204076Spjd			pjdlog_error("Found no request matching received 'seq' field (%ju).",
1519204076Spjd			    (uintmax_t)seq);
1520204076Spjd			nv_free(nv);
1521204076Spjd			continue;
1522204076Spjd		}
1523204076Spjd		error = nv_get_int16(nv, "error");
1524204076Spjd		if (error != 0) {
1525204076Spjd			/* Request failed on remote side. */
1526216478Spjd			hio->hio_errors[ncomp] = error;
1527216479Spjd			reqlog(LOG_WARNING, 0, &hio->hio_ggio,
1528216479Spjd			    "Remote request failed (%s): ", strerror(error));
1529204076Spjd			nv_free(nv);
1530204076Spjd			goto done_queue;
1531204076Spjd		}
1532204076Spjd		ggio = &hio->hio_ggio;
1533204076Spjd		switch (ggio->gctl_cmd) {
1534204076Spjd		case BIO_READ:
1535204076Spjd			rw_rlock(&hio_remote_lock[ncomp]);
1536204076Spjd			if (!ISCONNECTED(res, ncomp)) {
1537204076Spjd				rw_unlock(&hio_remote_lock[ncomp]);
1538204076Spjd				nv_free(nv);
1539204076Spjd				goto done_queue;
1540204076Spjd			}
1541204076Spjd			if (hast_proto_recv_data(res, res->hr_remotein, nv,
1542204076Spjd			    ggio->gctl_data, ggio->gctl_length) < 0) {
1543204076Spjd				hio->hio_errors[ncomp] = errno;
1544204076Spjd				pjdlog_errno(LOG_ERR,
1545204076Spjd				    "Unable to receive reply data");
1546204076Spjd				rw_unlock(&hio_remote_lock[ncomp]);
1547204076Spjd				nv_free(nv);
1548204076Spjd				remote_close(res, ncomp);
1549204076Spjd				goto done_queue;
1550204076Spjd			}
1551204076Spjd			rw_unlock(&hio_remote_lock[ncomp]);
1552204076Spjd			break;
1553204076Spjd		case BIO_WRITE:
1554204076Spjd		case BIO_DELETE:
1555204076Spjd		case BIO_FLUSH:
1556204076Spjd			break;
1557204076Spjd		default:
1558218138Spjd			PJDLOG_ASSERT(!"invalid condition");
1559204076Spjd			abort();
1560204076Spjd		}
1561204076Spjd		hio->hio_errors[ncomp] = 0;
1562204076Spjd		nv_free(nv);
1563204076Spjddone_queue:
1564204076Spjd		if (refcount_release(&hio->hio_countdown)) {
1565204076Spjd			if (ISSYNCREQ(hio)) {
1566204076Spjd				mtx_lock(&sync_lock);
1567204076Spjd				SYNCREQDONE(hio);
1568204076Spjd				mtx_unlock(&sync_lock);
1569204076Spjd				cv_signal(&sync_cond);
1570204076Spjd			} else {
1571204076Spjd				pjdlog_debug(2,
1572204076Spjd				    "remote_recv: (%p) Moving request to the done queue.",
1573204076Spjd				    hio);
1574204076Spjd				QUEUE_INSERT2(hio, done);
1575204076Spjd			}
1576204076Spjd		}
1577204076Spjd	}
1578204076Spjd	/* NOTREACHED */
1579204076Spjd	return (NULL);
1580204076Spjd}
1581204076Spjd
1582204076Spjd/*
1583204076Spjd * Thread sends answer to the kernel.
1584204076Spjd */
1585204076Spjdstatic void *
1586204076Spjdggate_send_thread(void *arg)
1587204076Spjd{
1588204076Spjd	struct hast_resource *res = arg;
1589204076Spjd	struct g_gate_ctl_io *ggio;
1590204076Spjd	struct hio *hio;
1591204076Spjd	unsigned int ii, ncomp, ncomps;
1592204076Spjd
1593204076Spjd	ncomps = HAST_NCOMPONENTS;
1594204076Spjd
1595204076Spjd	for (;;) {
1596204076Spjd		pjdlog_debug(2, "ggate_send: Taking request.");
1597204076Spjd		QUEUE_TAKE2(hio, done);
1598204076Spjd		pjdlog_debug(2, "ggate_send: (%p) Got request.", hio);
1599204076Spjd		ggio = &hio->hio_ggio;
1600204076Spjd		for (ii = 0; ii < ncomps; ii++) {
1601204076Spjd			if (hio->hio_errors[ii] == 0) {
1602204076Spjd				/*
1603204076Spjd				 * One successful request is enough to declare
1604204076Spjd				 * success.
1605204076Spjd				 */
1606204076Spjd				ggio->gctl_error = 0;
1607204076Spjd				break;
1608204076Spjd			}
1609204076Spjd		}
1610204076Spjd		if (ii == ncomps) {
1611204076Spjd			/*
1612204076Spjd			 * None of the requests were successful.
1613219879Strociny			 * Use the error from local component except the
1614219879Strociny			 * case when we did only remote request.
1615204076Spjd			 */
1616219879Strociny			if (ggio->gctl_cmd == BIO_READ &&
1617219879Strociny			    res->hr_syncsrc == HAST_SYNCSRC_SECONDARY)
1618219879Strociny				ggio->gctl_error = hio->hio_errors[1];
1619219879Strociny			else
1620219879Strociny				ggio->gctl_error = hio->hio_errors[0];
1621204076Spjd		}
1622204076Spjd		if (ggio->gctl_error == 0 && ggio->gctl_cmd == BIO_WRITE) {
1623204076Spjd			mtx_lock(&res->hr_amp_lock);
1624204076Spjd			activemap_write_complete(res->hr_amp,
1625204076Spjd			    ggio->gctl_offset, ggio->gctl_length);
1626204076Spjd			mtx_unlock(&res->hr_amp_lock);
1627204076Spjd		}
1628204076Spjd		if (ggio->gctl_cmd == BIO_WRITE) {
1629204076Spjd			/*
1630204076Spjd			 * Unlock range we locked.
1631204076Spjd			 */
1632204076Spjd			mtx_lock(&range_lock);
1633204076Spjd			rangelock_del(range_regular, ggio->gctl_offset,
1634204076Spjd			    ggio->gctl_length);
1635204076Spjd			if (range_sync_wait)
1636204076Spjd				cv_signal(&range_sync_cond);
1637204076Spjd			mtx_unlock(&range_lock);
1638204076Spjd			/*
1639204076Spjd			 * Bump local count if this is first write after
1640204076Spjd			 * connection failure with remote node.
1641204076Spjd			 */
1642204076Spjd			ncomp = 1;
1643204076Spjd			rw_rlock(&hio_remote_lock[ncomp]);
1644204076Spjd			if (!ISCONNECTED(res, ncomp)) {
1645204076Spjd				mtx_lock(&metadata_lock);
1646204076Spjd				if (res->hr_primary_localcnt ==
1647204076Spjd				    res->hr_secondary_remotecnt) {
1648204076Spjd					res->hr_primary_localcnt++;
1649204076Spjd					pjdlog_debug(1,
1650204076Spjd					    "Increasing localcnt to %ju.",
1651204076Spjd					    (uintmax_t)res->hr_primary_localcnt);
1652204076Spjd					(void)metadata_write(res);
1653204076Spjd				}
1654204076Spjd				mtx_unlock(&metadata_lock);
1655204076Spjd			}
1656204076Spjd			rw_unlock(&hio_remote_lock[ncomp]);
1657204076Spjd		}
1658204076Spjd		if (ioctl(res->hr_ggatefd, G_GATE_CMD_DONE, ggio) < 0)
1659204076Spjd			primary_exit(EX_OSERR, "G_GATE_CMD_DONE failed");
1660204076Spjd		pjdlog_debug(2,
1661204076Spjd		    "ggate_send: (%p) Moving request to the free queue.", hio);
1662204076Spjd		QUEUE_INSERT2(hio, free);
1663204076Spjd	}
1664204076Spjd	/* NOTREACHED */
1665204076Spjd	return (NULL);
1666204076Spjd}
1667204076Spjd
1668204076Spjd/*
1669204076Spjd * Thread synchronize local and remote components.
1670204076Spjd */
1671204076Spjdstatic void *
1672204076Spjdsync_thread(void *arg __unused)
1673204076Spjd{
1674204076Spjd	struct hast_resource *res = arg;
1675204076Spjd	struct hio *hio;
1676204076Spjd	struct g_gate_ctl_io *ggio;
1677219372Spjd	struct timeval tstart, tend, tdiff;
1678204076Spjd	unsigned int ii, ncomp, ncomps;
1679204076Spjd	off_t offset, length, synced;
1680204076Spjd	bool dorewind;
1681204076Spjd	int syncext;
1682204076Spjd
1683204076Spjd	ncomps = HAST_NCOMPONENTS;
1684204076Spjd	dorewind = true;
1685211897Spjd	synced = 0;
1686211897Spjd	offset = -1;
1687204076Spjd
1688204076Spjd	for (;;) {
1689204076Spjd		mtx_lock(&sync_lock);
1690211897Spjd		if (offset >= 0 && !sync_inprogress) {
1691219372Spjd			gettimeofday(&tend, NULL);
1692219372Spjd			timersub(&tend, &tstart, &tdiff);
1693219372Spjd			pjdlog_info("Synchronization interrupted after %#.0T. "
1694219372Spjd			    "%NB synchronized so far.", &tdiff,
1695211879Spjd			    (intmax_t)synced);
1696212038Spjd			event_send(res, EVENT_SYNCINTR);
1697211879Spjd		}
1698204076Spjd		while (!sync_inprogress) {
1699204076Spjd			dorewind = true;
1700204076Spjd			synced = 0;
1701204076Spjd			cv_wait(&sync_cond, &sync_lock);
1702204076Spjd		}
1703204076Spjd		mtx_unlock(&sync_lock);
1704204076Spjd		/*
1705204076Spjd		 * Obtain offset at which we should synchronize.
1706204076Spjd		 * Rewind synchronization if needed.
1707204076Spjd		 */
1708204076Spjd		mtx_lock(&res->hr_amp_lock);
1709204076Spjd		if (dorewind)
1710204076Spjd			activemap_sync_rewind(res->hr_amp);
1711204076Spjd		offset = activemap_sync_offset(res->hr_amp, &length, &syncext);
1712204076Spjd		if (syncext != -1) {
1713204076Spjd			/*
1714204076Spjd			 * We synchronized entire syncext extent, we can mark
1715204076Spjd			 * it as clean now.
1716204076Spjd			 */
1717204076Spjd			if (activemap_extent_complete(res->hr_amp, syncext))
1718204076Spjd				(void)hast_activemap_flush(res);
1719204076Spjd		}
1720204076Spjd		mtx_unlock(&res->hr_amp_lock);
1721204076Spjd		if (dorewind) {
1722204076Spjd			dorewind = false;
1723204076Spjd			if (offset < 0)
1724204076Spjd				pjdlog_info("Nodes are in sync.");
1725204076Spjd			else {
1726219372Spjd				pjdlog_info("Synchronization started. %NB to go.",
1727219372Spjd				    (intmax_t)(res->hr_extentsize *
1728204076Spjd				    activemap_ndirty(res->hr_amp)));
1729212038Spjd				event_send(res, EVENT_SYNCSTART);
1730219372Spjd				gettimeofday(&tstart, NULL);
1731204076Spjd			}
1732204076Spjd		}
1733204076Spjd		if (offset < 0) {
1734211878Spjd			sync_stop();
1735204076Spjd			pjdlog_debug(1, "Nothing to synchronize.");
1736204076Spjd			/*
1737204076Spjd			 * Synchronization complete, make both localcnt and
1738204076Spjd			 * remotecnt equal.
1739204076Spjd			 */
1740204076Spjd			ncomp = 1;
1741204076Spjd			rw_rlock(&hio_remote_lock[ncomp]);
1742204076Spjd			if (ISCONNECTED(res, ncomp)) {
1743204076Spjd				if (synced > 0) {
1744219372Spjd					int64_t bps;
1745219372Spjd
1746219372Spjd					gettimeofday(&tend, NULL);
1747219372Spjd					timersub(&tend, &tstart, &tdiff);
1748219372Spjd					bps = (int64_t)((double)synced /
1749219372Spjd					    ((double)tdiff.tv_sec +
1750219372Spjd					    (double)tdiff.tv_usec / 1000000));
1751204076Spjd					pjdlog_info("Synchronization complete. "
1752219372Spjd					    "%NB synchronized in %#.0lT (%NB/sec).",
1753219372Spjd					    (intmax_t)synced, &tdiff,
1754219372Spjd					    (intmax_t)bps);
1755212038Spjd					event_send(res, EVENT_SYNCDONE);
1756204076Spjd				}
1757204076Spjd				mtx_lock(&metadata_lock);
1758204076Spjd				res->hr_syncsrc = HAST_SYNCSRC_UNDEF;
1759204076Spjd				res->hr_primary_localcnt =
1760204076Spjd				    res->hr_secondary_localcnt;
1761204076Spjd				res->hr_primary_remotecnt =
1762204076Spjd				    res->hr_secondary_remotecnt;
1763204076Spjd				pjdlog_debug(1,
1764204076Spjd				    "Setting localcnt to %ju and remotecnt to %ju.",
1765204076Spjd				    (uintmax_t)res->hr_primary_localcnt,
1766204076Spjd				    (uintmax_t)res->hr_secondary_localcnt);
1767204076Spjd				(void)metadata_write(res);
1768204076Spjd				mtx_unlock(&metadata_lock);
1769204076Spjd			}
1770204076Spjd			rw_unlock(&hio_remote_lock[ncomp]);
1771204076Spjd			continue;
1772204076Spjd		}
1773204076Spjd		pjdlog_debug(2, "sync: Taking free request.");
1774204076Spjd		QUEUE_TAKE2(hio, free);
1775204076Spjd		pjdlog_debug(2, "sync: (%p) Got free request.", hio);
1776204076Spjd		/*
1777204076Spjd		 * Lock the range we are going to synchronize. We don't want
1778204076Spjd		 * race where someone writes between our read and write.
1779204076Spjd		 */
1780204076Spjd		for (;;) {
1781204076Spjd			mtx_lock(&range_lock);
1782204076Spjd			if (rangelock_islocked(range_regular, offset, length)) {
1783204076Spjd				pjdlog_debug(2,
1784204076Spjd				    "sync: Range offset=%jd length=%jd locked.",
1785204076Spjd				    (intmax_t)offset, (intmax_t)length);
1786204076Spjd				range_sync_wait = true;
1787204076Spjd				cv_wait(&range_sync_cond, &range_lock);
1788204076Spjd				range_sync_wait = false;
1789204076Spjd				mtx_unlock(&range_lock);
1790204076Spjd				continue;
1791204076Spjd			}
1792204076Spjd			if (rangelock_add(range_sync, offset, length) < 0) {
1793204076Spjd				mtx_unlock(&range_lock);
1794204076Spjd				pjdlog_debug(2,
1795204076Spjd				    "sync: Range offset=%jd length=%jd is already locked, waiting.",
1796204076Spjd				    (intmax_t)offset, (intmax_t)length);
1797204076Spjd				sleep(1);
1798204076Spjd				continue;
1799204076Spjd			}
1800204076Spjd			mtx_unlock(&range_lock);
1801204076Spjd			break;
1802204076Spjd		}
1803204076Spjd		/*
1804204076Spjd		 * First read the data from synchronization source.
1805204076Spjd		 */
1806204076Spjd		SYNCREQ(hio);
1807204076Spjd		ggio = &hio->hio_ggio;
1808204076Spjd		ggio->gctl_cmd = BIO_READ;
1809204076Spjd		ggio->gctl_offset = offset;
1810204076Spjd		ggio->gctl_length = length;
1811204076Spjd		ggio->gctl_error = 0;
1812204076Spjd		for (ii = 0; ii < ncomps; ii++)
1813204076Spjd			hio->hio_errors[ii] = EINVAL;
1814204076Spjd		reqlog(LOG_DEBUG, 2, ggio, "sync: (%p) Sending sync request: ",
1815204076Spjd		    hio);
1816204076Spjd		pjdlog_debug(2, "sync: (%p) Moving request to the send queue.",
1817204076Spjd		    hio);
1818204076Spjd		mtx_lock(&metadata_lock);
1819204076Spjd		if (res->hr_syncsrc == HAST_SYNCSRC_PRIMARY) {
1820204076Spjd			/*
1821204076Spjd			 * This range is up-to-date on local component,
1822204076Spjd			 * so handle request locally.
1823204076Spjd			 */
1824204076Spjd			 /* Local component is 0 for now. */
1825204076Spjd			ncomp = 0;
1826204076Spjd		} else /* if (res->hr_syncsrc == HAST_SYNCSRC_SECONDARY) */ {
1827218138Spjd			PJDLOG_ASSERT(res->hr_syncsrc == HAST_SYNCSRC_SECONDARY);
1828204076Spjd			/*
1829204076Spjd			 * This range is out-of-date on local component,
1830204076Spjd			 * so send request to the remote node.
1831204076Spjd			 */
1832204076Spjd			 /* Remote component is 1 for now. */
1833204076Spjd			ncomp = 1;
1834204076Spjd		}
1835204076Spjd		mtx_unlock(&metadata_lock);
1836204076Spjd		refcount_init(&hio->hio_countdown, 1);
1837204076Spjd		QUEUE_INSERT1(hio, send, ncomp);
1838204076Spjd
1839204076Spjd		/*
1840204076Spjd		 * Let's wait for READ to finish.
1841204076Spjd		 */
1842204076Spjd		mtx_lock(&sync_lock);
1843204076Spjd		while (!ISSYNCREQDONE(hio))
1844204076Spjd			cv_wait(&sync_cond, &sync_lock);
1845204076Spjd		mtx_unlock(&sync_lock);
1846204076Spjd
1847204076Spjd		if (hio->hio_errors[ncomp] != 0) {
1848204076Spjd			pjdlog_error("Unable to read synchronization data: %s.",
1849204076Spjd			    strerror(hio->hio_errors[ncomp]));
1850204076Spjd			goto free_queue;
1851204076Spjd		}
1852204076Spjd
1853204076Spjd		/*
1854204076Spjd		 * We read the data from synchronization source, now write it
1855204076Spjd		 * to synchronization target.
1856204076Spjd		 */
1857204076Spjd		SYNCREQ(hio);
1858204076Spjd		ggio->gctl_cmd = BIO_WRITE;
1859204076Spjd		for (ii = 0; ii < ncomps; ii++)
1860204076Spjd			hio->hio_errors[ii] = EINVAL;
1861204076Spjd		reqlog(LOG_DEBUG, 2, ggio, "sync: (%p) Sending sync request: ",
1862204076Spjd		    hio);
1863204076Spjd		pjdlog_debug(2, "sync: (%p) Moving request to the send queue.",
1864204076Spjd		    hio);
1865204076Spjd		mtx_lock(&metadata_lock);
1866204076Spjd		if (res->hr_syncsrc == HAST_SYNCSRC_PRIMARY) {
1867204076Spjd			/*
1868204076Spjd			 * This range is up-to-date on local component,
1869204076Spjd			 * so we update remote component.
1870204076Spjd			 */
1871204076Spjd			 /* Remote component is 1 for now. */
1872204076Spjd			ncomp = 1;
1873204076Spjd		} else /* if (res->hr_syncsrc == HAST_SYNCSRC_SECONDARY) */ {
1874218138Spjd			PJDLOG_ASSERT(res->hr_syncsrc == HAST_SYNCSRC_SECONDARY);
1875204076Spjd			/*
1876204076Spjd			 * This range is out-of-date on local component,
1877204076Spjd			 * so we update it.
1878204076Spjd			 */
1879204076Spjd			 /* Local component is 0 for now. */
1880204076Spjd			ncomp = 0;
1881204076Spjd		}
1882204076Spjd		mtx_unlock(&metadata_lock);
1883204076Spjd
1884204076Spjd		pjdlog_debug(2, "sync: (%p) Moving request to the send queues.",
1885204076Spjd		    hio);
1886204076Spjd		refcount_init(&hio->hio_countdown, 1);
1887204076Spjd		QUEUE_INSERT1(hio, send, ncomp);
1888204076Spjd
1889204076Spjd		/*
1890204076Spjd		 * Let's wait for WRITE to finish.
1891204076Spjd		 */
1892204076Spjd		mtx_lock(&sync_lock);
1893204076Spjd		while (!ISSYNCREQDONE(hio))
1894204076Spjd			cv_wait(&sync_cond, &sync_lock);
1895204076Spjd		mtx_unlock(&sync_lock);
1896204076Spjd
1897204076Spjd		if (hio->hio_errors[ncomp] != 0) {
1898204076Spjd			pjdlog_error("Unable to write synchronization data: %s.",
1899204076Spjd			    strerror(hio->hio_errors[ncomp]));
1900204076Spjd			goto free_queue;
1901204076Spjd		}
1902211880Spjd
1903211880Spjd		synced += length;
1904204076Spjdfree_queue:
1905204076Spjd		mtx_lock(&range_lock);
1906204076Spjd		rangelock_del(range_sync, offset, length);
1907204076Spjd		if (range_regular_wait)
1908204076Spjd			cv_signal(&range_regular_cond);
1909204076Spjd		mtx_unlock(&range_lock);
1910204076Spjd		pjdlog_debug(2, "sync: (%p) Moving request to the free queue.",
1911204076Spjd		    hio);
1912204076Spjd		QUEUE_INSERT2(hio, free);
1913204076Spjd	}
1914204076Spjd	/* NOTREACHED */
1915204076Spjd	return (NULL);
1916204076Spjd}
1917204076Spjd
1918217784Spjdvoid
1919217784Spjdprimary_config_reload(struct hast_resource *res, struct nv *nv)
1920210886Spjd{
1921210886Spjd	unsigned int ii, ncomps;
1922217784Spjd	int modified, vint;
1923217784Spjd	const char *vstr;
1924210886Spjd
1925210886Spjd	pjdlog_info("Reloading configuration...");
1926210886Spjd
1927218138Spjd	PJDLOG_ASSERT(res->hr_role == HAST_ROLE_PRIMARY);
1928218138Spjd	PJDLOG_ASSERT(gres == res);
1929217784Spjd	nv_assert(nv, "remoteaddr");
1930219818Spjd	nv_assert(nv, "sourceaddr");
1931217784Spjd	nv_assert(nv, "replication");
1932219351Spjd	nv_assert(nv, "checksum");
1933219354Spjd	nv_assert(nv, "compression");
1934217784Spjd	nv_assert(nv, "timeout");
1935217784Spjd	nv_assert(nv, "exec");
1936217784Spjd
1937210886Spjd	ncomps = HAST_NCOMPONENTS;
1938210886Spjd
1939219351Spjd#define MODIFIED_REMOTEADDR	0x01
1940219818Spjd#define MODIFIED_SOURCEADDR	0x02
1941219818Spjd#define MODIFIED_REPLICATION	0x04
1942219818Spjd#define MODIFIED_CHECKSUM	0x08
1943219818Spjd#define MODIFIED_COMPRESSION	0x10
1944219818Spjd#define MODIFIED_TIMEOUT	0x20
1945219818Spjd#define MODIFIED_EXEC		0x40
1946210886Spjd	modified = 0;
1947217784Spjd
1948217784Spjd	vstr = nv_get_string(nv, "remoteaddr");
1949217784Spjd	if (strcmp(gres->hr_remoteaddr, vstr) != 0) {
1950210886Spjd		/*
1951210886Spjd		 * Don't copy res->hr_remoteaddr to gres just yet.
1952210886Spjd		 * We want remote_close() to log disconnect from the old
1953210886Spjd		 * addresses, not from the new ones.
1954210886Spjd		 */
1955210886Spjd		modified |= MODIFIED_REMOTEADDR;
1956210886Spjd	}
1957219818Spjd	vstr = nv_get_string(nv, "sourceaddr");
1958219818Spjd	if (strcmp(gres->hr_sourceaddr, vstr) != 0) {
1959219818Spjd		strlcpy(gres->hr_sourceaddr, vstr, sizeof(gres->hr_sourceaddr));
1960219818Spjd		modified |= MODIFIED_SOURCEADDR;
1961219818Spjd	}
1962217784Spjd	vint = nv_get_int32(nv, "replication");
1963217784Spjd	if (gres->hr_replication != vint) {
1964217784Spjd		gres->hr_replication = vint;
1965210886Spjd		modified |= MODIFIED_REPLICATION;
1966210886Spjd	}
1967219351Spjd	vint = nv_get_int32(nv, "checksum");
1968219351Spjd	if (gres->hr_checksum != vint) {
1969219351Spjd		gres->hr_checksum = vint;
1970219351Spjd		modified |= MODIFIED_CHECKSUM;
1971219351Spjd	}
1972219354Spjd	vint = nv_get_int32(nv, "compression");
1973219354Spjd	if (gres->hr_compression != vint) {
1974219354Spjd		gres->hr_compression = vint;
1975219354Spjd		modified |= MODIFIED_COMPRESSION;
1976219354Spjd	}
1977217784Spjd	vint = nv_get_int32(nv, "timeout");
1978217784Spjd	if (gres->hr_timeout != vint) {
1979217784Spjd		gres->hr_timeout = vint;
1980210886Spjd		modified |= MODIFIED_TIMEOUT;
1981210886Spjd	}
1982217784Spjd	vstr = nv_get_string(nv, "exec");
1983217784Spjd	if (strcmp(gres->hr_exec, vstr) != 0) {
1984217784Spjd		strlcpy(gres->hr_exec, vstr, sizeof(gres->hr_exec));
1985211886Spjd		modified |= MODIFIED_EXEC;
1986211886Spjd	}
1987217784Spjd
1988210886Spjd	/*
1989219351Spjd	 * Change timeout for connected sockets.
1990219351Spjd	 * Don't bother if we need to reconnect.
1991210886Spjd	 */
1992219351Spjd	if ((modified & MODIFIED_TIMEOUT) != 0 &&
1993219818Spjd	    (modified & (MODIFIED_REMOTEADDR | MODIFIED_SOURCEADDR |
1994219818Spjd	    MODIFIED_REPLICATION)) == 0) {
1995210886Spjd		for (ii = 0; ii < ncomps; ii++) {
1996210886Spjd			if (!ISREMOTE(ii))
1997210886Spjd				continue;
1998210886Spjd			rw_rlock(&hio_remote_lock[ii]);
1999210886Spjd			if (!ISCONNECTED(gres, ii)) {
2000210886Spjd				rw_unlock(&hio_remote_lock[ii]);
2001210886Spjd				continue;
2002210886Spjd			}
2003210886Spjd			rw_unlock(&hio_remote_lock[ii]);
2004210886Spjd			if (proto_timeout(gres->hr_remotein,
2005210886Spjd			    gres->hr_timeout) < 0) {
2006210886Spjd				pjdlog_errno(LOG_WARNING,
2007210886Spjd				    "Unable to set connection timeout");
2008210886Spjd			}
2009210886Spjd			if (proto_timeout(gres->hr_remoteout,
2010210886Spjd			    gres->hr_timeout) < 0) {
2011210886Spjd				pjdlog_errno(LOG_WARNING,
2012210886Spjd				    "Unable to set connection timeout");
2013210886Spjd			}
2014210886Spjd		}
2015219351Spjd	}
2016219818Spjd	if ((modified & (MODIFIED_REMOTEADDR | MODIFIED_SOURCEADDR |
2017219818Spjd	    MODIFIED_REPLICATION)) != 0) {
2018210886Spjd		for (ii = 0; ii < ncomps; ii++) {
2019210886Spjd			if (!ISREMOTE(ii))
2020210886Spjd				continue;
2021210886Spjd			remote_close(gres, ii);
2022210886Spjd		}
2023210886Spjd		if (modified & MODIFIED_REMOTEADDR) {
2024217784Spjd			vstr = nv_get_string(nv, "remoteaddr");
2025217784Spjd			strlcpy(gres->hr_remoteaddr, vstr,
2026210886Spjd			    sizeof(gres->hr_remoteaddr));
2027210886Spjd		}
2028210886Spjd	}
2029210886Spjd#undef	MODIFIED_REMOTEADDR
2030219818Spjd#undef	MODIFIED_SOURCEADDR
2031210886Spjd#undef	MODIFIED_REPLICATION
2032219351Spjd#undef	MODIFIED_CHECKSUM
2033219354Spjd#undef	MODIFIED_COMPRESSION
2034210886Spjd#undef	MODIFIED_TIMEOUT
2035211886Spjd#undef	MODIFIED_EXEC
2036210886Spjd
2037210886Spjd	pjdlog_info("Configuration reloaded successfully.");
2038210886Spjd}
2039210886Spjd
2040211882Spjdstatic void
2041211981Spjdguard_one(struct hast_resource *res, unsigned int ncomp)
2042211981Spjd{
2043211981Spjd	struct proto_conn *in, *out;
2044211981Spjd
2045211981Spjd	if (!ISREMOTE(ncomp))
2046211981Spjd		return;
2047211981Spjd
2048211981Spjd	rw_rlock(&hio_remote_lock[ncomp]);
2049211981Spjd
2050211981Spjd	if (!real_remote(res)) {
2051211981Spjd		rw_unlock(&hio_remote_lock[ncomp]);
2052211981Spjd		return;
2053211981Spjd	}
2054211981Spjd
2055211981Spjd	if (ISCONNECTED(res, ncomp)) {
2056218138Spjd		PJDLOG_ASSERT(res->hr_remotein != NULL);
2057218138Spjd		PJDLOG_ASSERT(res->hr_remoteout != NULL);
2058211981Spjd		rw_unlock(&hio_remote_lock[ncomp]);
2059211981Spjd		pjdlog_debug(2, "remote_guard: Connection to %s is ok.",
2060211981Spjd		    res->hr_remoteaddr);
2061211981Spjd		return;
2062211981Spjd	}
2063211981Spjd
2064218138Spjd	PJDLOG_ASSERT(res->hr_remotein == NULL);
2065218138Spjd	PJDLOG_ASSERT(res->hr_remoteout == NULL);
2066211981Spjd	/*
2067211981Spjd	 * Upgrade the lock. It doesn't have to be atomic as no other thread
2068211981Spjd	 * can change connection status from disconnected to connected.
2069211981Spjd	 */
2070211981Spjd	rw_unlock(&hio_remote_lock[ncomp]);
2071211981Spjd	pjdlog_debug(2, "remote_guard: Reconnecting to %s.",
2072211981Spjd	    res->hr_remoteaddr);
2073211981Spjd	in = out = NULL;
2074211981Spjd	if (init_remote(res, &in, &out)) {
2075211981Spjd		rw_wlock(&hio_remote_lock[ncomp]);
2076218138Spjd		PJDLOG_ASSERT(res->hr_remotein == NULL);
2077218138Spjd		PJDLOG_ASSERT(res->hr_remoteout == NULL);
2078218138Spjd		PJDLOG_ASSERT(in != NULL && out != NULL);
2079211981Spjd		res->hr_remotein = in;
2080211981Spjd		res->hr_remoteout = out;
2081211981Spjd		rw_unlock(&hio_remote_lock[ncomp]);
2082211981Spjd		pjdlog_info("Successfully reconnected to %s.",
2083211981Spjd		    res->hr_remoteaddr);
2084211981Spjd		sync_start();
2085211981Spjd	} else {
2086211981Spjd		/* Both connections should be NULL. */
2087218138Spjd		PJDLOG_ASSERT(res->hr_remotein == NULL);
2088218138Spjd		PJDLOG_ASSERT(res->hr_remoteout == NULL);
2089218138Spjd		PJDLOG_ASSERT(in == NULL && out == NULL);
2090211981Spjd		pjdlog_debug(2, "remote_guard: Reconnect to %s failed.",
2091211981Spjd		    res->hr_remoteaddr);
2092211981Spjd	}
2093211981Spjd}
2094211981Spjd
2095204076Spjd/*
2096204076Spjd * Thread guards remote connections and reconnects when needed, handles
2097204076Spjd * signals, etc.
2098204076Spjd */
2099204076Spjdstatic void *
2100204076Spjdguard_thread(void *arg)
2101204076Spjd{
2102204076Spjd	struct hast_resource *res = arg;
2103204076Spjd	unsigned int ii, ncomps;
2104211982Spjd	struct timespec timeout;
2105211981Spjd	time_t lastcheck, now;
2106211982Spjd	sigset_t mask;
2107211982Spjd	int signo;
2108204076Spjd
2109204076Spjd	ncomps = HAST_NCOMPONENTS;
2110211981Spjd	lastcheck = time(NULL);
2111204076Spjd
2112211982Spjd	PJDLOG_VERIFY(sigemptyset(&mask) == 0);
2113211982Spjd	PJDLOG_VERIFY(sigaddset(&mask, SIGINT) == 0);
2114211982Spjd	PJDLOG_VERIFY(sigaddset(&mask, SIGTERM) == 0);
2115211982Spjd
2116219721Strociny	timeout.tv_sec = HAST_KEEPALIVE;
2117211982Spjd	timeout.tv_nsec = 0;
2118211982Spjd	signo = -1;
2119211982Spjd
2120204076Spjd	for (;;) {
2121211982Spjd		switch (signo) {
2122211982Spjd		case SIGINT:
2123211982Spjd		case SIGTERM:
2124211982Spjd			sigexit_received = true;
2125204076Spjd			primary_exitx(EX_OK,
2126204076Spjd			    "Termination signal received, exiting.");
2127211982Spjd			break;
2128211982Spjd		default:
2129211982Spjd			break;
2130204076Spjd		}
2131211882Spjd
2132204076Spjd		pjdlog_debug(2, "remote_guard: Checking connections.");
2133211981Spjd		now = time(NULL);
2134219721Strociny		if (lastcheck + HAST_KEEPALIVE <= now) {
2135211982Spjd			for (ii = 0; ii < ncomps; ii++)
2136211981Spjd				guard_one(res, ii);
2137211981Spjd			lastcheck = now;
2138204076Spjd		}
2139211982Spjd		signo = sigtimedwait(&mask, NULL, &timeout);
2140204076Spjd	}
2141204076Spjd	/* NOTREACHED */
2142204076Spjd	return (NULL);
2143204076Spjd}
2144