primary.c revision 204076
1204076Spjd/*-
2204076Spjd * Copyright (c) 2009 The FreeBSD Foundation
3204076Spjd * All rights reserved.
4204076Spjd *
5204076Spjd * This software was developed by Pawel Jakub Dawidek under sponsorship from
6204076Spjd * the FreeBSD Foundation.
7204076Spjd *
8204076Spjd * Redistribution and use in source and binary forms, with or without
9204076Spjd * modification, are permitted provided that the following conditions
10204076Spjd * are met:
11204076Spjd * 1. Redistributions of source code must retain the above copyright
12204076Spjd *    notice, this list of conditions and the following disclaimer.
13204076Spjd * 2. Redistributions in binary form must reproduce the above copyright
14204076Spjd *    notice, this list of conditions and the following disclaimer in the
15204076Spjd *    documentation and/or other materials provided with the distribution.
16204076Spjd *
17204076Spjd * THIS SOFTWARE IS PROVIDED BY THE AUTHORS AND CONTRIBUTORS ``AS IS'' AND
18204076Spjd * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19204076Spjd * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20204076Spjd * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE
21204076Spjd * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22204076Spjd * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23204076Spjd * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24204076Spjd * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25204076Spjd * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26204076Spjd * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27204076Spjd * SUCH DAMAGE.
28204076Spjd */
29204076Spjd
30204076Spjd#include <sys/cdefs.h>
31204076Spjd__FBSDID("$FreeBSD: head/sbin/hastd/primary.c 204076 2010-02-18 23:16:19Z pjd $");
32204076Spjd
33204076Spjd#include <sys/types.h>
34204076Spjd#include <sys/time.h>
35204076Spjd#include <sys/bio.h>
36204076Spjd#include <sys/disk.h>
37204076Spjd#include <sys/refcount.h>
38204076Spjd#include <sys/stat.h>
39204076Spjd
40204076Spjd#include <geom/gate/g_gate.h>
41204076Spjd
42204076Spjd#include <assert.h>
43204076Spjd#include <err.h>
44204076Spjd#include <errno.h>
45204076Spjd#include <fcntl.h>
46204076Spjd#include <libgeom.h>
47204076Spjd#include <pthread.h>
48204076Spjd#include <stdint.h>
49204076Spjd#include <stdio.h>
50204076Spjd#include <string.h>
51204076Spjd#include <sysexits.h>
52204076Spjd#include <unistd.h>
53204076Spjd
54204076Spjd#include <activemap.h>
55204076Spjd#include <nv.h>
56204076Spjd#include <rangelock.h>
57204076Spjd
58204076Spjd#include "control.h"
59204076Spjd#include "hast.h"
60204076Spjd#include "hast_proto.h"
61204076Spjd#include "hastd.h"
62204076Spjd#include "metadata.h"
63204076Spjd#include "proto.h"
64204076Spjd#include "pjdlog.h"
65204076Spjd#include "subr.h"
66204076Spjd#include "synch.h"
67204076Spjd
68204076Spjdstruct hio {
69204076Spjd	/*
70204076Spjd	 * Number of components we are still waiting for.
71204076Spjd	 * When this field goes to 0, we can send the request back to the
72204076Spjd	 * kernel. Each component has to decrease this counter by one
73204076Spjd	 * even on failure.
74204076Spjd	 */
75204076Spjd	unsigned int		 hio_countdown;
76204076Spjd	/*
77204076Spjd	 * Each component has a place to store its own error.
78204076Spjd	 * Once the request is handled by all components we can decide if the
79204076Spjd	 * request overall is successful or not.
80204076Spjd	 */
81204076Spjd	int			*hio_errors;
82204076Spjd	/*
83204076Spjd	 * Structure used to comunicate with GEOM Gate class.
84204076Spjd	 */
85204076Spjd	struct g_gate_ctl_io	 hio_ggio;
86204076Spjd	TAILQ_ENTRY(hio)	*hio_next;
87204076Spjd};
88204076Spjd#define	hio_free_next	hio_next[0]
89204076Spjd#define	hio_done_next	hio_next[0]
90204076Spjd
91204076Spjd/*
92204076Spjd * Free list holds unused structures. When free list is empty, we have to wait
93204076Spjd * until some in-progress requests are freed.
94204076Spjd */
95204076Spjdstatic TAILQ_HEAD(, hio) hio_free_list;
96204076Spjdstatic pthread_mutex_t hio_free_list_lock;
97204076Spjdstatic pthread_cond_t hio_free_list_cond;
98204076Spjd/*
99204076Spjd * There is one send list for every component. One requests is placed on all
100204076Spjd * send lists - each component gets the same request, but each component is
101204076Spjd * responsible for managing his own send list.
102204076Spjd */
103204076Spjdstatic TAILQ_HEAD(, hio) *hio_send_list;
104204076Spjdstatic pthread_mutex_t *hio_send_list_lock;
105204076Spjdstatic pthread_cond_t *hio_send_list_cond;
106204076Spjd/*
107204076Spjd * There is one recv list for every component, although local components don't
108204076Spjd * use recv lists as local requests are done synchronously.
109204076Spjd */
110204076Spjdstatic TAILQ_HEAD(, hio) *hio_recv_list;
111204076Spjdstatic pthread_mutex_t *hio_recv_list_lock;
112204076Spjdstatic pthread_cond_t *hio_recv_list_cond;
113204076Spjd/*
114204076Spjd * Request is placed on done list by the slowest component (the one that
115204076Spjd * decreased hio_countdown from 1 to 0).
116204076Spjd */
117204076Spjdstatic TAILQ_HEAD(, hio) hio_done_list;
118204076Spjdstatic pthread_mutex_t hio_done_list_lock;
119204076Spjdstatic pthread_cond_t hio_done_list_cond;
120204076Spjd/*
121204076Spjd * Structure below are for interaction with sync thread.
122204076Spjd */
123204076Spjdstatic bool sync_inprogress;
124204076Spjdstatic pthread_mutex_t sync_lock;
125204076Spjdstatic pthread_cond_t sync_cond;
126204076Spjd/*
127204076Spjd * The lock below allows to synchornize access to remote connections.
128204076Spjd */
129204076Spjdstatic pthread_rwlock_t *hio_remote_lock;
130204076Spjdstatic pthread_mutex_t hio_guard_lock;
131204076Spjdstatic pthread_cond_t hio_guard_cond;
132204076Spjd
133204076Spjd/*
134204076Spjd * Lock to synchronize metadata updates. Also synchronize access to
135204076Spjd * hr_primary_localcnt and hr_primary_remotecnt fields.
136204076Spjd */
137204076Spjdstatic pthread_mutex_t metadata_lock;
138204076Spjd
139204076Spjd/*
140204076Spjd * Maximum number of outstanding I/O requests.
141204076Spjd */
142204076Spjd#define	HAST_HIO_MAX	256
143204076Spjd/*
144204076Spjd * Number of components. At this point there are only two components: local
145204076Spjd * and remote, but in the future it might be possible to use multiple local
146204076Spjd * and remote components.
147204076Spjd */
148204076Spjd#define	HAST_NCOMPONENTS	2
149204076Spjd/*
150204076Spjd * Number of seconds to sleep before next reconnect try.
151204076Spjd */
152204076Spjd#define	RECONNECT_SLEEP		5
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)
178204076Spjd#define	QUEUE_TAKE1(hio, name, ncomp)	do {				\
179204076Spjd	mtx_lock(&hio_##name##_list_lock[(ncomp)]);			\
180204076Spjd	while (((hio) = TAILQ_FIRST(&hio_##name##_list[(ncomp)])) == NULL) { \
181204076Spjd		cv_wait(&hio_##name##_list_cond[(ncomp)],		\
182204076Spjd		    &hio_##name##_list_lock[(ncomp)]);			\
183204076Spjd	}								\
184204076Spjd	TAILQ_REMOVE(&hio_##name##_list[(ncomp)], (hio),		\
185204076Spjd	    hio_next[(ncomp)]);						\
186204076Spjd	mtx_unlock(&hio_##name##_list_lock[(ncomp)]);			\
187204076Spjd} while (0)
188204076Spjd#define	QUEUE_TAKE2(hio, name)	do {					\
189204076Spjd	mtx_lock(&hio_##name##_list_lock);				\
190204076Spjd	while (((hio) = TAILQ_FIRST(&hio_##name##_list)) == NULL) {	\
191204076Spjd		cv_wait(&hio_##name##_list_cond,			\
192204076Spjd		    &hio_##name##_list_lock);				\
193204076Spjd	}								\
194204076Spjd	TAILQ_REMOVE(&hio_##name##_list, (hio), hio_##name##_next);	\
195204076Spjd	mtx_unlock(&hio_##name##_list_lock);				\
196204076Spjd} while (0)
197204076Spjd
198204076Spjd#define	SYNCREQ(hio)		do { (hio)->hio_ggio.gctl_unit = -1; } while (0)
199204076Spjd#define	ISSYNCREQ(hio)		((hio)->hio_ggio.gctl_unit == -1)
200204076Spjd#define	SYNCREQDONE(hio)	do { (hio)->hio_ggio.gctl_unit = -2; } while (0)
201204076Spjd#define	ISSYNCREQDONE(hio)	((hio)->hio_ggio.gctl_unit == -2)
202204076Spjd
203204076Spjdstatic struct hast_resource *gres;
204204076Spjd
205204076Spjdstatic pthread_mutex_t range_lock;
206204076Spjdstatic struct rangelocks *range_regular;
207204076Spjdstatic bool range_regular_wait;
208204076Spjdstatic pthread_cond_t range_regular_cond;
209204076Spjdstatic struct rangelocks *range_sync;
210204076Spjdstatic bool range_sync_wait;
211204076Spjdstatic pthread_cond_t range_sync_cond;
212204076Spjd
213204076Spjdstatic void *ggate_recv_thread(void *arg);
214204076Spjdstatic void *local_send_thread(void *arg);
215204076Spjdstatic void *remote_send_thread(void *arg);
216204076Spjdstatic void *remote_recv_thread(void *arg);
217204076Spjdstatic void *ggate_send_thread(void *arg);
218204076Spjdstatic void *sync_thread(void *arg);
219204076Spjdstatic void *guard_thread(void *arg);
220204076Spjd
221204076Spjdstatic void sighandler(int sig);
222204076Spjd
223204076Spjdstatic void
224204076Spjdcleanup(struct hast_resource *res)
225204076Spjd{
226204076Spjd	int rerrno;
227204076Spjd
228204076Spjd	/* Remember errno. */
229204076Spjd	rerrno = errno;
230204076Spjd
231204076Spjd	/*
232204076Spjd	 * Close descriptor to /dev/hast/<name>
233204076Spjd	 * to work-around race in the kernel.
234204076Spjd	 */
235204076Spjd	close(res->hr_localfd);
236204076Spjd
237204076Spjd	/* Destroy ggate provider if we created one. */
238204076Spjd	if (res->hr_ggateunit >= 0) {
239204076Spjd		struct g_gate_ctl_destroy ggiod;
240204076Spjd
241204076Spjd		ggiod.gctl_version = G_GATE_VERSION;
242204076Spjd		ggiod.gctl_unit = res->hr_ggateunit;
243204076Spjd		ggiod.gctl_force = 1;
244204076Spjd		if (ioctl(res->hr_ggatefd, G_GATE_CMD_DESTROY, &ggiod) < 0) {
245204076Spjd			pjdlog_warning("Unable to destroy hast/%s device",
246204076Spjd			    res->hr_provname);
247204076Spjd		}
248204076Spjd		res->hr_ggateunit = -1;
249204076Spjd	}
250204076Spjd
251204076Spjd	/* Restore errno. */
252204076Spjd	errno = rerrno;
253204076Spjd}
254204076Spjd
255204076Spjdstatic void
256204076Spjdprimary_exit(int exitcode, const char *fmt, ...)
257204076Spjd{
258204076Spjd	va_list ap;
259204076Spjd
260204076Spjd	assert(exitcode != EX_OK);
261204076Spjd	va_start(ap, fmt);
262204076Spjd	pjdlogv_errno(LOG_ERR, fmt, ap);
263204076Spjd	va_end(ap);
264204076Spjd	cleanup(gres);
265204076Spjd	exit(exitcode);
266204076Spjd}
267204076Spjd
268204076Spjdstatic void
269204076Spjdprimary_exitx(int exitcode, const char *fmt, ...)
270204076Spjd{
271204076Spjd	va_list ap;
272204076Spjd
273204076Spjd	va_start(ap, fmt);
274204076Spjd	pjdlogv(exitcode == EX_OK ? LOG_INFO : LOG_ERR, fmt, ap);
275204076Spjd	va_end(ap);
276204076Spjd	cleanup(gres);
277204076Spjd	exit(exitcode);
278204076Spjd}
279204076Spjd
280204076Spjdstatic int
281204076Spjdhast_activemap_flush(struct hast_resource *res)
282204076Spjd{
283204076Spjd	const unsigned char *buf;
284204076Spjd	size_t size;
285204076Spjd
286204076Spjd	buf = activemap_bitmap(res->hr_amp, &size);
287204076Spjd	assert(buf != NULL);
288204076Spjd	assert((size % res->hr_local_sectorsize) == 0);
289204076Spjd	if (pwrite(res->hr_localfd, buf, size, METADATA_SIZE) !=
290204076Spjd	    (ssize_t)size) {
291204076Spjd		KEEP_ERRNO(pjdlog_errno(LOG_ERR,
292204076Spjd		    "Unable to flush activemap to disk"));
293204076Spjd		return (-1);
294204076Spjd	}
295204076Spjd	return (0);
296204076Spjd}
297204076Spjd
298204076Spjdstatic void
299204076Spjdinit_environment(struct hast_resource *res __unused)
300204076Spjd{
301204076Spjd	struct hio *hio;
302204076Spjd	unsigned int ii, ncomps;
303204076Spjd
304204076Spjd	/*
305204076Spjd	 * In the future it might be per-resource value.
306204076Spjd	 */
307204076Spjd	ncomps = HAST_NCOMPONENTS;
308204076Spjd
309204076Spjd	/*
310204076Spjd	 * Allocate memory needed by lists.
311204076Spjd	 */
312204076Spjd	hio_send_list = malloc(sizeof(hio_send_list[0]) * ncomps);
313204076Spjd	if (hio_send_list == NULL) {
314204076Spjd		primary_exitx(EX_TEMPFAIL,
315204076Spjd		    "Unable to allocate %zu bytes of memory for send lists.",
316204076Spjd		    sizeof(hio_send_list[0]) * ncomps);
317204076Spjd	}
318204076Spjd	hio_send_list_lock = malloc(sizeof(hio_send_list_lock[0]) * ncomps);
319204076Spjd	if (hio_send_list_lock == NULL) {
320204076Spjd		primary_exitx(EX_TEMPFAIL,
321204076Spjd		    "Unable to allocate %zu bytes of memory for send list locks.",
322204076Spjd		    sizeof(hio_send_list_lock[0]) * ncomps);
323204076Spjd	}
324204076Spjd	hio_send_list_cond = malloc(sizeof(hio_send_list_cond[0]) * ncomps);
325204076Spjd	if (hio_send_list_cond == NULL) {
326204076Spjd		primary_exitx(EX_TEMPFAIL,
327204076Spjd		    "Unable to allocate %zu bytes of memory for send list condition variables.",
328204076Spjd		    sizeof(hio_send_list_cond[0]) * ncomps);
329204076Spjd	}
330204076Spjd	hio_recv_list = malloc(sizeof(hio_recv_list[0]) * ncomps);
331204076Spjd	if (hio_recv_list == NULL) {
332204076Spjd		primary_exitx(EX_TEMPFAIL,
333204076Spjd		    "Unable to allocate %zu bytes of memory for recv lists.",
334204076Spjd		    sizeof(hio_recv_list[0]) * ncomps);
335204076Spjd	}
336204076Spjd	hio_recv_list_lock = malloc(sizeof(hio_recv_list_lock[0]) * ncomps);
337204076Spjd	if (hio_recv_list_lock == NULL) {
338204076Spjd		primary_exitx(EX_TEMPFAIL,
339204076Spjd		    "Unable to allocate %zu bytes of memory for recv list locks.",
340204076Spjd		    sizeof(hio_recv_list_lock[0]) * ncomps);
341204076Spjd	}
342204076Spjd	hio_recv_list_cond = malloc(sizeof(hio_recv_list_cond[0]) * ncomps);
343204076Spjd	if (hio_recv_list_cond == NULL) {
344204076Spjd		primary_exitx(EX_TEMPFAIL,
345204076Spjd		    "Unable to allocate %zu bytes of memory for recv list condition variables.",
346204076Spjd		    sizeof(hio_recv_list_cond[0]) * ncomps);
347204076Spjd	}
348204076Spjd	hio_remote_lock = malloc(sizeof(hio_remote_lock[0]) * ncomps);
349204076Spjd	if (hio_remote_lock == NULL) {
350204076Spjd		primary_exitx(EX_TEMPFAIL,
351204076Spjd		    "Unable to allocate %zu bytes of memory for remote connections locks.",
352204076Spjd		    sizeof(hio_remote_lock[0]) * ncomps);
353204076Spjd	}
354204076Spjd
355204076Spjd	/*
356204076Spjd	 * Initialize lists, their locks and theirs condition variables.
357204076Spjd	 */
358204076Spjd	TAILQ_INIT(&hio_free_list);
359204076Spjd	mtx_init(&hio_free_list_lock);
360204076Spjd	cv_init(&hio_free_list_cond);
361204076Spjd	for (ii = 0; ii < HAST_NCOMPONENTS; ii++) {
362204076Spjd		TAILQ_INIT(&hio_send_list[ii]);
363204076Spjd		mtx_init(&hio_send_list_lock[ii]);
364204076Spjd		cv_init(&hio_send_list_cond[ii]);
365204076Spjd		TAILQ_INIT(&hio_recv_list[ii]);
366204076Spjd		mtx_init(&hio_recv_list_lock[ii]);
367204076Spjd		cv_init(&hio_recv_list_cond[ii]);
368204076Spjd		rw_init(&hio_remote_lock[ii]);
369204076Spjd	}
370204076Spjd	TAILQ_INIT(&hio_done_list);
371204076Spjd	mtx_init(&hio_done_list_lock);
372204076Spjd	cv_init(&hio_done_list_cond);
373204076Spjd	mtx_init(&hio_guard_lock);
374204076Spjd	cv_init(&hio_guard_cond);
375204076Spjd	mtx_init(&metadata_lock);
376204076Spjd
377204076Spjd	/*
378204076Spjd	 * Allocate requests pool and initialize requests.
379204076Spjd	 */
380204076Spjd	for (ii = 0; ii < HAST_HIO_MAX; ii++) {
381204076Spjd		hio = malloc(sizeof(*hio));
382204076Spjd		if (hio == NULL) {
383204076Spjd			primary_exitx(EX_TEMPFAIL,
384204076Spjd			    "Unable to allocate %zu bytes of memory for hio request.",
385204076Spjd			    sizeof(*hio));
386204076Spjd		}
387204076Spjd		hio->hio_countdown = 0;
388204076Spjd		hio->hio_errors = malloc(sizeof(hio->hio_errors[0]) * ncomps);
389204076Spjd		if (hio->hio_errors == NULL) {
390204076Spjd			primary_exitx(EX_TEMPFAIL,
391204076Spjd			    "Unable allocate %zu bytes of memory for hio errors.",
392204076Spjd			    sizeof(hio->hio_errors[0]) * ncomps);
393204076Spjd		}
394204076Spjd		hio->hio_next = malloc(sizeof(hio->hio_next[0]) * ncomps);
395204076Spjd		if (hio->hio_next == NULL) {
396204076Spjd			primary_exitx(EX_TEMPFAIL,
397204076Spjd			    "Unable allocate %zu bytes of memory for hio_next field.",
398204076Spjd			    sizeof(hio->hio_next[0]) * ncomps);
399204076Spjd		}
400204076Spjd		hio->hio_ggio.gctl_version = G_GATE_VERSION;
401204076Spjd		hio->hio_ggio.gctl_data = malloc(MAXPHYS);
402204076Spjd		if (hio->hio_ggio.gctl_data == NULL) {
403204076Spjd			primary_exitx(EX_TEMPFAIL,
404204076Spjd			    "Unable to allocate %zu bytes of memory for gctl_data.",
405204076Spjd			    MAXPHYS);
406204076Spjd		}
407204076Spjd		hio->hio_ggio.gctl_length = MAXPHYS;
408204076Spjd		hio->hio_ggio.gctl_error = 0;
409204076Spjd		TAILQ_INSERT_HEAD(&hio_free_list, hio, hio_free_next);
410204076Spjd	}
411204076Spjd
412204076Spjd	/*
413204076Spjd	 * Turn on signals handling.
414204076Spjd	 */
415204076Spjd	signal(SIGINT, sighandler);
416204076Spjd	signal(SIGTERM, sighandler);
417204076Spjd}
418204076Spjd
419204076Spjdstatic void
420204076Spjdinit_local(struct hast_resource *res)
421204076Spjd{
422204076Spjd	unsigned char *buf;
423204076Spjd	size_t mapsize;
424204076Spjd
425204076Spjd	if (metadata_read(res, true) < 0)
426204076Spjd		exit(EX_NOINPUT);
427204076Spjd	mtx_init(&res->hr_amp_lock);
428204076Spjd	if (activemap_init(&res->hr_amp, res->hr_datasize, res->hr_extentsize,
429204076Spjd	    res->hr_local_sectorsize, res->hr_keepdirty) < 0) {
430204076Spjd		primary_exit(EX_TEMPFAIL, "Unable to create activemap");
431204076Spjd	}
432204076Spjd	mtx_init(&range_lock);
433204076Spjd	cv_init(&range_regular_cond);
434204076Spjd	if (rangelock_init(&range_regular) < 0)
435204076Spjd		primary_exit(EX_TEMPFAIL, "Unable to create regular range lock");
436204076Spjd	cv_init(&range_sync_cond);
437204076Spjd	if (rangelock_init(&range_sync) < 0)
438204076Spjd		primary_exit(EX_TEMPFAIL, "Unable to create sync range lock");
439204076Spjd	mapsize = activemap_ondisk_size(res->hr_amp);
440204076Spjd	buf = calloc(1, mapsize);
441204076Spjd	if (buf == NULL) {
442204076Spjd		primary_exitx(EX_TEMPFAIL,
443204076Spjd		    "Unable to allocate buffer for activemap.");
444204076Spjd	}
445204076Spjd	if (pread(res->hr_localfd, buf, mapsize, METADATA_SIZE) !=
446204076Spjd	    (ssize_t)mapsize) {
447204076Spjd		primary_exit(EX_NOINPUT, "Unable to read activemap");
448204076Spjd	}
449204076Spjd	activemap_copyin(res->hr_amp, buf, mapsize);
450204076Spjd	if (res->hr_resuid != 0)
451204076Spjd		return;
452204076Spjd	/*
453204076Spjd	 * We're using provider for the first time, so we have to generate
454204076Spjd	 * resource unique identifier and initialize local and remote counts.
455204076Spjd	 */
456204076Spjd	arc4random_buf(&res->hr_resuid, sizeof(res->hr_resuid));
457204076Spjd	res->hr_primary_localcnt = 1;
458204076Spjd	res->hr_primary_remotecnt = 0;
459204076Spjd	if (metadata_write(res) < 0)
460204076Spjd		exit(EX_NOINPUT);
461204076Spjd}
462204076Spjd
463204076Spjdstatic void
464204076Spjdinit_remote(struct hast_resource *res)
465204076Spjd{
466204076Spjd	struct nv *nvout, *nvin;
467204076Spjd	const unsigned char *token;
468204076Spjd	unsigned char *map;
469204076Spjd	const char *errmsg;
470204076Spjd	int32_t extentsize;
471204076Spjd	int64_t datasize;
472204076Spjd	uint32_t mapsize;
473204076Spjd	size_t size;
474204076Spjd
475204076Spjd	/* Prepare outgoing connection with remote node. */
476204076Spjd	if (proto_client(res->hr_remoteaddr, &res->hr_remoteout) < 0) {
477204076Spjd		primary_exit(EX_OSERR, "Unable to create connection to %s",
478204076Spjd		    res->hr_remoteaddr);
479204076Spjd	}
480204076Spjd	/* Try to connect, but accept failure. */
481204076Spjd	if (proto_connect(res->hr_remoteout) < 0) {
482204076Spjd		pjdlog_errno(LOG_WARNING, "Unable to connect to %s",
483204076Spjd		    res->hr_remoteaddr);
484204076Spjd		goto close;
485204076Spjd	}
486204076Spjd	/*
487204076Spjd	 * First handshake step.
488204076Spjd	 * Setup outgoing connection with remote node.
489204076Spjd	 */
490204076Spjd	nvout = nv_alloc();
491204076Spjd	nv_add_string(nvout, res->hr_name, "resource");
492204076Spjd	if (nv_error(nvout) != 0) {
493204076Spjd		pjdlog_common(LOG_WARNING, 0, nv_error(nvout),
494204076Spjd		    "Unable to allocate header for connection with %s",
495204076Spjd		    res->hr_remoteaddr);
496204076Spjd		nv_free(nvout);
497204076Spjd		goto close;
498204076Spjd	}
499204076Spjd	if (hast_proto_send(res, res->hr_remoteout, nvout, NULL, 0) < 0) {
500204076Spjd		pjdlog_errno(LOG_WARNING,
501204076Spjd		    "Unable to send handshake header to %s",
502204076Spjd		    res->hr_remoteaddr);
503204076Spjd		nv_free(nvout);
504204076Spjd		goto close;
505204076Spjd	}
506204076Spjd	nv_free(nvout);
507204076Spjd	if (hast_proto_recv_hdr(res->hr_remoteout, &nvin) < 0) {
508204076Spjd		pjdlog_errno(LOG_WARNING,
509204076Spjd		    "Unable to receive handshake header from %s",
510204076Spjd		    res->hr_remoteaddr);
511204076Spjd		goto close;
512204076Spjd	}
513204076Spjd	errmsg = nv_get_string(nvin, "errmsg");
514204076Spjd	if (errmsg != NULL) {
515204076Spjd		pjdlog_warning("%s", errmsg);
516204076Spjd		nv_free(nvin);
517204076Spjd		goto close;
518204076Spjd	}
519204076Spjd	token = nv_get_uint8_array(nvin, &size, "token");
520204076Spjd	if (token == NULL) {
521204076Spjd		pjdlog_warning("Handshake header from %s has no 'token' field.",
522204076Spjd		    res->hr_remoteaddr);
523204076Spjd		nv_free(nvin);
524204076Spjd		goto close;
525204076Spjd	}
526204076Spjd	if (size != sizeof(res->hr_token)) {
527204076Spjd		pjdlog_warning("Handshake header from %s contains 'token' of wrong size (got %zu, expected %zu).",
528204076Spjd		    res->hr_remoteaddr, size, sizeof(res->hr_token));
529204076Spjd		nv_free(nvin);
530204076Spjd		goto close;
531204076Spjd	}
532204076Spjd	bcopy(token, res->hr_token, sizeof(res->hr_token));
533204076Spjd	nv_free(nvin);
534204076Spjd
535204076Spjd	/*
536204076Spjd	 * Second handshake step.
537204076Spjd	 * Setup incoming connection with remote node.
538204076Spjd	 */
539204076Spjd	if (proto_client(res->hr_remoteaddr, &res->hr_remotein) < 0) {
540204076Spjd		pjdlog_errno(LOG_WARNING, "Unable to create connection to %s",
541204076Spjd		    res->hr_remoteaddr);
542204076Spjd	}
543204076Spjd	/* Try to connect, but accept failure. */
544204076Spjd	if (proto_connect(res->hr_remotein) < 0) {
545204076Spjd		pjdlog_errno(LOG_WARNING, "Unable to connect to %s",
546204076Spjd		    res->hr_remoteaddr);
547204076Spjd		goto close;
548204076Spjd	}
549204076Spjd	nvout = nv_alloc();
550204076Spjd	nv_add_string(nvout, res->hr_name, "resource");
551204076Spjd	nv_add_uint8_array(nvout, res->hr_token, sizeof(res->hr_token),
552204076Spjd	    "token");
553204076Spjd	nv_add_uint64(nvout, res->hr_resuid, "resuid");
554204076Spjd	nv_add_uint64(nvout, res->hr_primary_localcnt, "localcnt");
555204076Spjd	nv_add_uint64(nvout, res->hr_primary_remotecnt, "remotecnt");
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	}
563204076Spjd	if (hast_proto_send(res, res->hr_remotein, 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);
571204076Spjd	if (hast_proto_recv_hdr(res->hr_remoteout, &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	datasize = nv_get_int64(nvin, "datasize");
584204076Spjd	if (datasize != res->hr_datasize) {
585204076Spjd		pjdlog_warning("Data size differs between nodes (local=%jd, remote=%jd).",
586204076Spjd		    (intmax_t)res->hr_datasize, (intmax_t)datasize);
587204076Spjd		nv_free(nvin);
588204076Spjd		goto close;
589204076Spjd	}
590204076Spjd	extentsize = nv_get_int32(nvin, "extentsize");
591204076Spjd	if (extentsize != res->hr_extentsize) {
592204076Spjd		pjdlog_warning("Extent size differs between nodes (local=%zd, remote=%zd).",
593204076Spjd		    (ssize_t)res->hr_extentsize, (ssize_t)extentsize);
594204076Spjd		nv_free(nvin);
595204076Spjd		goto close;
596204076Spjd	}
597204076Spjd	res->hr_secondary_localcnt = nv_get_uint64(nvin, "localcnt");
598204076Spjd	res->hr_secondary_remotecnt = nv_get_uint64(nvin, "remotecnt");
599204076Spjd	res->hr_syncsrc = nv_get_uint8(nvin, "syncsrc");
600204076Spjd	map = NULL;
601204076Spjd	mapsize = nv_get_uint32(nvin, "mapsize");
602204076Spjd	if (mapsize > 0) {
603204076Spjd		map = malloc(mapsize);
604204076Spjd		if (map == NULL) {
605204076Spjd			pjdlog_error("Unable to allocate memory for remote activemap (mapsize=%ju).",
606204076Spjd			    (uintmax_t)mapsize);
607204076Spjd			nv_free(nvin);
608204076Spjd			goto close;
609204076Spjd		}
610204076Spjd		/*
611204076Spjd		 * Remote node have some dirty extents on its own, lets
612204076Spjd		 * download its activemap.
613204076Spjd		 */
614204076Spjd		if (hast_proto_recv_data(res, res->hr_remoteout, nvin, map,
615204076Spjd		    mapsize) < 0) {
616204076Spjd			pjdlog_errno(LOG_ERR,
617204076Spjd			    "Unable to receive remote activemap");
618204076Spjd			nv_free(nvin);
619204076Spjd			free(map);
620204076Spjd			goto close;
621204076Spjd		}
622204076Spjd		/*
623204076Spjd		 * Merge local and remote bitmaps.
624204076Spjd		 */
625204076Spjd		activemap_merge(res->hr_amp, map, mapsize);
626204076Spjd		free(map);
627204076Spjd		/*
628204076Spjd		 * Now that we merged bitmaps from both nodes, flush it to the
629204076Spjd		 * disk before we start to synchronize.
630204076Spjd		 */
631204076Spjd		(void)hast_activemap_flush(res);
632204076Spjd	}
633204076Spjd	pjdlog_info("Connected to %s.", res->hr_remoteaddr);
634204076Spjd	mtx_lock(&sync_lock);
635204076Spjd	sync_inprogress = true;
636204076Spjd	mtx_unlock(&sync_lock);
637204076Spjd	cv_signal(&sync_cond);
638204076Spjd	return;
639204076Spjdclose:
640204076Spjd	proto_close(res->hr_remoteout);
641204076Spjd	res->hr_remoteout = NULL;
642204076Spjd	if (res->hr_remotein != NULL) {
643204076Spjd		proto_close(res->hr_remotein);
644204076Spjd		res->hr_remotein = NULL;
645204076Spjd	}
646204076Spjd}
647204076Spjd
648204076Spjdstatic void
649204076Spjdinit_ggate(struct hast_resource *res)
650204076Spjd{
651204076Spjd	struct g_gate_ctl_create ggiocreate;
652204076Spjd	struct g_gate_ctl_cancel ggiocancel;
653204076Spjd
654204076Spjd	/*
655204076Spjd	 * We communicate with ggate via /dev/ggctl. Open it.
656204076Spjd	 */
657204076Spjd	res->hr_ggatefd = open("/dev/" G_GATE_CTL_NAME, O_RDWR);
658204076Spjd	if (res->hr_ggatefd < 0)
659204076Spjd		primary_exit(EX_OSFILE, "Unable to open /dev/" G_GATE_CTL_NAME);
660204076Spjd	/*
661204076Spjd	 * Create provider before trying to connect, as connection failure
662204076Spjd	 * is not critical, but may take some time.
663204076Spjd	 */
664204076Spjd	ggiocreate.gctl_version = G_GATE_VERSION;
665204076Spjd	ggiocreate.gctl_mediasize = res->hr_datasize;
666204076Spjd	ggiocreate.gctl_sectorsize = res->hr_local_sectorsize;
667204076Spjd	ggiocreate.gctl_flags = 0;
668204076Spjd	ggiocreate.gctl_maxcount = 128;
669204076Spjd	ggiocreate.gctl_timeout = 0;
670204076Spjd	ggiocreate.gctl_unit = G_GATE_NAME_GIVEN;
671204076Spjd	snprintf(ggiocreate.gctl_name, sizeof(ggiocreate.gctl_name), "hast/%s",
672204076Spjd	    res->hr_provname);
673204076Spjd	bzero(ggiocreate.gctl_info, sizeof(ggiocreate.gctl_info));
674204076Spjd	if (ioctl(res->hr_ggatefd, G_GATE_CMD_CREATE, &ggiocreate) == 0) {
675204076Spjd		pjdlog_info("Device hast/%s created.", res->hr_provname);
676204076Spjd		res->hr_ggateunit = ggiocreate.gctl_unit;
677204076Spjd		return;
678204076Spjd	}
679204076Spjd	if (errno != EEXIST) {
680204076Spjd		primary_exit(EX_OSERR, "Unable to create hast/%s device",
681204076Spjd		    res->hr_provname);
682204076Spjd	}
683204076Spjd	pjdlog_debug(1,
684204076Spjd	    "Device hast/%s already exists, we will try to take it over.",
685204076Spjd	    res->hr_provname);
686204076Spjd	/*
687204076Spjd	 * If we received EEXIST, we assume that the process who created the
688204076Spjd	 * provider died and didn't clean up. In that case we will start from
689204076Spjd	 * where he left of.
690204076Spjd	 */
691204076Spjd	ggiocancel.gctl_version = G_GATE_VERSION;
692204076Spjd	ggiocancel.gctl_unit = G_GATE_NAME_GIVEN;
693204076Spjd	snprintf(ggiocancel.gctl_name, sizeof(ggiocancel.gctl_name), "hast/%s",
694204076Spjd	    res->hr_provname);
695204076Spjd	if (ioctl(res->hr_ggatefd, G_GATE_CMD_CANCEL, &ggiocancel) == 0) {
696204076Spjd		pjdlog_info("Device hast/%s recovered.", res->hr_provname);
697204076Spjd		res->hr_ggateunit = ggiocancel.gctl_unit;
698204076Spjd		return;
699204076Spjd	}
700204076Spjd	primary_exit(EX_OSERR, "Unable to take over hast/%s device",
701204076Spjd	    res->hr_provname);
702204076Spjd}
703204076Spjd
704204076Spjdvoid
705204076Spjdhastd_primary(struct hast_resource *res)
706204076Spjd{
707204076Spjd	pthread_t td;
708204076Spjd	pid_t pid;
709204076Spjd	int error;
710204076Spjd
711204076Spjd	gres = res;
712204076Spjd
713204076Spjd	/*
714204076Spjd	 * Create communication channel between parent and child.
715204076Spjd	 */
716204076Spjd	if (proto_client("socketpair://", &res->hr_ctrl) < 0) {
717204076Spjd		KEEP_ERRNO((void)pidfile_remove(pfh));
718204076Spjd		primary_exit(EX_OSERR,
719204076Spjd		    "Unable to create control sockets between parent and child");
720204076Spjd	}
721204076Spjd
722204076Spjd	pid = fork();
723204076Spjd	if (pid < 0) {
724204076Spjd		KEEP_ERRNO((void)pidfile_remove(pfh));
725204076Spjd		primary_exit(EX_OSERR, "Unable to fork");
726204076Spjd	}
727204076Spjd
728204076Spjd	if (pid > 0) {
729204076Spjd		/* This is parent. */
730204076Spjd		res->hr_workerpid = pid;
731204076Spjd		return;
732204076Spjd	}
733204076Spjd	(void)pidfile_close(pfh);
734204076Spjd
735204076Spjd	setproctitle("%s (primary)", res->hr_name);
736204076Spjd
737204076Spjd	init_local(res);
738204076Spjd	init_remote(res);
739204076Spjd	init_ggate(res);
740204076Spjd	init_environment(res);
741204076Spjd	error = pthread_create(&td, NULL, ggate_recv_thread, res);
742204076Spjd	assert(error == 0);
743204076Spjd	error = pthread_create(&td, NULL, local_send_thread, res);
744204076Spjd	assert(error == 0);
745204076Spjd	error = pthread_create(&td, NULL, remote_send_thread, res);
746204076Spjd	assert(error == 0);
747204076Spjd	error = pthread_create(&td, NULL, remote_recv_thread, res);
748204076Spjd	assert(error == 0);
749204076Spjd	error = pthread_create(&td, NULL, ggate_send_thread, res);
750204076Spjd	assert(error == 0);
751204076Spjd	error = pthread_create(&td, NULL, sync_thread, res);
752204076Spjd	assert(error == 0);
753204076Spjd	error = pthread_create(&td, NULL, ctrl_thread, res);
754204076Spjd	assert(error == 0);
755204076Spjd	(void)guard_thread(res);
756204076Spjd}
757204076Spjd
758204076Spjdstatic void
759204076Spjdreqlog(int loglevel, int debuglevel, struct g_gate_ctl_io *ggio, const char *fmt, ...)
760204076Spjd{
761204076Spjd	char msg[1024];
762204076Spjd	va_list ap;
763204076Spjd	int len;
764204076Spjd
765204076Spjd	va_start(ap, fmt);
766204076Spjd	len = vsnprintf(msg, sizeof(msg), fmt, ap);
767204076Spjd	va_end(ap);
768204076Spjd	if ((size_t)len < sizeof(msg)) {
769204076Spjd		switch (ggio->gctl_cmd) {
770204076Spjd		case BIO_READ:
771204076Spjd			(void)snprintf(msg + len, sizeof(msg) - len,
772204076Spjd			    "READ(%ju, %ju).", (uintmax_t)ggio->gctl_offset,
773204076Spjd			    (uintmax_t)ggio->gctl_length);
774204076Spjd			break;
775204076Spjd		case BIO_DELETE:
776204076Spjd			(void)snprintf(msg + len, sizeof(msg) - len,
777204076Spjd			    "DELETE(%ju, %ju).", (uintmax_t)ggio->gctl_offset,
778204076Spjd			    (uintmax_t)ggio->gctl_length);
779204076Spjd			break;
780204076Spjd		case BIO_FLUSH:
781204076Spjd			(void)snprintf(msg + len, sizeof(msg) - len, "FLUSH.");
782204076Spjd			break;
783204076Spjd		case BIO_WRITE:
784204076Spjd			(void)snprintf(msg + len, sizeof(msg) - len,
785204076Spjd			    "WRITE(%ju, %ju).", (uintmax_t)ggio->gctl_offset,
786204076Spjd			    (uintmax_t)ggio->gctl_length);
787204076Spjd			break;
788204076Spjd		default:
789204076Spjd			(void)snprintf(msg + len, sizeof(msg) - len,
790204076Spjd			    "UNKNOWN(%u).", (unsigned int)ggio->gctl_cmd);
791204076Spjd			break;
792204076Spjd		}
793204076Spjd	}
794204076Spjd	pjdlog_common(loglevel, debuglevel, -1, "%s", msg);
795204076Spjd}
796204076Spjd
797204076Spjdstatic void
798204076Spjdremote_close(struct hast_resource *res, int ncomp)
799204076Spjd{
800204076Spjd
801204076Spjd	rw_wlock(&hio_remote_lock[ncomp]);
802204076Spjd	/*
803204076Spjd	 * A race is possible between dropping rlock and acquiring wlock -
804204076Spjd	 * another thread can close connection in-between.
805204076Spjd	 */
806204076Spjd	if (!ISCONNECTED(res, ncomp)) {
807204076Spjd		assert(res->hr_remotein == NULL);
808204076Spjd		assert(res->hr_remoteout == NULL);
809204076Spjd		rw_unlock(&hio_remote_lock[ncomp]);
810204076Spjd		return;
811204076Spjd	}
812204076Spjd
813204076Spjd	assert(res->hr_remotein != NULL);
814204076Spjd	assert(res->hr_remoteout != NULL);
815204076Spjd
816204076Spjd	pjdlog_debug(2, "Closing old incoming connection to %s.",
817204076Spjd	    res->hr_remoteaddr);
818204076Spjd	proto_close(res->hr_remotein);
819204076Spjd	res->hr_remotein = NULL;
820204076Spjd	pjdlog_debug(2, "Closing old outgoing connection to %s.",
821204076Spjd	    res->hr_remoteaddr);
822204076Spjd	proto_close(res->hr_remoteout);
823204076Spjd	res->hr_remoteout = NULL;
824204076Spjd
825204076Spjd	rw_unlock(&hio_remote_lock[ncomp]);
826204076Spjd
827204076Spjd	/*
828204076Spjd	 * Stop synchronization if in-progress.
829204076Spjd	 */
830204076Spjd	mtx_lock(&sync_lock);
831204076Spjd	if (sync_inprogress)
832204076Spjd		sync_inprogress = false;
833204076Spjd	mtx_unlock(&sync_lock);
834204076Spjd
835204076Spjd	/*
836204076Spjd	 * Wake up guard thread, so it can immediately start reconnect.
837204076Spjd	 */
838204076Spjd	mtx_lock(&hio_guard_lock);
839204076Spjd	cv_signal(&hio_guard_cond);
840204076Spjd	mtx_unlock(&hio_guard_lock);
841204076Spjd}
842204076Spjd
843204076Spjd/*
844204076Spjd * Thread receives ggate I/O requests from the kernel and passes them to
845204076Spjd * appropriate threads:
846204076Spjd * WRITE - always goes to both local_send and remote_send threads
847204076Spjd * READ (when the block is up-to-date on local component) -
848204076Spjd *	only local_send thread
849204076Spjd * READ (when the block isn't up-to-date on local component) -
850204076Spjd *	only remote_send thread
851204076Spjd * DELETE - always goes to both local_send and remote_send threads
852204076Spjd * FLUSH - always goes to both local_send and remote_send threads
853204076Spjd */
854204076Spjdstatic void *
855204076Spjdggate_recv_thread(void *arg)
856204076Spjd{
857204076Spjd	struct hast_resource *res = arg;
858204076Spjd	struct g_gate_ctl_io *ggio;
859204076Spjd	struct hio *hio;
860204076Spjd	unsigned int ii, ncomp, ncomps;
861204076Spjd	int error;
862204076Spjd
863204076Spjd	ncomps = HAST_NCOMPONENTS;
864204076Spjd
865204076Spjd	for (;;) {
866204076Spjd		pjdlog_debug(2, "ggate_recv: Taking free request.");
867204076Spjd		QUEUE_TAKE2(hio, free);
868204076Spjd		pjdlog_debug(2, "ggate_recv: (%p) Got free request.", hio);
869204076Spjd		ggio = &hio->hio_ggio;
870204076Spjd		ggio->gctl_unit = res->hr_ggateunit;
871204076Spjd		ggio->gctl_length = MAXPHYS;
872204076Spjd		ggio->gctl_error = 0;
873204076Spjd		pjdlog_debug(2,
874204076Spjd		    "ggate_recv: (%p) Waiting for request from the kernel.",
875204076Spjd		    hio);
876204076Spjd		if (ioctl(res->hr_ggatefd, G_GATE_CMD_START, ggio) < 0) {
877204076Spjd			if (sigexit_received)
878204076Spjd				pthread_exit(NULL);
879204076Spjd			primary_exit(EX_OSERR, "G_GATE_CMD_START failed");
880204076Spjd		}
881204076Spjd		error = ggio->gctl_error;
882204076Spjd		switch (error) {
883204076Spjd		case 0:
884204076Spjd			break;
885204076Spjd		case ECANCELED:
886204076Spjd			/* Exit gracefully. */
887204076Spjd			if (!sigexit_received) {
888204076Spjd				pjdlog_debug(2,
889204076Spjd				    "ggate_recv: (%p) Received cancel from the kernel.",
890204076Spjd				    hio);
891204076Spjd				pjdlog_info("Received cancel from the kernel, exiting.");
892204076Spjd			}
893204076Spjd			pthread_exit(NULL);
894204076Spjd		case ENOMEM:
895204076Spjd			/*
896204076Spjd			 * Buffer too small? Impossible, we allocate MAXPHYS
897204076Spjd			 * bytes - request can't be bigger than that.
898204076Spjd			 */
899204076Spjd			/* FALLTHROUGH */
900204076Spjd		case ENXIO:
901204076Spjd		default:
902204076Spjd			primary_exitx(EX_OSERR, "G_GATE_CMD_START failed: %s.",
903204076Spjd			    strerror(error));
904204076Spjd		}
905204076Spjd		for (ii = 0; ii < ncomps; ii++)
906204076Spjd			hio->hio_errors[ii] = EINVAL;
907204076Spjd		reqlog(LOG_DEBUG, 2, ggio,
908204076Spjd		    "ggate_recv: (%p) Request received from the kernel: ",
909204076Spjd		    hio);
910204076Spjd		/*
911204076Spjd		 * Inform all components about new write request.
912204076Spjd		 * For read request prefer local component unless the given
913204076Spjd		 * range is out-of-date, then use remote component.
914204076Spjd		 */
915204076Spjd		switch (ggio->gctl_cmd) {
916204076Spjd		case BIO_READ:
917204076Spjd			pjdlog_debug(2,
918204076Spjd			    "ggate_recv: (%p) Moving request to the send queue.",
919204076Spjd			    hio);
920204076Spjd			refcount_init(&hio->hio_countdown, 1);
921204076Spjd			mtx_lock(&metadata_lock);
922204076Spjd			if (res->hr_syncsrc == HAST_SYNCSRC_UNDEF ||
923204076Spjd			    res->hr_syncsrc == HAST_SYNCSRC_PRIMARY) {
924204076Spjd				/*
925204076Spjd				 * This range is up-to-date on local component,
926204076Spjd				 * so handle request locally.
927204076Spjd				 */
928204076Spjd				 /* Local component is 0 for now. */
929204076Spjd				ncomp = 0;
930204076Spjd			} else /* if (res->hr_syncsrc ==
931204076Spjd			    HAST_SYNCSRC_SECONDARY) */ {
932204076Spjd				assert(res->hr_syncsrc ==
933204076Spjd				    HAST_SYNCSRC_SECONDARY);
934204076Spjd				/*
935204076Spjd				 * This range is out-of-date on local component,
936204076Spjd				 * so send request to the remote node.
937204076Spjd				 */
938204076Spjd				 /* Remote component is 1 for now. */
939204076Spjd				ncomp = 1;
940204076Spjd			}
941204076Spjd			mtx_unlock(&metadata_lock);
942204076Spjd			QUEUE_INSERT1(hio, send, ncomp);
943204076Spjd			break;
944204076Spjd		case BIO_WRITE:
945204076Spjd			for (;;) {
946204076Spjd				mtx_lock(&range_lock);
947204076Spjd				if (rangelock_islocked(range_sync,
948204076Spjd				    ggio->gctl_offset, ggio->gctl_length)) {
949204076Spjd					pjdlog_debug(2,
950204076Spjd					    "regular: Range offset=%jd length=%zu locked.",
951204076Spjd					    (intmax_t)ggio->gctl_offset,
952204076Spjd					    (size_t)ggio->gctl_length);
953204076Spjd					range_regular_wait = true;
954204076Spjd					cv_wait(&range_regular_cond, &range_lock);
955204076Spjd					range_regular_wait = false;
956204076Spjd					mtx_unlock(&range_lock);
957204076Spjd					continue;
958204076Spjd				}
959204076Spjd				if (rangelock_add(range_regular,
960204076Spjd				    ggio->gctl_offset, ggio->gctl_length) < 0) {
961204076Spjd					mtx_unlock(&range_lock);
962204076Spjd					pjdlog_debug(2,
963204076Spjd					    "regular: Range offset=%jd length=%zu is already locked, waiting.",
964204076Spjd					    (intmax_t)ggio->gctl_offset,
965204076Spjd					    (size_t)ggio->gctl_length);
966204076Spjd					sleep(1);
967204076Spjd					continue;
968204076Spjd				}
969204076Spjd				mtx_unlock(&range_lock);
970204076Spjd				break;
971204076Spjd			}
972204076Spjd			mtx_lock(&res->hr_amp_lock);
973204076Spjd			if (activemap_write_start(res->hr_amp,
974204076Spjd			    ggio->gctl_offset, ggio->gctl_length)) {
975204076Spjd				(void)hast_activemap_flush(res);
976204076Spjd			}
977204076Spjd			mtx_unlock(&res->hr_amp_lock);
978204076Spjd			/* FALLTHROUGH */
979204076Spjd		case BIO_DELETE:
980204076Spjd		case BIO_FLUSH:
981204076Spjd			pjdlog_debug(2,
982204076Spjd			    "ggate_recv: (%p) Moving request to the send queues.",
983204076Spjd			    hio);
984204076Spjd			refcount_init(&hio->hio_countdown, ncomps);
985204076Spjd			for (ii = 0; ii < ncomps; ii++)
986204076Spjd				QUEUE_INSERT1(hio, send, ii);
987204076Spjd			break;
988204076Spjd		}
989204076Spjd	}
990204076Spjd	/* NOTREACHED */
991204076Spjd	return (NULL);
992204076Spjd}
993204076Spjd
994204076Spjd/*
995204076Spjd * Thread reads from or writes to local component.
996204076Spjd * If local read fails, it redirects it to remote_send thread.
997204076Spjd */
998204076Spjdstatic void *
999204076Spjdlocal_send_thread(void *arg)
1000204076Spjd{
1001204076Spjd	struct hast_resource *res = arg;
1002204076Spjd	struct g_gate_ctl_io *ggio;
1003204076Spjd	struct hio *hio;
1004204076Spjd	unsigned int ncomp, rncomp;
1005204076Spjd	ssize_t ret;
1006204076Spjd
1007204076Spjd	/* Local component is 0 for now. */
1008204076Spjd	ncomp = 0;
1009204076Spjd	/* Remote component is 1 for now. */
1010204076Spjd	rncomp = 1;
1011204076Spjd
1012204076Spjd	for (;;) {
1013204076Spjd		pjdlog_debug(2, "local_send: Taking request.");
1014204076Spjd		QUEUE_TAKE1(hio, send, ncomp);
1015204076Spjd		pjdlog_debug(2, "local_send: (%p) Got request.", hio);
1016204076Spjd		ggio = &hio->hio_ggio;
1017204076Spjd		switch (ggio->gctl_cmd) {
1018204076Spjd		case BIO_READ:
1019204076Spjd			ret = pread(res->hr_localfd, ggio->gctl_data,
1020204076Spjd			    ggio->gctl_length,
1021204076Spjd			    ggio->gctl_offset + res->hr_localoff);
1022204076Spjd			if (ret == ggio->gctl_length)
1023204076Spjd				hio->hio_errors[ncomp] = 0;
1024204076Spjd			else {
1025204076Spjd				/*
1026204076Spjd				 * If READ failed, try to read from remote node.
1027204076Spjd				 */
1028204076Spjd				QUEUE_INSERT1(hio, send, rncomp);
1029204076Spjd				continue;
1030204076Spjd			}
1031204076Spjd			break;
1032204076Spjd		case BIO_WRITE:
1033204076Spjd			ret = pwrite(res->hr_localfd, ggio->gctl_data,
1034204076Spjd			    ggio->gctl_length,
1035204076Spjd			    ggio->gctl_offset + res->hr_localoff);
1036204076Spjd			if (ret < 0)
1037204076Spjd				hio->hio_errors[ncomp] = errno;
1038204076Spjd			else if (ret != ggio->gctl_length)
1039204076Spjd				hio->hio_errors[ncomp] = EIO;
1040204076Spjd			else
1041204076Spjd				hio->hio_errors[ncomp] = 0;
1042204076Spjd			break;
1043204076Spjd		case BIO_DELETE:
1044204076Spjd			ret = g_delete(res->hr_localfd,
1045204076Spjd			    ggio->gctl_offset + res->hr_localoff,
1046204076Spjd			    ggio->gctl_length);
1047204076Spjd			if (ret < 0)
1048204076Spjd				hio->hio_errors[ncomp] = errno;
1049204076Spjd			else
1050204076Spjd				hio->hio_errors[ncomp] = 0;
1051204076Spjd			break;
1052204076Spjd		case BIO_FLUSH:
1053204076Spjd			ret = g_flush(res->hr_localfd);
1054204076Spjd			if (ret < 0)
1055204076Spjd				hio->hio_errors[ncomp] = errno;
1056204076Spjd			else
1057204076Spjd				hio->hio_errors[ncomp] = 0;
1058204076Spjd			break;
1059204076Spjd		}
1060204076Spjd		if (refcount_release(&hio->hio_countdown)) {
1061204076Spjd			if (ISSYNCREQ(hio)) {
1062204076Spjd				mtx_lock(&sync_lock);
1063204076Spjd				SYNCREQDONE(hio);
1064204076Spjd				mtx_unlock(&sync_lock);
1065204076Spjd				cv_signal(&sync_cond);
1066204076Spjd			} else {
1067204076Spjd				pjdlog_debug(2,
1068204076Spjd				    "local_send: (%p) Moving request to the done queue.",
1069204076Spjd				    hio);
1070204076Spjd				QUEUE_INSERT2(hio, done);
1071204076Spjd			}
1072204076Spjd		}
1073204076Spjd	}
1074204076Spjd	/* NOTREACHED */
1075204076Spjd	return (NULL);
1076204076Spjd}
1077204076Spjd
1078204076Spjd/*
1079204076Spjd * Thread sends request to secondary node.
1080204076Spjd */
1081204076Spjdstatic void *
1082204076Spjdremote_send_thread(void *arg)
1083204076Spjd{
1084204076Spjd	struct hast_resource *res = arg;
1085204076Spjd	struct g_gate_ctl_io *ggio;
1086204076Spjd	struct hio *hio;
1087204076Spjd	struct nv *nv;
1088204076Spjd	unsigned int ncomp;
1089204076Spjd	bool wakeup;
1090204076Spjd	uint64_t offset, length;
1091204076Spjd	uint8_t cmd;
1092204076Spjd	void *data;
1093204076Spjd
1094204076Spjd	/* Remote component is 1 for now. */
1095204076Spjd	ncomp = 1;
1096204076Spjd
1097204076Spjd	for (;;) {
1098204076Spjd		pjdlog_debug(2, "remote_send: Taking request.");
1099204076Spjd		QUEUE_TAKE1(hio, send, ncomp);
1100204076Spjd		pjdlog_debug(2, "remote_send: (%p) Got request.", hio);
1101204076Spjd		ggio = &hio->hio_ggio;
1102204076Spjd		switch (ggio->gctl_cmd) {
1103204076Spjd		case BIO_READ:
1104204076Spjd			cmd = HIO_READ;
1105204076Spjd			data = NULL;
1106204076Spjd			offset = ggio->gctl_offset;
1107204076Spjd			length = ggio->gctl_length;
1108204076Spjd			break;
1109204076Spjd		case BIO_WRITE:
1110204076Spjd			cmd = HIO_WRITE;
1111204076Spjd			data = ggio->gctl_data;
1112204076Spjd			offset = ggio->gctl_offset;
1113204076Spjd			length = ggio->gctl_length;
1114204076Spjd			break;
1115204076Spjd		case BIO_DELETE:
1116204076Spjd			cmd = HIO_DELETE;
1117204076Spjd			data = NULL;
1118204076Spjd			offset = ggio->gctl_offset;
1119204076Spjd			length = ggio->gctl_length;
1120204076Spjd			break;
1121204076Spjd		case BIO_FLUSH:
1122204076Spjd			cmd = HIO_FLUSH;
1123204076Spjd			data = NULL;
1124204076Spjd			offset = 0;
1125204076Spjd			length = 0;
1126204076Spjd			break;
1127204076Spjd		default:
1128204076Spjd			assert(!"invalid condition");
1129204076Spjd			abort();
1130204076Spjd		}
1131204076Spjd		nv = nv_alloc();
1132204076Spjd		nv_add_uint8(nv, cmd, "cmd");
1133204076Spjd		nv_add_uint64(nv, (uint64_t)ggio->gctl_seq, "seq");
1134204076Spjd		nv_add_uint64(nv, offset, "offset");
1135204076Spjd		nv_add_uint64(nv, length, "length");
1136204076Spjd		if (nv_error(nv) != 0) {
1137204076Spjd			hio->hio_errors[ncomp] = nv_error(nv);
1138204076Spjd			pjdlog_debug(2,
1139204076Spjd			    "remote_send: (%p) Unable to prepare header to send.",
1140204076Spjd			    hio);
1141204076Spjd			reqlog(LOG_ERR, 0, ggio,
1142204076Spjd			    "Unable to prepare header to send (%s): ",
1143204076Spjd			    strerror(nv_error(nv)));
1144204076Spjd			/* Move failed request immediately to the done queue. */
1145204076Spjd			goto done_queue;
1146204076Spjd		}
1147204076Spjd		pjdlog_debug(2,
1148204076Spjd		    "remote_send: (%p) Moving request to the recv queue.",
1149204076Spjd		    hio);
1150204076Spjd		/*
1151204076Spjd		 * Protect connection from disappearing.
1152204076Spjd		 */
1153204076Spjd		rw_rlock(&hio_remote_lock[ncomp]);
1154204076Spjd		if (!ISCONNECTED(res, ncomp)) {
1155204076Spjd			rw_unlock(&hio_remote_lock[ncomp]);
1156204076Spjd			hio->hio_errors[ncomp] = ENOTCONN;
1157204076Spjd			goto done_queue;
1158204076Spjd		}
1159204076Spjd		/*
1160204076Spjd		 * Move the request to recv queue before sending it, because
1161204076Spjd		 * in different order we can get reply before we move request
1162204076Spjd		 * to recv queue.
1163204076Spjd		 */
1164204076Spjd		mtx_lock(&hio_recv_list_lock[ncomp]);
1165204076Spjd		wakeup = TAILQ_EMPTY(&hio_recv_list[ncomp]);
1166204076Spjd		TAILQ_INSERT_TAIL(&hio_recv_list[ncomp], hio, hio_next[ncomp]);
1167204076Spjd		mtx_unlock(&hio_recv_list_lock[ncomp]);
1168204076Spjd		if (hast_proto_send(res, res->hr_remoteout, nv, data,
1169204076Spjd		    data != NULL ? length : 0) < 0) {
1170204076Spjd			hio->hio_errors[ncomp] = errno;
1171204076Spjd			rw_unlock(&hio_remote_lock[ncomp]);
1172204076Spjd			remote_close(res, ncomp);
1173204076Spjd			pjdlog_debug(2,
1174204076Spjd			    "remote_send: (%p) Unable to send request.", hio);
1175204076Spjd			reqlog(LOG_ERR, 0, ggio,
1176204076Spjd			    "Unable to send request (%s): ",
1177204076Spjd			    strerror(hio->hio_errors[ncomp]));
1178204076Spjd			/*
1179204076Spjd			 * Take request back from the receive queue and move
1180204076Spjd			 * it immediately to the done queue.
1181204076Spjd			 */
1182204076Spjd			mtx_lock(&hio_recv_list_lock[ncomp]);
1183204076Spjd			TAILQ_REMOVE(&hio_recv_list[ncomp], hio, hio_next[ncomp]);
1184204076Spjd			mtx_unlock(&hio_recv_list_lock[ncomp]);
1185204076Spjd			goto done_queue;
1186204076Spjd		}
1187204076Spjd		rw_unlock(&hio_remote_lock[ncomp]);
1188204076Spjd		nv_free(nv);
1189204076Spjd		if (wakeup)
1190204076Spjd			cv_signal(&hio_recv_list_cond[ncomp]);
1191204076Spjd		continue;
1192204076Spjddone_queue:
1193204076Spjd		nv_free(nv);
1194204076Spjd		if (ISSYNCREQ(hio)) {
1195204076Spjd			if (!refcount_release(&hio->hio_countdown))
1196204076Spjd				continue;
1197204076Spjd			mtx_lock(&sync_lock);
1198204076Spjd			SYNCREQDONE(hio);
1199204076Spjd			mtx_unlock(&sync_lock);
1200204076Spjd			cv_signal(&sync_cond);
1201204076Spjd			continue;
1202204076Spjd		}
1203204076Spjd		if (ggio->gctl_cmd == BIO_WRITE) {
1204204076Spjd			mtx_lock(&res->hr_amp_lock);
1205204076Spjd			if (activemap_need_sync(res->hr_amp, ggio->gctl_offset,
1206204076Spjd			    ggio->gctl_length)) {
1207204076Spjd				(void)hast_activemap_flush(res);
1208204076Spjd			}
1209204076Spjd			mtx_unlock(&res->hr_amp_lock);
1210204076Spjd		}
1211204076Spjd		if (!refcount_release(&hio->hio_countdown))
1212204076Spjd			continue;
1213204076Spjd		pjdlog_debug(2,
1214204076Spjd		    "remote_send: (%p) Moving request to the done queue.",
1215204076Spjd		    hio);
1216204076Spjd		QUEUE_INSERT2(hio, done);
1217204076Spjd	}
1218204076Spjd	/* NOTREACHED */
1219204076Spjd	return (NULL);
1220204076Spjd}
1221204076Spjd
1222204076Spjd/*
1223204076Spjd * Thread receives answer from secondary node and passes it to ggate_send
1224204076Spjd * thread.
1225204076Spjd */
1226204076Spjdstatic void *
1227204076Spjdremote_recv_thread(void *arg)
1228204076Spjd{
1229204076Spjd	struct hast_resource *res = arg;
1230204076Spjd	struct g_gate_ctl_io *ggio;
1231204076Spjd	struct hio *hio;
1232204076Spjd	struct nv *nv;
1233204076Spjd	unsigned int ncomp;
1234204076Spjd	uint64_t seq;
1235204076Spjd	int error;
1236204076Spjd
1237204076Spjd	/* Remote component is 1 for now. */
1238204076Spjd	ncomp = 1;
1239204076Spjd
1240204076Spjd	for (;;) {
1241204076Spjd		/* Wait until there is anything to receive. */
1242204076Spjd		mtx_lock(&hio_recv_list_lock[ncomp]);
1243204076Spjd		while (TAILQ_EMPTY(&hio_recv_list[ncomp])) {
1244204076Spjd			pjdlog_debug(2, "remote_recv: No requests, waiting.");
1245204076Spjd			cv_wait(&hio_recv_list_cond[ncomp],
1246204076Spjd			    &hio_recv_list_lock[ncomp]);
1247204076Spjd		}
1248204076Spjd		mtx_unlock(&hio_recv_list_lock[ncomp]);
1249204076Spjd		rw_rlock(&hio_remote_lock[ncomp]);
1250204076Spjd		if (!ISCONNECTED(res, ncomp)) {
1251204076Spjd			rw_unlock(&hio_remote_lock[ncomp]);
1252204076Spjd			/*
1253204076Spjd			 * Connection is dead, so move all pending requests to
1254204076Spjd			 * the done queue (one-by-one).
1255204076Spjd			 */
1256204076Spjd			mtx_lock(&hio_recv_list_lock[ncomp]);
1257204076Spjd			hio = TAILQ_FIRST(&hio_recv_list[ncomp]);
1258204076Spjd			assert(hio != NULL);
1259204076Spjd			TAILQ_REMOVE(&hio_recv_list[ncomp], hio,
1260204076Spjd			    hio_next[ncomp]);
1261204076Spjd			mtx_unlock(&hio_recv_list_lock[ncomp]);
1262204076Spjd			goto done_queue;
1263204076Spjd		}
1264204076Spjd		if (hast_proto_recv_hdr(res->hr_remotein, &nv) < 0) {
1265204076Spjd			pjdlog_errno(LOG_ERR,
1266204076Spjd			    "Unable to receive reply header");
1267204076Spjd			rw_unlock(&hio_remote_lock[ncomp]);
1268204076Spjd			remote_close(res, ncomp);
1269204076Spjd			continue;
1270204076Spjd		}
1271204076Spjd		rw_unlock(&hio_remote_lock[ncomp]);
1272204076Spjd		seq = nv_get_uint64(nv, "seq");
1273204076Spjd		if (seq == 0) {
1274204076Spjd			pjdlog_error("Header contains no 'seq' field.");
1275204076Spjd			nv_free(nv);
1276204076Spjd			continue;
1277204076Spjd		}
1278204076Spjd		mtx_lock(&hio_recv_list_lock[ncomp]);
1279204076Spjd		TAILQ_FOREACH(hio, &hio_recv_list[ncomp], hio_next[ncomp]) {
1280204076Spjd			if (hio->hio_ggio.gctl_seq == seq) {
1281204076Spjd				TAILQ_REMOVE(&hio_recv_list[ncomp], hio,
1282204076Spjd				    hio_next[ncomp]);
1283204076Spjd				break;
1284204076Spjd			}
1285204076Spjd		}
1286204076Spjd		mtx_unlock(&hio_recv_list_lock[ncomp]);
1287204076Spjd		if (hio == NULL) {
1288204076Spjd			pjdlog_error("Found no request matching received 'seq' field (%ju).",
1289204076Spjd			    (uintmax_t)seq);
1290204076Spjd			nv_free(nv);
1291204076Spjd			continue;
1292204076Spjd		}
1293204076Spjd		error = nv_get_int16(nv, "error");
1294204076Spjd		if (error != 0) {
1295204076Spjd			/* Request failed on remote side. */
1296204076Spjd			hio->hio_errors[ncomp] = 0;
1297204076Spjd			nv_free(nv);
1298204076Spjd			goto done_queue;
1299204076Spjd		}
1300204076Spjd		ggio = &hio->hio_ggio;
1301204076Spjd		switch (ggio->gctl_cmd) {
1302204076Spjd		case BIO_READ:
1303204076Spjd			rw_rlock(&hio_remote_lock[ncomp]);
1304204076Spjd			if (!ISCONNECTED(res, ncomp)) {
1305204076Spjd				rw_unlock(&hio_remote_lock[ncomp]);
1306204076Spjd				nv_free(nv);
1307204076Spjd				goto done_queue;
1308204076Spjd			}
1309204076Spjd			if (hast_proto_recv_data(res, res->hr_remotein, nv,
1310204076Spjd			    ggio->gctl_data, ggio->gctl_length) < 0) {
1311204076Spjd				hio->hio_errors[ncomp] = errno;
1312204076Spjd				pjdlog_errno(LOG_ERR,
1313204076Spjd				    "Unable to receive reply data");
1314204076Spjd				rw_unlock(&hio_remote_lock[ncomp]);
1315204076Spjd				nv_free(nv);
1316204076Spjd				remote_close(res, ncomp);
1317204076Spjd				goto done_queue;
1318204076Spjd			}
1319204076Spjd			rw_unlock(&hio_remote_lock[ncomp]);
1320204076Spjd			break;
1321204076Spjd		case BIO_WRITE:
1322204076Spjd		case BIO_DELETE:
1323204076Spjd		case BIO_FLUSH:
1324204076Spjd			break;
1325204076Spjd		default:
1326204076Spjd			assert(!"invalid condition");
1327204076Spjd			abort();
1328204076Spjd		}
1329204076Spjd		hio->hio_errors[ncomp] = 0;
1330204076Spjd		nv_free(nv);
1331204076Spjddone_queue:
1332204076Spjd		if (refcount_release(&hio->hio_countdown)) {
1333204076Spjd			if (ISSYNCREQ(hio)) {
1334204076Spjd				mtx_lock(&sync_lock);
1335204076Spjd				SYNCREQDONE(hio);
1336204076Spjd				mtx_unlock(&sync_lock);
1337204076Spjd				cv_signal(&sync_cond);
1338204076Spjd			} else {
1339204076Spjd				pjdlog_debug(2,
1340204076Spjd				    "remote_recv: (%p) Moving request to the done queue.",
1341204076Spjd				    hio);
1342204076Spjd				QUEUE_INSERT2(hio, done);
1343204076Spjd			}
1344204076Spjd		}
1345204076Spjd	}
1346204076Spjd	/* NOTREACHED */
1347204076Spjd	return (NULL);
1348204076Spjd}
1349204076Spjd
1350204076Spjd/*
1351204076Spjd * Thread sends answer to the kernel.
1352204076Spjd */
1353204076Spjdstatic void *
1354204076Spjdggate_send_thread(void *arg)
1355204076Spjd{
1356204076Spjd	struct hast_resource *res = arg;
1357204076Spjd	struct g_gate_ctl_io *ggio;
1358204076Spjd	struct hio *hio;
1359204076Spjd	unsigned int ii, ncomp, ncomps;
1360204076Spjd
1361204076Spjd	ncomps = HAST_NCOMPONENTS;
1362204076Spjd
1363204076Spjd	for (;;) {
1364204076Spjd		pjdlog_debug(2, "ggate_send: Taking request.");
1365204076Spjd		QUEUE_TAKE2(hio, done);
1366204076Spjd		pjdlog_debug(2, "ggate_send: (%p) Got request.", hio);
1367204076Spjd		ggio = &hio->hio_ggio;
1368204076Spjd		for (ii = 0; ii < ncomps; ii++) {
1369204076Spjd			if (hio->hio_errors[ii] == 0) {
1370204076Spjd				/*
1371204076Spjd				 * One successful request is enough to declare
1372204076Spjd				 * success.
1373204076Spjd				 */
1374204076Spjd				ggio->gctl_error = 0;
1375204076Spjd				break;
1376204076Spjd			}
1377204076Spjd		}
1378204076Spjd		if (ii == ncomps) {
1379204076Spjd			/*
1380204076Spjd			 * None of the requests were successful.
1381204076Spjd			 * Use first error.
1382204076Spjd			 */
1383204076Spjd			ggio->gctl_error = hio->hio_errors[0];
1384204076Spjd		}
1385204076Spjd		if (ggio->gctl_error == 0 && ggio->gctl_cmd == BIO_WRITE) {
1386204076Spjd			mtx_lock(&res->hr_amp_lock);
1387204076Spjd			activemap_write_complete(res->hr_amp,
1388204076Spjd			    ggio->gctl_offset, ggio->gctl_length);
1389204076Spjd			mtx_unlock(&res->hr_amp_lock);
1390204076Spjd		}
1391204076Spjd		if (ggio->gctl_cmd == BIO_WRITE) {
1392204076Spjd			/*
1393204076Spjd			 * Unlock range we locked.
1394204076Spjd			 */
1395204076Spjd			mtx_lock(&range_lock);
1396204076Spjd			rangelock_del(range_regular, ggio->gctl_offset,
1397204076Spjd			    ggio->gctl_length);
1398204076Spjd			if (range_sync_wait)
1399204076Spjd				cv_signal(&range_sync_cond);
1400204076Spjd			mtx_unlock(&range_lock);
1401204076Spjd			/*
1402204076Spjd			 * Bump local count if this is first write after
1403204076Spjd			 * connection failure with remote node.
1404204076Spjd			 */
1405204076Spjd			ncomp = 1;
1406204076Spjd			rw_rlock(&hio_remote_lock[ncomp]);
1407204076Spjd			if (!ISCONNECTED(res, ncomp)) {
1408204076Spjd				mtx_lock(&metadata_lock);
1409204076Spjd				if (res->hr_primary_localcnt ==
1410204076Spjd				    res->hr_secondary_remotecnt) {
1411204076Spjd					res->hr_primary_localcnt++;
1412204076Spjd					pjdlog_debug(1,
1413204076Spjd					    "Increasing localcnt to %ju.",
1414204076Spjd					    (uintmax_t)res->hr_primary_localcnt);
1415204076Spjd					(void)metadata_write(res);
1416204076Spjd				}
1417204076Spjd				mtx_unlock(&metadata_lock);
1418204076Spjd			}
1419204076Spjd			rw_unlock(&hio_remote_lock[ncomp]);
1420204076Spjd		}
1421204076Spjd		if (ioctl(res->hr_ggatefd, G_GATE_CMD_DONE, ggio) < 0)
1422204076Spjd			primary_exit(EX_OSERR, "G_GATE_CMD_DONE failed");
1423204076Spjd		pjdlog_debug(2,
1424204076Spjd		    "ggate_send: (%p) Moving request to the free queue.", hio);
1425204076Spjd		QUEUE_INSERT2(hio, free);
1426204076Spjd	}
1427204076Spjd	/* NOTREACHED */
1428204076Spjd	return (NULL);
1429204076Spjd}
1430204076Spjd
1431204076Spjd/*
1432204076Spjd * Thread synchronize local and remote components.
1433204076Spjd */
1434204076Spjdstatic void *
1435204076Spjdsync_thread(void *arg __unused)
1436204076Spjd{
1437204076Spjd	struct hast_resource *res = arg;
1438204076Spjd	struct hio *hio;
1439204076Spjd	struct g_gate_ctl_io *ggio;
1440204076Spjd	unsigned int ii, ncomp, ncomps;
1441204076Spjd	off_t offset, length, synced;
1442204076Spjd	bool dorewind;
1443204076Spjd	int syncext;
1444204076Spjd
1445204076Spjd	ncomps = HAST_NCOMPONENTS;
1446204076Spjd	dorewind = true;
1447204076Spjd	synced = 0;
1448204076Spjd
1449204076Spjd	for (;;) {
1450204076Spjd		mtx_lock(&sync_lock);
1451204076Spjd		while (!sync_inprogress) {
1452204076Spjd			dorewind = true;
1453204076Spjd			synced = 0;
1454204076Spjd			cv_wait(&sync_cond, &sync_lock);
1455204076Spjd		}
1456204076Spjd		mtx_unlock(&sync_lock);
1457204076Spjd		/*
1458204076Spjd		 * Obtain offset at which we should synchronize.
1459204076Spjd		 * Rewind synchronization if needed.
1460204076Spjd		 */
1461204076Spjd		mtx_lock(&res->hr_amp_lock);
1462204076Spjd		if (dorewind)
1463204076Spjd			activemap_sync_rewind(res->hr_amp);
1464204076Spjd		offset = activemap_sync_offset(res->hr_amp, &length, &syncext);
1465204076Spjd		if (syncext != -1) {
1466204076Spjd			/*
1467204076Spjd			 * We synchronized entire syncext extent, we can mark
1468204076Spjd			 * it as clean now.
1469204076Spjd			 */
1470204076Spjd			if (activemap_extent_complete(res->hr_amp, syncext))
1471204076Spjd				(void)hast_activemap_flush(res);
1472204076Spjd		}
1473204076Spjd		mtx_unlock(&res->hr_amp_lock);
1474204076Spjd		if (dorewind) {
1475204076Spjd			dorewind = false;
1476204076Spjd			if (offset < 0)
1477204076Spjd				pjdlog_info("Nodes are in sync.");
1478204076Spjd			else {
1479204076Spjd				pjdlog_info("Synchronization started. %ju bytes to go.",
1480204076Spjd				    (uintmax_t)(res->hr_extentsize *
1481204076Spjd				    activemap_ndirty(res->hr_amp)));
1482204076Spjd			}
1483204076Spjd		}
1484204076Spjd		if (offset < 0) {
1485204076Spjd			mtx_lock(&sync_lock);
1486204076Spjd			sync_inprogress = false;
1487204076Spjd			mtx_unlock(&sync_lock);
1488204076Spjd			pjdlog_debug(1, "Nothing to synchronize.");
1489204076Spjd			/*
1490204076Spjd			 * Synchronization complete, make both localcnt and
1491204076Spjd			 * remotecnt equal.
1492204076Spjd			 */
1493204076Spjd			ncomp = 1;
1494204076Spjd			rw_rlock(&hio_remote_lock[ncomp]);
1495204076Spjd			if (ISCONNECTED(res, ncomp)) {
1496204076Spjd				if (synced > 0) {
1497204076Spjd					pjdlog_info("Synchronization complete. "
1498204076Spjd					    "%jd bytes synchronized.",
1499204076Spjd					    (intmax_t)synced);
1500204076Spjd				}
1501204076Spjd				mtx_lock(&metadata_lock);
1502204076Spjd				res->hr_syncsrc = HAST_SYNCSRC_UNDEF;
1503204076Spjd				res->hr_primary_localcnt =
1504204076Spjd				    res->hr_secondary_localcnt;
1505204076Spjd				res->hr_primary_remotecnt =
1506204076Spjd				    res->hr_secondary_remotecnt;
1507204076Spjd				pjdlog_debug(1,
1508204076Spjd				    "Setting localcnt to %ju and remotecnt to %ju.",
1509204076Spjd				    (uintmax_t)res->hr_primary_localcnt,
1510204076Spjd				    (uintmax_t)res->hr_secondary_localcnt);
1511204076Spjd				(void)metadata_write(res);
1512204076Spjd				mtx_unlock(&metadata_lock);
1513204076Spjd			} else if (synced > 0) {
1514204076Spjd				pjdlog_info("Synchronization interrupted. "
1515204076Spjd				    "%jd bytes synchronized so far.",
1516204076Spjd				    (intmax_t)synced);
1517204076Spjd			}
1518204076Spjd			rw_unlock(&hio_remote_lock[ncomp]);
1519204076Spjd			continue;
1520204076Spjd		}
1521204076Spjd		pjdlog_debug(2, "sync: Taking free request.");
1522204076Spjd		QUEUE_TAKE2(hio, free);
1523204076Spjd		pjdlog_debug(2, "sync: (%p) Got free request.", hio);
1524204076Spjd		/*
1525204076Spjd		 * Lock the range we are going to synchronize. We don't want
1526204076Spjd		 * race where someone writes between our read and write.
1527204076Spjd		 */
1528204076Spjd		for (;;) {
1529204076Spjd			mtx_lock(&range_lock);
1530204076Spjd			if (rangelock_islocked(range_regular, offset, length)) {
1531204076Spjd				pjdlog_debug(2,
1532204076Spjd				    "sync: Range offset=%jd length=%jd locked.",
1533204076Spjd				    (intmax_t)offset, (intmax_t)length);
1534204076Spjd				range_sync_wait = true;
1535204076Spjd				cv_wait(&range_sync_cond, &range_lock);
1536204076Spjd				range_sync_wait = false;
1537204076Spjd				mtx_unlock(&range_lock);
1538204076Spjd				continue;
1539204076Spjd			}
1540204076Spjd			if (rangelock_add(range_sync, offset, length) < 0) {
1541204076Spjd				mtx_unlock(&range_lock);
1542204076Spjd				pjdlog_debug(2,
1543204076Spjd				    "sync: Range offset=%jd length=%jd is already locked, waiting.",
1544204076Spjd				    (intmax_t)offset, (intmax_t)length);
1545204076Spjd				sleep(1);
1546204076Spjd				continue;
1547204076Spjd			}
1548204076Spjd			mtx_unlock(&range_lock);
1549204076Spjd			break;
1550204076Spjd		}
1551204076Spjd		/*
1552204076Spjd		 * First read the data from synchronization source.
1553204076Spjd		 */
1554204076Spjd		SYNCREQ(hio);
1555204076Spjd		ggio = &hio->hio_ggio;
1556204076Spjd		ggio->gctl_cmd = BIO_READ;
1557204076Spjd		ggio->gctl_offset = offset;
1558204076Spjd		ggio->gctl_length = length;
1559204076Spjd		ggio->gctl_error = 0;
1560204076Spjd		for (ii = 0; ii < ncomps; ii++)
1561204076Spjd			hio->hio_errors[ii] = EINVAL;
1562204076Spjd		reqlog(LOG_DEBUG, 2, ggio, "sync: (%p) Sending sync request: ",
1563204076Spjd		    hio);
1564204076Spjd		pjdlog_debug(2, "sync: (%p) Moving request to the send queue.",
1565204076Spjd		    hio);
1566204076Spjd		mtx_lock(&metadata_lock);
1567204076Spjd		if (res->hr_syncsrc == HAST_SYNCSRC_PRIMARY) {
1568204076Spjd			/*
1569204076Spjd			 * This range is up-to-date on local component,
1570204076Spjd			 * so handle request locally.
1571204076Spjd			 */
1572204076Spjd			 /* Local component is 0 for now. */
1573204076Spjd			ncomp = 0;
1574204076Spjd		} else /* if (res->hr_syncsrc == HAST_SYNCSRC_SECONDARY) */ {
1575204076Spjd			assert(res->hr_syncsrc == HAST_SYNCSRC_SECONDARY);
1576204076Spjd			/*
1577204076Spjd			 * This range is out-of-date on local component,
1578204076Spjd			 * so send request to the remote node.
1579204076Spjd			 */
1580204076Spjd			 /* Remote component is 1 for now. */
1581204076Spjd			ncomp = 1;
1582204076Spjd		}
1583204076Spjd		mtx_unlock(&metadata_lock);
1584204076Spjd		refcount_init(&hio->hio_countdown, 1);
1585204076Spjd		QUEUE_INSERT1(hio, send, ncomp);
1586204076Spjd
1587204076Spjd		/*
1588204076Spjd		 * Let's wait for READ to finish.
1589204076Spjd		 */
1590204076Spjd		mtx_lock(&sync_lock);
1591204076Spjd		while (!ISSYNCREQDONE(hio))
1592204076Spjd			cv_wait(&sync_cond, &sync_lock);
1593204076Spjd		mtx_unlock(&sync_lock);
1594204076Spjd
1595204076Spjd		if (hio->hio_errors[ncomp] != 0) {
1596204076Spjd			pjdlog_error("Unable to read synchronization data: %s.",
1597204076Spjd			    strerror(hio->hio_errors[ncomp]));
1598204076Spjd			goto free_queue;
1599204076Spjd		}
1600204076Spjd
1601204076Spjd		/*
1602204076Spjd		 * We read the data from synchronization source, now write it
1603204076Spjd		 * to synchronization target.
1604204076Spjd		 */
1605204076Spjd		SYNCREQ(hio);
1606204076Spjd		ggio->gctl_cmd = BIO_WRITE;
1607204076Spjd		for (ii = 0; ii < ncomps; ii++)
1608204076Spjd			hio->hio_errors[ii] = EINVAL;
1609204076Spjd		reqlog(LOG_DEBUG, 2, ggio, "sync: (%p) Sending sync request: ",
1610204076Spjd		    hio);
1611204076Spjd		pjdlog_debug(2, "sync: (%p) Moving request to the send queue.",
1612204076Spjd		    hio);
1613204076Spjd		mtx_lock(&metadata_lock);
1614204076Spjd		if (res->hr_syncsrc == HAST_SYNCSRC_PRIMARY) {
1615204076Spjd			/*
1616204076Spjd			 * This range is up-to-date on local component,
1617204076Spjd			 * so we update remote component.
1618204076Spjd			 */
1619204076Spjd			 /* Remote component is 1 for now. */
1620204076Spjd			ncomp = 1;
1621204076Spjd		} else /* if (res->hr_syncsrc == HAST_SYNCSRC_SECONDARY) */ {
1622204076Spjd			assert(res->hr_syncsrc == HAST_SYNCSRC_SECONDARY);
1623204076Spjd			/*
1624204076Spjd			 * This range is out-of-date on local component,
1625204076Spjd			 * so we update it.
1626204076Spjd			 */
1627204076Spjd			 /* Local component is 0 for now. */
1628204076Spjd			ncomp = 0;
1629204076Spjd		}
1630204076Spjd		mtx_unlock(&metadata_lock);
1631204076Spjd
1632204076Spjd		pjdlog_debug(2, "sync: (%p) Moving request to the send queues.",
1633204076Spjd		    hio);
1634204076Spjd		refcount_init(&hio->hio_countdown, 1);
1635204076Spjd		QUEUE_INSERT1(hio, send, ncomp);
1636204076Spjd
1637204076Spjd		/*
1638204076Spjd		 * Let's wait for WRITE to finish.
1639204076Spjd		 */
1640204076Spjd		mtx_lock(&sync_lock);
1641204076Spjd		while (!ISSYNCREQDONE(hio))
1642204076Spjd			cv_wait(&sync_cond, &sync_lock);
1643204076Spjd		mtx_unlock(&sync_lock);
1644204076Spjd
1645204076Spjd		if (hio->hio_errors[ncomp] != 0) {
1646204076Spjd			pjdlog_error("Unable to write synchronization data: %s.",
1647204076Spjd			    strerror(hio->hio_errors[ncomp]));
1648204076Spjd			goto free_queue;
1649204076Spjd		}
1650204076Spjdfree_queue:
1651204076Spjd		mtx_lock(&range_lock);
1652204076Spjd		rangelock_del(range_sync, offset, length);
1653204076Spjd		if (range_regular_wait)
1654204076Spjd			cv_signal(&range_regular_cond);
1655204076Spjd		mtx_unlock(&range_lock);
1656204076Spjd
1657204076Spjd		synced += length;
1658204076Spjd
1659204076Spjd		pjdlog_debug(2, "sync: (%p) Moving request to the free queue.",
1660204076Spjd		    hio);
1661204076Spjd		QUEUE_INSERT2(hio, free);
1662204076Spjd	}
1663204076Spjd	/* NOTREACHED */
1664204076Spjd	return (NULL);
1665204076Spjd}
1666204076Spjd
1667204076Spjdstatic void
1668204076Spjdsighandler(int sig)
1669204076Spjd{
1670204076Spjd	bool unlock;
1671204076Spjd
1672204076Spjd	switch (sig) {
1673204076Spjd	case SIGINT:
1674204076Spjd	case SIGTERM:
1675204076Spjd		sigexit_received = true;
1676204076Spjd		break;
1677204076Spjd	default:
1678204076Spjd		assert(!"invalid condition");
1679204076Spjd	}
1680204076Spjd	/*
1681204076Spjd	 * XXX: Racy, but if we cannot obtain hio_guard_lock here, we don't
1682204076Spjd	 * want to risk deadlock.
1683204076Spjd	 */
1684204076Spjd	unlock = mtx_trylock(&hio_guard_lock);
1685204076Spjd	cv_signal(&hio_guard_cond);
1686204076Spjd	if (unlock)
1687204076Spjd		mtx_unlock(&hio_guard_lock);
1688204076Spjd}
1689204076Spjd
1690204076Spjd/*
1691204076Spjd * Thread guards remote connections and reconnects when needed, handles
1692204076Spjd * signals, etc.
1693204076Spjd */
1694204076Spjdstatic void *
1695204076Spjdguard_thread(void *arg)
1696204076Spjd{
1697204076Spjd	struct hast_resource *res = arg;
1698204076Spjd	unsigned int ii, ncomps;
1699204076Spjd	int timeout;
1700204076Spjd
1701204076Spjd	ncomps = HAST_NCOMPONENTS;
1702204076Spjd	/* The is only one remote component for now. */
1703204076Spjd#define	ISREMOTE(no)	((no) == 1)
1704204076Spjd
1705204076Spjd	for (;;) {
1706204076Spjd		if (sigexit_received) {
1707204076Spjd			primary_exitx(EX_OK,
1708204076Spjd			    "Termination signal received, exiting.");
1709204076Spjd		}
1710204076Spjd		/*
1711204076Spjd		 * If all the connection will be fine, we will sleep until
1712204076Spjd		 * someone wakes us up.
1713204076Spjd		 * If any of the connections will be broken and we won't be
1714204076Spjd		 * able to connect, we will sleep only for RECONNECT_SLEEP
1715204076Spjd		 * seconds so we can retry soon.
1716204076Spjd		 */
1717204076Spjd		timeout = 0;
1718204076Spjd		pjdlog_debug(2, "remote_guard: Checking connections.");
1719204076Spjd		mtx_lock(&hio_guard_lock);
1720204076Spjd		for (ii = 0; ii < ncomps; ii++) {
1721204076Spjd			if (!ISREMOTE(ii))
1722204076Spjd				continue;
1723204076Spjd			rw_rlock(&hio_remote_lock[ii]);
1724204076Spjd			if (ISCONNECTED(res, ii)) {
1725204076Spjd				assert(res->hr_remotein != NULL);
1726204076Spjd				assert(res->hr_remoteout != NULL);
1727204076Spjd				rw_unlock(&hio_remote_lock[ii]);
1728204076Spjd				pjdlog_debug(2,
1729204076Spjd				    "remote_guard: Connection to %s is ok.",
1730204076Spjd				    res->hr_remoteaddr);
1731204076Spjd			} else {
1732204076Spjd				assert(res->hr_remotein == NULL);
1733204076Spjd				assert(res->hr_remoteout == NULL);
1734204076Spjd				/*
1735204076Spjd				 * Upgrade the lock. It doesn't have to be
1736204076Spjd				 * atomic as no other thread can change
1737204076Spjd				 * connection status from disconnected to
1738204076Spjd				 * connected.
1739204076Spjd				 */
1740204076Spjd				rw_unlock(&hio_remote_lock[ii]);
1741204076Spjd				rw_wlock(&hio_remote_lock[ii]);
1742204076Spjd				assert(res->hr_remotein == NULL);
1743204076Spjd				assert(res->hr_remoteout == NULL);
1744204076Spjd				pjdlog_debug(2,
1745204076Spjd				    "remote_guard: Reconnecting to %s.",
1746204076Spjd				    res->hr_remoteaddr);
1747204076Spjd				init_remote(res);
1748204076Spjd				if (ISCONNECTED(res, ii)) {
1749204076Spjd					pjdlog_info("Successfully reconnected to %s.",
1750204076Spjd					    res->hr_remoteaddr);
1751204076Spjd				} else {
1752204076Spjd					/* Both connections should be NULL. */
1753204076Spjd					assert(res->hr_remotein == NULL);
1754204076Spjd					assert(res->hr_remoteout == NULL);
1755204076Spjd					pjdlog_debug(2,
1756204076Spjd					    "remote_guard: Reconnect to %s failed.",
1757204076Spjd					    res->hr_remoteaddr);
1758204076Spjd					timeout = RECONNECT_SLEEP;
1759204076Spjd				}
1760204076Spjd				rw_unlock(&hio_remote_lock[ii]);
1761204076Spjd			}
1762204076Spjd		}
1763204076Spjd		(void)cv_timedwait(&hio_guard_cond, &hio_guard_lock, timeout);
1764204076Spjd		mtx_unlock(&hio_guard_lock);
1765204076Spjd	}
1766204076Spjd#undef	ISREMOTE
1767204076Spjd	/* NOTREACHED */
1768204076Spjd	return (NULL);
1769204076Spjd}
1770