primary.c revision 222228
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 222228 2011-05-23 21:15:19Z 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	/*
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;
222220898Spjdstatic bool fullystarted;
223204076Spjd
224204076Spjdstatic void *ggate_recv_thread(void *arg);
225204076Spjdstatic void *local_send_thread(void *arg);
226204076Spjdstatic void *remote_send_thread(void *arg);
227204076Spjdstatic void *remote_recv_thread(void *arg);
228204076Spjdstatic void *ggate_send_thread(void *arg);
229204076Spjdstatic void *sync_thread(void *arg);
230204076Spjdstatic void *guard_thread(void *arg);
231204076Spjd
232211982Spjdstatic void
233204076Spjdcleanup(struct hast_resource *res)
234204076Spjd{
235204076Spjd	int rerrno;
236204076Spjd
237204076Spjd	/* Remember errno. */
238204076Spjd	rerrno = errno;
239204076Spjd
240204076Spjd	/* Destroy ggate provider if we created one. */
241204076Spjd	if (res->hr_ggateunit >= 0) {
242204076Spjd		struct g_gate_ctl_destroy ggiod;
243204076Spjd
244213533Spjd		bzero(&ggiod, sizeof(ggiod));
245204076Spjd		ggiod.gctl_version = G_GATE_VERSION;
246204076Spjd		ggiod.gctl_unit = res->hr_ggateunit;
247204076Spjd		ggiod.gctl_force = 1;
248204076Spjd		if (ioctl(res->hr_ggatefd, G_GATE_CMD_DESTROY, &ggiod) < 0) {
249213531Spjd			pjdlog_errno(LOG_WARNING,
250213531Spjd			    "Unable to destroy hast/%s device",
251204076Spjd			    res->hr_provname);
252204076Spjd		}
253204076Spjd		res->hr_ggateunit = -1;
254204076Spjd	}
255204076Spjd
256204076Spjd	/* Restore errno. */
257204076Spjd	errno = rerrno;
258204076Spjd}
259204076Spjd
260212899Spjdstatic __dead2 void
261204076Spjdprimary_exit(int exitcode, const char *fmt, ...)
262204076Spjd{
263204076Spjd	va_list ap;
264204076Spjd
265218138Spjd	PJDLOG_ASSERT(exitcode != EX_OK);
266204076Spjd	va_start(ap, fmt);
267204076Spjd	pjdlogv_errno(LOG_ERR, fmt, ap);
268204076Spjd	va_end(ap);
269204076Spjd	cleanup(gres);
270204076Spjd	exit(exitcode);
271204076Spjd}
272204076Spjd
273212899Spjdstatic __dead2 void
274204076Spjdprimary_exitx(int exitcode, const char *fmt, ...)
275204076Spjd{
276204076Spjd	va_list ap;
277204076Spjd
278204076Spjd	va_start(ap, fmt);
279204076Spjd	pjdlogv(exitcode == EX_OK ? LOG_INFO : LOG_ERR, fmt, ap);
280204076Spjd	va_end(ap);
281204076Spjd	cleanup(gres);
282204076Spjd	exit(exitcode);
283204076Spjd}
284204076Spjd
285204076Spjdstatic int
286204076Spjdhast_activemap_flush(struct hast_resource *res)
287204076Spjd{
288204076Spjd	const unsigned char *buf;
289204076Spjd	size_t size;
290204076Spjd
291204076Spjd	buf = activemap_bitmap(res->hr_amp, &size);
292218138Spjd	PJDLOG_ASSERT(buf != NULL);
293218138Spjd	PJDLOG_ASSERT((size % res->hr_local_sectorsize) == 0);
294204076Spjd	if (pwrite(res->hr_localfd, buf, size, METADATA_SIZE) !=
295204076Spjd	    (ssize_t)size) {
296204076Spjd		KEEP_ERRNO(pjdlog_errno(LOG_ERR,
297204076Spjd		    "Unable to flush activemap to disk"));
298204076Spjd		return (-1);
299204076Spjd	}
300204076Spjd	return (0);
301204076Spjd}
302204076Spjd
303210881Spjdstatic bool
304210881Spjdreal_remote(const struct hast_resource *res)
305210881Spjd{
306210881Spjd
307210881Spjd	return (strcmp(res->hr_remoteaddr, "none") != 0);
308210881Spjd}
309210881Spjd
310204076Spjdstatic void
311204076Spjdinit_environment(struct hast_resource *res __unused)
312204076Spjd{
313204076Spjd	struct hio *hio;
314204076Spjd	unsigned int ii, ncomps;
315204076Spjd
316204076Spjd	/*
317204076Spjd	 * In the future it might be per-resource value.
318204076Spjd	 */
319204076Spjd	ncomps = HAST_NCOMPONENTS;
320204076Spjd
321204076Spjd	/*
322204076Spjd	 * Allocate memory needed by lists.
323204076Spjd	 */
324204076Spjd	hio_send_list = malloc(sizeof(hio_send_list[0]) * ncomps);
325204076Spjd	if (hio_send_list == NULL) {
326204076Spjd		primary_exitx(EX_TEMPFAIL,
327204076Spjd		    "Unable to allocate %zu bytes of memory for send lists.",
328204076Spjd		    sizeof(hio_send_list[0]) * ncomps);
329204076Spjd	}
330204076Spjd	hio_send_list_lock = malloc(sizeof(hio_send_list_lock[0]) * ncomps);
331204076Spjd	if (hio_send_list_lock == NULL) {
332204076Spjd		primary_exitx(EX_TEMPFAIL,
333204076Spjd		    "Unable to allocate %zu bytes of memory for send list locks.",
334204076Spjd		    sizeof(hio_send_list_lock[0]) * ncomps);
335204076Spjd	}
336204076Spjd	hio_send_list_cond = malloc(sizeof(hio_send_list_cond[0]) * ncomps);
337204076Spjd	if (hio_send_list_cond == NULL) {
338204076Spjd		primary_exitx(EX_TEMPFAIL,
339204076Spjd		    "Unable to allocate %zu bytes of memory for send list condition variables.",
340204076Spjd		    sizeof(hio_send_list_cond[0]) * ncomps);
341204076Spjd	}
342204076Spjd	hio_recv_list = malloc(sizeof(hio_recv_list[0]) * ncomps);
343204076Spjd	if (hio_recv_list == NULL) {
344204076Spjd		primary_exitx(EX_TEMPFAIL,
345204076Spjd		    "Unable to allocate %zu bytes of memory for recv lists.",
346204076Spjd		    sizeof(hio_recv_list[0]) * ncomps);
347204076Spjd	}
348204076Spjd	hio_recv_list_lock = malloc(sizeof(hio_recv_list_lock[0]) * ncomps);
349204076Spjd	if (hio_recv_list_lock == NULL) {
350204076Spjd		primary_exitx(EX_TEMPFAIL,
351204076Spjd		    "Unable to allocate %zu bytes of memory for recv list locks.",
352204076Spjd		    sizeof(hio_recv_list_lock[0]) * ncomps);
353204076Spjd	}
354204076Spjd	hio_recv_list_cond = malloc(sizeof(hio_recv_list_cond[0]) * ncomps);
355204076Spjd	if (hio_recv_list_cond == NULL) {
356204076Spjd		primary_exitx(EX_TEMPFAIL,
357204076Spjd		    "Unable to allocate %zu bytes of memory for recv list condition variables.",
358204076Spjd		    sizeof(hio_recv_list_cond[0]) * ncomps);
359204076Spjd	}
360204076Spjd	hio_remote_lock = malloc(sizeof(hio_remote_lock[0]) * ncomps);
361204076Spjd	if (hio_remote_lock == NULL) {
362204076Spjd		primary_exitx(EX_TEMPFAIL,
363204076Spjd		    "Unable to allocate %zu bytes of memory for remote connections locks.",
364204076Spjd		    sizeof(hio_remote_lock[0]) * ncomps);
365204076Spjd	}
366204076Spjd
367204076Spjd	/*
368204076Spjd	 * Initialize lists, their locks and theirs condition variables.
369204076Spjd	 */
370204076Spjd	TAILQ_INIT(&hio_free_list);
371204076Spjd	mtx_init(&hio_free_list_lock);
372204076Spjd	cv_init(&hio_free_list_cond);
373204076Spjd	for (ii = 0; ii < HAST_NCOMPONENTS; ii++) {
374204076Spjd		TAILQ_INIT(&hio_send_list[ii]);
375204076Spjd		mtx_init(&hio_send_list_lock[ii]);
376204076Spjd		cv_init(&hio_send_list_cond[ii]);
377204076Spjd		TAILQ_INIT(&hio_recv_list[ii]);
378204076Spjd		mtx_init(&hio_recv_list_lock[ii]);
379204076Spjd		cv_init(&hio_recv_list_cond[ii]);
380204076Spjd		rw_init(&hio_remote_lock[ii]);
381204076Spjd	}
382204076Spjd	TAILQ_INIT(&hio_done_list);
383204076Spjd	mtx_init(&hio_done_list_lock);
384204076Spjd	cv_init(&hio_done_list_cond);
385204076Spjd	mtx_init(&metadata_lock);
386204076Spjd
387204076Spjd	/*
388204076Spjd	 * Allocate requests pool and initialize requests.
389204076Spjd	 */
390204076Spjd	for (ii = 0; ii < HAST_HIO_MAX; ii++) {
391204076Spjd		hio = malloc(sizeof(*hio));
392204076Spjd		if (hio == NULL) {
393204076Spjd			primary_exitx(EX_TEMPFAIL,
394204076Spjd			    "Unable to allocate %zu bytes of memory for hio request.",
395204076Spjd			    sizeof(*hio));
396204076Spjd		}
397204076Spjd		hio->hio_countdown = 0;
398204076Spjd		hio->hio_errors = malloc(sizeof(hio->hio_errors[0]) * ncomps);
399204076Spjd		if (hio->hio_errors == NULL) {
400204076Spjd			primary_exitx(EX_TEMPFAIL,
401204076Spjd			    "Unable allocate %zu bytes of memory for hio errors.",
402204076Spjd			    sizeof(hio->hio_errors[0]) * ncomps);
403204076Spjd		}
404204076Spjd		hio->hio_next = malloc(sizeof(hio->hio_next[0]) * ncomps);
405204076Spjd		if (hio->hio_next == NULL) {
406204076Spjd			primary_exitx(EX_TEMPFAIL,
407204076Spjd			    "Unable allocate %zu bytes of memory for hio_next field.",
408204076Spjd			    sizeof(hio->hio_next[0]) * ncomps);
409204076Spjd		}
410204076Spjd		hio->hio_ggio.gctl_version = G_GATE_VERSION;
411204076Spjd		hio->hio_ggio.gctl_data = malloc(MAXPHYS);
412204076Spjd		if (hio->hio_ggio.gctl_data == NULL) {
413204076Spjd			primary_exitx(EX_TEMPFAIL,
414204076Spjd			    "Unable to allocate %zu bytes of memory for gctl_data.",
415204076Spjd			    MAXPHYS);
416204076Spjd		}
417204076Spjd		hio->hio_ggio.gctl_length = MAXPHYS;
418204076Spjd		hio->hio_ggio.gctl_error = 0;
419204076Spjd		TAILQ_INSERT_HEAD(&hio_free_list, hio, hio_free_next);
420204076Spjd	}
421204076Spjd}
422204076Spjd
423214284Spjdstatic bool
424214284Spjdinit_resuid(struct hast_resource *res)
425214284Spjd{
426214284Spjd
427214284Spjd	mtx_lock(&metadata_lock);
428214284Spjd	if (res->hr_resuid != 0) {
429214284Spjd		mtx_unlock(&metadata_lock);
430214284Spjd		return (false);
431214284Spjd	} else {
432214284Spjd		/* Initialize unique resource identifier. */
433214284Spjd		arc4random_buf(&res->hr_resuid, sizeof(res->hr_resuid));
434214284Spjd		mtx_unlock(&metadata_lock);
435214284Spjd		if (metadata_write(res) < 0)
436214284Spjd			exit(EX_NOINPUT);
437214284Spjd		return (true);
438214284Spjd	}
439214284Spjd}
440214284Spjd
441204076Spjdstatic void
442204076Spjdinit_local(struct hast_resource *res)
443204076Spjd{
444204076Spjd	unsigned char *buf;
445204076Spjd	size_t mapsize;
446204076Spjd
447204076Spjd	if (metadata_read(res, true) < 0)
448204076Spjd		exit(EX_NOINPUT);
449204076Spjd	mtx_init(&res->hr_amp_lock);
450204076Spjd	if (activemap_init(&res->hr_amp, res->hr_datasize, res->hr_extentsize,
451204076Spjd	    res->hr_local_sectorsize, res->hr_keepdirty) < 0) {
452204076Spjd		primary_exit(EX_TEMPFAIL, "Unable to create activemap");
453204076Spjd	}
454204076Spjd	mtx_init(&range_lock);
455204076Spjd	cv_init(&range_regular_cond);
456204076Spjd	if (rangelock_init(&range_regular) < 0)
457204076Spjd		primary_exit(EX_TEMPFAIL, "Unable to create regular range lock");
458204076Spjd	cv_init(&range_sync_cond);
459204076Spjd	if (rangelock_init(&range_sync) < 0)
460204076Spjd		primary_exit(EX_TEMPFAIL, "Unable to create sync range lock");
461204076Spjd	mapsize = activemap_ondisk_size(res->hr_amp);
462204076Spjd	buf = calloc(1, mapsize);
463204076Spjd	if (buf == NULL) {
464204076Spjd		primary_exitx(EX_TEMPFAIL,
465204076Spjd		    "Unable to allocate buffer for activemap.");
466204076Spjd	}
467204076Spjd	if (pread(res->hr_localfd, buf, mapsize, METADATA_SIZE) !=
468204076Spjd	    (ssize_t)mapsize) {
469204076Spjd		primary_exit(EX_NOINPUT, "Unable to read activemap");
470204076Spjd	}
471204076Spjd	activemap_copyin(res->hr_amp, buf, mapsize);
472209181Spjd	free(buf);
473204076Spjd	if (res->hr_resuid != 0)
474204076Spjd		return;
475204076Spjd	/*
476214284Spjd	 * We're using provider for the first time. Initialize local and remote
477214284Spjd	 * counters. We don't initialize resuid here, as we want to do it just
478214284Spjd	 * in time. The reason for this is that we want to inform secondary
479214284Spjd	 * that there were no writes yet, so there is no need to synchronize
480214284Spjd	 * anything.
481204076Spjd	 */
482219844Spjd	res->hr_primary_localcnt = 0;
483204076Spjd	res->hr_primary_remotecnt = 0;
484204076Spjd	if (metadata_write(res) < 0)
485204076Spjd		exit(EX_NOINPUT);
486204076Spjd}
487204076Spjd
488218218Spjdstatic int
489218218Spjdprimary_connect(struct hast_resource *res, struct proto_conn **connp)
490218218Spjd{
491218218Spjd	struct proto_conn *conn;
492218218Spjd	int16_t val;
493218218Spjd
494218218Spjd	val = 1;
495218218Spjd	if (proto_send(res->hr_conn, &val, sizeof(val)) < 0) {
496218218Spjd		primary_exit(EX_TEMPFAIL,
497218218Spjd		    "Unable to send connection request to parent");
498218218Spjd	}
499218218Spjd	if (proto_recv(res->hr_conn, &val, sizeof(val)) < 0) {
500218218Spjd		primary_exit(EX_TEMPFAIL,
501218218Spjd		    "Unable to receive reply to connection request from parent");
502218218Spjd	}
503218218Spjd	if (val != 0) {
504218218Spjd		errno = val;
505218218Spjd		pjdlog_errno(LOG_WARNING, "Unable to connect to %s",
506218218Spjd		    res->hr_remoteaddr);
507218218Spjd		return (-1);
508218218Spjd	}
509218218Spjd	if (proto_connection_recv(res->hr_conn, true, &conn) < 0) {
510218218Spjd		primary_exit(EX_TEMPFAIL,
511218218Spjd		    "Unable to receive connection from parent");
512218218Spjd	}
513220006Spjd	if (proto_connect_wait(conn, res->hr_timeout) < 0) {
514218218Spjd		pjdlog_errno(LOG_WARNING, "Unable to connect to %s",
515218218Spjd		    res->hr_remoteaddr);
516218218Spjd		proto_close(conn);
517218218Spjd		return (-1);
518218218Spjd	}
519218218Spjd	/* Error in setting timeout is not critical, but why should it fail? */
520218218Spjd	if (proto_timeout(conn, res->hr_timeout) < 0)
521218218Spjd		pjdlog_errno(LOG_WARNING, "Unable to set connection timeout");
522218218Spjd
523218218Spjd	*connp = conn;
524218218Spjd
525218218Spjd	return (0);
526218218Spjd}
527218218Spjd
528220898Spjdstatic int
529205738Spjdinit_remote(struct hast_resource *res, struct proto_conn **inp,
530205738Spjd    struct proto_conn **outp)
531204076Spjd{
532205738Spjd	struct proto_conn *in, *out;
533204076Spjd	struct nv *nvout, *nvin;
534204076Spjd	const unsigned char *token;
535204076Spjd	unsigned char *map;
536204076Spjd	const char *errmsg;
537204076Spjd	int32_t extentsize;
538204076Spjd	int64_t datasize;
539204076Spjd	uint32_t mapsize;
540204076Spjd	size_t size;
541220898Spjd	int error;
542204076Spjd
543218138Spjd	PJDLOG_ASSERT((inp == NULL && outp == NULL) || (inp != NULL && outp != NULL));
544218138Spjd	PJDLOG_ASSERT(real_remote(res));
545205738Spjd
546205738Spjd	in = out = NULL;
547211983Spjd	errmsg = NULL;
548205738Spjd
549218218Spjd	if (primary_connect(res, &out) == -1)
550220898Spjd		return (ECONNREFUSED);
551218218Spjd
552220898Spjd	error = ECONNABORTED;
553220898Spjd
554204076Spjd	/*
555204076Spjd	 * First handshake step.
556204076Spjd	 * Setup outgoing connection with remote node.
557204076Spjd	 */
558204076Spjd	nvout = nv_alloc();
559204076Spjd	nv_add_string(nvout, res->hr_name, "resource");
560204076Spjd	if (nv_error(nvout) != 0) {
561204076Spjd		pjdlog_common(LOG_WARNING, 0, nv_error(nvout),
562204076Spjd		    "Unable to allocate header for connection with %s",
563204076Spjd		    res->hr_remoteaddr);
564204076Spjd		nv_free(nvout);
565204076Spjd		goto close;
566204076Spjd	}
567205738Spjd	if (hast_proto_send(res, out, nvout, NULL, 0) < 0) {
568204076Spjd		pjdlog_errno(LOG_WARNING,
569204076Spjd		    "Unable to send handshake header to %s",
570204076Spjd		    res->hr_remoteaddr);
571204076Spjd		nv_free(nvout);
572204076Spjd		goto close;
573204076Spjd	}
574204076Spjd	nv_free(nvout);
575205738Spjd	if (hast_proto_recv_hdr(out, &nvin) < 0) {
576204076Spjd		pjdlog_errno(LOG_WARNING,
577204076Spjd		    "Unable to receive handshake header from %s",
578204076Spjd		    res->hr_remoteaddr);
579204076Spjd		goto close;
580204076Spjd	}
581204076Spjd	errmsg = nv_get_string(nvin, "errmsg");
582204076Spjd	if (errmsg != NULL) {
583204076Spjd		pjdlog_warning("%s", errmsg);
584220898Spjd		if (nv_exists(nvin, "wait"))
585220898Spjd			error = EBUSY;
586204076Spjd		nv_free(nvin);
587204076Spjd		goto close;
588204076Spjd	}
589204076Spjd	token = nv_get_uint8_array(nvin, &size, "token");
590204076Spjd	if (token == NULL) {
591204076Spjd		pjdlog_warning("Handshake header from %s has no 'token' field.",
592204076Spjd		    res->hr_remoteaddr);
593204076Spjd		nv_free(nvin);
594204076Spjd		goto close;
595204076Spjd	}
596204076Spjd	if (size != sizeof(res->hr_token)) {
597204076Spjd		pjdlog_warning("Handshake header from %s contains 'token' of wrong size (got %zu, expected %zu).",
598204076Spjd		    res->hr_remoteaddr, size, sizeof(res->hr_token));
599204076Spjd		nv_free(nvin);
600204076Spjd		goto close;
601204076Spjd	}
602204076Spjd	bcopy(token, res->hr_token, sizeof(res->hr_token));
603204076Spjd	nv_free(nvin);
604204076Spjd
605204076Spjd	/*
606204076Spjd	 * Second handshake step.
607204076Spjd	 * Setup incoming connection with remote node.
608204076Spjd	 */
609218218Spjd	if (primary_connect(res, &in) == -1)
610204076Spjd		goto close;
611218218Spjd
612204076Spjd	nvout = nv_alloc();
613204076Spjd	nv_add_string(nvout, res->hr_name, "resource");
614204076Spjd	nv_add_uint8_array(nvout, res->hr_token, sizeof(res->hr_token),
615204076Spjd	    "token");
616214284Spjd	if (res->hr_resuid == 0) {
617214284Spjd		/*
618214284Spjd		 * The resuid field was not yet initialized.
619214284Spjd		 * Because we do synchronization inside init_resuid(), it is
620214284Spjd		 * possible that someone already initialized it, the function
621214284Spjd		 * will return false then, but if we successfully initialized
622214284Spjd		 * it, we will get true. True means that there were no writes
623214284Spjd		 * to this resource yet and we want to inform secondary that
624214284Spjd		 * synchronization is not needed by sending "virgin" argument.
625214284Spjd		 */
626214284Spjd		if (init_resuid(res))
627214284Spjd			nv_add_int8(nvout, 1, "virgin");
628214284Spjd	}
629204076Spjd	nv_add_uint64(nvout, res->hr_resuid, "resuid");
630204076Spjd	nv_add_uint64(nvout, res->hr_primary_localcnt, "localcnt");
631204076Spjd	nv_add_uint64(nvout, res->hr_primary_remotecnt, "remotecnt");
632204076Spjd	if (nv_error(nvout) != 0) {
633204076Spjd		pjdlog_common(LOG_WARNING, 0, nv_error(nvout),
634204076Spjd		    "Unable to allocate header for connection with %s",
635204076Spjd		    res->hr_remoteaddr);
636204076Spjd		nv_free(nvout);
637204076Spjd		goto close;
638204076Spjd	}
639205738Spjd	if (hast_proto_send(res, in, nvout, NULL, 0) < 0) {
640204076Spjd		pjdlog_errno(LOG_WARNING,
641204076Spjd		    "Unable to send handshake header to %s",
642204076Spjd		    res->hr_remoteaddr);
643204076Spjd		nv_free(nvout);
644204076Spjd		goto close;
645204076Spjd	}
646204076Spjd	nv_free(nvout);
647205738Spjd	if (hast_proto_recv_hdr(out, &nvin) < 0) {
648204076Spjd		pjdlog_errno(LOG_WARNING,
649204076Spjd		    "Unable to receive handshake header from %s",
650204076Spjd		    res->hr_remoteaddr);
651204076Spjd		goto close;
652204076Spjd	}
653204076Spjd	errmsg = nv_get_string(nvin, "errmsg");
654204076Spjd	if (errmsg != NULL) {
655204076Spjd		pjdlog_warning("%s", errmsg);
656204076Spjd		nv_free(nvin);
657204076Spjd		goto close;
658204076Spjd	}
659204076Spjd	datasize = nv_get_int64(nvin, "datasize");
660204076Spjd	if (datasize != res->hr_datasize) {
661204076Spjd		pjdlog_warning("Data size differs between nodes (local=%jd, remote=%jd).",
662204076Spjd		    (intmax_t)res->hr_datasize, (intmax_t)datasize);
663204076Spjd		nv_free(nvin);
664204076Spjd		goto close;
665204076Spjd	}
666204076Spjd	extentsize = nv_get_int32(nvin, "extentsize");
667204076Spjd	if (extentsize != res->hr_extentsize) {
668204076Spjd		pjdlog_warning("Extent size differs between nodes (local=%zd, remote=%zd).",
669204076Spjd		    (ssize_t)res->hr_extentsize, (ssize_t)extentsize);
670204076Spjd		nv_free(nvin);
671204076Spjd		goto close;
672204076Spjd	}
673204076Spjd	res->hr_secondary_localcnt = nv_get_uint64(nvin, "localcnt");
674204076Spjd	res->hr_secondary_remotecnt = nv_get_uint64(nvin, "remotecnt");
675204076Spjd	res->hr_syncsrc = nv_get_uint8(nvin, "syncsrc");
676220865Spjd	if (nv_exists(nvin, "virgin")) {
677220865Spjd		/*
678220865Spjd		 * Secondary was reinitialized, bump localcnt if it is 0 as
679220865Spjd		 * only we have the data.
680220865Spjd		 */
681220865Spjd		PJDLOG_ASSERT(res->hr_syncsrc == HAST_SYNCSRC_PRIMARY);
682220865Spjd		PJDLOG_ASSERT(res->hr_secondary_localcnt == 0);
683220865Spjd
684220865Spjd		if (res->hr_primary_localcnt == 0) {
685220865Spjd			PJDLOG_ASSERT(res->hr_secondary_remotecnt == 0);
686220865Spjd
687220865Spjd			mtx_lock(&metadata_lock);
688220865Spjd			res->hr_primary_localcnt++;
689220865Spjd			pjdlog_debug(1, "Increasing localcnt to %ju.",
690220865Spjd			    (uintmax_t)res->hr_primary_localcnt);
691220865Spjd			(void)metadata_write(res);
692220865Spjd			mtx_unlock(&metadata_lock);
693220865Spjd		}
694220865Spjd	}
695204076Spjd	map = NULL;
696204076Spjd	mapsize = nv_get_uint32(nvin, "mapsize");
697204076Spjd	if (mapsize > 0) {
698204076Spjd		map = malloc(mapsize);
699204076Spjd		if (map == NULL) {
700204076Spjd			pjdlog_error("Unable to allocate memory for remote activemap (mapsize=%ju).",
701204076Spjd			    (uintmax_t)mapsize);
702204076Spjd			nv_free(nvin);
703204076Spjd			goto close;
704204076Spjd		}
705204076Spjd		/*
706204076Spjd		 * Remote node have some dirty extents on its own, lets
707204076Spjd		 * download its activemap.
708204076Spjd		 */
709205738Spjd		if (hast_proto_recv_data(res, out, nvin, map,
710204076Spjd		    mapsize) < 0) {
711204076Spjd			pjdlog_errno(LOG_ERR,
712204076Spjd			    "Unable to receive remote activemap");
713204076Spjd			nv_free(nvin);
714204076Spjd			free(map);
715204076Spjd			goto close;
716204076Spjd		}
717204076Spjd		/*
718204076Spjd		 * Merge local and remote bitmaps.
719204076Spjd		 */
720204076Spjd		activemap_merge(res->hr_amp, map, mapsize);
721204076Spjd		free(map);
722204076Spjd		/*
723204076Spjd		 * Now that we merged bitmaps from both nodes, flush it to the
724204076Spjd		 * disk before we start to synchronize.
725204076Spjd		 */
726204076Spjd		(void)hast_activemap_flush(res);
727204076Spjd	}
728214274Spjd	nv_free(nvin);
729220271Spjd	/* Setup directions. */
730220271Spjd	if (proto_send(out, NULL, 0) == -1)
731220271Spjd		pjdlog_errno(LOG_WARNING, "Unable to set connection direction");
732220271Spjd	if (proto_recv(in, NULL, 0) == -1)
733220271Spjd		pjdlog_errno(LOG_WARNING, "Unable to set connection direction");
734204076Spjd	pjdlog_info("Connected to %s.", res->hr_remoteaddr);
735205738Spjd	if (inp != NULL && outp != NULL) {
736205738Spjd		*inp = in;
737205738Spjd		*outp = out;
738205738Spjd	} else {
739205738Spjd		res->hr_remotein = in;
740205738Spjd		res->hr_remoteout = out;
741205738Spjd	}
742212038Spjd	event_send(res, EVENT_CONNECT);
743220898Spjd	return (0);
744205738Spjdclose:
745211983Spjd	if (errmsg != NULL && strcmp(errmsg, "Split-brain condition!") == 0)
746212038Spjd		event_send(res, EVENT_SPLITBRAIN);
747205738Spjd	proto_close(out);
748205738Spjd	if (in != NULL)
749205738Spjd		proto_close(in);
750220898Spjd	return (error);
751205738Spjd}
752205738Spjd
753205738Spjdstatic void
754205738Spjdsync_start(void)
755205738Spjd{
756205738Spjd
757204076Spjd	mtx_lock(&sync_lock);
758204076Spjd	sync_inprogress = true;
759204076Spjd	mtx_unlock(&sync_lock);
760204076Spjd	cv_signal(&sync_cond);
761204076Spjd}
762204076Spjd
763204076Spjdstatic void
764211878Spjdsync_stop(void)
765211878Spjd{
766211878Spjd
767211878Spjd	mtx_lock(&sync_lock);
768211878Spjd	if (sync_inprogress)
769211878Spjd		sync_inprogress = false;
770211878Spjd	mtx_unlock(&sync_lock);
771211878Spjd}
772211878Spjd
773211878Spjdstatic void
774204076Spjdinit_ggate(struct hast_resource *res)
775204076Spjd{
776204076Spjd	struct g_gate_ctl_create ggiocreate;
777204076Spjd	struct g_gate_ctl_cancel ggiocancel;
778204076Spjd
779204076Spjd	/*
780204076Spjd	 * We communicate with ggate via /dev/ggctl. Open it.
781204076Spjd	 */
782204076Spjd	res->hr_ggatefd = open("/dev/" G_GATE_CTL_NAME, O_RDWR);
783204076Spjd	if (res->hr_ggatefd < 0)
784204076Spjd		primary_exit(EX_OSFILE, "Unable to open /dev/" G_GATE_CTL_NAME);
785204076Spjd	/*
786204076Spjd	 * Create provider before trying to connect, as connection failure
787204076Spjd	 * is not critical, but may take some time.
788204076Spjd	 */
789213533Spjd	bzero(&ggiocreate, sizeof(ggiocreate));
790204076Spjd	ggiocreate.gctl_version = G_GATE_VERSION;
791204076Spjd	ggiocreate.gctl_mediasize = res->hr_datasize;
792204076Spjd	ggiocreate.gctl_sectorsize = res->hr_local_sectorsize;
793204076Spjd	ggiocreate.gctl_flags = 0;
794220266Spjd	ggiocreate.gctl_maxcount = 0;
795204076Spjd	ggiocreate.gctl_timeout = 0;
796204076Spjd	ggiocreate.gctl_unit = G_GATE_NAME_GIVEN;
797204076Spjd	snprintf(ggiocreate.gctl_name, sizeof(ggiocreate.gctl_name), "hast/%s",
798204076Spjd	    res->hr_provname);
799204076Spjd	if (ioctl(res->hr_ggatefd, G_GATE_CMD_CREATE, &ggiocreate) == 0) {
800204076Spjd		pjdlog_info("Device hast/%s created.", res->hr_provname);
801204076Spjd		res->hr_ggateunit = ggiocreate.gctl_unit;
802204076Spjd		return;
803204076Spjd	}
804204076Spjd	if (errno != EEXIST) {
805204076Spjd		primary_exit(EX_OSERR, "Unable to create hast/%s device",
806204076Spjd		    res->hr_provname);
807204076Spjd	}
808204076Spjd	pjdlog_debug(1,
809204076Spjd	    "Device hast/%s already exists, we will try to take it over.",
810204076Spjd	    res->hr_provname);
811204076Spjd	/*
812204076Spjd	 * If we received EEXIST, we assume that the process who created the
813204076Spjd	 * provider died and didn't clean up. In that case we will start from
814204076Spjd	 * where he left of.
815204076Spjd	 */
816213533Spjd	bzero(&ggiocancel, sizeof(ggiocancel));
817204076Spjd	ggiocancel.gctl_version = G_GATE_VERSION;
818204076Spjd	ggiocancel.gctl_unit = G_GATE_NAME_GIVEN;
819204076Spjd	snprintf(ggiocancel.gctl_name, sizeof(ggiocancel.gctl_name), "hast/%s",
820204076Spjd	    res->hr_provname);
821204076Spjd	if (ioctl(res->hr_ggatefd, G_GATE_CMD_CANCEL, &ggiocancel) == 0) {
822204076Spjd		pjdlog_info("Device hast/%s recovered.", res->hr_provname);
823204076Spjd		res->hr_ggateunit = ggiocancel.gctl_unit;
824204076Spjd		return;
825204076Spjd	}
826204076Spjd	primary_exit(EX_OSERR, "Unable to take over hast/%s device",
827204076Spjd	    res->hr_provname);
828204076Spjd}
829204076Spjd
830204076Spjdvoid
831204076Spjdhastd_primary(struct hast_resource *res)
832204076Spjd{
833204076Spjd	pthread_t td;
834204076Spjd	pid_t pid;
835219482Strociny	int error, mode, debuglevel;
836204076Spjd
837204076Spjd	/*
838218218Spjd	 * Create communication channel for sending control commands from
839218218Spjd	 * parent to child.
840204076Spjd	 */
841219818Spjd	if (proto_client(NULL, "socketpair://", &res->hr_ctrl) < 0) {
842218042Spjd		/* TODO: There's no need for this to be fatal error. */
843204076Spjd		KEEP_ERRNO((void)pidfile_remove(pfh));
844212034Spjd		pjdlog_exit(EX_OSERR,
845204076Spjd		    "Unable to create control sockets between parent and child");
846204076Spjd	}
847212038Spjd	/*
848218218Spjd	 * Create communication channel for sending events from child to parent.
849212038Spjd	 */
850219818Spjd	if (proto_client(NULL, "socketpair://", &res->hr_event) < 0) {
851218042Spjd		/* TODO: There's no need for this to be fatal error. */
852212038Spjd		KEEP_ERRNO((void)pidfile_remove(pfh));
853212038Spjd		pjdlog_exit(EX_OSERR,
854212038Spjd		    "Unable to create event sockets between child and parent");
855212038Spjd	}
856218218Spjd	/*
857218218Spjd	 * Create communication channel for sending connection requests from
858218218Spjd	 * child to parent.
859218218Spjd	 */
860219818Spjd	if (proto_client(NULL, "socketpair://", &res->hr_conn) < 0) {
861218218Spjd		/* TODO: There's no need for this to be fatal error. */
862218218Spjd		KEEP_ERRNO((void)pidfile_remove(pfh));
863218218Spjd		pjdlog_exit(EX_OSERR,
864218218Spjd		    "Unable to create connection sockets between child and parent");
865218218Spjd	}
866204076Spjd
867204076Spjd	pid = fork();
868204076Spjd	if (pid < 0) {
869218042Spjd		/* TODO: There's no need for this to be fatal error. */
870204076Spjd		KEEP_ERRNO((void)pidfile_remove(pfh));
871212034Spjd		pjdlog_exit(EX_TEMPFAIL, "Unable to fork");
872204076Spjd	}
873204076Spjd
874204076Spjd	if (pid > 0) {
875204076Spjd		/* This is parent. */
876212038Spjd		/* Declare that we are receiver. */
877212038Spjd		proto_recv(res->hr_event, NULL, 0);
878218218Spjd		proto_recv(res->hr_conn, NULL, 0);
879218043Spjd		/* Declare that we are sender. */
880218043Spjd		proto_send(res->hr_ctrl, NULL, 0);
881204076Spjd		res->hr_workerpid = pid;
882204076Spjd		return;
883204076Spjd	}
884211977Spjd
885211984Spjd	gres = res;
886218043Spjd	mode = pjdlog_mode_get();
887219482Strociny	debuglevel = pjdlog_debug_get();
888211984Spjd
889218043Spjd	/* Declare that we are sender. */
890218043Spjd	proto_send(res->hr_event, NULL, 0);
891218218Spjd	proto_send(res->hr_conn, NULL, 0);
892218043Spjd	/* Declare that we are receiver. */
893218043Spjd	proto_recv(res->hr_ctrl, NULL, 0);
894218043Spjd	descriptors_cleanup(res);
895204076Spjd
896218045Spjd	descriptors_assert(res, mode);
897218045Spjd
898218043Spjd	pjdlog_init(mode);
899219482Strociny	pjdlog_debug_set(debuglevel);
900218043Spjd	pjdlog_prefix_set("[%s] (%s) ", res->hr_name, role2str(res->hr_role));
901220005Spjd	setproctitle("%s (%s)", res->hr_name, role2str(res->hr_role));
902204076Spjd
903204076Spjd	init_local(res);
904213007Spjd	init_ggate(res);
905213007Spjd	init_environment(res);
906217784Spjd
907221899Spjd	if (drop_privs(res) != 0) {
908218049Spjd		cleanup(res);
909218049Spjd		exit(EX_CONFIG);
910218049Spjd	}
911218214Spjd	pjdlog_info("Privileges successfully dropped.");
912218049Spjd
913213007Spjd	/*
914213530Spjd	 * Create the guard thread first, so we can handle signals from the
915213530Spjd	 * very begining.
916213530Spjd	 */
917213530Spjd	error = pthread_create(&td, NULL, guard_thread, res);
918218138Spjd	PJDLOG_ASSERT(error == 0);
919213530Spjd	/*
920213007Spjd	 * Create the control thread before sending any event to the parent,
921213007Spjd	 * as we can deadlock when parent sends control request to worker,
922213007Spjd	 * but worker has no control thread started yet, so parent waits.
923213007Spjd	 * In the meantime worker sends an event to the parent, but parent
924213007Spjd	 * is unable to handle the event, because it waits for control
925213007Spjd	 * request response.
926213007Spjd	 */
927213007Spjd	error = pthread_create(&td, NULL, ctrl_thread, res);
928218138Spjd	PJDLOG_ASSERT(error == 0);
929220898Spjd	if (real_remote(res)) {
930220898Spjd		error = init_remote(res, NULL, NULL);
931220898Spjd		if (error == 0) {
932220898Spjd			sync_start();
933220898Spjd		} else if (error == EBUSY) {
934220898Spjd			time_t start = time(NULL);
935220898Spjd
936220898Spjd			pjdlog_warning("Waiting for remote node to become %s for %ds.",
937220898Spjd			    role2str(HAST_ROLE_SECONDARY),
938220898Spjd			    res->hr_timeout);
939220898Spjd			for (;;) {
940220898Spjd				sleep(1);
941220898Spjd				error = init_remote(res, NULL, NULL);
942220898Spjd				if (error != EBUSY)
943220898Spjd					break;
944220898Spjd				if (time(NULL) > start + res->hr_timeout)
945220898Spjd					break;
946220898Spjd			}
947220898Spjd			if (error == EBUSY) {
948220898Spjd				pjdlog_warning("Remote node is still %s, starting anyway.",
949220898Spjd				    role2str(HAST_ROLE_PRIMARY));
950220898Spjd			}
951220898Spjd		}
952220898Spjd	}
953204076Spjd	error = pthread_create(&td, NULL, ggate_recv_thread, res);
954218138Spjd	PJDLOG_ASSERT(error == 0);
955204076Spjd	error = pthread_create(&td, NULL, local_send_thread, res);
956218138Spjd	PJDLOG_ASSERT(error == 0);
957204076Spjd	error = pthread_create(&td, NULL, remote_send_thread, res);
958218138Spjd	PJDLOG_ASSERT(error == 0);
959204076Spjd	error = pthread_create(&td, NULL, remote_recv_thread, res);
960218138Spjd	PJDLOG_ASSERT(error == 0);
961204076Spjd	error = pthread_create(&td, NULL, ggate_send_thread, res);
962218138Spjd	PJDLOG_ASSERT(error == 0);
963220898Spjd	fullystarted = true;
964213530Spjd	(void)sync_thread(res);
965204076Spjd}
966204076Spjd
967204076Spjdstatic void
968204076Spjdreqlog(int loglevel, int debuglevel, struct g_gate_ctl_io *ggio, const char *fmt, ...)
969204076Spjd{
970204076Spjd	char msg[1024];
971204076Spjd	va_list ap;
972204076Spjd	int len;
973204076Spjd
974204076Spjd	va_start(ap, fmt);
975204076Spjd	len = vsnprintf(msg, sizeof(msg), fmt, ap);
976204076Spjd	va_end(ap);
977204076Spjd	if ((size_t)len < sizeof(msg)) {
978204076Spjd		switch (ggio->gctl_cmd) {
979204076Spjd		case BIO_READ:
980204076Spjd			(void)snprintf(msg + len, sizeof(msg) - len,
981204076Spjd			    "READ(%ju, %ju).", (uintmax_t)ggio->gctl_offset,
982204076Spjd			    (uintmax_t)ggio->gctl_length);
983204076Spjd			break;
984204076Spjd		case BIO_DELETE:
985204076Spjd			(void)snprintf(msg + len, sizeof(msg) - len,
986204076Spjd			    "DELETE(%ju, %ju).", (uintmax_t)ggio->gctl_offset,
987204076Spjd			    (uintmax_t)ggio->gctl_length);
988204076Spjd			break;
989204076Spjd		case BIO_FLUSH:
990204076Spjd			(void)snprintf(msg + len, sizeof(msg) - len, "FLUSH.");
991204076Spjd			break;
992204076Spjd		case BIO_WRITE:
993204076Spjd			(void)snprintf(msg + len, sizeof(msg) - len,
994204076Spjd			    "WRITE(%ju, %ju).", (uintmax_t)ggio->gctl_offset,
995204076Spjd			    (uintmax_t)ggio->gctl_length);
996204076Spjd			break;
997204076Spjd		default:
998204076Spjd			(void)snprintf(msg + len, sizeof(msg) - len,
999204076Spjd			    "UNKNOWN(%u).", (unsigned int)ggio->gctl_cmd);
1000204076Spjd			break;
1001204076Spjd		}
1002204076Spjd	}
1003204076Spjd	pjdlog_common(loglevel, debuglevel, -1, "%s", msg);
1004204076Spjd}
1005204076Spjd
1006204076Spjdstatic void
1007204076Spjdremote_close(struct hast_resource *res, int ncomp)
1008204076Spjd{
1009204076Spjd
1010204076Spjd	rw_wlock(&hio_remote_lock[ncomp]);
1011204076Spjd	/*
1012204076Spjd	 * A race is possible between dropping rlock and acquiring wlock -
1013204076Spjd	 * another thread can close connection in-between.
1014204076Spjd	 */
1015204076Spjd	if (!ISCONNECTED(res, ncomp)) {
1016218138Spjd		PJDLOG_ASSERT(res->hr_remotein == NULL);
1017218138Spjd		PJDLOG_ASSERT(res->hr_remoteout == NULL);
1018204076Spjd		rw_unlock(&hio_remote_lock[ncomp]);
1019204076Spjd		return;
1020204076Spjd	}
1021204076Spjd
1022218138Spjd	PJDLOG_ASSERT(res->hr_remotein != NULL);
1023218138Spjd	PJDLOG_ASSERT(res->hr_remoteout != NULL);
1024204076Spjd
1025211881Spjd	pjdlog_debug(2, "Closing incoming connection to %s.",
1026204076Spjd	    res->hr_remoteaddr);
1027204076Spjd	proto_close(res->hr_remotein);
1028204076Spjd	res->hr_remotein = NULL;
1029211881Spjd	pjdlog_debug(2, "Closing outgoing connection to %s.",
1030204076Spjd	    res->hr_remoteaddr);
1031204076Spjd	proto_close(res->hr_remoteout);
1032204076Spjd	res->hr_remoteout = NULL;
1033204076Spjd
1034204076Spjd	rw_unlock(&hio_remote_lock[ncomp]);
1035204076Spjd
1036211881Spjd	pjdlog_warning("Disconnected from %s.", res->hr_remoteaddr);
1037211881Spjd
1038204076Spjd	/*
1039204076Spjd	 * Stop synchronization if in-progress.
1040204076Spjd	 */
1041211878Spjd	sync_stop();
1042211984Spjd
1043212038Spjd	event_send(res, EVENT_DISCONNECT);
1044204076Spjd}
1045204076Spjd
1046204076Spjd/*
1047204076Spjd * Thread receives ggate I/O requests from the kernel and passes them to
1048204076Spjd * appropriate threads:
1049204076Spjd * WRITE - always goes to both local_send and remote_send threads
1050204076Spjd * READ (when the block is up-to-date on local component) -
1051204076Spjd *	only local_send thread
1052204076Spjd * READ (when the block isn't up-to-date on local component) -
1053204076Spjd *	only remote_send thread
1054204076Spjd * DELETE - always goes to both local_send and remote_send threads
1055204076Spjd * FLUSH - always goes to both local_send and remote_send threads
1056204076Spjd */
1057204076Spjdstatic void *
1058204076Spjdggate_recv_thread(void *arg)
1059204076Spjd{
1060204076Spjd	struct hast_resource *res = arg;
1061204076Spjd	struct g_gate_ctl_io *ggio;
1062204076Spjd	struct hio *hio;
1063204076Spjd	unsigned int ii, ncomp, ncomps;
1064204076Spjd	int error;
1065204076Spjd
1066204076Spjd	ncomps = HAST_NCOMPONENTS;
1067204076Spjd
1068204076Spjd	for (;;) {
1069204076Spjd		pjdlog_debug(2, "ggate_recv: Taking free request.");
1070204076Spjd		QUEUE_TAKE2(hio, free);
1071204076Spjd		pjdlog_debug(2, "ggate_recv: (%p) Got free request.", hio);
1072204076Spjd		ggio = &hio->hio_ggio;
1073204076Spjd		ggio->gctl_unit = res->hr_ggateunit;
1074204076Spjd		ggio->gctl_length = MAXPHYS;
1075204076Spjd		ggio->gctl_error = 0;
1076204076Spjd		pjdlog_debug(2,
1077204076Spjd		    "ggate_recv: (%p) Waiting for request from the kernel.",
1078204076Spjd		    hio);
1079204076Spjd		if (ioctl(res->hr_ggatefd, G_GATE_CMD_START, ggio) < 0) {
1080204076Spjd			if (sigexit_received)
1081204076Spjd				pthread_exit(NULL);
1082204076Spjd			primary_exit(EX_OSERR, "G_GATE_CMD_START failed");
1083204076Spjd		}
1084204076Spjd		error = ggio->gctl_error;
1085204076Spjd		switch (error) {
1086204076Spjd		case 0:
1087204076Spjd			break;
1088204076Spjd		case ECANCELED:
1089204076Spjd			/* Exit gracefully. */
1090204076Spjd			if (!sigexit_received) {
1091204076Spjd				pjdlog_debug(2,
1092204076Spjd				    "ggate_recv: (%p) Received cancel from the kernel.",
1093204076Spjd				    hio);
1094204076Spjd				pjdlog_info("Received cancel from the kernel, exiting.");
1095204076Spjd			}
1096204076Spjd			pthread_exit(NULL);
1097204076Spjd		case ENOMEM:
1098204076Spjd			/*
1099204076Spjd			 * Buffer too small? Impossible, we allocate MAXPHYS
1100204076Spjd			 * bytes - request can't be bigger than that.
1101204076Spjd			 */
1102204076Spjd			/* FALLTHROUGH */
1103204076Spjd		case ENXIO:
1104204076Spjd		default:
1105204076Spjd			primary_exitx(EX_OSERR, "G_GATE_CMD_START failed: %s.",
1106204076Spjd			    strerror(error));
1107204076Spjd		}
1108204076Spjd		for (ii = 0; ii < ncomps; ii++)
1109204076Spjd			hio->hio_errors[ii] = EINVAL;
1110204076Spjd		reqlog(LOG_DEBUG, 2, ggio,
1111204076Spjd		    "ggate_recv: (%p) Request received from the kernel: ",
1112204076Spjd		    hio);
1113204076Spjd		/*
1114204076Spjd		 * Inform all components about new write request.
1115204076Spjd		 * For read request prefer local component unless the given
1116204076Spjd		 * range is out-of-date, then use remote component.
1117204076Spjd		 */
1118204076Spjd		switch (ggio->gctl_cmd) {
1119204076Spjd		case BIO_READ:
1120222228Spjd			res->hr_stat_read++;
1121204076Spjd			pjdlog_debug(2,
1122204076Spjd			    "ggate_recv: (%p) Moving request to the send queue.",
1123204076Spjd			    hio);
1124204076Spjd			refcount_init(&hio->hio_countdown, 1);
1125204076Spjd			mtx_lock(&metadata_lock);
1126204076Spjd			if (res->hr_syncsrc == HAST_SYNCSRC_UNDEF ||
1127204076Spjd			    res->hr_syncsrc == HAST_SYNCSRC_PRIMARY) {
1128204076Spjd				/*
1129204076Spjd				 * This range is up-to-date on local component,
1130204076Spjd				 * so handle request locally.
1131204076Spjd				 */
1132204076Spjd				 /* Local component is 0 for now. */
1133204076Spjd				ncomp = 0;
1134204076Spjd			} else /* if (res->hr_syncsrc ==
1135204076Spjd			    HAST_SYNCSRC_SECONDARY) */ {
1136218138Spjd				PJDLOG_ASSERT(res->hr_syncsrc ==
1137204076Spjd				    HAST_SYNCSRC_SECONDARY);
1138204076Spjd				/*
1139204076Spjd				 * This range is out-of-date on local component,
1140204076Spjd				 * so send request to the remote node.
1141204076Spjd				 */
1142204076Spjd				 /* Remote component is 1 for now. */
1143204076Spjd				ncomp = 1;
1144204076Spjd			}
1145204076Spjd			mtx_unlock(&metadata_lock);
1146204076Spjd			QUEUE_INSERT1(hio, send, ncomp);
1147204076Spjd			break;
1148204076Spjd		case BIO_WRITE:
1149222228Spjd			res->hr_stat_write++;
1150214284Spjd			if (res->hr_resuid == 0) {
1151219844Spjd				/*
1152219844Spjd				 * This is first write, initialize localcnt and
1153219844Spjd				 * resuid.
1154219844Spjd				 */
1155219844Spjd				res->hr_primary_localcnt = 1;
1156214284Spjd				(void)init_resuid(res);
1157214284Spjd			}
1158204076Spjd			for (;;) {
1159204076Spjd				mtx_lock(&range_lock);
1160204076Spjd				if (rangelock_islocked(range_sync,
1161204076Spjd				    ggio->gctl_offset, ggio->gctl_length)) {
1162204076Spjd					pjdlog_debug(2,
1163204076Spjd					    "regular: Range offset=%jd length=%zu locked.",
1164204076Spjd					    (intmax_t)ggio->gctl_offset,
1165204076Spjd					    (size_t)ggio->gctl_length);
1166204076Spjd					range_regular_wait = true;
1167204076Spjd					cv_wait(&range_regular_cond, &range_lock);
1168204076Spjd					range_regular_wait = false;
1169204076Spjd					mtx_unlock(&range_lock);
1170204076Spjd					continue;
1171204076Spjd				}
1172204076Spjd				if (rangelock_add(range_regular,
1173204076Spjd				    ggio->gctl_offset, ggio->gctl_length) < 0) {
1174204076Spjd					mtx_unlock(&range_lock);
1175204076Spjd					pjdlog_debug(2,
1176204076Spjd					    "regular: Range offset=%jd length=%zu is already locked, waiting.",
1177204076Spjd					    (intmax_t)ggio->gctl_offset,
1178204076Spjd					    (size_t)ggio->gctl_length);
1179204076Spjd					sleep(1);
1180204076Spjd					continue;
1181204076Spjd				}
1182204076Spjd				mtx_unlock(&range_lock);
1183204076Spjd				break;
1184204076Spjd			}
1185204076Spjd			mtx_lock(&res->hr_amp_lock);
1186204076Spjd			if (activemap_write_start(res->hr_amp,
1187204076Spjd			    ggio->gctl_offset, ggio->gctl_length)) {
1188222228Spjd				res->hr_stat_activemap_update++;
1189204076Spjd				(void)hast_activemap_flush(res);
1190204076Spjd			}
1191204076Spjd			mtx_unlock(&res->hr_amp_lock);
1192204076Spjd			/* FALLTHROUGH */
1193204076Spjd		case BIO_DELETE:
1194204076Spjd		case BIO_FLUSH:
1195222228Spjd			switch (ggio->gctl_cmd) {
1196222228Spjd			case BIO_DELETE:
1197222228Spjd				res->hr_stat_delete++;
1198222228Spjd				break;
1199222228Spjd			case BIO_FLUSH:
1200222228Spjd				res->hr_stat_flush++;
1201222228Spjd				break;
1202222228Spjd			}
1203204076Spjd			pjdlog_debug(2,
1204204076Spjd			    "ggate_recv: (%p) Moving request to the send queues.",
1205204076Spjd			    hio);
1206204076Spjd			refcount_init(&hio->hio_countdown, ncomps);
1207204076Spjd			for (ii = 0; ii < ncomps; ii++)
1208204076Spjd				QUEUE_INSERT1(hio, send, ii);
1209204076Spjd			break;
1210204076Spjd		}
1211204076Spjd	}
1212204076Spjd	/* NOTREACHED */
1213204076Spjd	return (NULL);
1214204076Spjd}
1215204076Spjd
1216204076Spjd/*
1217204076Spjd * Thread reads from or writes to local component.
1218204076Spjd * If local read fails, it redirects it to remote_send thread.
1219204076Spjd */
1220204076Spjdstatic void *
1221204076Spjdlocal_send_thread(void *arg)
1222204076Spjd{
1223204076Spjd	struct hast_resource *res = arg;
1224204076Spjd	struct g_gate_ctl_io *ggio;
1225204076Spjd	struct hio *hio;
1226204076Spjd	unsigned int ncomp, rncomp;
1227204076Spjd	ssize_t ret;
1228204076Spjd
1229204076Spjd	/* Local component is 0 for now. */
1230204076Spjd	ncomp = 0;
1231204076Spjd	/* Remote component is 1 for now. */
1232204076Spjd	rncomp = 1;
1233204076Spjd
1234204076Spjd	for (;;) {
1235204076Spjd		pjdlog_debug(2, "local_send: Taking request.");
1236214692Spjd		QUEUE_TAKE1(hio, send, ncomp, 0);
1237204076Spjd		pjdlog_debug(2, "local_send: (%p) Got request.", hio);
1238204076Spjd		ggio = &hio->hio_ggio;
1239204076Spjd		switch (ggio->gctl_cmd) {
1240204076Spjd		case BIO_READ:
1241204076Spjd			ret = pread(res->hr_localfd, ggio->gctl_data,
1242204076Spjd			    ggio->gctl_length,
1243204076Spjd			    ggio->gctl_offset + res->hr_localoff);
1244204076Spjd			if (ret == ggio->gctl_length)
1245204076Spjd				hio->hio_errors[ncomp] = 0;
1246204076Spjd			else {
1247204076Spjd				/*
1248204076Spjd				 * If READ failed, try to read from remote node.
1249204076Spjd				 */
1250216479Spjd				if (ret < 0) {
1251216479Spjd					reqlog(LOG_WARNING, 0, ggio,
1252216479Spjd					    "Local request failed (%s), trying remote node. ",
1253216479Spjd					    strerror(errno));
1254216479Spjd				} else if (ret != ggio->gctl_length) {
1255216479Spjd					reqlog(LOG_WARNING, 0, ggio,
1256216479Spjd					    "Local request failed (%zd != %jd), trying remote node. ",
1257216494Spjd					    ret, (intmax_t)ggio->gctl_length);
1258216479Spjd				}
1259204076Spjd				QUEUE_INSERT1(hio, send, rncomp);
1260204076Spjd				continue;
1261204076Spjd			}
1262204076Spjd			break;
1263204076Spjd		case BIO_WRITE:
1264204076Spjd			ret = pwrite(res->hr_localfd, ggio->gctl_data,
1265204076Spjd			    ggio->gctl_length,
1266204076Spjd			    ggio->gctl_offset + res->hr_localoff);
1267216479Spjd			if (ret < 0) {
1268204076Spjd				hio->hio_errors[ncomp] = errno;
1269216479Spjd				reqlog(LOG_WARNING, 0, ggio,
1270216479Spjd				    "Local request failed (%s): ",
1271216479Spjd				    strerror(errno));
1272216479Spjd			} else if (ret != ggio->gctl_length) {
1273204076Spjd				hio->hio_errors[ncomp] = EIO;
1274216479Spjd				reqlog(LOG_WARNING, 0, ggio,
1275216479Spjd				    "Local request failed (%zd != %jd): ",
1276216494Spjd				    ret, (intmax_t)ggio->gctl_length);
1277216479Spjd			} else {
1278204076Spjd				hio->hio_errors[ncomp] = 0;
1279216479Spjd			}
1280204076Spjd			break;
1281204076Spjd		case BIO_DELETE:
1282204076Spjd			ret = g_delete(res->hr_localfd,
1283204076Spjd			    ggio->gctl_offset + res->hr_localoff,
1284204076Spjd			    ggio->gctl_length);
1285216479Spjd			if (ret < 0) {
1286204076Spjd				hio->hio_errors[ncomp] = errno;
1287216479Spjd				reqlog(LOG_WARNING, 0, ggio,
1288216479Spjd				    "Local request failed (%s): ",
1289216479Spjd				    strerror(errno));
1290216479Spjd			} else {
1291204076Spjd				hio->hio_errors[ncomp] = 0;
1292216479Spjd			}
1293204076Spjd			break;
1294204076Spjd		case BIO_FLUSH:
1295204076Spjd			ret = g_flush(res->hr_localfd);
1296216479Spjd			if (ret < 0) {
1297204076Spjd				hio->hio_errors[ncomp] = errno;
1298216479Spjd				reqlog(LOG_WARNING, 0, ggio,
1299216479Spjd				    "Local request failed (%s): ",
1300216479Spjd				    strerror(errno));
1301216479Spjd			} else {
1302204076Spjd				hio->hio_errors[ncomp] = 0;
1303216479Spjd			}
1304204076Spjd			break;
1305204076Spjd		}
1306204076Spjd		if (refcount_release(&hio->hio_countdown)) {
1307204076Spjd			if (ISSYNCREQ(hio)) {
1308204076Spjd				mtx_lock(&sync_lock);
1309204076Spjd				SYNCREQDONE(hio);
1310204076Spjd				mtx_unlock(&sync_lock);
1311204076Spjd				cv_signal(&sync_cond);
1312204076Spjd			} else {
1313204076Spjd				pjdlog_debug(2,
1314204076Spjd				    "local_send: (%p) Moving request to the done queue.",
1315204076Spjd				    hio);
1316204076Spjd				QUEUE_INSERT2(hio, done);
1317204076Spjd			}
1318204076Spjd		}
1319204076Spjd	}
1320204076Spjd	/* NOTREACHED */
1321204076Spjd	return (NULL);
1322204076Spjd}
1323204076Spjd
1324214692Spjdstatic void
1325214692Spjdkeepalive_send(struct hast_resource *res, unsigned int ncomp)
1326214692Spjd{
1327214692Spjd	struct nv *nv;
1328214692Spjd
1329218217Spjd	rw_rlock(&hio_remote_lock[ncomp]);
1330218217Spjd
1331218217Spjd	if (!ISCONNECTED(res, ncomp)) {
1332218217Spjd		rw_unlock(&hio_remote_lock[ncomp]);
1333214692Spjd		return;
1334218217Spjd	}
1335219864Spjd
1336218138Spjd	PJDLOG_ASSERT(res->hr_remotein != NULL);
1337218138Spjd	PJDLOG_ASSERT(res->hr_remoteout != NULL);
1338214692Spjd
1339214692Spjd	nv = nv_alloc();
1340214692Spjd	nv_add_uint8(nv, HIO_KEEPALIVE, "cmd");
1341214692Spjd	if (nv_error(nv) != 0) {
1342218217Spjd		rw_unlock(&hio_remote_lock[ncomp]);
1343214692Spjd		nv_free(nv);
1344214692Spjd		pjdlog_debug(1,
1345214692Spjd		    "keepalive_send: Unable to prepare header to send.");
1346214692Spjd		return;
1347214692Spjd	}
1348214692Spjd	if (hast_proto_send(res, res->hr_remoteout, nv, NULL, 0) < 0) {
1349218217Spjd		rw_unlock(&hio_remote_lock[ncomp]);
1350214692Spjd		pjdlog_common(LOG_DEBUG, 1, errno,
1351214692Spjd		    "keepalive_send: Unable to send request");
1352214692Spjd		nv_free(nv);
1353214692Spjd		remote_close(res, ncomp);
1354214692Spjd		return;
1355214692Spjd	}
1356218217Spjd
1357218217Spjd	rw_unlock(&hio_remote_lock[ncomp]);
1358214692Spjd	nv_free(nv);
1359214692Spjd	pjdlog_debug(2, "keepalive_send: Request sent.");
1360214692Spjd}
1361214692Spjd
1362204076Spjd/*
1363204076Spjd * Thread sends request to secondary node.
1364204076Spjd */
1365204076Spjdstatic void *
1366204076Spjdremote_send_thread(void *arg)
1367204076Spjd{
1368204076Spjd	struct hast_resource *res = arg;
1369204076Spjd	struct g_gate_ctl_io *ggio;
1370214692Spjd	time_t lastcheck, now;
1371204076Spjd	struct hio *hio;
1372204076Spjd	struct nv *nv;
1373204076Spjd	unsigned int ncomp;
1374204076Spjd	bool wakeup;
1375204076Spjd	uint64_t offset, length;
1376204076Spjd	uint8_t cmd;
1377204076Spjd	void *data;
1378204076Spjd
1379204076Spjd	/* Remote component is 1 for now. */
1380204076Spjd	ncomp = 1;
1381219864Spjd	lastcheck = time(NULL);
1382204076Spjd
1383204076Spjd	for (;;) {
1384204076Spjd		pjdlog_debug(2, "remote_send: Taking request.");
1385219721Strociny		QUEUE_TAKE1(hio, send, ncomp, HAST_KEEPALIVE);
1386214692Spjd		if (hio == NULL) {
1387214692Spjd			now = time(NULL);
1388219721Strociny			if (lastcheck + HAST_KEEPALIVE <= now) {
1389214692Spjd				keepalive_send(res, ncomp);
1390214692Spjd				lastcheck = now;
1391214692Spjd			}
1392214692Spjd			continue;
1393214692Spjd		}
1394204076Spjd		pjdlog_debug(2, "remote_send: (%p) Got request.", hio);
1395204076Spjd		ggio = &hio->hio_ggio;
1396204076Spjd		switch (ggio->gctl_cmd) {
1397204076Spjd		case BIO_READ:
1398204076Spjd			cmd = HIO_READ;
1399204076Spjd			data = NULL;
1400204076Spjd			offset = ggio->gctl_offset;
1401204076Spjd			length = ggio->gctl_length;
1402204076Spjd			break;
1403204076Spjd		case BIO_WRITE:
1404204076Spjd			cmd = HIO_WRITE;
1405204076Spjd			data = ggio->gctl_data;
1406204076Spjd			offset = ggio->gctl_offset;
1407204076Spjd			length = ggio->gctl_length;
1408204076Spjd			break;
1409204076Spjd		case BIO_DELETE:
1410204076Spjd			cmd = HIO_DELETE;
1411204076Spjd			data = NULL;
1412204076Spjd			offset = ggio->gctl_offset;
1413204076Spjd			length = ggio->gctl_length;
1414204076Spjd			break;
1415204076Spjd		case BIO_FLUSH:
1416204076Spjd			cmd = HIO_FLUSH;
1417204076Spjd			data = NULL;
1418204076Spjd			offset = 0;
1419204076Spjd			length = 0;
1420204076Spjd			break;
1421204076Spjd		default:
1422218138Spjd			PJDLOG_ASSERT(!"invalid condition");
1423204076Spjd			abort();
1424204076Spjd		}
1425204076Spjd		nv = nv_alloc();
1426204076Spjd		nv_add_uint8(nv, cmd, "cmd");
1427204076Spjd		nv_add_uint64(nv, (uint64_t)ggio->gctl_seq, "seq");
1428204076Spjd		nv_add_uint64(nv, offset, "offset");
1429204076Spjd		nv_add_uint64(nv, length, "length");
1430204076Spjd		if (nv_error(nv) != 0) {
1431204076Spjd			hio->hio_errors[ncomp] = nv_error(nv);
1432204076Spjd			pjdlog_debug(2,
1433204076Spjd			    "remote_send: (%p) Unable to prepare header to send.",
1434204076Spjd			    hio);
1435204076Spjd			reqlog(LOG_ERR, 0, ggio,
1436204076Spjd			    "Unable to prepare header to send (%s): ",
1437204076Spjd			    strerror(nv_error(nv)));
1438204076Spjd			/* Move failed request immediately to the done queue. */
1439204076Spjd			goto done_queue;
1440204076Spjd		}
1441204076Spjd		pjdlog_debug(2,
1442204076Spjd		    "remote_send: (%p) Moving request to the recv queue.",
1443204076Spjd		    hio);
1444204076Spjd		/*
1445204076Spjd		 * Protect connection from disappearing.
1446204076Spjd		 */
1447204076Spjd		rw_rlock(&hio_remote_lock[ncomp]);
1448204076Spjd		if (!ISCONNECTED(res, ncomp)) {
1449204076Spjd			rw_unlock(&hio_remote_lock[ncomp]);
1450204076Spjd			hio->hio_errors[ncomp] = ENOTCONN;
1451204076Spjd			goto done_queue;
1452204076Spjd		}
1453204076Spjd		/*
1454204076Spjd		 * Move the request to recv queue before sending it, because
1455204076Spjd		 * in different order we can get reply before we move request
1456204076Spjd		 * to recv queue.
1457204076Spjd		 */
1458204076Spjd		mtx_lock(&hio_recv_list_lock[ncomp]);
1459204076Spjd		wakeup = TAILQ_EMPTY(&hio_recv_list[ncomp]);
1460204076Spjd		TAILQ_INSERT_TAIL(&hio_recv_list[ncomp], hio, hio_next[ncomp]);
1461204076Spjd		mtx_unlock(&hio_recv_list_lock[ncomp]);
1462204076Spjd		if (hast_proto_send(res, res->hr_remoteout, nv, data,
1463204076Spjd		    data != NULL ? length : 0) < 0) {
1464204076Spjd			hio->hio_errors[ncomp] = errno;
1465204076Spjd			rw_unlock(&hio_remote_lock[ncomp]);
1466204076Spjd			pjdlog_debug(2,
1467204076Spjd			    "remote_send: (%p) Unable to send request.", hio);
1468204076Spjd			reqlog(LOG_ERR, 0, ggio,
1469204076Spjd			    "Unable to send request (%s): ",
1470204076Spjd			    strerror(hio->hio_errors[ncomp]));
1471211979Spjd			remote_close(res, ncomp);
1472204076Spjd			/*
1473204076Spjd			 * Take request back from the receive queue and move
1474204076Spjd			 * it immediately to the done queue.
1475204076Spjd			 */
1476204076Spjd			mtx_lock(&hio_recv_list_lock[ncomp]);
1477204076Spjd			TAILQ_REMOVE(&hio_recv_list[ncomp], hio, hio_next[ncomp]);
1478204076Spjd			mtx_unlock(&hio_recv_list_lock[ncomp]);
1479204076Spjd			goto done_queue;
1480204076Spjd		}
1481204076Spjd		rw_unlock(&hio_remote_lock[ncomp]);
1482204076Spjd		nv_free(nv);
1483204076Spjd		if (wakeup)
1484204076Spjd			cv_signal(&hio_recv_list_cond[ncomp]);
1485204076Spjd		continue;
1486204076Spjddone_queue:
1487204076Spjd		nv_free(nv);
1488204076Spjd		if (ISSYNCREQ(hio)) {
1489204076Spjd			if (!refcount_release(&hio->hio_countdown))
1490204076Spjd				continue;
1491204076Spjd			mtx_lock(&sync_lock);
1492204076Spjd			SYNCREQDONE(hio);
1493204076Spjd			mtx_unlock(&sync_lock);
1494204076Spjd			cv_signal(&sync_cond);
1495204076Spjd			continue;
1496204076Spjd		}
1497204076Spjd		if (ggio->gctl_cmd == BIO_WRITE) {
1498204076Spjd			mtx_lock(&res->hr_amp_lock);
1499204076Spjd			if (activemap_need_sync(res->hr_amp, ggio->gctl_offset,
1500204076Spjd			    ggio->gctl_length)) {
1501204076Spjd				(void)hast_activemap_flush(res);
1502204076Spjd			}
1503204076Spjd			mtx_unlock(&res->hr_amp_lock);
1504204076Spjd		}
1505204076Spjd		if (!refcount_release(&hio->hio_countdown))
1506204076Spjd			continue;
1507204076Spjd		pjdlog_debug(2,
1508204076Spjd		    "remote_send: (%p) Moving request to the done queue.",
1509204076Spjd		    hio);
1510204076Spjd		QUEUE_INSERT2(hio, done);
1511204076Spjd	}
1512204076Spjd	/* NOTREACHED */
1513204076Spjd	return (NULL);
1514204076Spjd}
1515204076Spjd
1516204076Spjd/*
1517204076Spjd * Thread receives answer from secondary node and passes it to ggate_send
1518204076Spjd * thread.
1519204076Spjd */
1520204076Spjdstatic void *
1521204076Spjdremote_recv_thread(void *arg)
1522204076Spjd{
1523204076Spjd	struct hast_resource *res = arg;
1524204076Spjd	struct g_gate_ctl_io *ggio;
1525204076Spjd	struct hio *hio;
1526204076Spjd	struct nv *nv;
1527204076Spjd	unsigned int ncomp;
1528204076Spjd	uint64_t seq;
1529204076Spjd	int error;
1530204076Spjd
1531204076Spjd	/* Remote component is 1 for now. */
1532204076Spjd	ncomp = 1;
1533204076Spjd
1534204076Spjd	for (;;) {
1535204076Spjd		/* Wait until there is anything to receive. */
1536204076Spjd		mtx_lock(&hio_recv_list_lock[ncomp]);
1537204076Spjd		while (TAILQ_EMPTY(&hio_recv_list[ncomp])) {
1538204076Spjd			pjdlog_debug(2, "remote_recv: No requests, waiting.");
1539204076Spjd			cv_wait(&hio_recv_list_cond[ncomp],
1540204076Spjd			    &hio_recv_list_lock[ncomp]);
1541204076Spjd		}
1542204076Spjd		mtx_unlock(&hio_recv_list_lock[ncomp]);
1543204076Spjd		rw_rlock(&hio_remote_lock[ncomp]);
1544204076Spjd		if (!ISCONNECTED(res, ncomp)) {
1545204076Spjd			rw_unlock(&hio_remote_lock[ncomp]);
1546204076Spjd			/*
1547204076Spjd			 * Connection is dead, so move all pending requests to
1548204076Spjd			 * the done queue (one-by-one).
1549204076Spjd			 */
1550204076Spjd			mtx_lock(&hio_recv_list_lock[ncomp]);
1551204076Spjd			hio = TAILQ_FIRST(&hio_recv_list[ncomp]);
1552218138Spjd			PJDLOG_ASSERT(hio != NULL);
1553204076Spjd			TAILQ_REMOVE(&hio_recv_list[ncomp], hio,
1554204076Spjd			    hio_next[ncomp]);
1555204076Spjd			mtx_unlock(&hio_recv_list_lock[ncomp]);
1556204076Spjd			goto done_queue;
1557204076Spjd		}
1558204076Spjd		if (hast_proto_recv_hdr(res->hr_remotein, &nv) < 0) {
1559204076Spjd			pjdlog_errno(LOG_ERR,
1560204076Spjd			    "Unable to receive reply header");
1561204076Spjd			rw_unlock(&hio_remote_lock[ncomp]);
1562204076Spjd			remote_close(res, ncomp);
1563204076Spjd			continue;
1564204076Spjd		}
1565204076Spjd		rw_unlock(&hio_remote_lock[ncomp]);
1566204076Spjd		seq = nv_get_uint64(nv, "seq");
1567204076Spjd		if (seq == 0) {
1568204076Spjd			pjdlog_error("Header contains no 'seq' field.");
1569204076Spjd			nv_free(nv);
1570204076Spjd			continue;
1571204076Spjd		}
1572204076Spjd		mtx_lock(&hio_recv_list_lock[ncomp]);
1573204076Spjd		TAILQ_FOREACH(hio, &hio_recv_list[ncomp], hio_next[ncomp]) {
1574204076Spjd			if (hio->hio_ggio.gctl_seq == seq) {
1575204076Spjd				TAILQ_REMOVE(&hio_recv_list[ncomp], hio,
1576204076Spjd				    hio_next[ncomp]);
1577204076Spjd				break;
1578204076Spjd			}
1579204076Spjd		}
1580204076Spjd		mtx_unlock(&hio_recv_list_lock[ncomp]);
1581204076Spjd		if (hio == NULL) {
1582204076Spjd			pjdlog_error("Found no request matching received 'seq' field (%ju).",
1583204076Spjd			    (uintmax_t)seq);
1584204076Spjd			nv_free(nv);
1585204076Spjd			continue;
1586204076Spjd		}
1587204076Spjd		error = nv_get_int16(nv, "error");
1588204076Spjd		if (error != 0) {
1589204076Spjd			/* Request failed on remote side. */
1590216478Spjd			hio->hio_errors[ncomp] = error;
1591216479Spjd			reqlog(LOG_WARNING, 0, &hio->hio_ggio,
1592216479Spjd			    "Remote request failed (%s): ", strerror(error));
1593204076Spjd			nv_free(nv);
1594204076Spjd			goto done_queue;
1595204076Spjd		}
1596204076Spjd		ggio = &hio->hio_ggio;
1597204076Spjd		switch (ggio->gctl_cmd) {
1598204076Spjd		case BIO_READ:
1599204076Spjd			rw_rlock(&hio_remote_lock[ncomp]);
1600204076Spjd			if (!ISCONNECTED(res, ncomp)) {
1601204076Spjd				rw_unlock(&hio_remote_lock[ncomp]);
1602204076Spjd				nv_free(nv);
1603204076Spjd				goto done_queue;
1604204076Spjd			}
1605204076Spjd			if (hast_proto_recv_data(res, res->hr_remotein, nv,
1606204076Spjd			    ggio->gctl_data, ggio->gctl_length) < 0) {
1607204076Spjd				hio->hio_errors[ncomp] = errno;
1608204076Spjd				pjdlog_errno(LOG_ERR,
1609204076Spjd				    "Unable to receive reply data");
1610204076Spjd				rw_unlock(&hio_remote_lock[ncomp]);
1611204076Spjd				nv_free(nv);
1612204076Spjd				remote_close(res, ncomp);
1613204076Spjd				goto done_queue;
1614204076Spjd			}
1615204076Spjd			rw_unlock(&hio_remote_lock[ncomp]);
1616204076Spjd			break;
1617204076Spjd		case BIO_WRITE:
1618204076Spjd		case BIO_DELETE:
1619204076Spjd		case BIO_FLUSH:
1620204076Spjd			break;
1621204076Spjd		default:
1622218138Spjd			PJDLOG_ASSERT(!"invalid condition");
1623204076Spjd			abort();
1624204076Spjd		}
1625204076Spjd		hio->hio_errors[ncomp] = 0;
1626204076Spjd		nv_free(nv);
1627204076Spjddone_queue:
1628204076Spjd		if (refcount_release(&hio->hio_countdown)) {
1629204076Spjd			if (ISSYNCREQ(hio)) {
1630204076Spjd				mtx_lock(&sync_lock);
1631204076Spjd				SYNCREQDONE(hio);
1632204076Spjd				mtx_unlock(&sync_lock);
1633204076Spjd				cv_signal(&sync_cond);
1634204076Spjd			} else {
1635204076Spjd				pjdlog_debug(2,
1636204076Spjd				    "remote_recv: (%p) Moving request to the done queue.",
1637204076Spjd				    hio);
1638204076Spjd				QUEUE_INSERT2(hio, done);
1639204076Spjd			}
1640204076Spjd		}
1641204076Spjd	}
1642204076Spjd	/* NOTREACHED */
1643204076Spjd	return (NULL);
1644204076Spjd}
1645204076Spjd
1646204076Spjd/*
1647204076Spjd * Thread sends answer to the kernel.
1648204076Spjd */
1649204076Spjdstatic void *
1650204076Spjdggate_send_thread(void *arg)
1651204076Spjd{
1652204076Spjd	struct hast_resource *res = arg;
1653204076Spjd	struct g_gate_ctl_io *ggio;
1654204076Spjd	struct hio *hio;
1655204076Spjd	unsigned int ii, ncomp, ncomps;
1656204076Spjd
1657204076Spjd	ncomps = HAST_NCOMPONENTS;
1658204076Spjd
1659204076Spjd	for (;;) {
1660204076Spjd		pjdlog_debug(2, "ggate_send: Taking request.");
1661204076Spjd		QUEUE_TAKE2(hio, done);
1662204076Spjd		pjdlog_debug(2, "ggate_send: (%p) Got request.", hio);
1663204076Spjd		ggio = &hio->hio_ggio;
1664204076Spjd		for (ii = 0; ii < ncomps; ii++) {
1665204076Spjd			if (hio->hio_errors[ii] == 0) {
1666204076Spjd				/*
1667204076Spjd				 * One successful request is enough to declare
1668204076Spjd				 * success.
1669204076Spjd				 */
1670204076Spjd				ggio->gctl_error = 0;
1671204076Spjd				break;
1672204076Spjd			}
1673204076Spjd		}
1674204076Spjd		if (ii == ncomps) {
1675204076Spjd			/*
1676204076Spjd			 * None of the requests were successful.
1677219879Strociny			 * Use the error from local component except the
1678219879Strociny			 * case when we did only remote request.
1679204076Spjd			 */
1680219879Strociny			if (ggio->gctl_cmd == BIO_READ &&
1681219879Strociny			    res->hr_syncsrc == HAST_SYNCSRC_SECONDARY)
1682219879Strociny				ggio->gctl_error = hio->hio_errors[1];
1683219879Strociny			else
1684219879Strociny				ggio->gctl_error = hio->hio_errors[0];
1685204076Spjd		}
1686204076Spjd		if (ggio->gctl_error == 0 && ggio->gctl_cmd == BIO_WRITE) {
1687204076Spjd			mtx_lock(&res->hr_amp_lock);
1688204076Spjd			activemap_write_complete(res->hr_amp,
1689204076Spjd			    ggio->gctl_offset, ggio->gctl_length);
1690204076Spjd			mtx_unlock(&res->hr_amp_lock);
1691204076Spjd		}
1692204076Spjd		if (ggio->gctl_cmd == BIO_WRITE) {
1693204076Spjd			/*
1694204076Spjd			 * Unlock range we locked.
1695204076Spjd			 */
1696204076Spjd			mtx_lock(&range_lock);
1697204076Spjd			rangelock_del(range_regular, ggio->gctl_offset,
1698204076Spjd			    ggio->gctl_length);
1699204076Spjd			if (range_sync_wait)
1700204076Spjd				cv_signal(&range_sync_cond);
1701204076Spjd			mtx_unlock(&range_lock);
1702204076Spjd			/*
1703204076Spjd			 * Bump local count if this is first write after
1704204076Spjd			 * connection failure with remote node.
1705204076Spjd			 */
1706204076Spjd			ncomp = 1;
1707204076Spjd			rw_rlock(&hio_remote_lock[ncomp]);
1708204076Spjd			if (!ISCONNECTED(res, ncomp)) {
1709204076Spjd				mtx_lock(&metadata_lock);
1710204076Spjd				if (res->hr_primary_localcnt ==
1711204076Spjd				    res->hr_secondary_remotecnt) {
1712204076Spjd					res->hr_primary_localcnt++;
1713204076Spjd					pjdlog_debug(1,
1714204076Spjd					    "Increasing localcnt to %ju.",
1715204076Spjd					    (uintmax_t)res->hr_primary_localcnt);
1716204076Spjd					(void)metadata_write(res);
1717204076Spjd				}
1718204076Spjd				mtx_unlock(&metadata_lock);
1719204076Spjd			}
1720204076Spjd			rw_unlock(&hio_remote_lock[ncomp]);
1721204076Spjd		}
1722204076Spjd		if (ioctl(res->hr_ggatefd, G_GATE_CMD_DONE, ggio) < 0)
1723204076Spjd			primary_exit(EX_OSERR, "G_GATE_CMD_DONE failed");
1724204076Spjd		pjdlog_debug(2,
1725204076Spjd		    "ggate_send: (%p) Moving request to the free queue.", hio);
1726204076Spjd		QUEUE_INSERT2(hio, free);
1727204076Spjd	}
1728204076Spjd	/* NOTREACHED */
1729204076Spjd	return (NULL);
1730204076Spjd}
1731204076Spjd
1732204076Spjd/*
1733204076Spjd * Thread synchronize local and remote components.
1734204076Spjd */
1735204076Spjdstatic void *
1736204076Spjdsync_thread(void *arg __unused)
1737204076Spjd{
1738204076Spjd	struct hast_resource *res = arg;
1739204076Spjd	struct hio *hio;
1740204076Spjd	struct g_gate_ctl_io *ggio;
1741219372Spjd	struct timeval tstart, tend, tdiff;
1742204076Spjd	unsigned int ii, ncomp, ncomps;
1743204076Spjd	off_t offset, length, synced;
1744204076Spjd	bool dorewind;
1745204076Spjd	int syncext;
1746204076Spjd
1747204076Spjd	ncomps = HAST_NCOMPONENTS;
1748204076Spjd	dorewind = true;
1749211897Spjd	synced = 0;
1750211897Spjd	offset = -1;
1751204076Spjd
1752204076Spjd	for (;;) {
1753204076Spjd		mtx_lock(&sync_lock);
1754211897Spjd		if (offset >= 0 && !sync_inprogress) {
1755219372Spjd			gettimeofday(&tend, NULL);
1756219372Spjd			timersub(&tend, &tstart, &tdiff);
1757219372Spjd			pjdlog_info("Synchronization interrupted after %#.0T. "
1758219372Spjd			    "%NB synchronized so far.", &tdiff,
1759211879Spjd			    (intmax_t)synced);
1760212038Spjd			event_send(res, EVENT_SYNCINTR);
1761211879Spjd		}
1762204076Spjd		while (!sync_inprogress) {
1763204076Spjd			dorewind = true;
1764204076Spjd			synced = 0;
1765204076Spjd			cv_wait(&sync_cond, &sync_lock);
1766204076Spjd		}
1767204076Spjd		mtx_unlock(&sync_lock);
1768204076Spjd		/*
1769204076Spjd		 * Obtain offset at which we should synchronize.
1770204076Spjd		 * Rewind synchronization if needed.
1771204076Spjd		 */
1772204076Spjd		mtx_lock(&res->hr_amp_lock);
1773204076Spjd		if (dorewind)
1774204076Spjd			activemap_sync_rewind(res->hr_amp);
1775204076Spjd		offset = activemap_sync_offset(res->hr_amp, &length, &syncext);
1776204076Spjd		if (syncext != -1) {
1777204076Spjd			/*
1778204076Spjd			 * We synchronized entire syncext extent, we can mark
1779204076Spjd			 * it as clean now.
1780204076Spjd			 */
1781204076Spjd			if (activemap_extent_complete(res->hr_amp, syncext))
1782204076Spjd				(void)hast_activemap_flush(res);
1783204076Spjd		}
1784204076Spjd		mtx_unlock(&res->hr_amp_lock);
1785204076Spjd		if (dorewind) {
1786204076Spjd			dorewind = false;
1787204076Spjd			if (offset < 0)
1788204076Spjd				pjdlog_info("Nodes are in sync.");
1789204076Spjd			else {
1790219372Spjd				pjdlog_info("Synchronization started. %NB to go.",
1791219372Spjd				    (intmax_t)(res->hr_extentsize *
1792204076Spjd				    activemap_ndirty(res->hr_amp)));
1793212038Spjd				event_send(res, EVENT_SYNCSTART);
1794219372Spjd				gettimeofday(&tstart, NULL);
1795204076Spjd			}
1796204076Spjd		}
1797204076Spjd		if (offset < 0) {
1798211878Spjd			sync_stop();
1799204076Spjd			pjdlog_debug(1, "Nothing to synchronize.");
1800204076Spjd			/*
1801204076Spjd			 * Synchronization complete, make both localcnt and
1802204076Spjd			 * remotecnt equal.
1803204076Spjd			 */
1804204076Spjd			ncomp = 1;
1805204076Spjd			rw_rlock(&hio_remote_lock[ncomp]);
1806204076Spjd			if (ISCONNECTED(res, ncomp)) {
1807204076Spjd				if (synced > 0) {
1808219372Spjd					int64_t bps;
1809219372Spjd
1810219372Spjd					gettimeofday(&tend, NULL);
1811219372Spjd					timersub(&tend, &tstart, &tdiff);
1812219372Spjd					bps = (int64_t)((double)synced /
1813219372Spjd					    ((double)tdiff.tv_sec +
1814219372Spjd					    (double)tdiff.tv_usec / 1000000));
1815204076Spjd					pjdlog_info("Synchronization complete. "
1816219372Spjd					    "%NB synchronized in %#.0lT (%NB/sec).",
1817219372Spjd					    (intmax_t)synced, &tdiff,
1818219372Spjd					    (intmax_t)bps);
1819212038Spjd					event_send(res, EVENT_SYNCDONE);
1820204076Spjd				}
1821204076Spjd				mtx_lock(&metadata_lock);
1822204076Spjd				res->hr_syncsrc = HAST_SYNCSRC_UNDEF;
1823204076Spjd				res->hr_primary_localcnt =
1824219882Strociny				    res->hr_secondary_remotecnt;
1825219882Strociny				res->hr_primary_remotecnt =
1826204076Spjd				    res->hr_secondary_localcnt;
1827204076Spjd				pjdlog_debug(1,
1828204076Spjd				    "Setting localcnt to %ju and remotecnt to %ju.",
1829204076Spjd				    (uintmax_t)res->hr_primary_localcnt,
1830219882Strociny				    (uintmax_t)res->hr_primary_remotecnt);
1831204076Spjd				(void)metadata_write(res);
1832204076Spjd				mtx_unlock(&metadata_lock);
1833204076Spjd			}
1834204076Spjd			rw_unlock(&hio_remote_lock[ncomp]);
1835204076Spjd			continue;
1836204076Spjd		}
1837204076Spjd		pjdlog_debug(2, "sync: Taking free request.");
1838204076Spjd		QUEUE_TAKE2(hio, free);
1839204076Spjd		pjdlog_debug(2, "sync: (%p) Got free request.", hio);
1840204076Spjd		/*
1841204076Spjd		 * Lock the range we are going to synchronize. We don't want
1842204076Spjd		 * race where someone writes between our read and write.
1843204076Spjd		 */
1844204076Spjd		for (;;) {
1845204076Spjd			mtx_lock(&range_lock);
1846204076Spjd			if (rangelock_islocked(range_regular, offset, length)) {
1847204076Spjd				pjdlog_debug(2,
1848204076Spjd				    "sync: Range offset=%jd length=%jd locked.",
1849204076Spjd				    (intmax_t)offset, (intmax_t)length);
1850204076Spjd				range_sync_wait = true;
1851204076Spjd				cv_wait(&range_sync_cond, &range_lock);
1852204076Spjd				range_sync_wait = false;
1853204076Spjd				mtx_unlock(&range_lock);
1854204076Spjd				continue;
1855204076Spjd			}
1856204076Spjd			if (rangelock_add(range_sync, offset, length) < 0) {
1857204076Spjd				mtx_unlock(&range_lock);
1858204076Spjd				pjdlog_debug(2,
1859204076Spjd				    "sync: Range offset=%jd length=%jd is already locked, waiting.",
1860204076Spjd				    (intmax_t)offset, (intmax_t)length);
1861204076Spjd				sleep(1);
1862204076Spjd				continue;
1863204076Spjd			}
1864204076Spjd			mtx_unlock(&range_lock);
1865204076Spjd			break;
1866204076Spjd		}
1867204076Spjd		/*
1868204076Spjd		 * First read the data from synchronization source.
1869204076Spjd		 */
1870204076Spjd		SYNCREQ(hio);
1871204076Spjd		ggio = &hio->hio_ggio;
1872204076Spjd		ggio->gctl_cmd = BIO_READ;
1873204076Spjd		ggio->gctl_offset = offset;
1874204076Spjd		ggio->gctl_length = length;
1875204076Spjd		ggio->gctl_error = 0;
1876204076Spjd		for (ii = 0; ii < ncomps; ii++)
1877204076Spjd			hio->hio_errors[ii] = EINVAL;
1878204076Spjd		reqlog(LOG_DEBUG, 2, ggio, "sync: (%p) Sending sync request: ",
1879204076Spjd		    hio);
1880204076Spjd		pjdlog_debug(2, "sync: (%p) Moving request to the send queue.",
1881204076Spjd		    hio);
1882204076Spjd		mtx_lock(&metadata_lock);
1883204076Spjd		if (res->hr_syncsrc == HAST_SYNCSRC_PRIMARY) {
1884204076Spjd			/*
1885204076Spjd			 * This range is up-to-date on local component,
1886204076Spjd			 * so handle request locally.
1887204076Spjd			 */
1888204076Spjd			 /* Local component is 0 for now. */
1889204076Spjd			ncomp = 0;
1890204076Spjd		} else /* if (res->hr_syncsrc == HAST_SYNCSRC_SECONDARY) */ {
1891218138Spjd			PJDLOG_ASSERT(res->hr_syncsrc == HAST_SYNCSRC_SECONDARY);
1892204076Spjd			/*
1893204076Spjd			 * This range is out-of-date on local component,
1894204076Spjd			 * so send request to the remote node.
1895204076Spjd			 */
1896204076Spjd			 /* Remote component is 1 for now. */
1897204076Spjd			ncomp = 1;
1898204076Spjd		}
1899204076Spjd		mtx_unlock(&metadata_lock);
1900204076Spjd		refcount_init(&hio->hio_countdown, 1);
1901204076Spjd		QUEUE_INSERT1(hio, send, ncomp);
1902204076Spjd
1903204076Spjd		/*
1904204076Spjd		 * Let's wait for READ to finish.
1905204076Spjd		 */
1906204076Spjd		mtx_lock(&sync_lock);
1907204076Spjd		while (!ISSYNCREQDONE(hio))
1908204076Spjd			cv_wait(&sync_cond, &sync_lock);
1909204076Spjd		mtx_unlock(&sync_lock);
1910204076Spjd
1911204076Spjd		if (hio->hio_errors[ncomp] != 0) {
1912204076Spjd			pjdlog_error("Unable to read synchronization data: %s.",
1913204076Spjd			    strerror(hio->hio_errors[ncomp]));
1914204076Spjd			goto free_queue;
1915204076Spjd		}
1916204076Spjd
1917204076Spjd		/*
1918204076Spjd		 * We read the data from synchronization source, now write it
1919204076Spjd		 * to synchronization target.
1920204076Spjd		 */
1921204076Spjd		SYNCREQ(hio);
1922204076Spjd		ggio->gctl_cmd = BIO_WRITE;
1923204076Spjd		for (ii = 0; ii < ncomps; ii++)
1924204076Spjd			hio->hio_errors[ii] = EINVAL;
1925204076Spjd		reqlog(LOG_DEBUG, 2, ggio, "sync: (%p) Sending sync request: ",
1926204076Spjd		    hio);
1927204076Spjd		pjdlog_debug(2, "sync: (%p) Moving request to the send queue.",
1928204076Spjd		    hio);
1929204076Spjd		mtx_lock(&metadata_lock);
1930204076Spjd		if (res->hr_syncsrc == HAST_SYNCSRC_PRIMARY) {
1931204076Spjd			/*
1932204076Spjd			 * This range is up-to-date on local component,
1933204076Spjd			 * so we update remote component.
1934204076Spjd			 */
1935204076Spjd			 /* Remote component is 1 for now. */
1936204076Spjd			ncomp = 1;
1937204076Spjd		} else /* if (res->hr_syncsrc == HAST_SYNCSRC_SECONDARY) */ {
1938218138Spjd			PJDLOG_ASSERT(res->hr_syncsrc == HAST_SYNCSRC_SECONDARY);
1939204076Spjd			/*
1940204076Spjd			 * This range is out-of-date on local component,
1941204076Spjd			 * so we update it.
1942204076Spjd			 */
1943204076Spjd			 /* Local component is 0 for now. */
1944204076Spjd			ncomp = 0;
1945204076Spjd		}
1946204076Spjd		mtx_unlock(&metadata_lock);
1947204076Spjd
1948204076Spjd		pjdlog_debug(2, "sync: (%p) Moving request to the send queues.",
1949204076Spjd		    hio);
1950204076Spjd		refcount_init(&hio->hio_countdown, 1);
1951204076Spjd		QUEUE_INSERT1(hio, send, ncomp);
1952204076Spjd
1953204076Spjd		/*
1954204076Spjd		 * Let's wait for WRITE to finish.
1955204076Spjd		 */
1956204076Spjd		mtx_lock(&sync_lock);
1957204076Spjd		while (!ISSYNCREQDONE(hio))
1958204076Spjd			cv_wait(&sync_cond, &sync_lock);
1959204076Spjd		mtx_unlock(&sync_lock);
1960204076Spjd
1961204076Spjd		if (hio->hio_errors[ncomp] != 0) {
1962204076Spjd			pjdlog_error("Unable to write synchronization data: %s.",
1963204076Spjd			    strerror(hio->hio_errors[ncomp]));
1964204076Spjd			goto free_queue;
1965204076Spjd		}
1966211880Spjd
1967211880Spjd		synced += length;
1968204076Spjdfree_queue:
1969204076Spjd		mtx_lock(&range_lock);
1970204076Spjd		rangelock_del(range_sync, offset, length);
1971204076Spjd		if (range_regular_wait)
1972204076Spjd			cv_signal(&range_regular_cond);
1973204076Spjd		mtx_unlock(&range_lock);
1974204076Spjd		pjdlog_debug(2, "sync: (%p) Moving request to the free queue.",
1975204076Spjd		    hio);
1976204076Spjd		QUEUE_INSERT2(hio, free);
1977204076Spjd	}
1978204076Spjd	/* NOTREACHED */
1979204076Spjd	return (NULL);
1980204076Spjd}
1981204076Spjd
1982217784Spjdvoid
1983217784Spjdprimary_config_reload(struct hast_resource *res, struct nv *nv)
1984210886Spjd{
1985210886Spjd	unsigned int ii, ncomps;
1986217784Spjd	int modified, vint;
1987217784Spjd	const char *vstr;
1988210886Spjd
1989210886Spjd	pjdlog_info("Reloading configuration...");
1990210886Spjd
1991218138Spjd	PJDLOG_ASSERT(res->hr_role == HAST_ROLE_PRIMARY);
1992218138Spjd	PJDLOG_ASSERT(gres == res);
1993217784Spjd	nv_assert(nv, "remoteaddr");
1994219818Spjd	nv_assert(nv, "sourceaddr");
1995217784Spjd	nv_assert(nv, "replication");
1996219351Spjd	nv_assert(nv, "checksum");
1997219354Spjd	nv_assert(nv, "compression");
1998217784Spjd	nv_assert(nv, "timeout");
1999217784Spjd	nv_assert(nv, "exec");
2000217784Spjd
2001210886Spjd	ncomps = HAST_NCOMPONENTS;
2002210886Spjd
2003219351Spjd#define MODIFIED_REMOTEADDR	0x01
2004219818Spjd#define MODIFIED_SOURCEADDR	0x02
2005219818Spjd#define MODIFIED_REPLICATION	0x04
2006219818Spjd#define MODIFIED_CHECKSUM	0x08
2007219818Spjd#define MODIFIED_COMPRESSION	0x10
2008219818Spjd#define MODIFIED_TIMEOUT	0x20
2009219818Spjd#define MODIFIED_EXEC		0x40
2010210886Spjd	modified = 0;
2011217784Spjd
2012217784Spjd	vstr = nv_get_string(nv, "remoteaddr");
2013217784Spjd	if (strcmp(gres->hr_remoteaddr, vstr) != 0) {
2014210886Spjd		/*
2015210886Spjd		 * Don't copy res->hr_remoteaddr to gres just yet.
2016210886Spjd		 * We want remote_close() to log disconnect from the old
2017210886Spjd		 * addresses, not from the new ones.
2018210886Spjd		 */
2019210886Spjd		modified |= MODIFIED_REMOTEADDR;
2020210886Spjd	}
2021219818Spjd	vstr = nv_get_string(nv, "sourceaddr");
2022219818Spjd	if (strcmp(gres->hr_sourceaddr, vstr) != 0) {
2023219818Spjd		strlcpy(gres->hr_sourceaddr, vstr, sizeof(gres->hr_sourceaddr));
2024219818Spjd		modified |= MODIFIED_SOURCEADDR;
2025219818Spjd	}
2026217784Spjd	vint = nv_get_int32(nv, "replication");
2027217784Spjd	if (gres->hr_replication != vint) {
2028217784Spjd		gres->hr_replication = vint;
2029210886Spjd		modified |= MODIFIED_REPLICATION;
2030210886Spjd	}
2031219351Spjd	vint = nv_get_int32(nv, "checksum");
2032219351Spjd	if (gres->hr_checksum != vint) {
2033219351Spjd		gres->hr_checksum = vint;
2034219351Spjd		modified |= MODIFIED_CHECKSUM;
2035219351Spjd	}
2036219354Spjd	vint = nv_get_int32(nv, "compression");
2037219354Spjd	if (gres->hr_compression != vint) {
2038219354Spjd		gres->hr_compression = vint;
2039219354Spjd		modified |= MODIFIED_COMPRESSION;
2040219354Spjd	}
2041217784Spjd	vint = nv_get_int32(nv, "timeout");
2042217784Spjd	if (gres->hr_timeout != vint) {
2043217784Spjd		gres->hr_timeout = vint;
2044210886Spjd		modified |= MODIFIED_TIMEOUT;
2045210886Spjd	}
2046217784Spjd	vstr = nv_get_string(nv, "exec");
2047217784Spjd	if (strcmp(gres->hr_exec, vstr) != 0) {
2048217784Spjd		strlcpy(gres->hr_exec, vstr, sizeof(gres->hr_exec));
2049211886Spjd		modified |= MODIFIED_EXEC;
2050211886Spjd	}
2051217784Spjd
2052210886Spjd	/*
2053219351Spjd	 * Change timeout for connected sockets.
2054219351Spjd	 * Don't bother if we need to reconnect.
2055210886Spjd	 */
2056219351Spjd	if ((modified & MODIFIED_TIMEOUT) != 0 &&
2057219818Spjd	    (modified & (MODIFIED_REMOTEADDR | MODIFIED_SOURCEADDR |
2058219818Spjd	    MODIFIED_REPLICATION)) == 0) {
2059210886Spjd		for (ii = 0; ii < ncomps; ii++) {
2060210886Spjd			if (!ISREMOTE(ii))
2061210886Spjd				continue;
2062210886Spjd			rw_rlock(&hio_remote_lock[ii]);
2063210886Spjd			if (!ISCONNECTED(gres, ii)) {
2064210886Spjd				rw_unlock(&hio_remote_lock[ii]);
2065210886Spjd				continue;
2066210886Spjd			}
2067210886Spjd			rw_unlock(&hio_remote_lock[ii]);
2068210886Spjd			if (proto_timeout(gres->hr_remotein,
2069210886Spjd			    gres->hr_timeout) < 0) {
2070210886Spjd				pjdlog_errno(LOG_WARNING,
2071210886Spjd				    "Unable to set connection timeout");
2072210886Spjd			}
2073210886Spjd			if (proto_timeout(gres->hr_remoteout,
2074210886Spjd			    gres->hr_timeout) < 0) {
2075210886Spjd				pjdlog_errno(LOG_WARNING,
2076210886Spjd				    "Unable to set connection timeout");
2077210886Spjd			}
2078210886Spjd		}
2079219351Spjd	}
2080219818Spjd	if ((modified & (MODIFIED_REMOTEADDR | MODIFIED_SOURCEADDR |
2081219818Spjd	    MODIFIED_REPLICATION)) != 0) {
2082210886Spjd		for (ii = 0; ii < ncomps; ii++) {
2083210886Spjd			if (!ISREMOTE(ii))
2084210886Spjd				continue;
2085210886Spjd			remote_close(gres, ii);
2086210886Spjd		}
2087210886Spjd		if (modified & MODIFIED_REMOTEADDR) {
2088217784Spjd			vstr = nv_get_string(nv, "remoteaddr");
2089217784Spjd			strlcpy(gres->hr_remoteaddr, vstr,
2090210886Spjd			    sizeof(gres->hr_remoteaddr));
2091210886Spjd		}
2092210886Spjd	}
2093210886Spjd#undef	MODIFIED_REMOTEADDR
2094219818Spjd#undef	MODIFIED_SOURCEADDR
2095210886Spjd#undef	MODIFIED_REPLICATION
2096219351Spjd#undef	MODIFIED_CHECKSUM
2097219354Spjd#undef	MODIFIED_COMPRESSION
2098210886Spjd#undef	MODIFIED_TIMEOUT
2099211886Spjd#undef	MODIFIED_EXEC
2100210886Spjd
2101210886Spjd	pjdlog_info("Configuration reloaded successfully.");
2102210886Spjd}
2103210886Spjd
2104211882Spjdstatic void
2105211981Spjdguard_one(struct hast_resource *res, unsigned int ncomp)
2106211981Spjd{
2107211981Spjd	struct proto_conn *in, *out;
2108211981Spjd
2109211981Spjd	if (!ISREMOTE(ncomp))
2110211981Spjd		return;
2111211981Spjd
2112211981Spjd	rw_rlock(&hio_remote_lock[ncomp]);
2113211981Spjd
2114211981Spjd	if (!real_remote(res)) {
2115211981Spjd		rw_unlock(&hio_remote_lock[ncomp]);
2116211981Spjd		return;
2117211981Spjd	}
2118211981Spjd
2119211981Spjd	if (ISCONNECTED(res, ncomp)) {
2120218138Spjd		PJDLOG_ASSERT(res->hr_remotein != NULL);
2121218138Spjd		PJDLOG_ASSERT(res->hr_remoteout != NULL);
2122211981Spjd		rw_unlock(&hio_remote_lock[ncomp]);
2123211981Spjd		pjdlog_debug(2, "remote_guard: Connection to %s is ok.",
2124211981Spjd		    res->hr_remoteaddr);
2125211981Spjd		return;
2126211981Spjd	}
2127211981Spjd
2128218138Spjd	PJDLOG_ASSERT(res->hr_remotein == NULL);
2129218138Spjd	PJDLOG_ASSERT(res->hr_remoteout == NULL);
2130211981Spjd	/*
2131211981Spjd	 * Upgrade the lock. It doesn't have to be atomic as no other thread
2132211981Spjd	 * can change connection status from disconnected to connected.
2133211981Spjd	 */
2134211981Spjd	rw_unlock(&hio_remote_lock[ncomp]);
2135211981Spjd	pjdlog_debug(2, "remote_guard: Reconnecting to %s.",
2136211981Spjd	    res->hr_remoteaddr);
2137211981Spjd	in = out = NULL;
2138220898Spjd	if (init_remote(res, &in, &out) == 0) {
2139211981Spjd		rw_wlock(&hio_remote_lock[ncomp]);
2140218138Spjd		PJDLOG_ASSERT(res->hr_remotein == NULL);
2141218138Spjd		PJDLOG_ASSERT(res->hr_remoteout == NULL);
2142218138Spjd		PJDLOG_ASSERT(in != NULL && out != NULL);
2143211981Spjd		res->hr_remotein = in;
2144211981Spjd		res->hr_remoteout = out;
2145211981Spjd		rw_unlock(&hio_remote_lock[ncomp]);
2146211981Spjd		pjdlog_info("Successfully reconnected to %s.",
2147211981Spjd		    res->hr_remoteaddr);
2148211981Spjd		sync_start();
2149211981Spjd	} else {
2150211981Spjd		/* Both connections should be NULL. */
2151218138Spjd		PJDLOG_ASSERT(res->hr_remotein == NULL);
2152218138Spjd		PJDLOG_ASSERT(res->hr_remoteout == NULL);
2153218138Spjd		PJDLOG_ASSERT(in == NULL && out == NULL);
2154211981Spjd		pjdlog_debug(2, "remote_guard: Reconnect to %s failed.",
2155211981Spjd		    res->hr_remoteaddr);
2156211981Spjd	}
2157211981Spjd}
2158211981Spjd
2159204076Spjd/*
2160204076Spjd * Thread guards remote connections and reconnects when needed, handles
2161204076Spjd * signals, etc.
2162204076Spjd */
2163204076Spjdstatic void *
2164204076Spjdguard_thread(void *arg)
2165204076Spjd{
2166204076Spjd	struct hast_resource *res = arg;
2167204076Spjd	unsigned int ii, ncomps;
2168211982Spjd	struct timespec timeout;
2169211981Spjd	time_t lastcheck, now;
2170211982Spjd	sigset_t mask;
2171211982Spjd	int signo;
2172204076Spjd
2173204076Spjd	ncomps = HAST_NCOMPONENTS;
2174211981Spjd	lastcheck = time(NULL);
2175204076Spjd
2176211982Spjd	PJDLOG_VERIFY(sigemptyset(&mask) == 0);
2177211982Spjd	PJDLOG_VERIFY(sigaddset(&mask, SIGINT) == 0);
2178211982Spjd	PJDLOG_VERIFY(sigaddset(&mask, SIGTERM) == 0);
2179211982Spjd
2180219721Strociny	timeout.tv_sec = HAST_KEEPALIVE;
2181211982Spjd	timeout.tv_nsec = 0;
2182211982Spjd	signo = -1;
2183211982Spjd
2184204076Spjd	for (;;) {
2185211982Spjd		switch (signo) {
2186211982Spjd		case SIGINT:
2187211982Spjd		case SIGTERM:
2188211982Spjd			sigexit_received = true;
2189204076Spjd			primary_exitx(EX_OK,
2190204076Spjd			    "Termination signal received, exiting.");
2191211982Spjd			break;
2192211982Spjd		default:
2193211982Spjd			break;
2194204076Spjd		}
2195211882Spjd
2196220898Spjd		/*
2197220898Spjd		 * Don't check connections until we fully started,
2198220898Spjd		 * as we may still be looping, waiting for remote node
2199220898Spjd		 * to switch from primary to secondary.
2200220898Spjd		 */
2201220898Spjd		if (fullystarted) {
2202220898Spjd			pjdlog_debug(2, "remote_guard: Checking connections.");
2203220898Spjd			now = time(NULL);
2204220898Spjd			if (lastcheck + HAST_KEEPALIVE <= now) {
2205220898Spjd				for (ii = 0; ii < ncomps; ii++)
2206220898Spjd					guard_one(res, ii);
2207220898Spjd				lastcheck = now;
2208220898Spjd			}
2209204076Spjd		}
2210211982Spjd		signo = sigtimedwait(&mask, NULL, &timeout);
2211204076Spjd	}
2212204076Spjd	/* NOTREACHED */
2213204076Spjd	return (NULL);
2214204076Spjd}
2215