primary.c revision 219864
1131962Smp/*-
259243Sobrien * Copyright (c) 2009 The FreeBSD Foundation
359243Sobrien * Copyright (c) 2010-2011 Pawel Jakub Dawidek <pawel@dawidek.net>
459243Sobrien * All rights reserved.
559243Sobrien *
659243Sobrien * This software was developed by Pawel Jakub Dawidek under sponsorship from
759243Sobrien * the FreeBSD Foundation.
859243Sobrien *
959243Sobrien * Redistribution and use in source and binary forms, with or without
1059243Sobrien * modification, are permitted provided that the following conditions
1159243Sobrien * are met:
1259243Sobrien * 1. Redistributions of source code must retain the above copyright
1359243Sobrien *    notice, this list of conditions and the following disclaimer.
1459243Sobrien * 2. Redistributions in binary form must reproduce the above copyright
1559243Sobrien *    notice, this list of conditions and the following disclaimer in the
1659243Sobrien *    documentation and/or other materials provided with the distribution.
17100616Smp *
1859243Sobrien * THIS SOFTWARE IS PROVIDED BY THE AUTHORS AND CONTRIBUTORS ``AS IS'' AND
1959243Sobrien * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
2059243Sobrien * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
2159243Sobrien * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE
2259243Sobrien * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
2359243Sobrien * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
2459243Sobrien * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
2559243Sobrien * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
2659243Sobrien * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
2759243Sobrien * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
2859243Sobrien * SUCH DAMAGE.
2959243Sobrien */
3059243Sobrien
3159243Sobrien#include <sys/cdefs.h>
3259243Sobrien__FBSDID("$FreeBSD: head/sbin/hastd/primary.c 219864 2011-03-22 10:39:34Z pjd $");
3359243Sobrien
3459243Sobrien#include <sys/types.h>
35131962Smp#include <sys/time.h>
3659243Sobrien#include <sys/bio.h>
3759243Sobrien#include <sys/disk.h>
3859243Sobrien#include <sys/refcount.h>
3959243Sobrien#include <sys/stat.h>
4059243Sobrien
4159243Sobrien#include <geom/gate/g_gate.h>
4259243Sobrien
4359243Sobrien#include <err.h>
4459243Sobrien#include <errno.h>
4559243Sobrien#include <fcntl.h>
4659243Sobrien#include <libgeom.h>
4759243Sobrien#include <pthread.h>
4859243Sobrien#include <signal.h>
4959243Sobrien#include <stdint.h>
5059243Sobrien#include <stdio.h>
5159243Sobrien#include <string.h>
5259243Sobrien#include <sysexits.h>
5359243Sobrien#include <unistd.h>
5459243Sobrien
5559243Sobrien#include <activemap.h>
5659243Sobrien#include <nv.h>
5759243Sobrien#include <rangelock.h>
5859243Sobrien
5959243Sobrien#include "control.h"
6059243Sobrien#include "event.h"
6159243Sobrien#include "hast.h"
6259243Sobrien#include "hast_proto.h"
6359243Sobrien#include "hastd.h"
6459243Sobrien#include "hooks.h"
6559243Sobrien#include "metadata.h"
6659243Sobrien#include "proto.h"
6759243Sobrien#include "pjdlog.h"
6859243Sobrien#include "subr.h"
6959243Sobrien#include "synch.h"
7059243Sobrien
7159243Sobrien/* The is only one remote component for now. */
7259243Sobrien#define	ISREMOTE(no)	((no) == 1)
7359243Sobrien
7459243Sobrienstruct hio {
7559243Sobrien	/*
7659243Sobrien	 * Number of components we are still waiting for.
7759243Sobrien	 * When this field goes to 0, we can send the request back to the
7859243Sobrien	 * kernel. Each component has to decrease this counter by one
7959243Sobrien	 * even on failure.
8059243Sobrien	 */
8159243Sobrien	unsigned int		 hio_countdown;
8259243Sobrien	/*
8359243Sobrien	 * Each component has a place to store its own error.
8459243Sobrien	 * Once the request is handled by all components we can decide if the
8559243Sobrien	 * request overall is successful or not.
8659243Sobrien	 */
8759243Sobrien	int			*hio_errors;
8859243Sobrien	/*
8959243Sobrien	 * Structure used to communicate with GEOM Gate class.
9059243Sobrien	 */
9159243Sobrien	struct g_gate_ctl_io	 hio_ggio;
9259243Sobrien	TAILQ_ENTRY(hio)	*hio_next;
9359243Sobrien};
9459243Sobrien#define	hio_free_next	hio_next[0]
9559243Sobrien#define	hio_done_next	hio_next[0]
9659243Sobrien
9759243Sobrien/*
9859243Sobrien * Free list holds unused structures. When free list is empty, we have to wait
9959243Sobrien * until some in-progress requests are freed.
10059243Sobrien */
10159243Sobrienstatic TAILQ_HEAD(, hio) hio_free_list;
10259243Sobrienstatic pthread_mutex_t hio_free_list_lock;
10359243Sobrienstatic pthread_cond_t hio_free_list_cond;
10459243Sobrien/*
10559243Sobrien * There is one send list for every component. One requests is placed on all
10659243Sobrien * send lists - each component gets the same request, but each component is
10759243Sobrien * responsible for managing his own send list.
10859243Sobrien */
10959243Sobrienstatic TAILQ_HEAD(, hio) *hio_send_list;
11059243Sobrienstatic pthread_mutex_t *hio_send_list_lock;
11159243Sobrienstatic pthread_cond_t *hio_send_list_cond;
11259243Sobrien/*
11359243Sobrien * There is one recv list for every component, although local components don't
11459243Sobrien * use recv lists as local requests are done synchronously.
11559243Sobrien */
11659243Sobrienstatic TAILQ_HEAD(, hio) *hio_recv_list;
11759243Sobrienstatic pthread_mutex_t *hio_recv_list_lock;
11859243Sobrienstatic pthread_cond_t *hio_recv_list_cond;
11959243Sobrien/*
12059243Sobrien * Request is placed on done list by the slowest component (the one that
12159243Sobrien * decreased hio_countdown from 1 to 0).
12259243Sobrien */
12359243Sobrienstatic TAILQ_HEAD(, hio) hio_done_list;
12459243Sobrienstatic pthread_mutex_t hio_done_list_lock;
12559243Sobrienstatic pthread_cond_t hio_done_list_cond;
12659243Sobrien/*
12759243Sobrien * Structure below are for interaction with sync thread.
12859243Sobrien */
12959243Sobrienstatic bool sync_inprogress;
13059243Sobrienstatic pthread_mutex_t sync_lock;
13159243Sobrienstatic pthread_cond_t sync_cond;
13259243Sobrien/*
13359243Sobrien * The lock below allows to synchornize access to remote connections.
13459243Sobrien */
13559243Sobrienstatic pthread_rwlock_t *hio_remote_lock;
13659243Sobrien
13759243Sobrien/*
13859243Sobrien * Lock to synchronize metadata updates. Also synchronize access to
13959243Sobrien * hr_primary_localcnt and hr_primary_remotecnt fields.
14059243Sobrien */
14159243Sobrienstatic pthread_mutex_t metadata_lock;
14259243Sobrien
14359243Sobrien/*
14459243Sobrien * Maximum number of outstanding I/O requests.
14559243Sobrien */
14659243Sobrien#define	HAST_HIO_MAX	256
14759243Sobrien/*
14859243Sobrien * Number of components. At this point there are only two components: local
14959243Sobrien * and remote, but in the future it might be possible to use multiple local
15059243Sobrien * and remote components.
15159243Sobrien */
15259243Sobrien#define	HAST_NCOMPONENTS	2
15359243Sobrien
15459243Sobrien#define	ISCONNECTED(res, no)	\
15559243Sobrien	((res)->hr_remotein != NULL && (res)->hr_remoteout != NULL)
15659243Sobrien
15759243Sobrien#define	QUEUE_INSERT1(hio, name, ncomp)	do {				\
15859243Sobrien	bool _wakeup;							\
15959243Sobrien									\
16059243Sobrien	mtx_lock(&hio_##name##_list_lock[(ncomp)]);			\
16159243Sobrien	_wakeup = TAILQ_EMPTY(&hio_##name##_list[(ncomp)]);		\
16259243Sobrien	TAILQ_INSERT_TAIL(&hio_##name##_list[(ncomp)], (hio),		\
16359243Sobrien	    hio_next[(ncomp)]);						\
16459243Sobrien	mtx_unlock(&hio_##name##_list_lock[ncomp]);			\
16559243Sobrien	if (_wakeup)							\
16659243Sobrien		cv_signal(&hio_##name##_list_cond[(ncomp)]);		\
16759243Sobrien} while (0)
16859243Sobrien#define	QUEUE_INSERT2(hio, name)	do {				\
16959243Sobrien	bool _wakeup;							\
17059243Sobrien									\
17159243Sobrien	mtx_lock(&hio_##name##_list_lock);				\
17259243Sobrien	_wakeup = TAILQ_EMPTY(&hio_##name##_list);			\
17359243Sobrien	TAILQ_INSERT_TAIL(&hio_##name##_list, (hio), hio_##name##_next);\
17459243Sobrien	mtx_unlock(&hio_##name##_list_lock);				\
17559243Sobrien	if (_wakeup)							\
17659243Sobrien		cv_signal(&hio_##name##_list_cond);			\
17759243Sobrien} while (0)
17859243Sobrien#define	QUEUE_TAKE1(hio, name, ncomp, timeout)	do {			\
17959243Sobrien	bool _last;							\
18059243Sobrien									\
18159243Sobrien	mtx_lock(&hio_##name##_list_lock[(ncomp)]);			\
18259243Sobrien	_last = false;							\
18359243Sobrien	while (((hio) = TAILQ_FIRST(&hio_##name##_list[(ncomp)])) == NULL && !_last) { \
18459243Sobrien		cv_timedwait(&hio_##name##_list_cond[(ncomp)],		\
18559243Sobrien		    &hio_##name##_list_lock[(ncomp)], (timeout));	\
18659243Sobrien		if ((timeout) != 0)					\
18759243Sobrien			_last = true;					\
18859243Sobrien	}								\
18959243Sobrien	if (hio != NULL) {						\
19059243Sobrien		TAILQ_REMOVE(&hio_##name##_list[(ncomp)], (hio),	\
19159243Sobrien		    hio_next[(ncomp)]);					\
19259243Sobrien	}								\
19359243Sobrien	mtx_unlock(&hio_##name##_list_lock[(ncomp)]);			\
19459243Sobrien} while (0)
19559243Sobrien#define	QUEUE_TAKE2(hio, name)	do {					\
19659243Sobrien	mtx_lock(&hio_##name##_list_lock);				\
19759243Sobrien	while (((hio) = TAILQ_FIRST(&hio_##name##_list)) == NULL) {	\
19859243Sobrien		cv_wait(&hio_##name##_list_cond,			\
19959243Sobrien		    &hio_##name##_list_lock);				\
20059243Sobrien	}								\
20159243Sobrien	TAILQ_REMOVE(&hio_##name##_list, (hio), hio_##name##_next);	\
20259243Sobrien	mtx_unlock(&hio_##name##_list_lock);				\
20359243Sobrien} while (0)
20459243Sobrien
20559243Sobrien#define	SYNCREQ(hio)		do {					\
20659243Sobrien	(hio)->hio_ggio.gctl_unit = -1;					\
20759243Sobrien	(hio)->hio_ggio.gctl_seq = 1;					\
20859243Sobrien} while (0)
20959243Sobrien#define	ISSYNCREQ(hio)		((hio)->hio_ggio.gctl_unit == -1)
21059243Sobrien#define	SYNCREQDONE(hio)	do { (hio)->hio_ggio.gctl_unit = -2; } while (0)
21159243Sobrien#define	ISSYNCREQDONE(hio)	((hio)->hio_ggio.gctl_unit == -2)
21259243Sobrien
21359243Sobrienstatic struct hast_resource *gres;
21459243Sobrien
21559243Sobrienstatic pthread_mutex_t range_lock;
21659243Sobrienstatic struct rangelocks *range_regular;
21759243Sobrienstatic bool range_regular_wait;
21859243Sobrienstatic pthread_cond_t range_regular_cond;
21959243Sobrienstatic struct rangelocks *range_sync;
22059243Sobrienstatic bool range_sync_wait;
22159243Sobrienstatic pthread_cond_t range_sync_cond;
22259243Sobrien
22359243Sobrienstatic void *ggate_recv_thread(void *arg);
22459243Sobrienstatic void *local_send_thread(void *arg);
22559243Sobrienstatic void *remote_send_thread(void *arg);
22659243Sobrienstatic void *remote_recv_thread(void *arg);
22759243Sobrienstatic void *ggate_send_thread(void *arg);
22859243Sobrienstatic void *sync_thread(void *arg);
22959243Sobrienstatic void *guard_thread(void *arg);
23059243Sobrien
23159243Sobrienstatic void
23259243Sobriencleanup(struct hast_resource *res)
23359243Sobrien{
23459243Sobrien	int rerrno;
23559243Sobrien
23659243Sobrien	/* Remember errno. */
23759243Sobrien	rerrno = errno;
23859243Sobrien
23959243Sobrien	/* Destroy ggate provider if we created one. */
24059243Sobrien	if (res->hr_ggateunit >= 0) {
24159243Sobrien		struct g_gate_ctl_destroy ggiod;
24259243Sobrien
24359243Sobrien		bzero(&ggiod, sizeof(ggiod));
24459243Sobrien		ggiod.gctl_version = G_GATE_VERSION;
24559243Sobrien		ggiod.gctl_unit = res->hr_ggateunit;
24659243Sobrien		ggiod.gctl_force = 1;
24759243Sobrien		if (ioctl(res->hr_ggatefd, G_GATE_CMD_DESTROY, &ggiod) < 0) {
24859243Sobrien			pjdlog_errno(LOG_WARNING,
24959243Sobrien			    "Unable to destroy hast/%s device",
25059243Sobrien			    res->hr_provname);
25159243Sobrien		}
25259243Sobrien		res->hr_ggateunit = -1;
25359243Sobrien	}
25459243Sobrien
25559243Sobrien	/* Restore errno. */
25659243Sobrien	errno = rerrno;
25759243Sobrien}
25859243Sobrien
25959243Sobrienstatic __dead2 void
26059243Sobrienprimary_exit(int exitcode, const char *fmt, ...)
261131962Smp{
262131962Smp	va_list ap;
263131962Smp
264131962Smp	PJDLOG_ASSERT(exitcode != EX_OK);
265131962Smp	va_start(ap, fmt);
26659243Sobrien	pjdlogv_errno(LOG_ERR, fmt, ap);
26759243Sobrien	va_end(ap);
26859243Sobrien	cleanup(gres);
26959243Sobrien	exit(exitcode);
27059243Sobrien}
27159243Sobrien
27259243Sobrienstatic __dead2 void
27359243Sobrienprimary_exitx(int exitcode, const char *fmt, ...)
27459243Sobrien{
27559243Sobrien	va_list ap;
27659243Sobrien
27759243Sobrien	va_start(ap, fmt);
27859243Sobrien	pjdlogv(exitcode == EX_OK ? LOG_INFO : LOG_ERR, fmt, ap);
27959243Sobrien	va_end(ap);
28059243Sobrien	cleanup(gres);
281131962Smp	exit(exitcode);
28259243Sobrien}
28359243Sobrien
284131962Smpstatic int
285131962Smphast_activemap_flush(struct hast_resource *res)
286131962Smp{
287131962Smp	const unsigned char *buf;
288131962Smp	size_t size;
28959243Sobrien
29059243Sobrien	buf = activemap_bitmap(res->hr_amp, &size);
29159243Sobrien	PJDLOG_ASSERT(buf != NULL);
29259243Sobrien	PJDLOG_ASSERT((size % res->hr_local_sectorsize) == 0);
29359243Sobrien	if (pwrite(res->hr_localfd, buf, size, METADATA_SIZE) !=
29459243Sobrien	    (ssize_t)size) {
29559243Sobrien		KEEP_ERRNO(pjdlog_errno(LOG_ERR,
29659243Sobrien		    "Unable to flush activemap to disk"));
29759243Sobrien		return (-1);
29859243Sobrien	}
29959243Sobrien	return (0);
30059243Sobrien}
30159243Sobrien
30259243Sobrienstatic bool
30359243Sobrienreal_remote(const struct hast_resource *res)
30459243Sobrien{
30559243Sobrien
30659243Sobrien	return (strcmp(res->hr_remoteaddr, "none") != 0);
30759243Sobrien}
30859243Sobrien
30959243Sobrienstatic void
31059243Sobrieninit_environment(struct hast_resource *res __unused)
31159243Sobrien{
31259243Sobrien	struct hio *hio;
31359243Sobrien	unsigned int ii, ncomps;
31459243Sobrien
31559243Sobrien	/*
31659243Sobrien	 * In the future it might be per-resource value.
31759243Sobrien	 */
31859243Sobrien	ncomps = HAST_NCOMPONENTS;
31959243Sobrien
32059243Sobrien	/*
32159243Sobrien	 * Allocate memory needed by lists.
32259243Sobrien	 */
32359243Sobrien	hio_send_list = malloc(sizeof(hio_send_list[0]) * ncomps);
32459243Sobrien	if (hio_send_list == NULL) {
32559243Sobrien		primary_exitx(EX_TEMPFAIL,
32659243Sobrien		    "Unable to allocate %zu bytes of memory for send lists.",
32759243Sobrien		    sizeof(hio_send_list[0]) * ncomps);
328131962Smp	}
32959243Sobrien	hio_send_list_lock = malloc(sizeof(hio_send_list_lock[0]) * ncomps);
33059243Sobrien	if (hio_send_list_lock == NULL) {
33159243Sobrien		primary_exitx(EX_TEMPFAIL,
33259243Sobrien		    "Unable to allocate %zu bytes of memory for send list locks.",
33359243Sobrien		    sizeof(hio_send_list_lock[0]) * ncomps);
33459243Sobrien	}
33559243Sobrien	hio_send_list_cond = malloc(sizeof(hio_send_list_cond[0]) * ncomps);
33659243Sobrien	if (hio_send_list_cond == NULL) {
33759243Sobrien		primary_exitx(EX_TEMPFAIL,
33859243Sobrien		    "Unable to allocate %zu bytes of memory for send list condition variables.",
33959243Sobrien		    sizeof(hio_send_list_cond[0]) * ncomps);
34059243Sobrien	}
34159243Sobrien	hio_recv_list = malloc(sizeof(hio_recv_list[0]) * ncomps);
34259243Sobrien	if (hio_recv_list == NULL) {
34359243Sobrien		primary_exitx(EX_TEMPFAIL,
34459243Sobrien		    "Unable to allocate %zu bytes of memory for recv lists.",
34559243Sobrien		    sizeof(hio_recv_list[0]) * ncomps);
34659243Sobrien	}
34759243Sobrien	hio_recv_list_lock = malloc(sizeof(hio_recv_list_lock[0]) * ncomps);
34859243Sobrien	if (hio_recv_list_lock == NULL) {
34959243Sobrien		primary_exitx(EX_TEMPFAIL,
35059243Sobrien		    "Unable to allocate %zu bytes of memory for recv list locks.",
35159243Sobrien		    sizeof(hio_recv_list_lock[0]) * ncomps);
35259243Sobrien	}
35359243Sobrien	hio_recv_list_cond = malloc(sizeof(hio_recv_list_cond[0]) * ncomps);
35459243Sobrien	if (hio_recv_list_cond == NULL) {
35559243Sobrien		primary_exitx(EX_TEMPFAIL,
35659243Sobrien		    "Unable to allocate %zu bytes of memory for recv list condition variables.",
35759243Sobrien		    sizeof(hio_recv_list_cond[0]) * ncomps);
35859243Sobrien	}
35959243Sobrien	hio_remote_lock = malloc(sizeof(hio_remote_lock[0]) * ncomps);
36059243Sobrien	if (hio_remote_lock == NULL) {
36159243Sobrien		primary_exitx(EX_TEMPFAIL,
36259243Sobrien		    "Unable to allocate %zu bytes of memory for remote connections locks.",
36359243Sobrien		    sizeof(hio_remote_lock[0]) * ncomps);
36459243Sobrien	}
36559243Sobrien
36659243Sobrien	/*
36759243Sobrien	 * Initialize lists, their locks and theirs condition variables.
36859243Sobrien	 */
36959243Sobrien	TAILQ_INIT(&hio_free_list);
37059243Sobrien	mtx_init(&hio_free_list_lock);
37159243Sobrien	cv_init(&hio_free_list_cond);
37259243Sobrien	for (ii = 0; ii < HAST_NCOMPONENTS; ii++) {
37359243Sobrien		TAILQ_INIT(&hio_send_list[ii]);
37459243Sobrien		mtx_init(&hio_send_list_lock[ii]);
37559243Sobrien		cv_init(&hio_send_list_cond[ii]);
37659243Sobrien		TAILQ_INIT(&hio_recv_list[ii]);
37759243Sobrien		mtx_init(&hio_recv_list_lock[ii]);
37859243Sobrien		cv_init(&hio_recv_list_cond[ii]);
37959243Sobrien		rw_init(&hio_remote_lock[ii]);
38059243Sobrien	}
38159243Sobrien	TAILQ_INIT(&hio_done_list);
38259243Sobrien	mtx_init(&hio_done_list_lock);
38359243Sobrien	cv_init(&hio_done_list_cond);
38459243Sobrien	mtx_init(&metadata_lock);
38559243Sobrien
38659243Sobrien	/*
38759243Sobrien	 * Allocate requests pool and initialize requests.
38859243Sobrien	 */
38959243Sobrien	for (ii = 0; ii < HAST_HIO_MAX; ii++) {
39059243Sobrien		hio = malloc(sizeof(*hio));
39159243Sobrien		if (hio == NULL) {
39259243Sobrien			primary_exitx(EX_TEMPFAIL,
39359243Sobrien			    "Unable to allocate %zu bytes of memory for hio request.",
39459243Sobrien			    sizeof(*hio));
39559243Sobrien		}
39659243Sobrien		hio->hio_countdown = 0;
39759243Sobrien		hio->hio_errors = malloc(sizeof(hio->hio_errors[0]) * ncomps);
39859243Sobrien		if (hio->hio_errors == NULL) {
39959243Sobrien			primary_exitx(EX_TEMPFAIL,
40059243Sobrien			    "Unable allocate %zu bytes of memory for hio errors.",
40159243Sobrien			    sizeof(hio->hio_errors[0]) * ncomps);
40259243Sobrien		}
40359243Sobrien		hio->hio_next = malloc(sizeof(hio->hio_next[0]) * ncomps);
40459243Sobrien		if (hio->hio_next == NULL) {
40559243Sobrien			primary_exitx(EX_TEMPFAIL,
40659243Sobrien			    "Unable allocate %zu bytes of memory for hio_next field.",
40759243Sobrien			    sizeof(hio->hio_next[0]) * ncomps);
40859243Sobrien		}
40959243Sobrien		hio->hio_ggio.gctl_version = G_GATE_VERSION;
41059243Sobrien		hio->hio_ggio.gctl_data = malloc(MAXPHYS);
41159243Sobrien		if (hio->hio_ggio.gctl_data == NULL) {
41259243Sobrien			primary_exitx(EX_TEMPFAIL,
41359243Sobrien			    "Unable to allocate %zu bytes of memory for gctl_data.",
41459243Sobrien			    MAXPHYS);
41559243Sobrien		}
41659243Sobrien		hio->hio_ggio.gctl_length = MAXPHYS;
41759243Sobrien		hio->hio_ggio.gctl_error = 0;
41859243Sobrien		TAILQ_INSERT_HEAD(&hio_free_list, hio, hio_free_next);
41959243Sobrien	}
42059243Sobrien}
42159243Sobrien
42259243Sobrienstatic bool
42359243Sobrieninit_resuid(struct hast_resource *res)
42459243Sobrien{
42559243Sobrien
42659243Sobrien	mtx_lock(&metadata_lock);
42759243Sobrien	if (res->hr_resuid != 0) {
42859243Sobrien		mtx_unlock(&metadata_lock);
42959243Sobrien		return (false);
43059243Sobrien	} else {
43159243Sobrien		/* Initialize unique resource identifier. */
43259243Sobrien		arc4random_buf(&res->hr_resuid, sizeof(res->hr_resuid));
43359243Sobrien		mtx_unlock(&metadata_lock);
43459243Sobrien		if (metadata_write(res) < 0)
43559243Sobrien			exit(EX_NOINPUT);
43659243Sobrien		return (true);
43759243Sobrien	}
43859243Sobrien}
43959243Sobrien
44059243Sobrienstatic void
44159243Sobrieninit_local(struct hast_resource *res)
44259243Sobrien{
44359243Sobrien	unsigned char *buf;
44459243Sobrien	size_t mapsize;
44559243Sobrien
44659243Sobrien	if (metadata_read(res, true) < 0)
44759243Sobrien		exit(EX_NOINPUT);
44859243Sobrien	mtx_init(&res->hr_amp_lock);
44959243Sobrien	if (activemap_init(&res->hr_amp, res->hr_datasize, res->hr_extentsize,
45059243Sobrien	    res->hr_local_sectorsize, res->hr_keepdirty) < 0) {
45159243Sobrien		primary_exit(EX_TEMPFAIL, "Unable to create activemap");
45259243Sobrien	}
45359243Sobrien	mtx_init(&range_lock);
45459243Sobrien	cv_init(&range_regular_cond);
45559243Sobrien	if (rangelock_init(&range_regular) < 0)
45659243Sobrien		primary_exit(EX_TEMPFAIL, "Unable to create regular range lock");
45759243Sobrien	cv_init(&range_sync_cond);
45859243Sobrien	if (rangelock_init(&range_sync) < 0)
45959243Sobrien		primary_exit(EX_TEMPFAIL, "Unable to create sync range lock");
46059243Sobrien	mapsize = activemap_ondisk_size(res->hr_amp);
46159243Sobrien	buf = calloc(1, mapsize);
46259243Sobrien	if (buf == NULL) {
46359243Sobrien		primary_exitx(EX_TEMPFAIL,
46459243Sobrien		    "Unable to allocate buffer for activemap.");
46559243Sobrien	}
46659243Sobrien	if (pread(res->hr_localfd, buf, mapsize, METADATA_SIZE) !=
46759243Sobrien	    (ssize_t)mapsize) {
46859243Sobrien		primary_exit(EX_NOINPUT, "Unable to read activemap");
46959243Sobrien	}
47059243Sobrien	activemap_copyin(res->hr_amp, buf, mapsize);
47159243Sobrien	free(buf);
47259243Sobrien	if (res->hr_resuid != 0)
47359243Sobrien		return;
47459243Sobrien	/*
47559243Sobrien	 * We're using provider for the first time. Initialize local and remote
47659243Sobrien	 * counters. We don't initialize resuid here, as we want to do it just
47759243Sobrien	 * in time. The reason for this is that we want to inform secondary
47859243Sobrien	 * that there were no writes yet, so there is no need to synchronize
47959243Sobrien	 * anything.
48059243Sobrien	 */
48159243Sobrien	res->hr_primary_localcnt = 0;
48259243Sobrien	res->hr_primary_remotecnt = 0;
48359243Sobrien	if (metadata_write(res) < 0)
48459243Sobrien		exit(EX_NOINPUT);
48559243Sobrien}
48659243Sobrien
48759243Sobrienstatic int
48859243Sobrienprimary_connect(struct hast_resource *res, struct proto_conn **connp)
48959243Sobrien{
49059243Sobrien	struct proto_conn *conn;
49159243Sobrien	int16_t val;
49259243Sobrien
49359243Sobrien	val = 1;
49459243Sobrien	if (proto_send(res->hr_conn, &val, sizeof(val)) < 0) {
49559243Sobrien		primary_exit(EX_TEMPFAIL,
49659243Sobrien		    "Unable to send connection request to parent");
49759243Sobrien	}
49859243Sobrien	if (proto_recv(res->hr_conn, &val, sizeof(val)) < 0) {
49959243Sobrien		primary_exit(EX_TEMPFAIL,
50059243Sobrien		    "Unable to receive reply to connection request from parent");
50159243Sobrien	}
50259243Sobrien	if (val != 0) {
50359243Sobrien		errno = val;
50459243Sobrien		pjdlog_errno(LOG_WARNING, "Unable to connect to %s",
50559243Sobrien		    res->hr_remoteaddr);
50659243Sobrien		return (-1);
50759243Sobrien	}
50859243Sobrien	if (proto_connection_recv(res->hr_conn, true, &conn) < 0) {
50959243Sobrien		primary_exit(EX_TEMPFAIL,
51059243Sobrien		    "Unable to receive connection from parent");
51159243Sobrien	}
51259243Sobrien	if (proto_connect_wait(conn, HAST_TIMEOUT) < 0) {
51359243Sobrien		pjdlog_errno(LOG_WARNING, "Unable to connect to %s",
51459243Sobrien		    res->hr_remoteaddr);
51559243Sobrien		proto_close(conn);
51659243Sobrien		return (-1);
51759243Sobrien	}
51859243Sobrien	/* Error in setting timeout is not critical, but why should it fail? */
51959243Sobrien	if (proto_timeout(conn, res->hr_timeout) < 0)
52059243Sobrien		pjdlog_errno(LOG_WARNING, "Unable to set connection timeout");
52159243Sobrien
52259243Sobrien	*connp = conn;
523
524	return (0);
525}
526
527static bool
528init_remote(struct hast_resource *res, struct proto_conn **inp,
529    struct proto_conn **outp)
530{
531	struct proto_conn *in, *out;
532	struct nv *nvout, *nvin;
533	const unsigned char *token;
534	unsigned char *map;
535	const char *errmsg;
536	int32_t extentsize;
537	int64_t datasize;
538	uint32_t mapsize;
539	size_t size;
540
541	PJDLOG_ASSERT((inp == NULL && outp == NULL) || (inp != NULL && outp != NULL));
542	PJDLOG_ASSERT(real_remote(res));
543
544	in = out = NULL;
545	errmsg = NULL;
546
547	if (primary_connect(res, &out) == -1)
548		return (false);
549
550	/*
551	 * First handshake step.
552	 * Setup outgoing connection with remote node.
553	 */
554	nvout = nv_alloc();
555	nv_add_string(nvout, res->hr_name, "resource");
556	if (nv_error(nvout) != 0) {
557		pjdlog_common(LOG_WARNING, 0, nv_error(nvout),
558		    "Unable to allocate header for connection with %s",
559		    res->hr_remoteaddr);
560		nv_free(nvout);
561		goto close;
562	}
563	if (hast_proto_send(res, out, nvout, NULL, 0) < 0) {
564		pjdlog_errno(LOG_WARNING,
565		    "Unable to send handshake header to %s",
566		    res->hr_remoteaddr);
567		nv_free(nvout);
568		goto close;
569	}
570	nv_free(nvout);
571	if (hast_proto_recv_hdr(out, &nvin) < 0) {
572		pjdlog_errno(LOG_WARNING,
573		    "Unable to receive handshake header from %s",
574		    res->hr_remoteaddr);
575		goto close;
576	}
577	errmsg = nv_get_string(nvin, "errmsg");
578	if (errmsg != NULL) {
579		pjdlog_warning("%s", errmsg);
580		nv_free(nvin);
581		goto close;
582	}
583	token = nv_get_uint8_array(nvin, &size, "token");
584	if (token == NULL) {
585		pjdlog_warning("Handshake header from %s has no 'token' field.",
586		    res->hr_remoteaddr);
587		nv_free(nvin);
588		goto close;
589	}
590	if (size != sizeof(res->hr_token)) {
591		pjdlog_warning("Handshake header from %s contains 'token' of wrong size (got %zu, expected %zu).",
592		    res->hr_remoteaddr, size, sizeof(res->hr_token));
593		nv_free(nvin);
594		goto close;
595	}
596	bcopy(token, res->hr_token, sizeof(res->hr_token));
597	nv_free(nvin);
598
599	/*
600	 * Second handshake step.
601	 * Setup incoming connection with remote node.
602	 */
603	if (primary_connect(res, &in) == -1)
604		goto close;
605
606	nvout = nv_alloc();
607	nv_add_string(nvout, res->hr_name, "resource");
608	nv_add_uint8_array(nvout, res->hr_token, sizeof(res->hr_token),
609	    "token");
610	if (res->hr_resuid == 0) {
611		/*
612		 * The resuid field was not yet initialized.
613		 * Because we do synchronization inside init_resuid(), it is
614		 * possible that someone already initialized it, the function
615		 * will return false then, but if we successfully initialized
616		 * it, we will get true. True means that there were no writes
617		 * to this resource yet and we want to inform secondary that
618		 * synchronization is not needed by sending "virgin" argument.
619		 */
620		if (init_resuid(res))
621			nv_add_int8(nvout, 1, "virgin");
622	}
623	nv_add_uint64(nvout, res->hr_resuid, "resuid");
624	nv_add_uint64(nvout, res->hr_primary_localcnt, "localcnt");
625	nv_add_uint64(nvout, res->hr_primary_remotecnt, "remotecnt");
626	if (nv_error(nvout) != 0) {
627		pjdlog_common(LOG_WARNING, 0, nv_error(nvout),
628		    "Unable to allocate header for connection with %s",
629		    res->hr_remoteaddr);
630		nv_free(nvout);
631		goto close;
632	}
633	if (hast_proto_send(res, in, nvout, NULL, 0) < 0) {
634		pjdlog_errno(LOG_WARNING,
635		    "Unable to send handshake header to %s",
636		    res->hr_remoteaddr);
637		nv_free(nvout);
638		goto close;
639	}
640	nv_free(nvout);
641	if (hast_proto_recv_hdr(out, &nvin) < 0) {
642		pjdlog_errno(LOG_WARNING,
643		    "Unable to receive handshake header from %s",
644		    res->hr_remoteaddr);
645		goto close;
646	}
647	errmsg = nv_get_string(nvin, "errmsg");
648	if (errmsg != NULL) {
649		pjdlog_warning("%s", errmsg);
650		nv_free(nvin);
651		goto close;
652	}
653	datasize = nv_get_int64(nvin, "datasize");
654	if (datasize != res->hr_datasize) {
655		pjdlog_warning("Data size differs between nodes (local=%jd, remote=%jd).",
656		    (intmax_t)res->hr_datasize, (intmax_t)datasize);
657		nv_free(nvin);
658		goto close;
659	}
660	extentsize = nv_get_int32(nvin, "extentsize");
661	if (extentsize != res->hr_extentsize) {
662		pjdlog_warning("Extent size differs between nodes (local=%zd, remote=%zd).",
663		    (ssize_t)res->hr_extentsize, (ssize_t)extentsize);
664		nv_free(nvin);
665		goto close;
666	}
667	res->hr_secondary_localcnt = nv_get_uint64(nvin, "localcnt");
668	res->hr_secondary_remotecnt = nv_get_uint64(nvin, "remotecnt");
669	res->hr_syncsrc = nv_get_uint8(nvin, "syncsrc");
670	map = NULL;
671	mapsize = nv_get_uint32(nvin, "mapsize");
672	if (mapsize > 0) {
673		map = malloc(mapsize);
674		if (map == NULL) {
675			pjdlog_error("Unable to allocate memory for remote activemap (mapsize=%ju).",
676			    (uintmax_t)mapsize);
677			nv_free(nvin);
678			goto close;
679		}
680		/*
681		 * Remote node have some dirty extents on its own, lets
682		 * download its activemap.
683		 */
684		if (hast_proto_recv_data(res, out, nvin, map,
685		    mapsize) < 0) {
686			pjdlog_errno(LOG_ERR,
687			    "Unable to receive remote activemap");
688			nv_free(nvin);
689			free(map);
690			goto close;
691		}
692		/*
693		 * Merge local and remote bitmaps.
694		 */
695		activemap_merge(res->hr_amp, map, mapsize);
696		free(map);
697		/*
698		 * Now that we merged bitmaps from both nodes, flush it to the
699		 * disk before we start to synchronize.
700		 */
701		(void)hast_activemap_flush(res);
702	}
703	nv_free(nvin);
704	pjdlog_info("Connected to %s.", res->hr_remoteaddr);
705	if (inp != NULL && outp != NULL) {
706		*inp = in;
707		*outp = out;
708	} else {
709		res->hr_remotein = in;
710		res->hr_remoteout = out;
711	}
712	event_send(res, EVENT_CONNECT);
713	return (true);
714close:
715	if (errmsg != NULL && strcmp(errmsg, "Split-brain condition!") == 0)
716		event_send(res, EVENT_SPLITBRAIN);
717	proto_close(out);
718	if (in != NULL)
719		proto_close(in);
720	return (false);
721}
722
723static void
724sync_start(void)
725{
726
727	mtx_lock(&sync_lock);
728	sync_inprogress = true;
729	mtx_unlock(&sync_lock);
730	cv_signal(&sync_cond);
731}
732
733static void
734sync_stop(void)
735{
736
737	mtx_lock(&sync_lock);
738	if (sync_inprogress)
739		sync_inprogress = false;
740	mtx_unlock(&sync_lock);
741}
742
743static void
744init_ggate(struct hast_resource *res)
745{
746	struct g_gate_ctl_create ggiocreate;
747	struct g_gate_ctl_cancel ggiocancel;
748
749	/*
750	 * We communicate with ggate via /dev/ggctl. Open it.
751	 */
752	res->hr_ggatefd = open("/dev/" G_GATE_CTL_NAME, O_RDWR);
753	if (res->hr_ggatefd < 0)
754		primary_exit(EX_OSFILE, "Unable to open /dev/" G_GATE_CTL_NAME);
755	/*
756	 * Create provider before trying to connect, as connection failure
757	 * is not critical, but may take some time.
758	 */
759	bzero(&ggiocreate, sizeof(ggiocreate));
760	ggiocreate.gctl_version = G_GATE_VERSION;
761	ggiocreate.gctl_mediasize = res->hr_datasize;
762	ggiocreate.gctl_sectorsize = res->hr_local_sectorsize;
763	ggiocreate.gctl_flags = 0;
764	ggiocreate.gctl_maxcount = G_GATE_MAX_QUEUE_SIZE;
765	ggiocreate.gctl_timeout = 0;
766	ggiocreate.gctl_unit = G_GATE_NAME_GIVEN;
767	snprintf(ggiocreate.gctl_name, sizeof(ggiocreate.gctl_name), "hast/%s",
768	    res->hr_provname);
769	if (ioctl(res->hr_ggatefd, G_GATE_CMD_CREATE, &ggiocreate) == 0) {
770		pjdlog_info("Device hast/%s created.", res->hr_provname);
771		res->hr_ggateunit = ggiocreate.gctl_unit;
772		return;
773	}
774	if (errno != EEXIST) {
775		primary_exit(EX_OSERR, "Unable to create hast/%s device",
776		    res->hr_provname);
777	}
778	pjdlog_debug(1,
779	    "Device hast/%s already exists, we will try to take it over.",
780	    res->hr_provname);
781	/*
782	 * If we received EEXIST, we assume that the process who created the
783	 * provider died and didn't clean up. In that case we will start from
784	 * where he left of.
785	 */
786	bzero(&ggiocancel, sizeof(ggiocancel));
787	ggiocancel.gctl_version = G_GATE_VERSION;
788	ggiocancel.gctl_unit = G_GATE_NAME_GIVEN;
789	snprintf(ggiocancel.gctl_name, sizeof(ggiocancel.gctl_name), "hast/%s",
790	    res->hr_provname);
791	if (ioctl(res->hr_ggatefd, G_GATE_CMD_CANCEL, &ggiocancel) == 0) {
792		pjdlog_info("Device hast/%s recovered.", res->hr_provname);
793		res->hr_ggateunit = ggiocancel.gctl_unit;
794		return;
795	}
796	primary_exit(EX_OSERR, "Unable to take over hast/%s device",
797	    res->hr_provname);
798}
799
800void
801hastd_primary(struct hast_resource *res)
802{
803	pthread_t td;
804	pid_t pid;
805	int error, mode, debuglevel;
806
807	/*
808	 * Create communication channel for sending control commands from
809	 * parent to child.
810	 */
811	if (proto_client(NULL, "socketpair://", &res->hr_ctrl) < 0) {
812		/* TODO: There's no need for this to be fatal error. */
813		KEEP_ERRNO((void)pidfile_remove(pfh));
814		pjdlog_exit(EX_OSERR,
815		    "Unable to create control sockets between parent and child");
816	}
817	/*
818	 * Create communication channel for sending events from child to parent.
819	 */
820	if (proto_client(NULL, "socketpair://", &res->hr_event) < 0) {
821		/* TODO: There's no need for this to be fatal error. */
822		KEEP_ERRNO((void)pidfile_remove(pfh));
823		pjdlog_exit(EX_OSERR,
824		    "Unable to create event sockets between child and parent");
825	}
826	/*
827	 * Create communication channel for sending connection requests from
828	 * child to parent.
829	 */
830	if (proto_client(NULL, "socketpair://", &res->hr_conn) < 0) {
831		/* TODO: There's no need for this to be fatal error. */
832		KEEP_ERRNO((void)pidfile_remove(pfh));
833		pjdlog_exit(EX_OSERR,
834		    "Unable to create connection sockets between child and parent");
835	}
836
837	pid = fork();
838	if (pid < 0) {
839		/* TODO: There's no need for this to be fatal error. */
840		KEEP_ERRNO((void)pidfile_remove(pfh));
841		pjdlog_exit(EX_TEMPFAIL, "Unable to fork");
842	}
843
844	if (pid > 0) {
845		/* This is parent. */
846		/* Declare that we are receiver. */
847		proto_recv(res->hr_event, NULL, 0);
848		proto_recv(res->hr_conn, NULL, 0);
849		/* Declare that we are sender. */
850		proto_send(res->hr_ctrl, NULL, 0);
851		res->hr_workerpid = pid;
852		return;
853	}
854
855	gres = res;
856	mode = pjdlog_mode_get();
857	debuglevel = pjdlog_debug_get();
858
859	/* Declare that we are sender. */
860	proto_send(res->hr_event, NULL, 0);
861	proto_send(res->hr_conn, NULL, 0);
862	/* Declare that we are receiver. */
863	proto_recv(res->hr_ctrl, NULL, 0);
864	descriptors_cleanup(res);
865
866	descriptors_assert(res, mode);
867
868	pjdlog_init(mode);
869	pjdlog_debug_set(debuglevel);
870	pjdlog_prefix_set("[%s] (%s) ", res->hr_name, role2str(res->hr_role));
871	setproctitle("%s (primary)", res->hr_name);
872
873	init_local(res);
874	init_ggate(res);
875	init_environment(res);
876
877	if (drop_privs(true) != 0) {
878		cleanup(res);
879		exit(EX_CONFIG);
880	}
881	pjdlog_info("Privileges successfully dropped.");
882
883	/*
884	 * Create the guard thread first, so we can handle signals from the
885	 * very begining.
886	 */
887	error = pthread_create(&td, NULL, guard_thread, res);
888	PJDLOG_ASSERT(error == 0);
889	/*
890	 * Create the control thread before sending any event to the parent,
891	 * as we can deadlock when parent sends control request to worker,
892	 * but worker has no control thread started yet, so parent waits.
893	 * In the meantime worker sends an event to the parent, but parent
894	 * is unable to handle the event, because it waits for control
895	 * request response.
896	 */
897	error = pthread_create(&td, NULL, ctrl_thread, res);
898	PJDLOG_ASSERT(error == 0);
899	if (real_remote(res) && init_remote(res, NULL, NULL))
900		sync_start();
901	error = pthread_create(&td, NULL, ggate_recv_thread, res);
902	PJDLOG_ASSERT(error == 0);
903	error = pthread_create(&td, NULL, local_send_thread, res);
904	PJDLOG_ASSERT(error == 0);
905	error = pthread_create(&td, NULL, remote_send_thread, res);
906	PJDLOG_ASSERT(error == 0);
907	error = pthread_create(&td, NULL, remote_recv_thread, res);
908	PJDLOG_ASSERT(error == 0);
909	error = pthread_create(&td, NULL, ggate_send_thread, res);
910	PJDLOG_ASSERT(error == 0);
911	(void)sync_thread(res);
912}
913
914static void
915reqlog(int loglevel, int debuglevel, struct g_gate_ctl_io *ggio, const char *fmt, ...)
916{
917	char msg[1024];
918	va_list ap;
919	int len;
920
921	va_start(ap, fmt);
922	len = vsnprintf(msg, sizeof(msg), fmt, ap);
923	va_end(ap);
924	if ((size_t)len < sizeof(msg)) {
925		switch (ggio->gctl_cmd) {
926		case BIO_READ:
927			(void)snprintf(msg + len, sizeof(msg) - len,
928			    "READ(%ju, %ju).", (uintmax_t)ggio->gctl_offset,
929			    (uintmax_t)ggio->gctl_length);
930			break;
931		case BIO_DELETE:
932			(void)snprintf(msg + len, sizeof(msg) - len,
933			    "DELETE(%ju, %ju).", (uintmax_t)ggio->gctl_offset,
934			    (uintmax_t)ggio->gctl_length);
935			break;
936		case BIO_FLUSH:
937			(void)snprintf(msg + len, sizeof(msg) - len, "FLUSH.");
938			break;
939		case BIO_WRITE:
940			(void)snprintf(msg + len, sizeof(msg) - len,
941			    "WRITE(%ju, %ju).", (uintmax_t)ggio->gctl_offset,
942			    (uintmax_t)ggio->gctl_length);
943			break;
944		default:
945			(void)snprintf(msg + len, sizeof(msg) - len,
946			    "UNKNOWN(%u).", (unsigned int)ggio->gctl_cmd);
947			break;
948		}
949	}
950	pjdlog_common(loglevel, debuglevel, -1, "%s", msg);
951}
952
953static void
954remote_close(struct hast_resource *res, int ncomp)
955{
956
957	rw_wlock(&hio_remote_lock[ncomp]);
958	/*
959	 * A race is possible between dropping rlock and acquiring wlock -
960	 * another thread can close connection in-between.
961	 */
962	if (!ISCONNECTED(res, ncomp)) {
963		PJDLOG_ASSERT(res->hr_remotein == NULL);
964		PJDLOG_ASSERT(res->hr_remoteout == NULL);
965		rw_unlock(&hio_remote_lock[ncomp]);
966		return;
967	}
968
969	PJDLOG_ASSERT(res->hr_remotein != NULL);
970	PJDLOG_ASSERT(res->hr_remoteout != NULL);
971
972	pjdlog_debug(2, "Closing incoming connection to %s.",
973	    res->hr_remoteaddr);
974	proto_close(res->hr_remotein);
975	res->hr_remotein = NULL;
976	pjdlog_debug(2, "Closing outgoing connection to %s.",
977	    res->hr_remoteaddr);
978	proto_close(res->hr_remoteout);
979	res->hr_remoteout = NULL;
980
981	rw_unlock(&hio_remote_lock[ncomp]);
982
983	pjdlog_warning("Disconnected from %s.", res->hr_remoteaddr);
984
985	/*
986	 * Stop synchronization if in-progress.
987	 */
988	sync_stop();
989
990	event_send(res, EVENT_DISCONNECT);
991}
992
993/*
994 * Thread receives ggate I/O requests from the kernel and passes them to
995 * appropriate threads:
996 * WRITE - always goes to both local_send and remote_send threads
997 * READ (when the block is up-to-date on local component) -
998 *	only local_send thread
999 * READ (when the block isn't up-to-date on local component) -
1000 *	only remote_send thread
1001 * DELETE - always goes to both local_send and remote_send threads
1002 * FLUSH - always goes to both local_send and remote_send threads
1003 */
1004static void *
1005ggate_recv_thread(void *arg)
1006{
1007	struct hast_resource *res = arg;
1008	struct g_gate_ctl_io *ggio;
1009	struct hio *hio;
1010	unsigned int ii, ncomp, ncomps;
1011	int error;
1012
1013	ncomps = HAST_NCOMPONENTS;
1014
1015	for (;;) {
1016		pjdlog_debug(2, "ggate_recv: Taking free request.");
1017		QUEUE_TAKE2(hio, free);
1018		pjdlog_debug(2, "ggate_recv: (%p) Got free request.", hio);
1019		ggio = &hio->hio_ggio;
1020		ggio->gctl_unit = res->hr_ggateunit;
1021		ggio->gctl_length = MAXPHYS;
1022		ggio->gctl_error = 0;
1023		pjdlog_debug(2,
1024		    "ggate_recv: (%p) Waiting for request from the kernel.",
1025		    hio);
1026		if (ioctl(res->hr_ggatefd, G_GATE_CMD_START, ggio) < 0) {
1027			if (sigexit_received)
1028				pthread_exit(NULL);
1029			primary_exit(EX_OSERR, "G_GATE_CMD_START failed");
1030		}
1031		error = ggio->gctl_error;
1032		switch (error) {
1033		case 0:
1034			break;
1035		case ECANCELED:
1036			/* Exit gracefully. */
1037			if (!sigexit_received) {
1038				pjdlog_debug(2,
1039				    "ggate_recv: (%p) Received cancel from the kernel.",
1040				    hio);
1041				pjdlog_info("Received cancel from the kernel, exiting.");
1042			}
1043			pthread_exit(NULL);
1044		case ENOMEM:
1045			/*
1046			 * Buffer too small? Impossible, we allocate MAXPHYS
1047			 * bytes - request can't be bigger than that.
1048			 */
1049			/* FALLTHROUGH */
1050		case ENXIO:
1051		default:
1052			primary_exitx(EX_OSERR, "G_GATE_CMD_START failed: %s.",
1053			    strerror(error));
1054		}
1055		for (ii = 0; ii < ncomps; ii++)
1056			hio->hio_errors[ii] = EINVAL;
1057		reqlog(LOG_DEBUG, 2, ggio,
1058		    "ggate_recv: (%p) Request received from the kernel: ",
1059		    hio);
1060		/*
1061		 * Inform all components about new write request.
1062		 * For read request prefer local component unless the given
1063		 * range is out-of-date, then use remote component.
1064		 */
1065		switch (ggio->gctl_cmd) {
1066		case BIO_READ:
1067			pjdlog_debug(2,
1068			    "ggate_recv: (%p) Moving request to the send queue.",
1069			    hio);
1070			refcount_init(&hio->hio_countdown, 1);
1071			mtx_lock(&metadata_lock);
1072			if (res->hr_syncsrc == HAST_SYNCSRC_UNDEF ||
1073			    res->hr_syncsrc == HAST_SYNCSRC_PRIMARY) {
1074				/*
1075				 * This range is up-to-date on local component,
1076				 * so handle request locally.
1077				 */
1078				 /* Local component is 0 for now. */
1079				ncomp = 0;
1080			} else /* if (res->hr_syncsrc ==
1081			    HAST_SYNCSRC_SECONDARY) */ {
1082				PJDLOG_ASSERT(res->hr_syncsrc ==
1083				    HAST_SYNCSRC_SECONDARY);
1084				/*
1085				 * This range is out-of-date on local component,
1086				 * so send request to the remote node.
1087				 */
1088				 /* Remote component is 1 for now. */
1089				ncomp = 1;
1090			}
1091			mtx_unlock(&metadata_lock);
1092			QUEUE_INSERT1(hio, send, ncomp);
1093			break;
1094		case BIO_WRITE:
1095			if (res->hr_resuid == 0) {
1096				/*
1097				 * This is first write, initialize localcnt and
1098				 * resuid.
1099				 */
1100				res->hr_primary_localcnt = 1;
1101				(void)init_resuid(res);
1102			}
1103			for (;;) {
1104				mtx_lock(&range_lock);
1105				if (rangelock_islocked(range_sync,
1106				    ggio->gctl_offset, ggio->gctl_length)) {
1107					pjdlog_debug(2,
1108					    "regular: Range offset=%jd length=%zu locked.",
1109					    (intmax_t)ggio->gctl_offset,
1110					    (size_t)ggio->gctl_length);
1111					range_regular_wait = true;
1112					cv_wait(&range_regular_cond, &range_lock);
1113					range_regular_wait = false;
1114					mtx_unlock(&range_lock);
1115					continue;
1116				}
1117				if (rangelock_add(range_regular,
1118				    ggio->gctl_offset, ggio->gctl_length) < 0) {
1119					mtx_unlock(&range_lock);
1120					pjdlog_debug(2,
1121					    "regular: Range offset=%jd length=%zu is already locked, waiting.",
1122					    (intmax_t)ggio->gctl_offset,
1123					    (size_t)ggio->gctl_length);
1124					sleep(1);
1125					continue;
1126				}
1127				mtx_unlock(&range_lock);
1128				break;
1129			}
1130			mtx_lock(&res->hr_amp_lock);
1131			if (activemap_write_start(res->hr_amp,
1132			    ggio->gctl_offset, ggio->gctl_length)) {
1133				(void)hast_activemap_flush(res);
1134			}
1135			mtx_unlock(&res->hr_amp_lock);
1136			/* FALLTHROUGH */
1137		case BIO_DELETE:
1138		case BIO_FLUSH:
1139			pjdlog_debug(2,
1140			    "ggate_recv: (%p) Moving request to the send queues.",
1141			    hio);
1142			refcount_init(&hio->hio_countdown, ncomps);
1143			for (ii = 0; ii < ncomps; ii++)
1144				QUEUE_INSERT1(hio, send, ii);
1145			break;
1146		}
1147	}
1148	/* NOTREACHED */
1149	return (NULL);
1150}
1151
1152/*
1153 * Thread reads from or writes to local component.
1154 * If local read fails, it redirects it to remote_send thread.
1155 */
1156static void *
1157local_send_thread(void *arg)
1158{
1159	struct hast_resource *res = arg;
1160	struct g_gate_ctl_io *ggio;
1161	struct hio *hio;
1162	unsigned int ncomp, rncomp;
1163	ssize_t ret;
1164
1165	/* Local component is 0 for now. */
1166	ncomp = 0;
1167	/* Remote component is 1 for now. */
1168	rncomp = 1;
1169
1170	for (;;) {
1171		pjdlog_debug(2, "local_send: Taking request.");
1172		QUEUE_TAKE1(hio, send, ncomp, 0);
1173		pjdlog_debug(2, "local_send: (%p) Got request.", hio);
1174		ggio = &hio->hio_ggio;
1175		switch (ggio->gctl_cmd) {
1176		case BIO_READ:
1177			ret = pread(res->hr_localfd, ggio->gctl_data,
1178			    ggio->gctl_length,
1179			    ggio->gctl_offset + res->hr_localoff);
1180			if (ret == ggio->gctl_length)
1181				hio->hio_errors[ncomp] = 0;
1182			else {
1183				/*
1184				 * If READ failed, try to read from remote node.
1185				 */
1186				if (ret < 0) {
1187					reqlog(LOG_WARNING, 0, ggio,
1188					    "Local request failed (%s), trying remote node. ",
1189					    strerror(errno));
1190				} else if (ret != ggio->gctl_length) {
1191					reqlog(LOG_WARNING, 0, ggio,
1192					    "Local request failed (%zd != %jd), trying remote node. ",
1193					    ret, (intmax_t)ggio->gctl_length);
1194				}
1195				QUEUE_INSERT1(hio, send, rncomp);
1196				continue;
1197			}
1198			break;
1199		case BIO_WRITE:
1200			ret = pwrite(res->hr_localfd, ggio->gctl_data,
1201			    ggio->gctl_length,
1202			    ggio->gctl_offset + res->hr_localoff);
1203			if (ret < 0) {
1204				hio->hio_errors[ncomp] = errno;
1205				reqlog(LOG_WARNING, 0, ggio,
1206				    "Local request failed (%s): ",
1207				    strerror(errno));
1208			} else if (ret != ggio->gctl_length) {
1209				hio->hio_errors[ncomp] = EIO;
1210				reqlog(LOG_WARNING, 0, ggio,
1211				    "Local request failed (%zd != %jd): ",
1212				    ret, (intmax_t)ggio->gctl_length);
1213			} else {
1214				hio->hio_errors[ncomp] = 0;
1215			}
1216			break;
1217		case BIO_DELETE:
1218			ret = g_delete(res->hr_localfd,
1219			    ggio->gctl_offset + res->hr_localoff,
1220			    ggio->gctl_length);
1221			if (ret < 0) {
1222				hio->hio_errors[ncomp] = errno;
1223				reqlog(LOG_WARNING, 0, ggio,
1224				    "Local request failed (%s): ",
1225				    strerror(errno));
1226			} else {
1227				hio->hio_errors[ncomp] = 0;
1228			}
1229			break;
1230		case BIO_FLUSH:
1231			ret = g_flush(res->hr_localfd);
1232			if (ret < 0) {
1233				hio->hio_errors[ncomp] = errno;
1234				reqlog(LOG_WARNING, 0, ggio,
1235				    "Local request failed (%s): ",
1236				    strerror(errno));
1237			} else {
1238				hio->hio_errors[ncomp] = 0;
1239			}
1240			break;
1241		}
1242		if (refcount_release(&hio->hio_countdown)) {
1243			if (ISSYNCREQ(hio)) {
1244				mtx_lock(&sync_lock);
1245				SYNCREQDONE(hio);
1246				mtx_unlock(&sync_lock);
1247				cv_signal(&sync_cond);
1248			} else {
1249				pjdlog_debug(2,
1250				    "local_send: (%p) Moving request to the done queue.",
1251				    hio);
1252				QUEUE_INSERT2(hio, done);
1253			}
1254		}
1255	}
1256	/* NOTREACHED */
1257	return (NULL);
1258}
1259
1260static void
1261keepalive_send(struct hast_resource *res, unsigned int ncomp)
1262{
1263	struct nv *nv;
1264
1265	rw_rlock(&hio_remote_lock[ncomp]);
1266
1267	if (!ISCONNECTED(res, ncomp)) {
1268		rw_unlock(&hio_remote_lock[ncomp]);
1269		return;
1270	}
1271
1272	PJDLOG_ASSERT(res->hr_remotein != NULL);
1273	PJDLOG_ASSERT(res->hr_remoteout != NULL);
1274
1275	nv = nv_alloc();
1276	nv_add_uint8(nv, HIO_KEEPALIVE, "cmd");
1277	if (nv_error(nv) != 0) {
1278		rw_unlock(&hio_remote_lock[ncomp]);
1279		nv_free(nv);
1280		pjdlog_debug(1,
1281		    "keepalive_send: Unable to prepare header to send.");
1282		return;
1283	}
1284	if (hast_proto_send(res, res->hr_remoteout, nv, NULL, 0) < 0) {
1285		rw_unlock(&hio_remote_lock[ncomp]);
1286		pjdlog_common(LOG_DEBUG, 1, errno,
1287		    "keepalive_send: Unable to send request");
1288		nv_free(nv);
1289		remote_close(res, ncomp);
1290		return;
1291	}
1292
1293	rw_unlock(&hio_remote_lock[ncomp]);
1294	nv_free(nv);
1295	pjdlog_debug(2, "keepalive_send: Request sent.");
1296}
1297
1298/*
1299 * Thread sends request to secondary node.
1300 */
1301static void *
1302remote_send_thread(void *arg)
1303{
1304	struct hast_resource *res = arg;
1305	struct g_gate_ctl_io *ggio;
1306	time_t lastcheck, now;
1307	struct hio *hio;
1308	struct nv *nv;
1309	unsigned int ncomp;
1310	bool wakeup;
1311	uint64_t offset, length;
1312	uint8_t cmd;
1313	void *data;
1314
1315	/* Remote component is 1 for now. */
1316	ncomp = 1;
1317	lastcheck = time(NULL);
1318
1319	for (;;) {
1320		pjdlog_debug(2, "remote_send: Taking request.");
1321		QUEUE_TAKE1(hio, send, ncomp, HAST_KEEPALIVE);
1322		if (hio == NULL) {
1323			now = time(NULL);
1324			if (lastcheck + HAST_KEEPALIVE <= now) {
1325				keepalive_send(res, ncomp);
1326				lastcheck = now;
1327			}
1328			continue;
1329		}
1330		pjdlog_debug(2, "remote_send: (%p) Got request.", hio);
1331		ggio = &hio->hio_ggio;
1332		switch (ggio->gctl_cmd) {
1333		case BIO_READ:
1334			cmd = HIO_READ;
1335			data = NULL;
1336			offset = ggio->gctl_offset;
1337			length = ggio->gctl_length;
1338			break;
1339		case BIO_WRITE:
1340			cmd = HIO_WRITE;
1341			data = ggio->gctl_data;
1342			offset = ggio->gctl_offset;
1343			length = ggio->gctl_length;
1344			break;
1345		case BIO_DELETE:
1346			cmd = HIO_DELETE;
1347			data = NULL;
1348			offset = ggio->gctl_offset;
1349			length = ggio->gctl_length;
1350			break;
1351		case BIO_FLUSH:
1352			cmd = HIO_FLUSH;
1353			data = NULL;
1354			offset = 0;
1355			length = 0;
1356			break;
1357		default:
1358			PJDLOG_ASSERT(!"invalid condition");
1359			abort();
1360		}
1361		nv = nv_alloc();
1362		nv_add_uint8(nv, cmd, "cmd");
1363		nv_add_uint64(nv, (uint64_t)ggio->gctl_seq, "seq");
1364		nv_add_uint64(nv, offset, "offset");
1365		nv_add_uint64(nv, length, "length");
1366		if (nv_error(nv) != 0) {
1367			hio->hio_errors[ncomp] = nv_error(nv);
1368			pjdlog_debug(2,
1369			    "remote_send: (%p) Unable to prepare header to send.",
1370			    hio);
1371			reqlog(LOG_ERR, 0, ggio,
1372			    "Unable to prepare header to send (%s): ",
1373			    strerror(nv_error(nv)));
1374			/* Move failed request immediately to the done queue. */
1375			goto done_queue;
1376		}
1377		pjdlog_debug(2,
1378		    "remote_send: (%p) Moving request to the recv queue.",
1379		    hio);
1380		/*
1381		 * Protect connection from disappearing.
1382		 */
1383		rw_rlock(&hio_remote_lock[ncomp]);
1384		if (!ISCONNECTED(res, ncomp)) {
1385			rw_unlock(&hio_remote_lock[ncomp]);
1386			hio->hio_errors[ncomp] = ENOTCONN;
1387			goto done_queue;
1388		}
1389		/*
1390		 * Move the request to recv queue before sending it, because
1391		 * in different order we can get reply before we move request
1392		 * to recv queue.
1393		 */
1394		mtx_lock(&hio_recv_list_lock[ncomp]);
1395		wakeup = TAILQ_EMPTY(&hio_recv_list[ncomp]);
1396		TAILQ_INSERT_TAIL(&hio_recv_list[ncomp], hio, hio_next[ncomp]);
1397		mtx_unlock(&hio_recv_list_lock[ncomp]);
1398		if (hast_proto_send(res, res->hr_remoteout, nv, data,
1399		    data != NULL ? length : 0) < 0) {
1400			hio->hio_errors[ncomp] = errno;
1401			rw_unlock(&hio_remote_lock[ncomp]);
1402			pjdlog_debug(2,
1403			    "remote_send: (%p) Unable to send request.", hio);
1404			reqlog(LOG_ERR, 0, ggio,
1405			    "Unable to send request (%s): ",
1406			    strerror(hio->hio_errors[ncomp]));
1407			remote_close(res, ncomp);
1408			/*
1409			 * Take request back from the receive queue and move
1410			 * it immediately to the done queue.
1411			 */
1412			mtx_lock(&hio_recv_list_lock[ncomp]);
1413			TAILQ_REMOVE(&hio_recv_list[ncomp], hio, hio_next[ncomp]);
1414			mtx_unlock(&hio_recv_list_lock[ncomp]);
1415			goto done_queue;
1416		}
1417		rw_unlock(&hio_remote_lock[ncomp]);
1418		nv_free(nv);
1419		if (wakeup)
1420			cv_signal(&hio_recv_list_cond[ncomp]);
1421		continue;
1422done_queue:
1423		nv_free(nv);
1424		if (ISSYNCREQ(hio)) {
1425			if (!refcount_release(&hio->hio_countdown))
1426				continue;
1427			mtx_lock(&sync_lock);
1428			SYNCREQDONE(hio);
1429			mtx_unlock(&sync_lock);
1430			cv_signal(&sync_cond);
1431			continue;
1432		}
1433		if (ggio->gctl_cmd == BIO_WRITE) {
1434			mtx_lock(&res->hr_amp_lock);
1435			if (activemap_need_sync(res->hr_amp, ggio->gctl_offset,
1436			    ggio->gctl_length)) {
1437				(void)hast_activemap_flush(res);
1438			}
1439			mtx_unlock(&res->hr_amp_lock);
1440		}
1441		if (!refcount_release(&hio->hio_countdown))
1442			continue;
1443		pjdlog_debug(2,
1444		    "remote_send: (%p) Moving request to the done queue.",
1445		    hio);
1446		QUEUE_INSERT2(hio, done);
1447	}
1448	/* NOTREACHED */
1449	return (NULL);
1450}
1451
1452/*
1453 * Thread receives answer from secondary node and passes it to ggate_send
1454 * thread.
1455 */
1456static void *
1457remote_recv_thread(void *arg)
1458{
1459	struct hast_resource *res = arg;
1460	struct g_gate_ctl_io *ggio;
1461	struct hio *hio;
1462	struct nv *nv;
1463	unsigned int ncomp;
1464	uint64_t seq;
1465	int error;
1466
1467	/* Remote component is 1 for now. */
1468	ncomp = 1;
1469
1470	for (;;) {
1471		/* Wait until there is anything to receive. */
1472		mtx_lock(&hio_recv_list_lock[ncomp]);
1473		while (TAILQ_EMPTY(&hio_recv_list[ncomp])) {
1474			pjdlog_debug(2, "remote_recv: No requests, waiting.");
1475			cv_wait(&hio_recv_list_cond[ncomp],
1476			    &hio_recv_list_lock[ncomp]);
1477		}
1478		mtx_unlock(&hio_recv_list_lock[ncomp]);
1479		rw_rlock(&hio_remote_lock[ncomp]);
1480		if (!ISCONNECTED(res, ncomp)) {
1481			rw_unlock(&hio_remote_lock[ncomp]);
1482			/*
1483			 * Connection is dead, so move all pending requests to
1484			 * the done queue (one-by-one).
1485			 */
1486			mtx_lock(&hio_recv_list_lock[ncomp]);
1487			hio = TAILQ_FIRST(&hio_recv_list[ncomp]);
1488			PJDLOG_ASSERT(hio != NULL);
1489			TAILQ_REMOVE(&hio_recv_list[ncomp], hio,
1490			    hio_next[ncomp]);
1491			mtx_unlock(&hio_recv_list_lock[ncomp]);
1492			goto done_queue;
1493		}
1494		if (hast_proto_recv_hdr(res->hr_remotein, &nv) < 0) {
1495			pjdlog_errno(LOG_ERR,
1496			    "Unable to receive reply header");
1497			rw_unlock(&hio_remote_lock[ncomp]);
1498			remote_close(res, ncomp);
1499			continue;
1500		}
1501		rw_unlock(&hio_remote_lock[ncomp]);
1502		seq = nv_get_uint64(nv, "seq");
1503		if (seq == 0) {
1504			pjdlog_error("Header contains no 'seq' field.");
1505			nv_free(nv);
1506			continue;
1507		}
1508		mtx_lock(&hio_recv_list_lock[ncomp]);
1509		TAILQ_FOREACH(hio, &hio_recv_list[ncomp], hio_next[ncomp]) {
1510			if (hio->hio_ggio.gctl_seq == seq) {
1511				TAILQ_REMOVE(&hio_recv_list[ncomp], hio,
1512				    hio_next[ncomp]);
1513				break;
1514			}
1515		}
1516		mtx_unlock(&hio_recv_list_lock[ncomp]);
1517		if (hio == NULL) {
1518			pjdlog_error("Found no request matching received 'seq' field (%ju).",
1519			    (uintmax_t)seq);
1520			nv_free(nv);
1521			continue;
1522		}
1523		error = nv_get_int16(nv, "error");
1524		if (error != 0) {
1525			/* Request failed on remote side. */
1526			hio->hio_errors[ncomp] = error;
1527			reqlog(LOG_WARNING, 0, &hio->hio_ggio,
1528			    "Remote request failed (%s): ", strerror(error));
1529			nv_free(nv);
1530			goto done_queue;
1531		}
1532		ggio = &hio->hio_ggio;
1533		switch (ggio->gctl_cmd) {
1534		case BIO_READ:
1535			rw_rlock(&hio_remote_lock[ncomp]);
1536			if (!ISCONNECTED(res, ncomp)) {
1537				rw_unlock(&hio_remote_lock[ncomp]);
1538				nv_free(nv);
1539				goto done_queue;
1540			}
1541			if (hast_proto_recv_data(res, res->hr_remotein, nv,
1542			    ggio->gctl_data, ggio->gctl_length) < 0) {
1543				hio->hio_errors[ncomp] = errno;
1544				pjdlog_errno(LOG_ERR,
1545				    "Unable to receive reply data");
1546				rw_unlock(&hio_remote_lock[ncomp]);
1547				nv_free(nv);
1548				remote_close(res, ncomp);
1549				goto done_queue;
1550			}
1551			rw_unlock(&hio_remote_lock[ncomp]);
1552			break;
1553		case BIO_WRITE:
1554		case BIO_DELETE:
1555		case BIO_FLUSH:
1556			break;
1557		default:
1558			PJDLOG_ASSERT(!"invalid condition");
1559			abort();
1560		}
1561		hio->hio_errors[ncomp] = 0;
1562		nv_free(nv);
1563done_queue:
1564		if (refcount_release(&hio->hio_countdown)) {
1565			if (ISSYNCREQ(hio)) {
1566				mtx_lock(&sync_lock);
1567				SYNCREQDONE(hio);
1568				mtx_unlock(&sync_lock);
1569				cv_signal(&sync_cond);
1570			} else {
1571				pjdlog_debug(2,
1572				    "remote_recv: (%p) Moving request to the done queue.",
1573				    hio);
1574				QUEUE_INSERT2(hio, done);
1575			}
1576		}
1577	}
1578	/* NOTREACHED */
1579	return (NULL);
1580}
1581
1582/*
1583 * Thread sends answer to the kernel.
1584 */
1585static void *
1586ggate_send_thread(void *arg)
1587{
1588	struct hast_resource *res = arg;
1589	struct g_gate_ctl_io *ggio;
1590	struct hio *hio;
1591	unsigned int ii, ncomp, ncomps;
1592
1593	ncomps = HAST_NCOMPONENTS;
1594
1595	for (;;) {
1596		pjdlog_debug(2, "ggate_send: Taking request.");
1597		QUEUE_TAKE2(hio, done);
1598		pjdlog_debug(2, "ggate_send: (%p) Got request.", hio);
1599		ggio = &hio->hio_ggio;
1600		for (ii = 0; ii < ncomps; ii++) {
1601			if (hio->hio_errors[ii] == 0) {
1602				/*
1603				 * One successful request is enough to declare
1604				 * success.
1605				 */
1606				ggio->gctl_error = 0;
1607				break;
1608			}
1609		}
1610		if (ii == ncomps) {
1611			/*
1612			 * None of the requests were successful.
1613			 * Use first error.
1614			 */
1615			ggio->gctl_error = hio->hio_errors[0];
1616		}
1617		if (ggio->gctl_error == 0 && ggio->gctl_cmd == BIO_WRITE) {
1618			mtx_lock(&res->hr_amp_lock);
1619			activemap_write_complete(res->hr_amp,
1620			    ggio->gctl_offset, ggio->gctl_length);
1621			mtx_unlock(&res->hr_amp_lock);
1622		}
1623		if (ggio->gctl_cmd == BIO_WRITE) {
1624			/*
1625			 * Unlock range we locked.
1626			 */
1627			mtx_lock(&range_lock);
1628			rangelock_del(range_regular, ggio->gctl_offset,
1629			    ggio->gctl_length);
1630			if (range_sync_wait)
1631				cv_signal(&range_sync_cond);
1632			mtx_unlock(&range_lock);
1633			/*
1634			 * Bump local count if this is first write after
1635			 * connection failure with remote node.
1636			 */
1637			ncomp = 1;
1638			rw_rlock(&hio_remote_lock[ncomp]);
1639			if (!ISCONNECTED(res, ncomp)) {
1640				mtx_lock(&metadata_lock);
1641				if (res->hr_primary_localcnt ==
1642				    res->hr_secondary_remotecnt) {
1643					res->hr_primary_localcnt++;
1644					pjdlog_debug(1,
1645					    "Increasing localcnt to %ju.",
1646					    (uintmax_t)res->hr_primary_localcnt);
1647					(void)metadata_write(res);
1648				}
1649				mtx_unlock(&metadata_lock);
1650			}
1651			rw_unlock(&hio_remote_lock[ncomp]);
1652		}
1653		if (ioctl(res->hr_ggatefd, G_GATE_CMD_DONE, ggio) < 0)
1654			primary_exit(EX_OSERR, "G_GATE_CMD_DONE failed");
1655		pjdlog_debug(2,
1656		    "ggate_send: (%p) Moving request to the free queue.", hio);
1657		QUEUE_INSERT2(hio, free);
1658	}
1659	/* NOTREACHED */
1660	return (NULL);
1661}
1662
1663/*
1664 * Thread synchronize local and remote components.
1665 */
1666static void *
1667sync_thread(void *arg __unused)
1668{
1669	struct hast_resource *res = arg;
1670	struct hio *hio;
1671	struct g_gate_ctl_io *ggio;
1672	struct timeval tstart, tend, tdiff;
1673	unsigned int ii, ncomp, ncomps;
1674	off_t offset, length, synced;
1675	bool dorewind;
1676	int syncext;
1677
1678	ncomps = HAST_NCOMPONENTS;
1679	dorewind = true;
1680	synced = 0;
1681	offset = -1;
1682
1683	for (;;) {
1684		mtx_lock(&sync_lock);
1685		if (offset >= 0 && !sync_inprogress) {
1686			gettimeofday(&tend, NULL);
1687			timersub(&tend, &tstart, &tdiff);
1688			pjdlog_info("Synchronization interrupted after %#.0T. "
1689			    "%NB synchronized so far.", &tdiff,
1690			    (intmax_t)synced);
1691			event_send(res, EVENT_SYNCINTR);
1692		}
1693		while (!sync_inprogress) {
1694			dorewind = true;
1695			synced = 0;
1696			cv_wait(&sync_cond, &sync_lock);
1697		}
1698		mtx_unlock(&sync_lock);
1699		/*
1700		 * Obtain offset at which we should synchronize.
1701		 * Rewind synchronization if needed.
1702		 */
1703		mtx_lock(&res->hr_amp_lock);
1704		if (dorewind)
1705			activemap_sync_rewind(res->hr_amp);
1706		offset = activemap_sync_offset(res->hr_amp, &length, &syncext);
1707		if (syncext != -1) {
1708			/*
1709			 * We synchronized entire syncext extent, we can mark
1710			 * it as clean now.
1711			 */
1712			if (activemap_extent_complete(res->hr_amp, syncext))
1713				(void)hast_activemap_flush(res);
1714		}
1715		mtx_unlock(&res->hr_amp_lock);
1716		if (dorewind) {
1717			dorewind = false;
1718			if (offset < 0)
1719				pjdlog_info("Nodes are in sync.");
1720			else {
1721				pjdlog_info("Synchronization started. %NB to go.",
1722				    (intmax_t)(res->hr_extentsize *
1723				    activemap_ndirty(res->hr_amp)));
1724				event_send(res, EVENT_SYNCSTART);
1725				gettimeofday(&tstart, NULL);
1726			}
1727		}
1728		if (offset < 0) {
1729			sync_stop();
1730			pjdlog_debug(1, "Nothing to synchronize.");
1731			/*
1732			 * Synchronization complete, make both localcnt and
1733			 * remotecnt equal.
1734			 */
1735			ncomp = 1;
1736			rw_rlock(&hio_remote_lock[ncomp]);
1737			if (ISCONNECTED(res, ncomp)) {
1738				if (synced > 0) {
1739					int64_t bps;
1740
1741					gettimeofday(&tend, NULL);
1742					timersub(&tend, &tstart, &tdiff);
1743					bps = (int64_t)((double)synced /
1744					    ((double)tdiff.tv_sec +
1745					    (double)tdiff.tv_usec / 1000000));
1746					pjdlog_info("Synchronization complete. "
1747					    "%NB synchronized in %#.0lT (%NB/sec).",
1748					    (intmax_t)synced, &tdiff,
1749					    (intmax_t)bps);
1750					event_send(res, EVENT_SYNCDONE);
1751				}
1752				mtx_lock(&metadata_lock);
1753				res->hr_syncsrc = HAST_SYNCSRC_UNDEF;
1754				res->hr_primary_localcnt =
1755				    res->hr_secondary_localcnt;
1756				res->hr_primary_remotecnt =
1757				    res->hr_secondary_remotecnt;
1758				pjdlog_debug(1,
1759				    "Setting localcnt to %ju and remotecnt to %ju.",
1760				    (uintmax_t)res->hr_primary_localcnt,
1761				    (uintmax_t)res->hr_secondary_localcnt);
1762				(void)metadata_write(res);
1763				mtx_unlock(&metadata_lock);
1764			}
1765			rw_unlock(&hio_remote_lock[ncomp]);
1766			continue;
1767		}
1768		pjdlog_debug(2, "sync: Taking free request.");
1769		QUEUE_TAKE2(hio, free);
1770		pjdlog_debug(2, "sync: (%p) Got free request.", hio);
1771		/*
1772		 * Lock the range we are going to synchronize. We don't want
1773		 * race where someone writes between our read and write.
1774		 */
1775		for (;;) {
1776			mtx_lock(&range_lock);
1777			if (rangelock_islocked(range_regular, offset, length)) {
1778				pjdlog_debug(2,
1779				    "sync: Range offset=%jd length=%jd locked.",
1780				    (intmax_t)offset, (intmax_t)length);
1781				range_sync_wait = true;
1782				cv_wait(&range_sync_cond, &range_lock);
1783				range_sync_wait = false;
1784				mtx_unlock(&range_lock);
1785				continue;
1786			}
1787			if (rangelock_add(range_sync, offset, length) < 0) {
1788				mtx_unlock(&range_lock);
1789				pjdlog_debug(2,
1790				    "sync: Range offset=%jd length=%jd is already locked, waiting.",
1791				    (intmax_t)offset, (intmax_t)length);
1792				sleep(1);
1793				continue;
1794			}
1795			mtx_unlock(&range_lock);
1796			break;
1797		}
1798		/*
1799		 * First read the data from synchronization source.
1800		 */
1801		SYNCREQ(hio);
1802		ggio = &hio->hio_ggio;
1803		ggio->gctl_cmd = BIO_READ;
1804		ggio->gctl_offset = offset;
1805		ggio->gctl_length = length;
1806		ggio->gctl_error = 0;
1807		for (ii = 0; ii < ncomps; ii++)
1808			hio->hio_errors[ii] = EINVAL;
1809		reqlog(LOG_DEBUG, 2, ggio, "sync: (%p) Sending sync request: ",
1810		    hio);
1811		pjdlog_debug(2, "sync: (%p) Moving request to the send queue.",
1812		    hio);
1813		mtx_lock(&metadata_lock);
1814		if (res->hr_syncsrc == HAST_SYNCSRC_PRIMARY) {
1815			/*
1816			 * This range is up-to-date on local component,
1817			 * so handle request locally.
1818			 */
1819			 /* Local component is 0 for now. */
1820			ncomp = 0;
1821		} else /* if (res->hr_syncsrc == HAST_SYNCSRC_SECONDARY) */ {
1822			PJDLOG_ASSERT(res->hr_syncsrc == HAST_SYNCSRC_SECONDARY);
1823			/*
1824			 * This range is out-of-date on local component,
1825			 * so send request to the remote node.
1826			 */
1827			 /* Remote component is 1 for now. */
1828			ncomp = 1;
1829		}
1830		mtx_unlock(&metadata_lock);
1831		refcount_init(&hio->hio_countdown, 1);
1832		QUEUE_INSERT1(hio, send, ncomp);
1833
1834		/*
1835		 * Let's wait for READ to finish.
1836		 */
1837		mtx_lock(&sync_lock);
1838		while (!ISSYNCREQDONE(hio))
1839			cv_wait(&sync_cond, &sync_lock);
1840		mtx_unlock(&sync_lock);
1841
1842		if (hio->hio_errors[ncomp] != 0) {
1843			pjdlog_error("Unable to read synchronization data: %s.",
1844			    strerror(hio->hio_errors[ncomp]));
1845			goto free_queue;
1846		}
1847
1848		/*
1849		 * We read the data from synchronization source, now write it
1850		 * to synchronization target.
1851		 */
1852		SYNCREQ(hio);
1853		ggio->gctl_cmd = BIO_WRITE;
1854		for (ii = 0; ii < ncomps; ii++)
1855			hio->hio_errors[ii] = EINVAL;
1856		reqlog(LOG_DEBUG, 2, ggio, "sync: (%p) Sending sync request: ",
1857		    hio);
1858		pjdlog_debug(2, "sync: (%p) Moving request to the send queue.",
1859		    hio);
1860		mtx_lock(&metadata_lock);
1861		if (res->hr_syncsrc == HAST_SYNCSRC_PRIMARY) {
1862			/*
1863			 * This range is up-to-date on local component,
1864			 * so we update remote component.
1865			 */
1866			 /* Remote component is 1 for now. */
1867			ncomp = 1;
1868		} else /* if (res->hr_syncsrc == HAST_SYNCSRC_SECONDARY) */ {
1869			PJDLOG_ASSERT(res->hr_syncsrc == HAST_SYNCSRC_SECONDARY);
1870			/*
1871			 * This range is out-of-date on local component,
1872			 * so we update it.
1873			 */
1874			 /* Local component is 0 for now. */
1875			ncomp = 0;
1876		}
1877		mtx_unlock(&metadata_lock);
1878
1879		pjdlog_debug(2, "sync: (%p) Moving request to the send queues.",
1880		    hio);
1881		refcount_init(&hio->hio_countdown, 1);
1882		QUEUE_INSERT1(hio, send, ncomp);
1883
1884		/*
1885		 * Let's wait for WRITE to finish.
1886		 */
1887		mtx_lock(&sync_lock);
1888		while (!ISSYNCREQDONE(hio))
1889			cv_wait(&sync_cond, &sync_lock);
1890		mtx_unlock(&sync_lock);
1891
1892		if (hio->hio_errors[ncomp] != 0) {
1893			pjdlog_error("Unable to write synchronization data: %s.",
1894			    strerror(hio->hio_errors[ncomp]));
1895			goto free_queue;
1896		}
1897
1898		synced += length;
1899free_queue:
1900		mtx_lock(&range_lock);
1901		rangelock_del(range_sync, offset, length);
1902		if (range_regular_wait)
1903			cv_signal(&range_regular_cond);
1904		mtx_unlock(&range_lock);
1905		pjdlog_debug(2, "sync: (%p) Moving request to the free queue.",
1906		    hio);
1907		QUEUE_INSERT2(hio, free);
1908	}
1909	/* NOTREACHED */
1910	return (NULL);
1911}
1912
1913void
1914primary_config_reload(struct hast_resource *res, struct nv *nv)
1915{
1916	unsigned int ii, ncomps;
1917	int modified, vint;
1918	const char *vstr;
1919
1920	pjdlog_info("Reloading configuration...");
1921
1922	PJDLOG_ASSERT(res->hr_role == HAST_ROLE_PRIMARY);
1923	PJDLOG_ASSERT(gres == res);
1924	nv_assert(nv, "remoteaddr");
1925	nv_assert(nv, "sourceaddr");
1926	nv_assert(nv, "replication");
1927	nv_assert(nv, "checksum");
1928	nv_assert(nv, "compression");
1929	nv_assert(nv, "timeout");
1930	nv_assert(nv, "exec");
1931
1932	ncomps = HAST_NCOMPONENTS;
1933
1934#define MODIFIED_REMOTEADDR	0x01
1935#define MODIFIED_SOURCEADDR	0x02
1936#define MODIFIED_REPLICATION	0x04
1937#define MODIFIED_CHECKSUM	0x08
1938#define MODIFIED_COMPRESSION	0x10
1939#define MODIFIED_TIMEOUT	0x20
1940#define MODIFIED_EXEC		0x40
1941	modified = 0;
1942
1943	vstr = nv_get_string(nv, "remoteaddr");
1944	if (strcmp(gres->hr_remoteaddr, vstr) != 0) {
1945		/*
1946		 * Don't copy res->hr_remoteaddr to gres just yet.
1947		 * We want remote_close() to log disconnect from the old
1948		 * addresses, not from the new ones.
1949		 */
1950		modified |= MODIFIED_REMOTEADDR;
1951	}
1952	vstr = nv_get_string(nv, "sourceaddr");
1953	if (strcmp(gres->hr_sourceaddr, vstr) != 0) {
1954		strlcpy(gres->hr_sourceaddr, vstr, sizeof(gres->hr_sourceaddr));
1955		modified |= MODIFIED_SOURCEADDR;
1956	}
1957	vint = nv_get_int32(nv, "replication");
1958	if (gres->hr_replication != vint) {
1959		gres->hr_replication = vint;
1960		modified |= MODIFIED_REPLICATION;
1961	}
1962	vint = nv_get_int32(nv, "checksum");
1963	if (gres->hr_checksum != vint) {
1964		gres->hr_checksum = vint;
1965		modified |= MODIFIED_CHECKSUM;
1966	}
1967	vint = nv_get_int32(nv, "compression");
1968	if (gres->hr_compression != vint) {
1969		gres->hr_compression = vint;
1970		modified |= MODIFIED_COMPRESSION;
1971	}
1972	vint = nv_get_int32(nv, "timeout");
1973	if (gres->hr_timeout != vint) {
1974		gres->hr_timeout = vint;
1975		modified |= MODIFIED_TIMEOUT;
1976	}
1977	vstr = nv_get_string(nv, "exec");
1978	if (strcmp(gres->hr_exec, vstr) != 0) {
1979		strlcpy(gres->hr_exec, vstr, sizeof(gres->hr_exec));
1980		modified |= MODIFIED_EXEC;
1981	}
1982
1983	/*
1984	 * Change timeout for connected sockets.
1985	 * Don't bother if we need to reconnect.
1986	 */
1987	if ((modified & MODIFIED_TIMEOUT) != 0 &&
1988	    (modified & (MODIFIED_REMOTEADDR | MODIFIED_SOURCEADDR |
1989	    MODIFIED_REPLICATION)) == 0) {
1990		for (ii = 0; ii < ncomps; ii++) {
1991			if (!ISREMOTE(ii))
1992				continue;
1993			rw_rlock(&hio_remote_lock[ii]);
1994			if (!ISCONNECTED(gres, ii)) {
1995				rw_unlock(&hio_remote_lock[ii]);
1996				continue;
1997			}
1998			rw_unlock(&hio_remote_lock[ii]);
1999			if (proto_timeout(gres->hr_remotein,
2000			    gres->hr_timeout) < 0) {
2001				pjdlog_errno(LOG_WARNING,
2002				    "Unable to set connection timeout");
2003			}
2004			if (proto_timeout(gres->hr_remoteout,
2005			    gres->hr_timeout) < 0) {
2006				pjdlog_errno(LOG_WARNING,
2007				    "Unable to set connection timeout");
2008			}
2009		}
2010	}
2011	if ((modified & (MODIFIED_REMOTEADDR | MODIFIED_SOURCEADDR |
2012	    MODIFIED_REPLICATION)) != 0) {
2013		for (ii = 0; ii < ncomps; ii++) {
2014			if (!ISREMOTE(ii))
2015				continue;
2016			remote_close(gres, ii);
2017		}
2018		if (modified & MODIFIED_REMOTEADDR) {
2019			vstr = nv_get_string(nv, "remoteaddr");
2020			strlcpy(gres->hr_remoteaddr, vstr,
2021			    sizeof(gres->hr_remoteaddr));
2022		}
2023	}
2024#undef	MODIFIED_REMOTEADDR
2025#undef	MODIFIED_SOURCEADDR
2026#undef	MODIFIED_REPLICATION
2027#undef	MODIFIED_CHECKSUM
2028#undef	MODIFIED_COMPRESSION
2029#undef	MODIFIED_TIMEOUT
2030#undef	MODIFIED_EXEC
2031
2032	pjdlog_info("Configuration reloaded successfully.");
2033}
2034
2035static void
2036guard_one(struct hast_resource *res, unsigned int ncomp)
2037{
2038	struct proto_conn *in, *out;
2039
2040	if (!ISREMOTE(ncomp))
2041		return;
2042
2043	rw_rlock(&hio_remote_lock[ncomp]);
2044
2045	if (!real_remote(res)) {
2046		rw_unlock(&hio_remote_lock[ncomp]);
2047		return;
2048	}
2049
2050	if (ISCONNECTED(res, ncomp)) {
2051		PJDLOG_ASSERT(res->hr_remotein != NULL);
2052		PJDLOG_ASSERT(res->hr_remoteout != NULL);
2053		rw_unlock(&hio_remote_lock[ncomp]);
2054		pjdlog_debug(2, "remote_guard: Connection to %s is ok.",
2055		    res->hr_remoteaddr);
2056		return;
2057	}
2058
2059	PJDLOG_ASSERT(res->hr_remotein == NULL);
2060	PJDLOG_ASSERT(res->hr_remoteout == NULL);
2061	/*
2062	 * Upgrade the lock. It doesn't have to be atomic as no other thread
2063	 * can change connection status from disconnected to connected.
2064	 */
2065	rw_unlock(&hio_remote_lock[ncomp]);
2066	pjdlog_debug(2, "remote_guard: Reconnecting to %s.",
2067	    res->hr_remoteaddr);
2068	in = out = NULL;
2069	if (init_remote(res, &in, &out)) {
2070		rw_wlock(&hio_remote_lock[ncomp]);
2071		PJDLOG_ASSERT(res->hr_remotein == NULL);
2072		PJDLOG_ASSERT(res->hr_remoteout == NULL);
2073		PJDLOG_ASSERT(in != NULL && out != NULL);
2074		res->hr_remotein = in;
2075		res->hr_remoteout = out;
2076		rw_unlock(&hio_remote_lock[ncomp]);
2077		pjdlog_info("Successfully reconnected to %s.",
2078		    res->hr_remoteaddr);
2079		sync_start();
2080	} else {
2081		/* Both connections should be NULL. */
2082		PJDLOG_ASSERT(res->hr_remotein == NULL);
2083		PJDLOG_ASSERT(res->hr_remoteout == NULL);
2084		PJDLOG_ASSERT(in == NULL && out == NULL);
2085		pjdlog_debug(2, "remote_guard: Reconnect to %s failed.",
2086		    res->hr_remoteaddr);
2087	}
2088}
2089
2090/*
2091 * Thread guards remote connections and reconnects when needed, handles
2092 * signals, etc.
2093 */
2094static void *
2095guard_thread(void *arg)
2096{
2097	struct hast_resource *res = arg;
2098	unsigned int ii, ncomps;
2099	struct timespec timeout;
2100	time_t lastcheck, now;
2101	sigset_t mask;
2102	int signo;
2103
2104	ncomps = HAST_NCOMPONENTS;
2105	lastcheck = time(NULL);
2106
2107	PJDLOG_VERIFY(sigemptyset(&mask) == 0);
2108	PJDLOG_VERIFY(sigaddset(&mask, SIGINT) == 0);
2109	PJDLOG_VERIFY(sigaddset(&mask, SIGTERM) == 0);
2110
2111	timeout.tv_sec = HAST_KEEPALIVE;
2112	timeout.tv_nsec = 0;
2113	signo = -1;
2114
2115	for (;;) {
2116		switch (signo) {
2117		case SIGINT:
2118		case SIGTERM:
2119			sigexit_received = true;
2120			primary_exitx(EX_OK,
2121			    "Termination signal received, exiting.");
2122			break;
2123		default:
2124			break;
2125		}
2126
2127		pjdlog_debug(2, "remote_guard: Checking connections.");
2128		now = time(NULL);
2129		if (lastcheck + HAST_KEEPALIVE <= now) {
2130			for (ii = 0; ii < ncomps; ii++)
2131				guard_one(res, ii);
2132			lastcheck = now;
2133		}
2134		signo = sigtimedwait(&mask, NULL, &timeout);
2135	}
2136	/* NOTREACHED */
2137	return (NULL);
2138}
2139