primary.c revision 205738
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 205738 2010-03-27 16:35:07Z 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
463205738Spjdstatic bool
464205738Spjdinit_remote(struct hast_resource *res, struct proto_conn **inp,
465205738Spjd    struct proto_conn **outp)
466204076Spjd{
467205738Spjd	struct proto_conn *in, *out;
468204076Spjd	struct nv *nvout, *nvin;
469204076Spjd	const unsigned char *token;
470204076Spjd	unsigned char *map;
471204076Spjd	const char *errmsg;
472204076Spjd	int32_t extentsize;
473204076Spjd	int64_t datasize;
474204076Spjd	uint32_t mapsize;
475204076Spjd	size_t size;
476204076Spjd
477205738Spjd	assert((inp == NULL && outp == NULL) || (inp != NULL && outp != NULL));
478205738Spjd
479205738Spjd	in = out = NULL;
480205738Spjd
481204076Spjd	/* Prepare outgoing connection with remote node. */
482205738Spjd	if (proto_client(res->hr_remoteaddr, &out) < 0) {
483204076Spjd		primary_exit(EX_OSERR, "Unable to create connection to %s",
484204076Spjd		    res->hr_remoteaddr);
485204076Spjd	}
486204076Spjd	/* Try to connect, but accept failure. */
487205738Spjd	if (proto_connect(out) < 0) {
488204076Spjd		pjdlog_errno(LOG_WARNING, "Unable to connect to %s",
489204076Spjd		    res->hr_remoteaddr);
490204076Spjd		goto close;
491204076Spjd	}
492204076Spjd	/*
493204076Spjd	 * First handshake step.
494204076Spjd	 * Setup outgoing connection with remote node.
495204076Spjd	 */
496204076Spjd	nvout = nv_alloc();
497204076Spjd	nv_add_string(nvout, res->hr_name, "resource");
498204076Spjd	if (nv_error(nvout) != 0) {
499204076Spjd		pjdlog_common(LOG_WARNING, 0, nv_error(nvout),
500204076Spjd		    "Unable to allocate header for connection with %s",
501204076Spjd		    res->hr_remoteaddr);
502204076Spjd		nv_free(nvout);
503204076Spjd		goto close;
504204076Spjd	}
505205738Spjd	if (hast_proto_send(res, out, nvout, NULL, 0) < 0) {
506204076Spjd		pjdlog_errno(LOG_WARNING,
507204076Spjd		    "Unable to send handshake header to %s",
508204076Spjd		    res->hr_remoteaddr);
509204076Spjd		nv_free(nvout);
510204076Spjd		goto close;
511204076Spjd	}
512204076Spjd	nv_free(nvout);
513205738Spjd	if (hast_proto_recv_hdr(out, &nvin) < 0) {
514204076Spjd		pjdlog_errno(LOG_WARNING,
515204076Spjd		    "Unable to receive handshake header from %s",
516204076Spjd		    res->hr_remoteaddr);
517204076Spjd		goto close;
518204076Spjd	}
519204076Spjd	errmsg = nv_get_string(nvin, "errmsg");
520204076Spjd	if (errmsg != NULL) {
521204076Spjd		pjdlog_warning("%s", errmsg);
522204076Spjd		nv_free(nvin);
523204076Spjd		goto close;
524204076Spjd	}
525204076Spjd	token = nv_get_uint8_array(nvin, &size, "token");
526204076Spjd	if (token == NULL) {
527204076Spjd		pjdlog_warning("Handshake header from %s has no 'token' field.",
528204076Spjd		    res->hr_remoteaddr);
529204076Spjd		nv_free(nvin);
530204076Spjd		goto close;
531204076Spjd	}
532204076Spjd	if (size != sizeof(res->hr_token)) {
533204076Spjd		pjdlog_warning("Handshake header from %s contains 'token' of wrong size (got %zu, expected %zu).",
534204076Spjd		    res->hr_remoteaddr, size, sizeof(res->hr_token));
535204076Spjd		nv_free(nvin);
536204076Spjd		goto close;
537204076Spjd	}
538204076Spjd	bcopy(token, res->hr_token, sizeof(res->hr_token));
539204076Spjd	nv_free(nvin);
540204076Spjd
541204076Spjd	/*
542204076Spjd	 * Second handshake step.
543204076Spjd	 * Setup incoming connection with remote node.
544204076Spjd	 */
545205738Spjd	if (proto_client(res->hr_remoteaddr, &in) < 0) {
546204076Spjd		pjdlog_errno(LOG_WARNING, "Unable to create connection to %s",
547204076Spjd		    res->hr_remoteaddr);
548204076Spjd	}
549204076Spjd	/* Try to connect, but accept failure. */
550205738Spjd	if (proto_connect(in) < 0) {
551204076Spjd		pjdlog_errno(LOG_WARNING, "Unable to connect to %s",
552204076Spjd		    res->hr_remoteaddr);
553204076Spjd		goto close;
554204076Spjd	}
555204076Spjd	nvout = nv_alloc();
556204076Spjd	nv_add_string(nvout, res->hr_name, "resource");
557204076Spjd	nv_add_uint8_array(nvout, res->hr_token, sizeof(res->hr_token),
558204076Spjd	    "token");
559204076Spjd	nv_add_uint64(nvout, res->hr_resuid, "resuid");
560204076Spjd	nv_add_uint64(nvout, res->hr_primary_localcnt, "localcnt");
561204076Spjd	nv_add_uint64(nvout, res->hr_primary_remotecnt, "remotecnt");
562204076Spjd	if (nv_error(nvout) != 0) {
563204076Spjd		pjdlog_common(LOG_WARNING, 0, nv_error(nvout),
564204076Spjd		    "Unable to allocate header for connection with %s",
565204076Spjd		    res->hr_remoteaddr);
566204076Spjd		nv_free(nvout);
567204076Spjd		goto close;
568204076Spjd	}
569205738Spjd	if (hast_proto_send(res, in, nvout, NULL, 0) < 0) {
570204076Spjd		pjdlog_errno(LOG_WARNING,
571204076Spjd		    "Unable to send handshake header to %s",
572204076Spjd		    res->hr_remoteaddr);
573204076Spjd		nv_free(nvout);
574204076Spjd		goto close;
575204076Spjd	}
576204076Spjd	nv_free(nvout);
577205738Spjd	if (hast_proto_recv_hdr(out, &nvin) < 0) {
578204076Spjd		pjdlog_errno(LOG_WARNING,
579204076Spjd		    "Unable to receive handshake header from %s",
580204076Spjd		    res->hr_remoteaddr);
581204076Spjd		goto close;
582204076Spjd	}
583204076Spjd	errmsg = nv_get_string(nvin, "errmsg");
584204076Spjd	if (errmsg != NULL) {
585204076Spjd		pjdlog_warning("%s", errmsg);
586204076Spjd		nv_free(nvin);
587204076Spjd		goto close;
588204076Spjd	}
589204076Spjd	datasize = nv_get_int64(nvin, "datasize");
590204076Spjd	if (datasize != res->hr_datasize) {
591204076Spjd		pjdlog_warning("Data size differs between nodes (local=%jd, remote=%jd).",
592204076Spjd		    (intmax_t)res->hr_datasize, (intmax_t)datasize);
593204076Spjd		nv_free(nvin);
594204076Spjd		goto close;
595204076Spjd	}
596204076Spjd	extentsize = nv_get_int32(nvin, "extentsize");
597204076Spjd	if (extentsize != res->hr_extentsize) {
598204076Spjd		pjdlog_warning("Extent size differs between nodes (local=%zd, remote=%zd).",
599204076Spjd		    (ssize_t)res->hr_extentsize, (ssize_t)extentsize);
600204076Spjd		nv_free(nvin);
601204076Spjd		goto close;
602204076Spjd	}
603204076Spjd	res->hr_secondary_localcnt = nv_get_uint64(nvin, "localcnt");
604204076Spjd	res->hr_secondary_remotecnt = nv_get_uint64(nvin, "remotecnt");
605204076Spjd	res->hr_syncsrc = nv_get_uint8(nvin, "syncsrc");
606204076Spjd	map = NULL;
607204076Spjd	mapsize = nv_get_uint32(nvin, "mapsize");
608204076Spjd	if (mapsize > 0) {
609204076Spjd		map = malloc(mapsize);
610204076Spjd		if (map == NULL) {
611204076Spjd			pjdlog_error("Unable to allocate memory for remote activemap (mapsize=%ju).",
612204076Spjd			    (uintmax_t)mapsize);
613204076Spjd			nv_free(nvin);
614204076Spjd			goto close;
615204076Spjd		}
616204076Spjd		/*
617204076Spjd		 * Remote node have some dirty extents on its own, lets
618204076Spjd		 * download its activemap.
619204076Spjd		 */
620205738Spjd		if (hast_proto_recv_data(res, out, nvin, map,
621204076Spjd		    mapsize) < 0) {
622204076Spjd			pjdlog_errno(LOG_ERR,
623204076Spjd			    "Unable to receive remote activemap");
624204076Spjd			nv_free(nvin);
625204076Spjd			free(map);
626204076Spjd			goto close;
627204076Spjd		}
628204076Spjd		/*
629204076Spjd		 * Merge local and remote bitmaps.
630204076Spjd		 */
631204076Spjd		activemap_merge(res->hr_amp, map, mapsize);
632204076Spjd		free(map);
633204076Spjd		/*
634204076Spjd		 * Now that we merged bitmaps from both nodes, flush it to the
635204076Spjd		 * disk before we start to synchronize.
636204076Spjd		 */
637204076Spjd		(void)hast_activemap_flush(res);
638204076Spjd	}
639204076Spjd	pjdlog_info("Connected to %s.", res->hr_remoteaddr);
640205738Spjd	if (inp != NULL && outp != NULL) {
641205738Spjd		*inp = in;
642205738Spjd		*outp = out;
643205738Spjd	} else {
644205738Spjd		res->hr_remotein = in;
645205738Spjd		res->hr_remoteout = out;
646205738Spjd	}
647205738Spjd	return (true);
648205738Spjdclose:
649205738Spjd	proto_close(out);
650205738Spjd	if (in != NULL)
651205738Spjd		proto_close(in);
652205738Spjd	return (false);
653205738Spjd}
654205738Spjd
655205738Spjdstatic void
656205738Spjdsync_start(void)
657205738Spjd{
658205738Spjd
659204076Spjd	mtx_lock(&sync_lock);
660204076Spjd	sync_inprogress = true;
661204076Spjd	mtx_unlock(&sync_lock);
662204076Spjd	cv_signal(&sync_cond);
663204076Spjd}
664204076Spjd
665204076Spjdstatic void
666204076Spjdinit_ggate(struct hast_resource *res)
667204076Spjd{
668204076Spjd	struct g_gate_ctl_create ggiocreate;
669204076Spjd	struct g_gate_ctl_cancel ggiocancel;
670204076Spjd
671204076Spjd	/*
672204076Spjd	 * We communicate with ggate via /dev/ggctl. Open it.
673204076Spjd	 */
674204076Spjd	res->hr_ggatefd = open("/dev/" G_GATE_CTL_NAME, O_RDWR);
675204076Spjd	if (res->hr_ggatefd < 0)
676204076Spjd		primary_exit(EX_OSFILE, "Unable to open /dev/" G_GATE_CTL_NAME);
677204076Spjd	/*
678204076Spjd	 * Create provider before trying to connect, as connection failure
679204076Spjd	 * is not critical, but may take some time.
680204076Spjd	 */
681204076Spjd	ggiocreate.gctl_version = G_GATE_VERSION;
682204076Spjd	ggiocreate.gctl_mediasize = res->hr_datasize;
683204076Spjd	ggiocreate.gctl_sectorsize = res->hr_local_sectorsize;
684204076Spjd	ggiocreate.gctl_flags = 0;
685204076Spjd	ggiocreate.gctl_maxcount = 128;
686204076Spjd	ggiocreate.gctl_timeout = 0;
687204076Spjd	ggiocreate.gctl_unit = G_GATE_NAME_GIVEN;
688204076Spjd	snprintf(ggiocreate.gctl_name, sizeof(ggiocreate.gctl_name), "hast/%s",
689204076Spjd	    res->hr_provname);
690204076Spjd	bzero(ggiocreate.gctl_info, sizeof(ggiocreate.gctl_info));
691204076Spjd	if (ioctl(res->hr_ggatefd, G_GATE_CMD_CREATE, &ggiocreate) == 0) {
692204076Spjd		pjdlog_info("Device hast/%s created.", res->hr_provname);
693204076Spjd		res->hr_ggateunit = ggiocreate.gctl_unit;
694204076Spjd		return;
695204076Spjd	}
696204076Spjd	if (errno != EEXIST) {
697204076Spjd		primary_exit(EX_OSERR, "Unable to create hast/%s device",
698204076Spjd		    res->hr_provname);
699204076Spjd	}
700204076Spjd	pjdlog_debug(1,
701204076Spjd	    "Device hast/%s already exists, we will try to take it over.",
702204076Spjd	    res->hr_provname);
703204076Spjd	/*
704204076Spjd	 * If we received EEXIST, we assume that the process who created the
705204076Spjd	 * provider died and didn't clean up. In that case we will start from
706204076Spjd	 * where he left of.
707204076Spjd	 */
708204076Spjd	ggiocancel.gctl_version = G_GATE_VERSION;
709204076Spjd	ggiocancel.gctl_unit = G_GATE_NAME_GIVEN;
710204076Spjd	snprintf(ggiocancel.gctl_name, sizeof(ggiocancel.gctl_name), "hast/%s",
711204076Spjd	    res->hr_provname);
712204076Spjd	if (ioctl(res->hr_ggatefd, G_GATE_CMD_CANCEL, &ggiocancel) == 0) {
713204076Spjd		pjdlog_info("Device hast/%s recovered.", res->hr_provname);
714204076Spjd		res->hr_ggateunit = ggiocancel.gctl_unit;
715204076Spjd		return;
716204076Spjd	}
717204076Spjd	primary_exit(EX_OSERR, "Unable to take over hast/%s device",
718204076Spjd	    res->hr_provname);
719204076Spjd}
720204076Spjd
721204076Spjdvoid
722204076Spjdhastd_primary(struct hast_resource *res)
723204076Spjd{
724204076Spjd	pthread_t td;
725204076Spjd	pid_t pid;
726204076Spjd	int error;
727204076Spjd
728204076Spjd	gres = res;
729204076Spjd
730204076Spjd	/*
731204076Spjd	 * Create communication channel between parent and child.
732204076Spjd	 */
733204076Spjd	if (proto_client("socketpair://", &res->hr_ctrl) < 0) {
734204076Spjd		KEEP_ERRNO((void)pidfile_remove(pfh));
735204076Spjd		primary_exit(EX_OSERR,
736204076Spjd		    "Unable to create control sockets between parent and child");
737204076Spjd	}
738204076Spjd
739204076Spjd	pid = fork();
740204076Spjd	if (pid < 0) {
741204076Spjd		KEEP_ERRNO((void)pidfile_remove(pfh));
742204076Spjd		primary_exit(EX_OSERR, "Unable to fork");
743204076Spjd	}
744204076Spjd
745204076Spjd	if (pid > 0) {
746204076Spjd		/* This is parent. */
747204076Spjd		res->hr_workerpid = pid;
748204076Spjd		return;
749204076Spjd	}
750204076Spjd	(void)pidfile_close(pfh);
751204076Spjd
752204076Spjd	setproctitle("%s (primary)", res->hr_name);
753204076Spjd
754204076Spjd	init_local(res);
755205738Spjd	if (init_remote(res, NULL, NULL))
756205738Spjd		sync_start();
757204076Spjd	init_ggate(res);
758204076Spjd	init_environment(res);
759204076Spjd	error = pthread_create(&td, NULL, ggate_recv_thread, res);
760204076Spjd	assert(error == 0);
761204076Spjd	error = pthread_create(&td, NULL, local_send_thread, res);
762204076Spjd	assert(error == 0);
763204076Spjd	error = pthread_create(&td, NULL, remote_send_thread, res);
764204076Spjd	assert(error == 0);
765204076Spjd	error = pthread_create(&td, NULL, remote_recv_thread, res);
766204076Spjd	assert(error == 0);
767204076Spjd	error = pthread_create(&td, NULL, ggate_send_thread, res);
768204076Spjd	assert(error == 0);
769204076Spjd	error = pthread_create(&td, NULL, sync_thread, res);
770204076Spjd	assert(error == 0);
771204076Spjd	error = pthread_create(&td, NULL, ctrl_thread, res);
772204076Spjd	assert(error == 0);
773204076Spjd	(void)guard_thread(res);
774204076Spjd}
775204076Spjd
776204076Spjdstatic void
777204076Spjdreqlog(int loglevel, int debuglevel, struct g_gate_ctl_io *ggio, const char *fmt, ...)
778204076Spjd{
779204076Spjd	char msg[1024];
780204076Spjd	va_list ap;
781204076Spjd	int len;
782204076Spjd
783204076Spjd	va_start(ap, fmt);
784204076Spjd	len = vsnprintf(msg, sizeof(msg), fmt, ap);
785204076Spjd	va_end(ap);
786204076Spjd	if ((size_t)len < sizeof(msg)) {
787204076Spjd		switch (ggio->gctl_cmd) {
788204076Spjd		case BIO_READ:
789204076Spjd			(void)snprintf(msg + len, sizeof(msg) - len,
790204076Spjd			    "READ(%ju, %ju).", (uintmax_t)ggio->gctl_offset,
791204076Spjd			    (uintmax_t)ggio->gctl_length);
792204076Spjd			break;
793204076Spjd		case BIO_DELETE:
794204076Spjd			(void)snprintf(msg + len, sizeof(msg) - len,
795204076Spjd			    "DELETE(%ju, %ju).", (uintmax_t)ggio->gctl_offset,
796204076Spjd			    (uintmax_t)ggio->gctl_length);
797204076Spjd			break;
798204076Spjd		case BIO_FLUSH:
799204076Spjd			(void)snprintf(msg + len, sizeof(msg) - len, "FLUSH.");
800204076Spjd			break;
801204076Spjd		case BIO_WRITE:
802204076Spjd			(void)snprintf(msg + len, sizeof(msg) - len,
803204076Spjd			    "WRITE(%ju, %ju).", (uintmax_t)ggio->gctl_offset,
804204076Spjd			    (uintmax_t)ggio->gctl_length);
805204076Spjd			break;
806204076Spjd		default:
807204076Spjd			(void)snprintf(msg + len, sizeof(msg) - len,
808204076Spjd			    "UNKNOWN(%u).", (unsigned int)ggio->gctl_cmd);
809204076Spjd			break;
810204076Spjd		}
811204076Spjd	}
812204076Spjd	pjdlog_common(loglevel, debuglevel, -1, "%s", msg);
813204076Spjd}
814204076Spjd
815204076Spjdstatic void
816204076Spjdremote_close(struct hast_resource *res, int ncomp)
817204076Spjd{
818204076Spjd
819204076Spjd	rw_wlock(&hio_remote_lock[ncomp]);
820204076Spjd	/*
821204076Spjd	 * A race is possible between dropping rlock and acquiring wlock -
822204076Spjd	 * another thread can close connection in-between.
823204076Spjd	 */
824204076Spjd	if (!ISCONNECTED(res, ncomp)) {
825204076Spjd		assert(res->hr_remotein == NULL);
826204076Spjd		assert(res->hr_remoteout == NULL);
827204076Spjd		rw_unlock(&hio_remote_lock[ncomp]);
828204076Spjd		return;
829204076Spjd	}
830204076Spjd
831204076Spjd	assert(res->hr_remotein != NULL);
832204076Spjd	assert(res->hr_remoteout != NULL);
833204076Spjd
834204076Spjd	pjdlog_debug(2, "Closing old incoming connection to %s.",
835204076Spjd	    res->hr_remoteaddr);
836204076Spjd	proto_close(res->hr_remotein);
837204076Spjd	res->hr_remotein = NULL;
838204076Spjd	pjdlog_debug(2, "Closing old outgoing connection to %s.",
839204076Spjd	    res->hr_remoteaddr);
840204076Spjd	proto_close(res->hr_remoteout);
841204076Spjd	res->hr_remoteout = NULL;
842204076Spjd
843204076Spjd	rw_unlock(&hio_remote_lock[ncomp]);
844204076Spjd
845204076Spjd	/*
846204076Spjd	 * Stop synchronization if in-progress.
847204076Spjd	 */
848204076Spjd	mtx_lock(&sync_lock);
849204076Spjd	if (sync_inprogress)
850204076Spjd		sync_inprogress = false;
851204076Spjd	mtx_unlock(&sync_lock);
852204076Spjd
853204076Spjd	/*
854204076Spjd	 * Wake up guard thread, so it can immediately start reconnect.
855204076Spjd	 */
856204076Spjd	mtx_lock(&hio_guard_lock);
857204076Spjd	cv_signal(&hio_guard_cond);
858204076Spjd	mtx_unlock(&hio_guard_lock);
859204076Spjd}
860204076Spjd
861204076Spjd/*
862204076Spjd * Thread receives ggate I/O requests from the kernel and passes them to
863204076Spjd * appropriate threads:
864204076Spjd * WRITE - always goes to both local_send and remote_send threads
865204076Spjd * READ (when the block is up-to-date on local component) -
866204076Spjd *	only local_send thread
867204076Spjd * READ (when the block isn't up-to-date on local component) -
868204076Spjd *	only remote_send thread
869204076Spjd * DELETE - always goes to both local_send and remote_send threads
870204076Spjd * FLUSH - always goes to both local_send and remote_send threads
871204076Spjd */
872204076Spjdstatic void *
873204076Spjdggate_recv_thread(void *arg)
874204076Spjd{
875204076Spjd	struct hast_resource *res = arg;
876204076Spjd	struct g_gate_ctl_io *ggio;
877204076Spjd	struct hio *hio;
878204076Spjd	unsigned int ii, ncomp, ncomps;
879204076Spjd	int error;
880204076Spjd
881204076Spjd	ncomps = HAST_NCOMPONENTS;
882204076Spjd
883204076Spjd	for (;;) {
884204076Spjd		pjdlog_debug(2, "ggate_recv: Taking free request.");
885204076Spjd		QUEUE_TAKE2(hio, free);
886204076Spjd		pjdlog_debug(2, "ggate_recv: (%p) Got free request.", hio);
887204076Spjd		ggio = &hio->hio_ggio;
888204076Spjd		ggio->gctl_unit = res->hr_ggateunit;
889204076Spjd		ggio->gctl_length = MAXPHYS;
890204076Spjd		ggio->gctl_error = 0;
891204076Spjd		pjdlog_debug(2,
892204076Spjd		    "ggate_recv: (%p) Waiting for request from the kernel.",
893204076Spjd		    hio);
894204076Spjd		if (ioctl(res->hr_ggatefd, G_GATE_CMD_START, ggio) < 0) {
895204076Spjd			if (sigexit_received)
896204076Spjd				pthread_exit(NULL);
897204076Spjd			primary_exit(EX_OSERR, "G_GATE_CMD_START failed");
898204076Spjd		}
899204076Spjd		error = ggio->gctl_error;
900204076Spjd		switch (error) {
901204076Spjd		case 0:
902204076Spjd			break;
903204076Spjd		case ECANCELED:
904204076Spjd			/* Exit gracefully. */
905204076Spjd			if (!sigexit_received) {
906204076Spjd				pjdlog_debug(2,
907204076Spjd				    "ggate_recv: (%p) Received cancel from the kernel.",
908204076Spjd				    hio);
909204076Spjd				pjdlog_info("Received cancel from the kernel, exiting.");
910204076Spjd			}
911204076Spjd			pthread_exit(NULL);
912204076Spjd		case ENOMEM:
913204076Spjd			/*
914204076Spjd			 * Buffer too small? Impossible, we allocate MAXPHYS
915204076Spjd			 * bytes - request can't be bigger than that.
916204076Spjd			 */
917204076Spjd			/* FALLTHROUGH */
918204076Spjd		case ENXIO:
919204076Spjd		default:
920204076Spjd			primary_exitx(EX_OSERR, "G_GATE_CMD_START failed: %s.",
921204076Spjd			    strerror(error));
922204076Spjd		}
923204076Spjd		for (ii = 0; ii < ncomps; ii++)
924204076Spjd			hio->hio_errors[ii] = EINVAL;
925204076Spjd		reqlog(LOG_DEBUG, 2, ggio,
926204076Spjd		    "ggate_recv: (%p) Request received from the kernel: ",
927204076Spjd		    hio);
928204076Spjd		/*
929204076Spjd		 * Inform all components about new write request.
930204076Spjd		 * For read request prefer local component unless the given
931204076Spjd		 * range is out-of-date, then use remote component.
932204076Spjd		 */
933204076Spjd		switch (ggio->gctl_cmd) {
934204076Spjd		case BIO_READ:
935204076Spjd			pjdlog_debug(2,
936204076Spjd			    "ggate_recv: (%p) Moving request to the send queue.",
937204076Spjd			    hio);
938204076Spjd			refcount_init(&hio->hio_countdown, 1);
939204076Spjd			mtx_lock(&metadata_lock);
940204076Spjd			if (res->hr_syncsrc == HAST_SYNCSRC_UNDEF ||
941204076Spjd			    res->hr_syncsrc == HAST_SYNCSRC_PRIMARY) {
942204076Spjd				/*
943204076Spjd				 * This range is up-to-date on local component,
944204076Spjd				 * so handle request locally.
945204076Spjd				 */
946204076Spjd				 /* Local component is 0 for now. */
947204076Spjd				ncomp = 0;
948204076Spjd			} else /* if (res->hr_syncsrc ==
949204076Spjd			    HAST_SYNCSRC_SECONDARY) */ {
950204076Spjd				assert(res->hr_syncsrc ==
951204076Spjd				    HAST_SYNCSRC_SECONDARY);
952204076Spjd				/*
953204076Spjd				 * This range is out-of-date on local component,
954204076Spjd				 * so send request to the remote node.
955204076Spjd				 */
956204076Spjd				 /* Remote component is 1 for now. */
957204076Spjd				ncomp = 1;
958204076Spjd			}
959204076Spjd			mtx_unlock(&metadata_lock);
960204076Spjd			QUEUE_INSERT1(hio, send, ncomp);
961204076Spjd			break;
962204076Spjd		case BIO_WRITE:
963204076Spjd			for (;;) {
964204076Spjd				mtx_lock(&range_lock);
965204076Spjd				if (rangelock_islocked(range_sync,
966204076Spjd				    ggio->gctl_offset, ggio->gctl_length)) {
967204076Spjd					pjdlog_debug(2,
968204076Spjd					    "regular: Range offset=%jd length=%zu locked.",
969204076Spjd					    (intmax_t)ggio->gctl_offset,
970204076Spjd					    (size_t)ggio->gctl_length);
971204076Spjd					range_regular_wait = true;
972204076Spjd					cv_wait(&range_regular_cond, &range_lock);
973204076Spjd					range_regular_wait = false;
974204076Spjd					mtx_unlock(&range_lock);
975204076Spjd					continue;
976204076Spjd				}
977204076Spjd				if (rangelock_add(range_regular,
978204076Spjd				    ggio->gctl_offset, ggio->gctl_length) < 0) {
979204076Spjd					mtx_unlock(&range_lock);
980204076Spjd					pjdlog_debug(2,
981204076Spjd					    "regular: Range offset=%jd length=%zu is already locked, waiting.",
982204076Spjd					    (intmax_t)ggio->gctl_offset,
983204076Spjd					    (size_t)ggio->gctl_length);
984204076Spjd					sleep(1);
985204076Spjd					continue;
986204076Spjd				}
987204076Spjd				mtx_unlock(&range_lock);
988204076Spjd				break;
989204076Spjd			}
990204076Spjd			mtx_lock(&res->hr_amp_lock);
991204076Spjd			if (activemap_write_start(res->hr_amp,
992204076Spjd			    ggio->gctl_offset, ggio->gctl_length)) {
993204076Spjd				(void)hast_activemap_flush(res);
994204076Spjd			}
995204076Spjd			mtx_unlock(&res->hr_amp_lock);
996204076Spjd			/* FALLTHROUGH */
997204076Spjd		case BIO_DELETE:
998204076Spjd		case BIO_FLUSH:
999204076Spjd			pjdlog_debug(2,
1000204076Spjd			    "ggate_recv: (%p) Moving request to the send queues.",
1001204076Spjd			    hio);
1002204076Spjd			refcount_init(&hio->hio_countdown, ncomps);
1003204076Spjd			for (ii = 0; ii < ncomps; ii++)
1004204076Spjd				QUEUE_INSERT1(hio, send, ii);
1005204076Spjd			break;
1006204076Spjd		}
1007204076Spjd	}
1008204076Spjd	/* NOTREACHED */
1009204076Spjd	return (NULL);
1010204076Spjd}
1011204076Spjd
1012204076Spjd/*
1013204076Spjd * Thread reads from or writes to local component.
1014204076Spjd * If local read fails, it redirects it to remote_send thread.
1015204076Spjd */
1016204076Spjdstatic void *
1017204076Spjdlocal_send_thread(void *arg)
1018204076Spjd{
1019204076Spjd	struct hast_resource *res = arg;
1020204076Spjd	struct g_gate_ctl_io *ggio;
1021204076Spjd	struct hio *hio;
1022204076Spjd	unsigned int ncomp, rncomp;
1023204076Spjd	ssize_t ret;
1024204076Spjd
1025204076Spjd	/* Local component is 0 for now. */
1026204076Spjd	ncomp = 0;
1027204076Spjd	/* Remote component is 1 for now. */
1028204076Spjd	rncomp = 1;
1029204076Spjd
1030204076Spjd	for (;;) {
1031204076Spjd		pjdlog_debug(2, "local_send: Taking request.");
1032204076Spjd		QUEUE_TAKE1(hio, send, ncomp);
1033204076Spjd		pjdlog_debug(2, "local_send: (%p) Got request.", hio);
1034204076Spjd		ggio = &hio->hio_ggio;
1035204076Spjd		switch (ggio->gctl_cmd) {
1036204076Spjd		case BIO_READ:
1037204076Spjd			ret = pread(res->hr_localfd, ggio->gctl_data,
1038204076Spjd			    ggio->gctl_length,
1039204076Spjd			    ggio->gctl_offset + res->hr_localoff);
1040204076Spjd			if (ret == ggio->gctl_length)
1041204076Spjd				hio->hio_errors[ncomp] = 0;
1042204076Spjd			else {
1043204076Spjd				/*
1044204076Spjd				 * If READ failed, try to read from remote node.
1045204076Spjd				 */
1046204076Spjd				QUEUE_INSERT1(hio, send, rncomp);
1047204076Spjd				continue;
1048204076Spjd			}
1049204076Spjd			break;
1050204076Spjd		case BIO_WRITE:
1051204076Spjd			ret = pwrite(res->hr_localfd, ggio->gctl_data,
1052204076Spjd			    ggio->gctl_length,
1053204076Spjd			    ggio->gctl_offset + res->hr_localoff);
1054204076Spjd			if (ret < 0)
1055204076Spjd				hio->hio_errors[ncomp] = errno;
1056204076Spjd			else if (ret != ggio->gctl_length)
1057204076Spjd				hio->hio_errors[ncomp] = EIO;
1058204076Spjd			else
1059204076Spjd				hio->hio_errors[ncomp] = 0;
1060204076Spjd			break;
1061204076Spjd		case BIO_DELETE:
1062204076Spjd			ret = g_delete(res->hr_localfd,
1063204076Spjd			    ggio->gctl_offset + res->hr_localoff,
1064204076Spjd			    ggio->gctl_length);
1065204076Spjd			if (ret < 0)
1066204076Spjd				hio->hio_errors[ncomp] = errno;
1067204076Spjd			else
1068204076Spjd				hio->hio_errors[ncomp] = 0;
1069204076Spjd			break;
1070204076Spjd		case BIO_FLUSH:
1071204076Spjd			ret = g_flush(res->hr_localfd);
1072204076Spjd			if (ret < 0)
1073204076Spjd				hio->hio_errors[ncomp] = errno;
1074204076Spjd			else
1075204076Spjd				hio->hio_errors[ncomp] = 0;
1076204076Spjd			break;
1077204076Spjd		}
1078204076Spjd		if (refcount_release(&hio->hio_countdown)) {
1079204076Spjd			if (ISSYNCREQ(hio)) {
1080204076Spjd				mtx_lock(&sync_lock);
1081204076Spjd				SYNCREQDONE(hio);
1082204076Spjd				mtx_unlock(&sync_lock);
1083204076Spjd				cv_signal(&sync_cond);
1084204076Spjd			} else {
1085204076Spjd				pjdlog_debug(2,
1086204076Spjd				    "local_send: (%p) Moving request to the done queue.",
1087204076Spjd				    hio);
1088204076Spjd				QUEUE_INSERT2(hio, done);
1089204076Spjd			}
1090204076Spjd		}
1091204076Spjd	}
1092204076Spjd	/* NOTREACHED */
1093204076Spjd	return (NULL);
1094204076Spjd}
1095204076Spjd
1096204076Spjd/*
1097204076Spjd * Thread sends request to secondary node.
1098204076Spjd */
1099204076Spjdstatic void *
1100204076Spjdremote_send_thread(void *arg)
1101204076Spjd{
1102204076Spjd	struct hast_resource *res = arg;
1103204076Spjd	struct g_gate_ctl_io *ggio;
1104204076Spjd	struct hio *hio;
1105204076Spjd	struct nv *nv;
1106204076Spjd	unsigned int ncomp;
1107204076Spjd	bool wakeup;
1108204076Spjd	uint64_t offset, length;
1109204076Spjd	uint8_t cmd;
1110204076Spjd	void *data;
1111204076Spjd
1112204076Spjd	/* Remote component is 1 for now. */
1113204076Spjd	ncomp = 1;
1114204076Spjd
1115204076Spjd	for (;;) {
1116204076Spjd		pjdlog_debug(2, "remote_send: Taking request.");
1117204076Spjd		QUEUE_TAKE1(hio, send, ncomp);
1118204076Spjd		pjdlog_debug(2, "remote_send: (%p) Got request.", hio);
1119204076Spjd		ggio = &hio->hio_ggio;
1120204076Spjd		switch (ggio->gctl_cmd) {
1121204076Spjd		case BIO_READ:
1122204076Spjd			cmd = HIO_READ;
1123204076Spjd			data = NULL;
1124204076Spjd			offset = ggio->gctl_offset;
1125204076Spjd			length = ggio->gctl_length;
1126204076Spjd			break;
1127204076Spjd		case BIO_WRITE:
1128204076Spjd			cmd = HIO_WRITE;
1129204076Spjd			data = ggio->gctl_data;
1130204076Spjd			offset = ggio->gctl_offset;
1131204076Spjd			length = ggio->gctl_length;
1132204076Spjd			break;
1133204076Spjd		case BIO_DELETE:
1134204076Spjd			cmd = HIO_DELETE;
1135204076Spjd			data = NULL;
1136204076Spjd			offset = ggio->gctl_offset;
1137204076Spjd			length = ggio->gctl_length;
1138204076Spjd			break;
1139204076Spjd		case BIO_FLUSH:
1140204076Spjd			cmd = HIO_FLUSH;
1141204076Spjd			data = NULL;
1142204076Spjd			offset = 0;
1143204076Spjd			length = 0;
1144204076Spjd			break;
1145204076Spjd		default:
1146204076Spjd			assert(!"invalid condition");
1147204076Spjd			abort();
1148204076Spjd		}
1149204076Spjd		nv = nv_alloc();
1150204076Spjd		nv_add_uint8(nv, cmd, "cmd");
1151204076Spjd		nv_add_uint64(nv, (uint64_t)ggio->gctl_seq, "seq");
1152204076Spjd		nv_add_uint64(nv, offset, "offset");
1153204076Spjd		nv_add_uint64(nv, length, "length");
1154204076Spjd		if (nv_error(nv) != 0) {
1155204076Spjd			hio->hio_errors[ncomp] = nv_error(nv);
1156204076Spjd			pjdlog_debug(2,
1157204076Spjd			    "remote_send: (%p) Unable to prepare header to send.",
1158204076Spjd			    hio);
1159204076Spjd			reqlog(LOG_ERR, 0, ggio,
1160204076Spjd			    "Unable to prepare header to send (%s): ",
1161204076Spjd			    strerror(nv_error(nv)));
1162204076Spjd			/* Move failed request immediately to the done queue. */
1163204076Spjd			goto done_queue;
1164204076Spjd		}
1165204076Spjd		pjdlog_debug(2,
1166204076Spjd		    "remote_send: (%p) Moving request to the recv queue.",
1167204076Spjd		    hio);
1168204076Spjd		/*
1169204076Spjd		 * Protect connection from disappearing.
1170204076Spjd		 */
1171204076Spjd		rw_rlock(&hio_remote_lock[ncomp]);
1172204076Spjd		if (!ISCONNECTED(res, ncomp)) {
1173204076Spjd			rw_unlock(&hio_remote_lock[ncomp]);
1174204076Spjd			hio->hio_errors[ncomp] = ENOTCONN;
1175204076Spjd			goto done_queue;
1176204076Spjd		}
1177204076Spjd		/*
1178204076Spjd		 * Move the request to recv queue before sending it, because
1179204076Spjd		 * in different order we can get reply before we move request
1180204076Spjd		 * to recv queue.
1181204076Spjd		 */
1182204076Spjd		mtx_lock(&hio_recv_list_lock[ncomp]);
1183204076Spjd		wakeup = TAILQ_EMPTY(&hio_recv_list[ncomp]);
1184204076Spjd		TAILQ_INSERT_TAIL(&hio_recv_list[ncomp], hio, hio_next[ncomp]);
1185204076Spjd		mtx_unlock(&hio_recv_list_lock[ncomp]);
1186204076Spjd		if (hast_proto_send(res, res->hr_remoteout, nv, data,
1187204076Spjd		    data != NULL ? length : 0) < 0) {
1188204076Spjd			hio->hio_errors[ncomp] = errno;
1189204076Spjd			rw_unlock(&hio_remote_lock[ncomp]);
1190204076Spjd			remote_close(res, ncomp);
1191204076Spjd			pjdlog_debug(2,
1192204076Spjd			    "remote_send: (%p) Unable to send request.", hio);
1193204076Spjd			reqlog(LOG_ERR, 0, ggio,
1194204076Spjd			    "Unable to send request (%s): ",
1195204076Spjd			    strerror(hio->hio_errors[ncomp]));
1196204076Spjd			/*
1197204076Spjd			 * Take request back from the receive queue and move
1198204076Spjd			 * it immediately to the done queue.
1199204076Spjd			 */
1200204076Spjd			mtx_lock(&hio_recv_list_lock[ncomp]);
1201204076Spjd			TAILQ_REMOVE(&hio_recv_list[ncomp], hio, hio_next[ncomp]);
1202204076Spjd			mtx_unlock(&hio_recv_list_lock[ncomp]);
1203204076Spjd			goto done_queue;
1204204076Spjd		}
1205204076Spjd		rw_unlock(&hio_remote_lock[ncomp]);
1206204076Spjd		nv_free(nv);
1207204076Spjd		if (wakeup)
1208204076Spjd			cv_signal(&hio_recv_list_cond[ncomp]);
1209204076Spjd		continue;
1210204076Spjddone_queue:
1211204076Spjd		nv_free(nv);
1212204076Spjd		if (ISSYNCREQ(hio)) {
1213204076Spjd			if (!refcount_release(&hio->hio_countdown))
1214204076Spjd				continue;
1215204076Spjd			mtx_lock(&sync_lock);
1216204076Spjd			SYNCREQDONE(hio);
1217204076Spjd			mtx_unlock(&sync_lock);
1218204076Spjd			cv_signal(&sync_cond);
1219204076Spjd			continue;
1220204076Spjd		}
1221204076Spjd		if (ggio->gctl_cmd == BIO_WRITE) {
1222204076Spjd			mtx_lock(&res->hr_amp_lock);
1223204076Spjd			if (activemap_need_sync(res->hr_amp, ggio->gctl_offset,
1224204076Spjd			    ggio->gctl_length)) {
1225204076Spjd				(void)hast_activemap_flush(res);
1226204076Spjd			}
1227204076Spjd			mtx_unlock(&res->hr_amp_lock);
1228204076Spjd		}
1229204076Spjd		if (!refcount_release(&hio->hio_countdown))
1230204076Spjd			continue;
1231204076Spjd		pjdlog_debug(2,
1232204076Spjd		    "remote_send: (%p) Moving request to the done queue.",
1233204076Spjd		    hio);
1234204076Spjd		QUEUE_INSERT2(hio, done);
1235204076Spjd	}
1236204076Spjd	/* NOTREACHED */
1237204076Spjd	return (NULL);
1238204076Spjd}
1239204076Spjd
1240204076Spjd/*
1241204076Spjd * Thread receives answer from secondary node and passes it to ggate_send
1242204076Spjd * thread.
1243204076Spjd */
1244204076Spjdstatic void *
1245204076Spjdremote_recv_thread(void *arg)
1246204076Spjd{
1247204076Spjd	struct hast_resource *res = arg;
1248204076Spjd	struct g_gate_ctl_io *ggio;
1249204076Spjd	struct hio *hio;
1250204076Spjd	struct nv *nv;
1251204076Spjd	unsigned int ncomp;
1252204076Spjd	uint64_t seq;
1253204076Spjd	int error;
1254204076Spjd
1255204076Spjd	/* Remote component is 1 for now. */
1256204076Spjd	ncomp = 1;
1257204076Spjd
1258204076Spjd	for (;;) {
1259204076Spjd		/* Wait until there is anything to receive. */
1260204076Spjd		mtx_lock(&hio_recv_list_lock[ncomp]);
1261204076Spjd		while (TAILQ_EMPTY(&hio_recv_list[ncomp])) {
1262204076Spjd			pjdlog_debug(2, "remote_recv: No requests, waiting.");
1263204076Spjd			cv_wait(&hio_recv_list_cond[ncomp],
1264204076Spjd			    &hio_recv_list_lock[ncomp]);
1265204076Spjd		}
1266204076Spjd		mtx_unlock(&hio_recv_list_lock[ncomp]);
1267204076Spjd		rw_rlock(&hio_remote_lock[ncomp]);
1268204076Spjd		if (!ISCONNECTED(res, ncomp)) {
1269204076Spjd			rw_unlock(&hio_remote_lock[ncomp]);
1270204076Spjd			/*
1271204076Spjd			 * Connection is dead, so move all pending requests to
1272204076Spjd			 * the done queue (one-by-one).
1273204076Spjd			 */
1274204076Spjd			mtx_lock(&hio_recv_list_lock[ncomp]);
1275204076Spjd			hio = TAILQ_FIRST(&hio_recv_list[ncomp]);
1276204076Spjd			assert(hio != NULL);
1277204076Spjd			TAILQ_REMOVE(&hio_recv_list[ncomp], hio,
1278204076Spjd			    hio_next[ncomp]);
1279204076Spjd			mtx_unlock(&hio_recv_list_lock[ncomp]);
1280204076Spjd			goto done_queue;
1281204076Spjd		}
1282204076Spjd		if (hast_proto_recv_hdr(res->hr_remotein, &nv) < 0) {
1283204076Spjd			pjdlog_errno(LOG_ERR,
1284204076Spjd			    "Unable to receive reply header");
1285204076Spjd			rw_unlock(&hio_remote_lock[ncomp]);
1286204076Spjd			remote_close(res, ncomp);
1287204076Spjd			continue;
1288204076Spjd		}
1289204076Spjd		rw_unlock(&hio_remote_lock[ncomp]);
1290204076Spjd		seq = nv_get_uint64(nv, "seq");
1291204076Spjd		if (seq == 0) {
1292204076Spjd			pjdlog_error("Header contains no 'seq' field.");
1293204076Spjd			nv_free(nv);
1294204076Spjd			continue;
1295204076Spjd		}
1296204076Spjd		mtx_lock(&hio_recv_list_lock[ncomp]);
1297204076Spjd		TAILQ_FOREACH(hio, &hio_recv_list[ncomp], hio_next[ncomp]) {
1298204076Spjd			if (hio->hio_ggio.gctl_seq == seq) {
1299204076Spjd				TAILQ_REMOVE(&hio_recv_list[ncomp], hio,
1300204076Spjd				    hio_next[ncomp]);
1301204076Spjd				break;
1302204076Spjd			}
1303204076Spjd		}
1304204076Spjd		mtx_unlock(&hio_recv_list_lock[ncomp]);
1305204076Spjd		if (hio == NULL) {
1306204076Spjd			pjdlog_error("Found no request matching received 'seq' field (%ju).",
1307204076Spjd			    (uintmax_t)seq);
1308204076Spjd			nv_free(nv);
1309204076Spjd			continue;
1310204076Spjd		}
1311204076Spjd		error = nv_get_int16(nv, "error");
1312204076Spjd		if (error != 0) {
1313204076Spjd			/* Request failed on remote side. */
1314204076Spjd			hio->hio_errors[ncomp] = 0;
1315204076Spjd			nv_free(nv);
1316204076Spjd			goto done_queue;
1317204076Spjd		}
1318204076Spjd		ggio = &hio->hio_ggio;
1319204076Spjd		switch (ggio->gctl_cmd) {
1320204076Spjd		case BIO_READ:
1321204076Spjd			rw_rlock(&hio_remote_lock[ncomp]);
1322204076Spjd			if (!ISCONNECTED(res, ncomp)) {
1323204076Spjd				rw_unlock(&hio_remote_lock[ncomp]);
1324204076Spjd				nv_free(nv);
1325204076Spjd				goto done_queue;
1326204076Spjd			}
1327204076Spjd			if (hast_proto_recv_data(res, res->hr_remotein, nv,
1328204076Spjd			    ggio->gctl_data, ggio->gctl_length) < 0) {
1329204076Spjd				hio->hio_errors[ncomp] = errno;
1330204076Spjd				pjdlog_errno(LOG_ERR,
1331204076Spjd				    "Unable to receive reply data");
1332204076Spjd				rw_unlock(&hio_remote_lock[ncomp]);
1333204076Spjd				nv_free(nv);
1334204076Spjd				remote_close(res, ncomp);
1335204076Spjd				goto done_queue;
1336204076Spjd			}
1337204076Spjd			rw_unlock(&hio_remote_lock[ncomp]);
1338204076Spjd			break;
1339204076Spjd		case BIO_WRITE:
1340204076Spjd		case BIO_DELETE:
1341204076Spjd		case BIO_FLUSH:
1342204076Spjd			break;
1343204076Spjd		default:
1344204076Spjd			assert(!"invalid condition");
1345204076Spjd			abort();
1346204076Spjd		}
1347204076Spjd		hio->hio_errors[ncomp] = 0;
1348204076Spjd		nv_free(nv);
1349204076Spjddone_queue:
1350204076Spjd		if (refcount_release(&hio->hio_countdown)) {
1351204076Spjd			if (ISSYNCREQ(hio)) {
1352204076Spjd				mtx_lock(&sync_lock);
1353204076Spjd				SYNCREQDONE(hio);
1354204076Spjd				mtx_unlock(&sync_lock);
1355204076Spjd				cv_signal(&sync_cond);
1356204076Spjd			} else {
1357204076Spjd				pjdlog_debug(2,
1358204076Spjd				    "remote_recv: (%p) Moving request to the done queue.",
1359204076Spjd				    hio);
1360204076Spjd				QUEUE_INSERT2(hio, done);
1361204076Spjd			}
1362204076Spjd		}
1363204076Spjd	}
1364204076Spjd	/* NOTREACHED */
1365204076Spjd	return (NULL);
1366204076Spjd}
1367204076Spjd
1368204076Spjd/*
1369204076Spjd * Thread sends answer to the kernel.
1370204076Spjd */
1371204076Spjdstatic void *
1372204076Spjdggate_send_thread(void *arg)
1373204076Spjd{
1374204076Spjd	struct hast_resource *res = arg;
1375204076Spjd	struct g_gate_ctl_io *ggio;
1376204076Spjd	struct hio *hio;
1377204076Spjd	unsigned int ii, ncomp, ncomps;
1378204076Spjd
1379204076Spjd	ncomps = HAST_NCOMPONENTS;
1380204076Spjd
1381204076Spjd	for (;;) {
1382204076Spjd		pjdlog_debug(2, "ggate_send: Taking request.");
1383204076Spjd		QUEUE_TAKE2(hio, done);
1384204076Spjd		pjdlog_debug(2, "ggate_send: (%p) Got request.", hio);
1385204076Spjd		ggio = &hio->hio_ggio;
1386204076Spjd		for (ii = 0; ii < ncomps; ii++) {
1387204076Spjd			if (hio->hio_errors[ii] == 0) {
1388204076Spjd				/*
1389204076Spjd				 * One successful request is enough to declare
1390204076Spjd				 * success.
1391204076Spjd				 */
1392204076Spjd				ggio->gctl_error = 0;
1393204076Spjd				break;
1394204076Spjd			}
1395204076Spjd		}
1396204076Spjd		if (ii == ncomps) {
1397204076Spjd			/*
1398204076Spjd			 * None of the requests were successful.
1399204076Spjd			 * Use first error.
1400204076Spjd			 */
1401204076Spjd			ggio->gctl_error = hio->hio_errors[0];
1402204076Spjd		}
1403204076Spjd		if (ggio->gctl_error == 0 && ggio->gctl_cmd == BIO_WRITE) {
1404204076Spjd			mtx_lock(&res->hr_amp_lock);
1405204076Spjd			activemap_write_complete(res->hr_amp,
1406204076Spjd			    ggio->gctl_offset, ggio->gctl_length);
1407204076Spjd			mtx_unlock(&res->hr_amp_lock);
1408204076Spjd		}
1409204076Spjd		if (ggio->gctl_cmd == BIO_WRITE) {
1410204076Spjd			/*
1411204076Spjd			 * Unlock range we locked.
1412204076Spjd			 */
1413204076Spjd			mtx_lock(&range_lock);
1414204076Spjd			rangelock_del(range_regular, ggio->gctl_offset,
1415204076Spjd			    ggio->gctl_length);
1416204076Spjd			if (range_sync_wait)
1417204076Spjd				cv_signal(&range_sync_cond);
1418204076Spjd			mtx_unlock(&range_lock);
1419204076Spjd			/*
1420204076Spjd			 * Bump local count if this is first write after
1421204076Spjd			 * connection failure with remote node.
1422204076Spjd			 */
1423204076Spjd			ncomp = 1;
1424204076Spjd			rw_rlock(&hio_remote_lock[ncomp]);
1425204076Spjd			if (!ISCONNECTED(res, ncomp)) {
1426204076Spjd				mtx_lock(&metadata_lock);
1427204076Spjd				if (res->hr_primary_localcnt ==
1428204076Spjd				    res->hr_secondary_remotecnt) {
1429204076Spjd					res->hr_primary_localcnt++;
1430204076Spjd					pjdlog_debug(1,
1431204076Spjd					    "Increasing localcnt to %ju.",
1432204076Spjd					    (uintmax_t)res->hr_primary_localcnt);
1433204076Spjd					(void)metadata_write(res);
1434204076Spjd				}
1435204076Spjd				mtx_unlock(&metadata_lock);
1436204076Spjd			}
1437204076Spjd			rw_unlock(&hio_remote_lock[ncomp]);
1438204076Spjd		}
1439204076Spjd		if (ioctl(res->hr_ggatefd, G_GATE_CMD_DONE, ggio) < 0)
1440204076Spjd			primary_exit(EX_OSERR, "G_GATE_CMD_DONE failed");
1441204076Spjd		pjdlog_debug(2,
1442204076Spjd		    "ggate_send: (%p) Moving request to the free queue.", hio);
1443204076Spjd		QUEUE_INSERT2(hio, free);
1444204076Spjd	}
1445204076Spjd	/* NOTREACHED */
1446204076Spjd	return (NULL);
1447204076Spjd}
1448204076Spjd
1449204076Spjd/*
1450204076Spjd * Thread synchronize local and remote components.
1451204076Spjd */
1452204076Spjdstatic void *
1453204076Spjdsync_thread(void *arg __unused)
1454204076Spjd{
1455204076Spjd	struct hast_resource *res = arg;
1456204076Spjd	struct hio *hio;
1457204076Spjd	struct g_gate_ctl_io *ggio;
1458204076Spjd	unsigned int ii, ncomp, ncomps;
1459204076Spjd	off_t offset, length, synced;
1460204076Spjd	bool dorewind;
1461204076Spjd	int syncext;
1462204076Spjd
1463204076Spjd	ncomps = HAST_NCOMPONENTS;
1464204076Spjd	dorewind = true;
1465204076Spjd	synced = 0;
1466204076Spjd
1467204076Spjd	for (;;) {
1468204076Spjd		mtx_lock(&sync_lock);
1469204076Spjd		while (!sync_inprogress) {
1470204076Spjd			dorewind = true;
1471204076Spjd			synced = 0;
1472204076Spjd			cv_wait(&sync_cond, &sync_lock);
1473204076Spjd		}
1474204076Spjd		mtx_unlock(&sync_lock);
1475204076Spjd		/*
1476204076Spjd		 * Obtain offset at which we should synchronize.
1477204076Spjd		 * Rewind synchronization if needed.
1478204076Spjd		 */
1479204076Spjd		mtx_lock(&res->hr_amp_lock);
1480204076Spjd		if (dorewind)
1481204076Spjd			activemap_sync_rewind(res->hr_amp);
1482204076Spjd		offset = activemap_sync_offset(res->hr_amp, &length, &syncext);
1483204076Spjd		if (syncext != -1) {
1484204076Spjd			/*
1485204076Spjd			 * We synchronized entire syncext extent, we can mark
1486204076Spjd			 * it as clean now.
1487204076Spjd			 */
1488204076Spjd			if (activemap_extent_complete(res->hr_amp, syncext))
1489204076Spjd				(void)hast_activemap_flush(res);
1490204076Spjd		}
1491204076Spjd		mtx_unlock(&res->hr_amp_lock);
1492204076Spjd		if (dorewind) {
1493204076Spjd			dorewind = false;
1494204076Spjd			if (offset < 0)
1495204076Spjd				pjdlog_info("Nodes are in sync.");
1496204076Spjd			else {
1497204076Spjd				pjdlog_info("Synchronization started. %ju bytes to go.",
1498204076Spjd				    (uintmax_t)(res->hr_extentsize *
1499204076Spjd				    activemap_ndirty(res->hr_amp)));
1500204076Spjd			}
1501204076Spjd		}
1502204076Spjd		if (offset < 0) {
1503204076Spjd			mtx_lock(&sync_lock);
1504204076Spjd			sync_inprogress = false;
1505204076Spjd			mtx_unlock(&sync_lock);
1506204076Spjd			pjdlog_debug(1, "Nothing to synchronize.");
1507204076Spjd			/*
1508204076Spjd			 * Synchronization complete, make both localcnt and
1509204076Spjd			 * remotecnt equal.
1510204076Spjd			 */
1511204076Spjd			ncomp = 1;
1512204076Spjd			rw_rlock(&hio_remote_lock[ncomp]);
1513204076Spjd			if (ISCONNECTED(res, ncomp)) {
1514204076Spjd				if (synced > 0) {
1515204076Spjd					pjdlog_info("Synchronization complete. "
1516204076Spjd					    "%jd bytes synchronized.",
1517204076Spjd					    (intmax_t)synced);
1518204076Spjd				}
1519204076Spjd				mtx_lock(&metadata_lock);
1520204076Spjd				res->hr_syncsrc = HAST_SYNCSRC_UNDEF;
1521204076Spjd				res->hr_primary_localcnt =
1522204076Spjd				    res->hr_secondary_localcnt;
1523204076Spjd				res->hr_primary_remotecnt =
1524204076Spjd				    res->hr_secondary_remotecnt;
1525204076Spjd				pjdlog_debug(1,
1526204076Spjd				    "Setting localcnt to %ju and remotecnt to %ju.",
1527204076Spjd				    (uintmax_t)res->hr_primary_localcnt,
1528204076Spjd				    (uintmax_t)res->hr_secondary_localcnt);
1529204076Spjd				(void)metadata_write(res);
1530204076Spjd				mtx_unlock(&metadata_lock);
1531204076Spjd			} else if (synced > 0) {
1532204076Spjd				pjdlog_info("Synchronization interrupted. "
1533204076Spjd				    "%jd bytes synchronized so far.",
1534204076Spjd				    (intmax_t)synced);
1535204076Spjd			}
1536204076Spjd			rw_unlock(&hio_remote_lock[ncomp]);
1537204076Spjd			continue;
1538204076Spjd		}
1539204076Spjd		pjdlog_debug(2, "sync: Taking free request.");
1540204076Spjd		QUEUE_TAKE2(hio, free);
1541204076Spjd		pjdlog_debug(2, "sync: (%p) Got free request.", hio);
1542204076Spjd		/*
1543204076Spjd		 * Lock the range we are going to synchronize. We don't want
1544204076Spjd		 * race where someone writes between our read and write.
1545204076Spjd		 */
1546204076Spjd		for (;;) {
1547204076Spjd			mtx_lock(&range_lock);
1548204076Spjd			if (rangelock_islocked(range_regular, offset, length)) {
1549204076Spjd				pjdlog_debug(2,
1550204076Spjd				    "sync: Range offset=%jd length=%jd locked.",
1551204076Spjd				    (intmax_t)offset, (intmax_t)length);
1552204076Spjd				range_sync_wait = true;
1553204076Spjd				cv_wait(&range_sync_cond, &range_lock);
1554204076Spjd				range_sync_wait = false;
1555204076Spjd				mtx_unlock(&range_lock);
1556204076Spjd				continue;
1557204076Spjd			}
1558204076Spjd			if (rangelock_add(range_sync, offset, length) < 0) {
1559204076Spjd				mtx_unlock(&range_lock);
1560204076Spjd				pjdlog_debug(2,
1561204076Spjd				    "sync: Range offset=%jd length=%jd is already locked, waiting.",
1562204076Spjd				    (intmax_t)offset, (intmax_t)length);
1563204076Spjd				sleep(1);
1564204076Spjd				continue;
1565204076Spjd			}
1566204076Spjd			mtx_unlock(&range_lock);
1567204076Spjd			break;
1568204076Spjd		}
1569204076Spjd		/*
1570204076Spjd		 * First read the data from synchronization source.
1571204076Spjd		 */
1572204076Spjd		SYNCREQ(hio);
1573204076Spjd		ggio = &hio->hio_ggio;
1574204076Spjd		ggio->gctl_cmd = BIO_READ;
1575204076Spjd		ggio->gctl_offset = offset;
1576204076Spjd		ggio->gctl_length = length;
1577204076Spjd		ggio->gctl_error = 0;
1578204076Spjd		for (ii = 0; ii < ncomps; ii++)
1579204076Spjd			hio->hio_errors[ii] = EINVAL;
1580204076Spjd		reqlog(LOG_DEBUG, 2, ggio, "sync: (%p) Sending sync request: ",
1581204076Spjd		    hio);
1582204076Spjd		pjdlog_debug(2, "sync: (%p) Moving request to the send queue.",
1583204076Spjd		    hio);
1584204076Spjd		mtx_lock(&metadata_lock);
1585204076Spjd		if (res->hr_syncsrc == HAST_SYNCSRC_PRIMARY) {
1586204076Spjd			/*
1587204076Spjd			 * This range is up-to-date on local component,
1588204076Spjd			 * so handle request locally.
1589204076Spjd			 */
1590204076Spjd			 /* Local component is 0 for now. */
1591204076Spjd			ncomp = 0;
1592204076Spjd		} else /* if (res->hr_syncsrc == HAST_SYNCSRC_SECONDARY) */ {
1593204076Spjd			assert(res->hr_syncsrc == HAST_SYNCSRC_SECONDARY);
1594204076Spjd			/*
1595204076Spjd			 * This range is out-of-date on local component,
1596204076Spjd			 * so send request to the remote node.
1597204076Spjd			 */
1598204076Spjd			 /* Remote component is 1 for now. */
1599204076Spjd			ncomp = 1;
1600204076Spjd		}
1601204076Spjd		mtx_unlock(&metadata_lock);
1602204076Spjd		refcount_init(&hio->hio_countdown, 1);
1603204076Spjd		QUEUE_INSERT1(hio, send, ncomp);
1604204076Spjd
1605204076Spjd		/*
1606204076Spjd		 * Let's wait for READ to finish.
1607204076Spjd		 */
1608204076Spjd		mtx_lock(&sync_lock);
1609204076Spjd		while (!ISSYNCREQDONE(hio))
1610204076Spjd			cv_wait(&sync_cond, &sync_lock);
1611204076Spjd		mtx_unlock(&sync_lock);
1612204076Spjd
1613204076Spjd		if (hio->hio_errors[ncomp] != 0) {
1614204076Spjd			pjdlog_error("Unable to read synchronization data: %s.",
1615204076Spjd			    strerror(hio->hio_errors[ncomp]));
1616204076Spjd			goto free_queue;
1617204076Spjd		}
1618204076Spjd
1619204076Spjd		/*
1620204076Spjd		 * We read the data from synchronization source, now write it
1621204076Spjd		 * to synchronization target.
1622204076Spjd		 */
1623204076Spjd		SYNCREQ(hio);
1624204076Spjd		ggio->gctl_cmd = BIO_WRITE;
1625204076Spjd		for (ii = 0; ii < ncomps; ii++)
1626204076Spjd			hio->hio_errors[ii] = EINVAL;
1627204076Spjd		reqlog(LOG_DEBUG, 2, ggio, "sync: (%p) Sending sync request: ",
1628204076Spjd		    hio);
1629204076Spjd		pjdlog_debug(2, "sync: (%p) Moving request to the send queue.",
1630204076Spjd		    hio);
1631204076Spjd		mtx_lock(&metadata_lock);
1632204076Spjd		if (res->hr_syncsrc == HAST_SYNCSRC_PRIMARY) {
1633204076Spjd			/*
1634204076Spjd			 * This range is up-to-date on local component,
1635204076Spjd			 * so we update remote component.
1636204076Spjd			 */
1637204076Spjd			 /* Remote component is 1 for now. */
1638204076Spjd			ncomp = 1;
1639204076Spjd		} else /* if (res->hr_syncsrc == HAST_SYNCSRC_SECONDARY) */ {
1640204076Spjd			assert(res->hr_syncsrc == HAST_SYNCSRC_SECONDARY);
1641204076Spjd			/*
1642204076Spjd			 * This range is out-of-date on local component,
1643204076Spjd			 * so we update it.
1644204076Spjd			 */
1645204076Spjd			 /* Local component is 0 for now. */
1646204076Spjd			ncomp = 0;
1647204076Spjd		}
1648204076Spjd		mtx_unlock(&metadata_lock);
1649204076Spjd
1650204076Spjd		pjdlog_debug(2, "sync: (%p) Moving request to the send queues.",
1651204076Spjd		    hio);
1652204076Spjd		refcount_init(&hio->hio_countdown, 1);
1653204076Spjd		QUEUE_INSERT1(hio, send, ncomp);
1654204076Spjd
1655204076Spjd		/*
1656204076Spjd		 * Let's wait for WRITE to finish.
1657204076Spjd		 */
1658204076Spjd		mtx_lock(&sync_lock);
1659204076Spjd		while (!ISSYNCREQDONE(hio))
1660204076Spjd			cv_wait(&sync_cond, &sync_lock);
1661204076Spjd		mtx_unlock(&sync_lock);
1662204076Spjd
1663204076Spjd		if (hio->hio_errors[ncomp] != 0) {
1664204076Spjd			pjdlog_error("Unable to write synchronization data: %s.",
1665204076Spjd			    strerror(hio->hio_errors[ncomp]));
1666204076Spjd			goto free_queue;
1667204076Spjd		}
1668204076Spjdfree_queue:
1669204076Spjd		mtx_lock(&range_lock);
1670204076Spjd		rangelock_del(range_sync, offset, length);
1671204076Spjd		if (range_regular_wait)
1672204076Spjd			cv_signal(&range_regular_cond);
1673204076Spjd		mtx_unlock(&range_lock);
1674204076Spjd
1675204076Spjd		synced += length;
1676204076Spjd
1677204076Spjd		pjdlog_debug(2, "sync: (%p) Moving request to the free queue.",
1678204076Spjd		    hio);
1679204076Spjd		QUEUE_INSERT2(hio, free);
1680204076Spjd	}
1681204076Spjd	/* NOTREACHED */
1682204076Spjd	return (NULL);
1683204076Spjd}
1684204076Spjd
1685204076Spjdstatic void
1686204076Spjdsighandler(int sig)
1687204076Spjd{
1688204076Spjd	bool unlock;
1689204076Spjd
1690204076Spjd	switch (sig) {
1691204076Spjd	case SIGINT:
1692204076Spjd	case SIGTERM:
1693204076Spjd		sigexit_received = true;
1694204076Spjd		break;
1695204076Spjd	default:
1696204076Spjd		assert(!"invalid condition");
1697204076Spjd	}
1698204076Spjd	/*
1699204076Spjd	 * XXX: Racy, but if we cannot obtain hio_guard_lock here, we don't
1700204076Spjd	 * want to risk deadlock.
1701204076Spjd	 */
1702204076Spjd	unlock = mtx_trylock(&hio_guard_lock);
1703204076Spjd	cv_signal(&hio_guard_cond);
1704204076Spjd	if (unlock)
1705204076Spjd		mtx_unlock(&hio_guard_lock);
1706204076Spjd}
1707204076Spjd
1708204076Spjd/*
1709204076Spjd * Thread guards remote connections and reconnects when needed, handles
1710204076Spjd * signals, etc.
1711204076Spjd */
1712204076Spjdstatic void *
1713204076Spjdguard_thread(void *arg)
1714204076Spjd{
1715204076Spjd	struct hast_resource *res = arg;
1716205738Spjd	struct proto_conn *in, *out;
1717204076Spjd	unsigned int ii, ncomps;
1718204076Spjd	int timeout;
1719204076Spjd
1720204076Spjd	ncomps = HAST_NCOMPONENTS;
1721204076Spjd	/* The is only one remote component for now. */
1722204076Spjd#define	ISREMOTE(no)	((no) == 1)
1723204076Spjd
1724204076Spjd	for (;;) {
1725204076Spjd		if (sigexit_received) {
1726204076Spjd			primary_exitx(EX_OK,
1727204076Spjd			    "Termination signal received, exiting.");
1728204076Spjd		}
1729204076Spjd		/*
1730204076Spjd		 * If all the connection will be fine, we will sleep until
1731204076Spjd		 * someone wakes us up.
1732204076Spjd		 * If any of the connections will be broken and we won't be
1733204076Spjd		 * able to connect, we will sleep only for RECONNECT_SLEEP
1734204076Spjd		 * seconds so we can retry soon.
1735204076Spjd		 */
1736204076Spjd		timeout = 0;
1737204076Spjd		pjdlog_debug(2, "remote_guard: Checking connections.");
1738204076Spjd		mtx_lock(&hio_guard_lock);
1739204076Spjd		for (ii = 0; ii < ncomps; ii++) {
1740204076Spjd			if (!ISREMOTE(ii))
1741204076Spjd				continue;
1742204076Spjd			rw_rlock(&hio_remote_lock[ii]);
1743204076Spjd			if (ISCONNECTED(res, ii)) {
1744204076Spjd				assert(res->hr_remotein != NULL);
1745204076Spjd				assert(res->hr_remoteout != NULL);
1746204076Spjd				rw_unlock(&hio_remote_lock[ii]);
1747204076Spjd				pjdlog_debug(2,
1748204076Spjd				    "remote_guard: Connection to %s is ok.",
1749204076Spjd				    res->hr_remoteaddr);
1750204076Spjd			} else {
1751204076Spjd				assert(res->hr_remotein == NULL);
1752204076Spjd				assert(res->hr_remoteout == NULL);
1753204076Spjd				/*
1754204076Spjd				 * Upgrade the lock. It doesn't have to be
1755204076Spjd				 * atomic as no other thread can change
1756204076Spjd				 * connection status from disconnected to
1757204076Spjd				 * connected.
1758204076Spjd				 */
1759204076Spjd				rw_unlock(&hio_remote_lock[ii]);
1760204076Spjd				pjdlog_debug(2,
1761204076Spjd				    "remote_guard: Reconnecting to %s.",
1762204076Spjd				    res->hr_remoteaddr);
1763205738Spjd				in = out = NULL;
1764205738Spjd				if (init_remote(res, &in, &out)) {
1765205738Spjd					rw_wlock(&hio_remote_lock[ii]);
1766205738Spjd					assert(res->hr_remotein == NULL);
1767205738Spjd					assert(res->hr_remoteout == NULL);
1768205738Spjd					assert(in != NULL && out != NULL);
1769205738Spjd					res->hr_remotein = in;
1770205738Spjd					res->hr_remoteout = out;
1771205738Spjd					rw_unlock(&hio_remote_lock[ii]);
1772204076Spjd					pjdlog_info("Successfully reconnected to %s.",
1773204076Spjd					    res->hr_remoteaddr);
1774205738Spjd					sync_start();
1775204076Spjd				} else {
1776204076Spjd					/* Both connections should be NULL. */
1777204076Spjd					assert(res->hr_remotein == NULL);
1778204076Spjd					assert(res->hr_remoteout == NULL);
1779205738Spjd					assert(in == NULL && out == NULL);
1780204076Spjd					pjdlog_debug(2,
1781204076Spjd					    "remote_guard: Reconnect to %s failed.",
1782204076Spjd					    res->hr_remoteaddr);
1783204076Spjd					timeout = RECONNECT_SLEEP;
1784204076Spjd				}
1785204076Spjd			}
1786204076Spjd		}
1787204076Spjd		(void)cv_timedwait(&hio_guard_cond, &hio_guard_lock, timeout);
1788204076Spjd		mtx_unlock(&hio_guard_lock);
1789204076Spjd	}
1790204076Spjd#undef	ISREMOTE
1791204076Spjd	/* NOTREACHED */
1792204076Spjd	return (NULL);
1793204076Spjd}
1794