xref: /freebsd/sbin/hastd/primary.c (revision 7a1c0d963366a31363d3705697a083dd8efee077)
1 /*-
2  * Copyright (c) 2009 The FreeBSD Foundation
3  * Copyright (c) 2010-2011 Pawel Jakub Dawidek <pawel@dawidek.net>
4  * All rights reserved.
5  *
6  * This software was developed by Pawel Jakub Dawidek under sponsorship from
7  * the FreeBSD Foundation.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE AUTHORS AND CONTRIBUTORS ``AS IS'' AND
19  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE
22  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
27  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28  * SUCH DAMAGE.
29  */
30 
31 #include <sys/cdefs.h>
32 __FBSDID("$FreeBSD$");
33 
34 #include <sys/types.h>
35 #include <sys/time.h>
36 #include <sys/bio.h>
37 #include <sys/disk.h>
38 #include <sys/refcount.h>
39 #include <sys/stat.h>
40 
41 #include <geom/gate/g_gate.h>
42 
43 #include <err.h>
44 #include <errno.h>
45 #include <fcntl.h>
46 #include <libgeom.h>
47 #include <pthread.h>
48 #include <signal.h>
49 #include <stdint.h>
50 #include <stdio.h>
51 #include <string.h>
52 #include <sysexits.h>
53 #include <unistd.h>
54 
55 #include <activemap.h>
56 #include <nv.h>
57 #include <rangelock.h>
58 
59 #include "control.h"
60 #include "event.h"
61 #include "hast.h"
62 #include "hast_proto.h"
63 #include "hastd.h"
64 #include "hooks.h"
65 #include "metadata.h"
66 #include "proto.h"
67 #include "pjdlog.h"
68 #include "subr.h"
69 #include "synch.h"
70 
71 /* The is only one remote component for now. */
72 #define	ISREMOTE(no)	((no) == 1)
73 
74 struct hio {
75 	/*
76 	 * Number of components we are still waiting for.
77 	 * When this field goes to 0, we can send the request back to the
78 	 * kernel. Each component has to decrease this counter by one
79 	 * even on failure.
80 	 */
81 	unsigned int		 hio_countdown;
82 	/*
83 	 * Each component has a place to store its own error.
84 	 * Once the request is handled by all components we can decide if the
85 	 * request overall is successful or not.
86 	 */
87 	int			*hio_errors;
88 	/*
89 	 * Structure used to communicate with GEOM Gate class.
90 	 */
91 	struct g_gate_ctl_io	 hio_ggio;
92 	TAILQ_ENTRY(hio)	*hio_next;
93 };
94 #define	hio_free_next	hio_next[0]
95 #define	hio_done_next	hio_next[0]
96 
97 /*
98  * Free list holds unused structures. When free list is empty, we have to wait
99  * until some in-progress requests are freed.
100  */
101 static TAILQ_HEAD(, hio) hio_free_list;
102 static pthread_mutex_t hio_free_list_lock;
103 static pthread_cond_t hio_free_list_cond;
104 /*
105  * There is one send list for every component. One requests is placed on all
106  * send lists - each component gets the same request, but each component is
107  * responsible for managing his own send list.
108  */
109 static TAILQ_HEAD(, hio) *hio_send_list;
110 static pthread_mutex_t *hio_send_list_lock;
111 static pthread_cond_t *hio_send_list_cond;
112 /*
113  * There is one recv list for every component, although local components don't
114  * use recv lists as local requests are done synchronously.
115  */
116 static TAILQ_HEAD(, hio) *hio_recv_list;
117 static pthread_mutex_t *hio_recv_list_lock;
118 static pthread_cond_t *hio_recv_list_cond;
119 /*
120  * Request is placed on done list by the slowest component (the one that
121  * decreased hio_countdown from 1 to 0).
122  */
123 static TAILQ_HEAD(, hio) hio_done_list;
124 static pthread_mutex_t hio_done_list_lock;
125 static pthread_cond_t hio_done_list_cond;
126 /*
127  * Structure below are for interaction with sync thread.
128  */
129 static bool sync_inprogress;
130 static pthread_mutex_t sync_lock;
131 static pthread_cond_t sync_cond;
132 /*
133  * The lock below allows to synchornize access to remote connections.
134  */
135 static pthread_rwlock_t *hio_remote_lock;
136 
137 /*
138  * Lock to synchronize metadata updates. Also synchronize access to
139  * hr_primary_localcnt and hr_primary_remotecnt fields.
140  */
141 static pthread_mutex_t metadata_lock;
142 
143 /*
144  * Maximum number of outstanding I/O requests.
145  */
146 #define	HAST_HIO_MAX	256
147 /*
148  * Number of components. At this point there are only two components: local
149  * and remote, but in the future it might be possible to use multiple local
150  * and remote components.
151  */
152 #define	HAST_NCOMPONENTS	2
153 
154 #define	ISCONNECTED(res, no)	\
155 	((res)->hr_remotein != NULL && (res)->hr_remoteout != NULL)
156 
157 #define	QUEUE_INSERT1(hio, name, ncomp)	do {				\
158 	bool _wakeup;							\
159 									\
160 	mtx_lock(&hio_##name##_list_lock[(ncomp)]);			\
161 	_wakeup = TAILQ_EMPTY(&hio_##name##_list[(ncomp)]);		\
162 	TAILQ_INSERT_TAIL(&hio_##name##_list[(ncomp)], (hio),		\
163 	    hio_next[(ncomp)]);						\
164 	mtx_unlock(&hio_##name##_list_lock[ncomp]);			\
165 	if (_wakeup)							\
166 		cv_signal(&hio_##name##_list_cond[(ncomp)]);		\
167 } while (0)
168 #define	QUEUE_INSERT2(hio, name)	do {				\
169 	bool _wakeup;							\
170 									\
171 	mtx_lock(&hio_##name##_list_lock);				\
172 	_wakeup = TAILQ_EMPTY(&hio_##name##_list);			\
173 	TAILQ_INSERT_TAIL(&hio_##name##_list, (hio), hio_##name##_next);\
174 	mtx_unlock(&hio_##name##_list_lock);				\
175 	if (_wakeup)							\
176 		cv_signal(&hio_##name##_list_cond);			\
177 } while (0)
178 #define	QUEUE_TAKE1(hio, name, ncomp, timeout)	do {			\
179 	bool _last;							\
180 									\
181 	mtx_lock(&hio_##name##_list_lock[(ncomp)]);			\
182 	_last = false;							\
183 	while (((hio) = TAILQ_FIRST(&hio_##name##_list[(ncomp)])) == NULL && !_last) { \
184 		cv_timedwait(&hio_##name##_list_cond[(ncomp)],		\
185 		    &hio_##name##_list_lock[(ncomp)], (timeout));	\
186 		if ((timeout) != 0)					\
187 			_last = true;					\
188 	}								\
189 	if (hio != NULL) {						\
190 		TAILQ_REMOVE(&hio_##name##_list[(ncomp)], (hio),	\
191 		    hio_next[(ncomp)]);					\
192 	}								\
193 	mtx_unlock(&hio_##name##_list_lock[(ncomp)]);			\
194 } while (0)
195 #define	QUEUE_TAKE2(hio, name)	do {					\
196 	mtx_lock(&hio_##name##_list_lock);				\
197 	while (((hio) = TAILQ_FIRST(&hio_##name##_list)) == NULL) {	\
198 		cv_wait(&hio_##name##_list_cond,			\
199 		    &hio_##name##_list_lock);				\
200 	}								\
201 	TAILQ_REMOVE(&hio_##name##_list, (hio), hio_##name##_next);	\
202 	mtx_unlock(&hio_##name##_list_lock);				\
203 } while (0)
204 
205 #define	SYNCREQ(hio)		do {					\
206 	(hio)->hio_ggio.gctl_unit = -1;					\
207 	(hio)->hio_ggio.gctl_seq = 1;					\
208 } while (0)
209 #define	ISSYNCREQ(hio)		((hio)->hio_ggio.gctl_unit == -1)
210 #define	SYNCREQDONE(hio)	do { (hio)->hio_ggio.gctl_unit = -2; } while (0)
211 #define	ISSYNCREQDONE(hio)	((hio)->hio_ggio.gctl_unit == -2)
212 
213 static struct hast_resource *gres;
214 
215 static pthread_mutex_t range_lock;
216 static struct rangelocks *range_regular;
217 static bool range_regular_wait;
218 static pthread_cond_t range_regular_cond;
219 static struct rangelocks *range_sync;
220 static bool range_sync_wait;
221 static pthread_cond_t range_sync_cond;
222 
223 static void *ggate_recv_thread(void *arg);
224 static void *local_send_thread(void *arg);
225 static void *remote_send_thread(void *arg);
226 static void *remote_recv_thread(void *arg);
227 static void *ggate_send_thread(void *arg);
228 static void *sync_thread(void *arg);
229 static void *guard_thread(void *arg);
230 
231 static void
232 cleanup(struct hast_resource *res)
233 {
234 	int rerrno;
235 
236 	/* Remember errno. */
237 	rerrno = errno;
238 
239 	/* Destroy ggate provider if we created one. */
240 	if (res->hr_ggateunit >= 0) {
241 		struct g_gate_ctl_destroy ggiod;
242 
243 		bzero(&ggiod, sizeof(ggiod));
244 		ggiod.gctl_version = G_GATE_VERSION;
245 		ggiod.gctl_unit = res->hr_ggateunit;
246 		ggiod.gctl_force = 1;
247 		if (ioctl(res->hr_ggatefd, G_GATE_CMD_DESTROY, &ggiod) < 0) {
248 			pjdlog_errno(LOG_WARNING,
249 			    "Unable to destroy hast/%s device",
250 			    res->hr_provname);
251 		}
252 		res->hr_ggateunit = -1;
253 	}
254 
255 	/* Restore errno. */
256 	errno = rerrno;
257 }
258 
259 static __dead2 void
260 primary_exit(int exitcode, const char *fmt, ...)
261 {
262 	va_list ap;
263 
264 	PJDLOG_ASSERT(exitcode != EX_OK);
265 	va_start(ap, fmt);
266 	pjdlogv_errno(LOG_ERR, fmt, ap);
267 	va_end(ap);
268 	cleanup(gres);
269 	exit(exitcode);
270 }
271 
272 static __dead2 void
273 primary_exitx(int exitcode, const char *fmt, ...)
274 {
275 	va_list ap;
276 
277 	va_start(ap, fmt);
278 	pjdlogv(exitcode == EX_OK ? LOG_INFO : LOG_ERR, fmt, ap);
279 	va_end(ap);
280 	cleanup(gres);
281 	exit(exitcode);
282 }
283 
284 static int
285 hast_activemap_flush(struct hast_resource *res)
286 {
287 	const unsigned char *buf;
288 	size_t size;
289 
290 	buf = activemap_bitmap(res->hr_amp, &size);
291 	PJDLOG_ASSERT(buf != NULL);
292 	PJDLOG_ASSERT((size % res->hr_local_sectorsize) == 0);
293 	if (pwrite(res->hr_localfd, buf, size, METADATA_SIZE) !=
294 	    (ssize_t)size) {
295 		KEEP_ERRNO(pjdlog_errno(LOG_ERR,
296 		    "Unable to flush activemap to disk"));
297 		return (-1);
298 	}
299 	return (0);
300 }
301 
302 static bool
303 real_remote(const struct hast_resource *res)
304 {
305 
306 	return (strcmp(res->hr_remoteaddr, "none") != 0);
307 }
308 
309 static void
310 init_environment(struct hast_resource *res __unused)
311 {
312 	struct hio *hio;
313 	unsigned int ii, ncomps;
314 
315 	/*
316 	 * In the future it might be per-resource value.
317 	 */
318 	ncomps = HAST_NCOMPONENTS;
319 
320 	/*
321 	 * Allocate memory needed by lists.
322 	 */
323 	hio_send_list = malloc(sizeof(hio_send_list[0]) * ncomps);
324 	if (hio_send_list == NULL) {
325 		primary_exitx(EX_TEMPFAIL,
326 		    "Unable to allocate %zu bytes of memory for send lists.",
327 		    sizeof(hio_send_list[0]) * ncomps);
328 	}
329 	hio_send_list_lock = malloc(sizeof(hio_send_list_lock[0]) * ncomps);
330 	if (hio_send_list_lock == NULL) {
331 		primary_exitx(EX_TEMPFAIL,
332 		    "Unable to allocate %zu bytes of memory for send list locks.",
333 		    sizeof(hio_send_list_lock[0]) * ncomps);
334 	}
335 	hio_send_list_cond = malloc(sizeof(hio_send_list_cond[0]) * ncomps);
336 	if (hio_send_list_cond == NULL) {
337 		primary_exitx(EX_TEMPFAIL,
338 		    "Unable to allocate %zu bytes of memory for send list condition variables.",
339 		    sizeof(hio_send_list_cond[0]) * ncomps);
340 	}
341 	hio_recv_list = malloc(sizeof(hio_recv_list[0]) * ncomps);
342 	if (hio_recv_list == NULL) {
343 		primary_exitx(EX_TEMPFAIL,
344 		    "Unable to allocate %zu bytes of memory for recv lists.",
345 		    sizeof(hio_recv_list[0]) * ncomps);
346 	}
347 	hio_recv_list_lock = malloc(sizeof(hio_recv_list_lock[0]) * ncomps);
348 	if (hio_recv_list_lock == NULL) {
349 		primary_exitx(EX_TEMPFAIL,
350 		    "Unable to allocate %zu bytes of memory for recv list locks.",
351 		    sizeof(hio_recv_list_lock[0]) * ncomps);
352 	}
353 	hio_recv_list_cond = malloc(sizeof(hio_recv_list_cond[0]) * ncomps);
354 	if (hio_recv_list_cond == NULL) {
355 		primary_exitx(EX_TEMPFAIL,
356 		    "Unable to allocate %zu bytes of memory for recv list condition variables.",
357 		    sizeof(hio_recv_list_cond[0]) * ncomps);
358 	}
359 	hio_remote_lock = malloc(sizeof(hio_remote_lock[0]) * ncomps);
360 	if (hio_remote_lock == NULL) {
361 		primary_exitx(EX_TEMPFAIL,
362 		    "Unable to allocate %zu bytes of memory for remote connections locks.",
363 		    sizeof(hio_remote_lock[0]) * ncomps);
364 	}
365 
366 	/*
367 	 * Initialize lists, their locks and theirs condition variables.
368 	 */
369 	TAILQ_INIT(&hio_free_list);
370 	mtx_init(&hio_free_list_lock);
371 	cv_init(&hio_free_list_cond);
372 	for (ii = 0; ii < HAST_NCOMPONENTS; ii++) {
373 		TAILQ_INIT(&hio_send_list[ii]);
374 		mtx_init(&hio_send_list_lock[ii]);
375 		cv_init(&hio_send_list_cond[ii]);
376 		TAILQ_INIT(&hio_recv_list[ii]);
377 		mtx_init(&hio_recv_list_lock[ii]);
378 		cv_init(&hio_recv_list_cond[ii]);
379 		rw_init(&hio_remote_lock[ii]);
380 	}
381 	TAILQ_INIT(&hio_done_list);
382 	mtx_init(&hio_done_list_lock);
383 	cv_init(&hio_done_list_cond);
384 	mtx_init(&metadata_lock);
385 
386 	/*
387 	 * Allocate requests pool and initialize requests.
388 	 */
389 	for (ii = 0; ii < HAST_HIO_MAX; ii++) {
390 		hio = malloc(sizeof(*hio));
391 		if (hio == NULL) {
392 			primary_exitx(EX_TEMPFAIL,
393 			    "Unable to allocate %zu bytes of memory for hio request.",
394 			    sizeof(*hio));
395 		}
396 		hio->hio_countdown = 0;
397 		hio->hio_errors = malloc(sizeof(hio->hio_errors[0]) * ncomps);
398 		if (hio->hio_errors == NULL) {
399 			primary_exitx(EX_TEMPFAIL,
400 			    "Unable allocate %zu bytes of memory for hio errors.",
401 			    sizeof(hio->hio_errors[0]) * ncomps);
402 		}
403 		hio->hio_next = malloc(sizeof(hio->hio_next[0]) * ncomps);
404 		if (hio->hio_next == NULL) {
405 			primary_exitx(EX_TEMPFAIL,
406 			    "Unable allocate %zu bytes of memory for hio_next field.",
407 			    sizeof(hio->hio_next[0]) * ncomps);
408 		}
409 		hio->hio_ggio.gctl_version = G_GATE_VERSION;
410 		hio->hio_ggio.gctl_data = malloc(MAXPHYS);
411 		if (hio->hio_ggio.gctl_data == NULL) {
412 			primary_exitx(EX_TEMPFAIL,
413 			    "Unable to allocate %zu bytes of memory for gctl_data.",
414 			    MAXPHYS);
415 		}
416 		hio->hio_ggio.gctl_length = MAXPHYS;
417 		hio->hio_ggio.gctl_error = 0;
418 		TAILQ_INSERT_HEAD(&hio_free_list, hio, hio_free_next);
419 	}
420 }
421 
422 static bool
423 init_resuid(struct hast_resource *res)
424 {
425 
426 	mtx_lock(&metadata_lock);
427 	if (res->hr_resuid != 0) {
428 		mtx_unlock(&metadata_lock);
429 		return (false);
430 	} else {
431 		/* Initialize unique resource identifier. */
432 		arc4random_buf(&res->hr_resuid, sizeof(res->hr_resuid));
433 		mtx_unlock(&metadata_lock);
434 		if (metadata_write(res) < 0)
435 			exit(EX_NOINPUT);
436 		return (true);
437 	}
438 }
439 
440 static void
441 init_local(struct hast_resource *res)
442 {
443 	unsigned char *buf;
444 	size_t mapsize;
445 
446 	if (metadata_read(res, true) < 0)
447 		exit(EX_NOINPUT);
448 	mtx_init(&res->hr_amp_lock);
449 	if (activemap_init(&res->hr_amp, res->hr_datasize, res->hr_extentsize,
450 	    res->hr_local_sectorsize, res->hr_keepdirty) < 0) {
451 		primary_exit(EX_TEMPFAIL, "Unable to create activemap");
452 	}
453 	mtx_init(&range_lock);
454 	cv_init(&range_regular_cond);
455 	if (rangelock_init(&range_regular) < 0)
456 		primary_exit(EX_TEMPFAIL, "Unable to create regular range lock");
457 	cv_init(&range_sync_cond);
458 	if (rangelock_init(&range_sync) < 0)
459 		primary_exit(EX_TEMPFAIL, "Unable to create sync range lock");
460 	mapsize = activemap_ondisk_size(res->hr_amp);
461 	buf = calloc(1, mapsize);
462 	if (buf == NULL) {
463 		primary_exitx(EX_TEMPFAIL,
464 		    "Unable to allocate buffer for activemap.");
465 	}
466 	if (pread(res->hr_localfd, buf, mapsize, METADATA_SIZE) !=
467 	    (ssize_t)mapsize) {
468 		primary_exit(EX_NOINPUT, "Unable to read activemap");
469 	}
470 	activemap_copyin(res->hr_amp, buf, mapsize);
471 	free(buf);
472 	if (res->hr_resuid != 0)
473 		return;
474 	/*
475 	 * We're using provider for the first time. Initialize local and remote
476 	 * counters. We don't initialize resuid here, as we want to do it just
477 	 * in time. The reason for this is that we want to inform secondary
478 	 * that there were no writes yet, so there is no need to synchronize
479 	 * anything.
480 	 */
481 	res->hr_primary_localcnt = 0;
482 	res->hr_primary_remotecnt = 0;
483 	if (metadata_write(res) < 0)
484 		exit(EX_NOINPUT);
485 }
486 
487 static int
488 primary_connect(struct hast_resource *res, struct proto_conn **connp)
489 {
490 	struct proto_conn *conn;
491 	int16_t val;
492 
493 	val = 1;
494 	if (proto_send(res->hr_conn, &val, sizeof(val)) < 0) {
495 		primary_exit(EX_TEMPFAIL,
496 		    "Unable to send connection request to parent");
497 	}
498 	if (proto_recv(res->hr_conn, &val, sizeof(val)) < 0) {
499 		primary_exit(EX_TEMPFAIL,
500 		    "Unable to receive reply to connection request from parent");
501 	}
502 	if (val != 0) {
503 		errno = val;
504 		pjdlog_errno(LOG_WARNING, "Unable to connect to %s",
505 		    res->hr_remoteaddr);
506 		return (-1);
507 	}
508 	if (proto_connection_recv(res->hr_conn, true, &conn) < 0) {
509 		primary_exit(EX_TEMPFAIL,
510 		    "Unable to receive connection from parent");
511 	}
512 	if (proto_connect_wait(conn, res->hr_timeout) < 0) {
513 		pjdlog_errno(LOG_WARNING, "Unable to connect to %s",
514 		    res->hr_remoteaddr);
515 		proto_close(conn);
516 		return (-1);
517 	}
518 	/* Error in setting timeout is not critical, but why should it fail? */
519 	if (proto_timeout(conn, res->hr_timeout) < 0)
520 		pjdlog_errno(LOG_WARNING, "Unable to set connection timeout");
521 
522 	*connp = conn;
523 
524 	return (0);
525 }
526 
527 static bool
528 init_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 	/* Setup directions. */
705 	if (proto_send(out, NULL, 0) == -1)
706 		pjdlog_errno(LOG_WARNING, "Unable to set connection direction");
707 	if (proto_recv(in, NULL, 0) == -1)
708 		pjdlog_errno(LOG_WARNING, "Unable to set connection direction");
709 	pjdlog_info("Connected to %s.", res->hr_remoteaddr);
710 	if (inp != NULL && outp != NULL) {
711 		*inp = in;
712 		*outp = out;
713 	} else {
714 		res->hr_remotein = in;
715 		res->hr_remoteout = out;
716 	}
717 	event_send(res, EVENT_CONNECT);
718 	return (true);
719 close:
720 	if (errmsg != NULL && strcmp(errmsg, "Split-brain condition!") == 0)
721 		event_send(res, EVENT_SPLITBRAIN);
722 	proto_close(out);
723 	if (in != NULL)
724 		proto_close(in);
725 	return (false);
726 }
727 
728 static void
729 sync_start(void)
730 {
731 
732 	mtx_lock(&sync_lock);
733 	sync_inprogress = true;
734 	mtx_unlock(&sync_lock);
735 	cv_signal(&sync_cond);
736 }
737 
738 static void
739 sync_stop(void)
740 {
741 
742 	mtx_lock(&sync_lock);
743 	if (sync_inprogress)
744 		sync_inprogress = false;
745 	mtx_unlock(&sync_lock);
746 }
747 
748 static void
749 init_ggate(struct hast_resource *res)
750 {
751 	struct g_gate_ctl_create ggiocreate;
752 	struct g_gate_ctl_cancel ggiocancel;
753 
754 	/*
755 	 * We communicate with ggate via /dev/ggctl. Open it.
756 	 */
757 	res->hr_ggatefd = open("/dev/" G_GATE_CTL_NAME, O_RDWR);
758 	if (res->hr_ggatefd < 0)
759 		primary_exit(EX_OSFILE, "Unable to open /dev/" G_GATE_CTL_NAME);
760 	/*
761 	 * Create provider before trying to connect, as connection failure
762 	 * is not critical, but may take some time.
763 	 */
764 	bzero(&ggiocreate, sizeof(ggiocreate));
765 	ggiocreate.gctl_version = G_GATE_VERSION;
766 	ggiocreate.gctl_mediasize = res->hr_datasize;
767 	ggiocreate.gctl_sectorsize = res->hr_local_sectorsize;
768 	ggiocreate.gctl_flags = 0;
769 	ggiocreate.gctl_maxcount = 0;
770 	ggiocreate.gctl_timeout = 0;
771 	ggiocreate.gctl_unit = G_GATE_NAME_GIVEN;
772 	snprintf(ggiocreate.gctl_name, sizeof(ggiocreate.gctl_name), "hast/%s",
773 	    res->hr_provname);
774 	if (ioctl(res->hr_ggatefd, G_GATE_CMD_CREATE, &ggiocreate) == 0) {
775 		pjdlog_info("Device hast/%s created.", res->hr_provname);
776 		res->hr_ggateunit = ggiocreate.gctl_unit;
777 		return;
778 	}
779 	if (errno != EEXIST) {
780 		primary_exit(EX_OSERR, "Unable to create hast/%s device",
781 		    res->hr_provname);
782 	}
783 	pjdlog_debug(1,
784 	    "Device hast/%s already exists, we will try to take it over.",
785 	    res->hr_provname);
786 	/*
787 	 * If we received EEXIST, we assume that the process who created the
788 	 * provider died and didn't clean up. In that case we will start from
789 	 * where he left of.
790 	 */
791 	bzero(&ggiocancel, sizeof(ggiocancel));
792 	ggiocancel.gctl_version = G_GATE_VERSION;
793 	ggiocancel.gctl_unit = G_GATE_NAME_GIVEN;
794 	snprintf(ggiocancel.gctl_name, sizeof(ggiocancel.gctl_name), "hast/%s",
795 	    res->hr_provname);
796 	if (ioctl(res->hr_ggatefd, G_GATE_CMD_CANCEL, &ggiocancel) == 0) {
797 		pjdlog_info("Device hast/%s recovered.", res->hr_provname);
798 		res->hr_ggateunit = ggiocancel.gctl_unit;
799 		return;
800 	}
801 	primary_exit(EX_OSERR, "Unable to take over hast/%s device",
802 	    res->hr_provname);
803 }
804 
805 void
806 hastd_primary(struct hast_resource *res)
807 {
808 	pthread_t td;
809 	pid_t pid;
810 	int error, mode, debuglevel;
811 
812 	/*
813 	 * Create communication channel for sending control commands from
814 	 * parent to child.
815 	 */
816 	if (proto_client(NULL, "socketpair://", &res->hr_ctrl) < 0) {
817 		/* TODO: There's no need for this to be fatal error. */
818 		KEEP_ERRNO((void)pidfile_remove(pfh));
819 		pjdlog_exit(EX_OSERR,
820 		    "Unable to create control sockets between parent and child");
821 	}
822 	/*
823 	 * Create communication channel for sending events from child to parent.
824 	 */
825 	if (proto_client(NULL, "socketpair://", &res->hr_event) < 0) {
826 		/* TODO: There's no need for this to be fatal error. */
827 		KEEP_ERRNO((void)pidfile_remove(pfh));
828 		pjdlog_exit(EX_OSERR,
829 		    "Unable to create event sockets between child and parent");
830 	}
831 	/*
832 	 * Create communication channel for sending connection requests from
833 	 * child to parent.
834 	 */
835 	if (proto_client(NULL, "socketpair://", &res->hr_conn) < 0) {
836 		/* TODO: There's no need for this to be fatal error. */
837 		KEEP_ERRNO((void)pidfile_remove(pfh));
838 		pjdlog_exit(EX_OSERR,
839 		    "Unable to create connection sockets between child and parent");
840 	}
841 
842 	pid = fork();
843 	if (pid < 0) {
844 		/* TODO: There's no need for this to be fatal error. */
845 		KEEP_ERRNO((void)pidfile_remove(pfh));
846 		pjdlog_exit(EX_TEMPFAIL, "Unable to fork");
847 	}
848 
849 	if (pid > 0) {
850 		/* This is parent. */
851 		/* Declare that we are receiver. */
852 		proto_recv(res->hr_event, NULL, 0);
853 		proto_recv(res->hr_conn, NULL, 0);
854 		/* Declare that we are sender. */
855 		proto_send(res->hr_ctrl, NULL, 0);
856 		res->hr_workerpid = pid;
857 		return;
858 	}
859 
860 	gres = res;
861 	mode = pjdlog_mode_get();
862 	debuglevel = pjdlog_debug_get();
863 
864 	/* Declare that we are sender. */
865 	proto_send(res->hr_event, NULL, 0);
866 	proto_send(res->hr_conn, NULL, 0);
867 	/* Declare that we are receiver. */
868 	proto_recv(res->hr_ctrl, NULL, 0);
869 	descriptors_cleanup(res);
870 
871 	descriptors_assert(res, mode);
872 
873 	pjdlog_init(mode);
874 	pjdlog_debug_set(debuglevel);
875 	pjdlog_prefix_set("[%s] (%s) ", res->hr_name, role2str(res->hr_role));
876 	setproctitle("%s (%s)", res->hr_name, role2str(res->hr_role));
877 
878 	init_local(res);
879 	init_ggate(res);
880 	init_environment(res);
881 
882 	if (drop_privs(true) != 0) {
883 		cleanup(res);
884 		exit(EX_CONFIG);
885 	}
886 	pjdlog_info("Privileges successfully dropped.");
887 
888 	/*
889 	 * Create the guard thread first, so we can handle signals from the
890 	 * very begining.
891 	 */
892 	error = pthread_create(&td, NULL, guard_thread, res);
893 	PJDLOG_ASSERT(error == 0);
894 	/*
895 	 * Create the control thread before sending any event to the parent,
896 	 * as we can deadlock when parent sends control request to worker,
897 	 * but worker has no control thread started yet, so parent waits.
898 	 * In the meantime worker sends an event to the parent, but parent
899 	 * is unable to handle the event, because it waits for control
900 	 * request response.
901 	 */
902 	error = pthread_create(&td, NULL, ctrl_thread, res);
903 	PJDLOG_ASSERT(error == 0);
904 	if (real_remote(res) && init_remote(res, NULL, NULL))
905 		sync_start();
906 	error = pthread_create(&td, NULL, ggate_recv_thread, res);
907 	PJDLOG_ASSERT(error == 0);
908 	error = pthread_create(&td, NULL, local_send_thread, res);
909 	PJDLOG_ASSERT(error == 0);
910 	error = pthread_create(&td, NULL, remote_send_thread, res);
911 	PJDLOG_ASSERT(error == 0);
912 	error = pthread_create(&td, NULL, remote_recv_thread, res);
913 	PJDLOG_ASSERT(error == 0);
914 	error = pthread_create(&td, NULL, ggate_send_thread, res);
915 	PJDLOG_ASSERT(error == 0);
916 	(void)sync_thread(res);
917 }
918 
919 static void
920 reqlog(int loglevel, int debuglevel, struct g_gate_ctl_io *ggio, const char *fmt, ...)
921 {
922 	char msg[1024];
923 	va_list ap;
924 	int len;
925 
926 	va_start(ap, fmt);
927 	len = vsnprintf(msg, sizeof(msg), fmt, ap);
928 	va_end(ap);
929 	if ((size_t)len < sizeof(msg)) {
930 		switch (ggio->gctl_cmd) {
931 		case BIO_READ:
932 			(void)snprintf(msg + len, sizeof(msg) - len,
933 			    "READ(%ju, %ju).", (uintmax_t)ggio->gctl_offset,
934 			    (uintmax_t)ggio->gctl_length);
935 			break;
936 		case BIO_DELETE:
937 			(void)snprintf(msg + len, sizeof(msg) - len,
938 			    "DELETE(%ju, %ju).", (uintmax_t)ggio->gctl_offset,
939 			    (uintmax_t)ggio->gctl_length);
940 			break;
941 		case BIO_FLUSH:
942 			(void)snprintf(msg + len, sizeof(msg) - len, "FLUSH.");
943 			break;
944 		case BIO_WRITE:
945 			(void)snprintf(msg + len, sizeof(msg) - len,
946 			    "WRITE(%ju, %ju).", (uintmax_t)ggio->gctl_offset,
947 			    (uintmax_t)ggio->gctl_length);
948 			break;
949 		default:
950 			(void)snprintf(msg + len, sizeof(msg) - len,
951 			    "UNKNOWN(%u).", (unsigned int)ggio->gctl_cmd);
952 			break;
953 		}
954 	}
955 	pjdlog_common(loglevel, debuglevel, -1, "%s", msg);
956 }
957 
958 static void
959 remote_close(struct hast_resource *res, int ncomp)
960 {
961 
962 	rw_wlock(&hio_remote_lock[ncomp]);
963 	/*
964 	 * A race is possible between dropping rlock and acquiring wlock -
965 	 * another thread can close connection in-between.
966 	 */
967 	if (!ISCONNECTED(res, ncomp)) {
968 		PJDLOG_ASSERT(res->hr_remotein == NULL);
969 		PJDLOG_ASSERT(res->hr_remoteout == NULL);
970 		rw_unlock(&hio_remote_lock[ncomp]);
971 		return;
972 	}
973 
974 	PJDLOG_ASSERT(res->hr_remotein != NULL);
975 	PJDLOG_ASSERT(res->hr_remoteout != NULL);
976 
977 	pjdlog_debug(2, "Closing incoming connection to %s.",
978 	    res->hr_remoteaddr);
979 	proto_close(res->hr_remotein);
980 	res->hr_remotein = NULL;
981 	pjdlog_debug(2, "Closing outgoing connection to %s.",
982 	    res->hr_remoteaddr);
983 	proto_close(res->hr_remoteout);
984 	res->hr_remoteout = NULL;
985 
986 	rw_unlock(&hio_remote_lock[ncomp]);
987 
988 	pjdlog_warning("Disconnected from %s.", res->hr_remoteaddr);
989 
990 	/*
991 	 * Stop synchronization if in-progress.
992 	 */
993 	sync_stop();
994 
995 	event_send(res, EVENT_DISCONNECT);
996 }
997 
998 /*
999  * Thread receives ggate I/O requests from the kernel and passes them to
1000  * appropriate threads:
1001  * WRITE - always goes to both local_send and remote_send threads
1002  * READ (when the block is up-to-date on local component) -
1003  *	only local_send thread
1004  * READ (when the block isn't up-to-date on local component) -
1005  *	only remote_send thread
1006  * DELETE - always goes to both local_send and remote_send threads
1007  * FLUSH - always goes to both local_send and remote_send threads
1008  */
1009 static void *
1010 ggate_recv_thread(void *arg)
1011 {
1012 	struct hast_resource *res = arg;
1013 	struct g_gate_ctl_io *ggio;
1014 	struct hio *hio;
1015 	unsigned int ii, ncomp, ncomps;
1016 	int error;
1017 
1018 	ncomps = HAST_NCOMPONENTS;
1019 
1020 	for (;;) {
1021 		pjdlog_debug(2, "ggate_recv: Taking free request.");
1022 		QUEUE_TAKE2(hio, free);
1023 		pjdlog_debug(2, "ggate_recv: (%p) Got free request.", hio);
1024 		ggio = &hio->hio_ggio;
1025 		ggio->gctl_unit = res->hr_ggateunit;
1026 		ggio->gctl_length = MAXPHYS;
1027 		ggio->gctl_error = 0;
1028 		pjdlog_debug(2,
1029 		    "ggate_recv: (%p) Waiting for request from the kernel.",
1030 		    hio);
1031 		if (ioctl(res->hr_ggatefd, G_GATE_CMD_START, ggio) < 0) {
1032 			if (sigexit_received)
1033 				pthread_exit(NULL);
1034 			primary_exit(EX_OSERR, "G_GATE_CMD_START failed");
1035 		}
1036 		error = ggio->gctl_error;
1037 		switch (error) {
1038 		case 0:
1039 			break;
1040 		case ECANCELED:
1041 			/* Exit gracefully. */
1042 			if (!sigexit_received) {
1043 				pjdlog_debug(2,
1044 				    "ggate_recv: (%p) Received cancel from the kernel.",
1045 				    hio);
1046 				pjdlog_info("Received cancel from the kernel, exiting.");
1047 			}
1048 			pthread_exit(NULL);
1049 		case ENOMEM:
1050 			/*
1051 			 * Buffer too small? Impossible, we allocate MAXPHYS
1052 			 * bytes - request can't be bigger than that.
1053 			 */
1054 			/* FALLTHROUGH */
1055 		case ENXIO:
1056 		default:
1057 			primary_exitx(EX_OSERR, "G_GATE_CMD_START failed: %s.",
1058 			    strerror(error));
1059 		}
1060 		for (ii = 0; ii < ncomps; ii++)
1061 			hio->hio_errors[ii] = EINVAL;
1062 		reqlog(LOG_DEBUG, 2, ggio,
1063 		    "ggate_recv: (%p) Request received from the kernel: ",
1064 		    hio);
1065 		/*
1066 		 * Inform all components about new write request.
1067 		 * For read request prefer local component unless the given
1068 		 * range is out-of-date, then use remote component.
1069 		 */
1070 		switch (ggio->gctl_cmd) {
1071 		case BIO_READ:
1072 			pjdlog_debug(2,
1073 			    "ggate_recv: (%p) Moving request to the send queue.",
1074 			    hio);
1075 			refcount_init(&hio->hio_countdown, 1);
1076 			mtx_lock(&metadata_lock);
1077 			if (res->hr_syncsrc == HAST_SYNCSRC_UNDEF ||
1078 			    res->hr_syncsrc == HAST_SYNCSRC_PRIMARY) {
1079 				/*
1080 				 * This range is up-to-date on local component,
1081 				 * so handle request locally.
1082 				 */
1083 				 /* Local component is 0 for now. */
1084 				ncomp = 0;
1085 			} else /* if (res->hr_syncsrc ==
1086 			    HAST_SYNCSRC_SECONDARY) */ {
1087 				PJDLOG_ASSERT(res->hr_syncsrc ==
1088 				    HAST_SYNCSRC_SECONDARY);
1089 				/*
1090 				 * This range is out-of-date on local component,
1091 				 * so send request to the remote node.
1092 				 */
1093 				 /* Remote component is 1 for now. */
1094 				ncomp = 1;
1095 			}
1096 			mtx_unlock(&metadata_lock);
1097 			QUEUE_INSERT1(hio, send, ncomp);
1098 			break;
1099 		case BIO_WRITE:
1100 			if (res->hr_resuid == 0) {
1101 				/*
1102 				 * This is first write, initialize localcnt and
1103 				 * resuid.
1104 				 */
1105 				res->hr_primary_localcnt = 1;
1106 				(void)init_resuid(res);
1107 			}
1108 			for (;;) {
1109 				mtx_lock(&range_lock);
1110 				if (rangelock_islocked(range_sync,
1111 				    ggio->gctl_offset, ggio->gctl_length)) {
1112 					pjdlog_debug(2,
1113 					    "regular: Range offset=%jd length=%zu locked.",
1114 					    (intmax_t)ggio->gctl_offset,
1115 					    (size_t)ggio->gctl_length);
1116 					range_regular_wait = true;
1117 					cv_wait(&range_regular_cond, &range_lock);
1118 					range_regular_wait = false;
1119 					mtx_unlock(&range_lock);
1120 					continue;
1121 				}
1122 				if (rangelock_add(range_regular,
1123 				    ggio->gctl_offset, ggio->gctl_length) < 0) {
1124 					mtx_unlock(&range_lock);
1125 					pjdlog_debug(2,
1126 					    "regular: Range offset=%jd length=%zu is already locked, waiting.",
1127 					    (intmax_t)ggio->gctl_offset,
1128 					    (size_t)ggio->gctl_length);
1129 					sleep(1);
1130 					continue;
1131 				}
1132 				mtx_unlock(&range_lock);
1133 				break;
1134 			}
1135 			mtx_lock(&res->hr_amp_lock);
1136 			if (activemap_write_start(res->hr_amp,
1137 			    ggio->gctl_offset, ggio->gctl_length)) {
1138 				(void)hast_activemap_flush(res);
1139 			}
1140 			mtx_unlock(&res->hr_amp_lock);
1141 			/* FALLTHROUGH */
1142 		case BIO_DELETE:
1143 		case BIO_FLUSH:
1144 			pjdlog_debug(2,
1145 			    "ggate_recv: (%p) Moving request to the send queues.",
1146 			    hio);
1147 			refcount_init(&hio->hio_countdown, ncomps);
1148 			for (ii = 0; ii < ncomps; ii++)
1149 				QUEUE_INSERT1(hio, send, ii);
1150 			break;
1151 		}
1152 	}
1153 	/* NOTREACHED */
1154 	return (NULL);
1155 }
1156 
1157 /*
1158  * Thread reads from or writes to local component.
1159  * If local read fails, it redirects it to remote_send thread.
1160  */
1161 static void *
1162 local_send_thread(void *arg)
1163 {
1164 	struct hast_resource *res = arg;
1165 	struct g_gate_ctl_io *ggio;
1166 	struct hio *hio;
1167 	unsigned int ncomp, rncomp;
1168 	ssize_t ret;
1169 
1170 	/* Local component is 0 for now. */
1171 	ncomp = 0;
1172 	/* Remote component is 1 for now. */
1173 	rncomp = 1;
1174 
1175 	for (;;) {
1176 		pjdlog_debug(2, "local_send: Taking request.");
1177 		QUEUE_TAKE1(hio, send, ncomp, 0);
1178 		pjdlog_debug(2, "local_send: (%p) Got request.", hio);
1179 		ggio = &hio->hio_ggio;
1180 		switch (ggio->gctl_cmd) {
1181 		case BIO_READ:
1182 			ret = pread(res->hr_localfd, ggio->gctl_data,
1183 			    ggio->gctl_length,
1184 			    ggio->gctl_offset + res->hr_localoff);
1185 			if (ret == ggio->gctl_length)
1186 				hio->hio_errors[ncomp] = 0;
1187 			else {
1188 				/*
1189 				 * If READ failed, try to read from remote node.
1190 				 */
1191 				if (ret < 0) {
1192 					reqlog(LOG_WARNING, 0, ggio,
1193 					    "Local request failed (%s), trying remote node. ",
1194 					    strerror(errno));
1195 				} else if (ret != ggio->gctl_length) {
1196 					reqlog(LOG_WARNING, 0, ggio,
1197 					    "Local request failed (%zd != %jd), trying remote node. ",
1198 					    ret, (intmax_t)ggio->gctl_length);
1199 				}
1200 				QUEUE_INSERT1(hio, send, rncomp);
1201 				continue;
1202 			}
1203 			break;
1204 		case BIO_WRITE:
1205 			ret = pwrite(res->hr_localfd, ggio->gctl_data,
1206 			    ggio->gctl_length,
1207 			    ggio->gctl_offset + res->hr_localoff);
1208 			if (ret < 0) {
1209 				hio->hio_errors[ncomp] = errno;
1210 				reqlog(LOG_WARNING, 0, ggio,
1211 				    "Local request failed (%s): ",
1212 				    strerror(errno));
1213 			} else if (ret != ggio->gctl_length) {
1214 				hio->hio_errors[ncomp] = EIO;
1215 				reqlog(LOG_WARNING, 0, ggio,
1216 				    "Local request failed (%zd != %jd): ",
1217 				    ret, (intmax_t)ggio->gctl_length);
1218 			} else {
1219 				hio->hio_errors[ncomp] = 0;
1220 			}
1221 			break;
1222 		case BIO_DELETE:
1223 			ret = g_delete(res->hr_localfd,
1224 			    ggio->gctl_offset + res->hr_localoff,
1225 			    ggio->gctl_length);
1226 			if (ret < 0) {
1227 				hio->hio_errors[ncomp] = errno;
1228 				reqlog(LOG_WARNING, 0, ggio,
1229 				    "Local request failed (%s): ",
1230 				    strerror(errno));
1231 			} else {
1232 				hio->hio_errors[ncomp] = 0;
1233 			}
1234 			break;
1235 		case BIO_FLUSH:
1236 			ret = g_flush(res->hr_localfd);
1237 			if (ret < 0) {
1238 				hio->hio_errors[ncomp] = errno;
1239 				reqlog(LOG_WARNING, 0, ggio,
1240 				    "Local request failed (%s): ",
1241 				    strerror(errno));
1242 			} else {
1243 				hio->hio_errors[ncomp] = 0;
1244 			}
1245 			break;
1246 		}
1247 		if (refcount_release(&hio->hio_countdown)) {
1248 			if (ISSYNCREQ(hio)) {
1249 				mtx_lock(&sync_lock);
1250 				SYNCREQDONE(hio);
1251 				mtx_unlock(&sync_lock);
1252 				cv_signal(&sync_cond);
1253 			} else {
1254 				pjdlog_debug(2,
1255 				    "local_send: (%p) Moving request to the done queue.",
1256 				    hio);
1257 				QUEUE_INSERT2(hio, done);
1258 			}
1259 		}
1260 	}
1261 	/* NOTREACHED */
1262 	return (NULL);
1263 }
1264 
1265 static void
1266 keepalive_send(struct hast_resource *res, unsigned int ncomp)
1267 {
1268 	struct nv *nv;
1269 
1270 	rw_rlock(&hio_remote_lock[ncomp]);
1271 
1272 	if (!ISCONNECTED(res, ncomp)) {
1273 		rw_unlock(&hio_remote_lock[ncomp]);
1274 		return;
1275 	}
1276 
1277 	PJDLOG_ASSERT(res->hr_remotein != NULL);
1278 	PJDLOG_ASSERT(res->hr_remoteout != NULL);
1279 
1280 	nv = nv_alloc();
1281 	nv_add_uint8(nv, HIO_KEEPALIVE, "cmd");
1282 	if (nv_error(nv) != 0) {
1283 		rw_unlock(&hio_remote_lock[ncomp]);
1284 		nv_free(nv);
1285 		pjdlog_debug(1,
1286 		    "keepalive_send: Unable to prepare header to send.");
1287 		return;
1288 	}
1289 	if (hast_proto_send(res, res->hr_remoteout, nv, NULL, 0) < 0) {
1290 		rw_unlock(&hio_remote_lock[ncomp]);
1291 		pjdlog_common(LOG_DEBUG, 1, errno,
1292 		    "keepalive_send: Unable to send request");
1293 		nv_free(nv);
1294 		remote_close(res, ncomp);
1295 		return;
1296 	}
1297 
1298 	rw_unlock(&hio_remote_lock[ncomp]);
1299 	nv_free(nv);
1300 	pjdlog_debug(2, "keepalive_send: Request sent.");
1301 }
1302 
1303 /*
1304  * Thread sends request to secondary node.
1305  */
1306 static void *
1307 remote_send_thread(void *arg)
1308 {
1309 	struct hast_resource *res = arg;
1310 	struct g_gate_ctl_io *ggio;
1311 	time_t lastcheck, now;
1312 	struct hio *hio;
1313 	struct nv *nv;
1314 	unsigned int ncomp;
1315 	bool wakeup;
1316 	uint64_t offset, length;
1317 	uint8_t cmd;
1318 	void *data;
1319 
1320 	/* Remote component is 1 for now. */
1321 	ncomp = 1;
1322 	lastcheck = time(NULL);
1323 
1324 	for (;;) {
1325 		pjdlog_debug(2, "remote_send: Taking request.");
1326 		QUEUE_TAKE1(hio, send, ncomp, HAST_KEEPALIVE);
1327 		if (hio == NULL) {
1328 			now = time(NULL);
1329 			if (lastcheck + HAST_KEEPALIVE <= now) {
1330 				keepalive_send(res, ncomp);
1331 				lastcheck = now;
1332 			}
1333 			continue;
1334 		}
1335 		pjdlog_debug(2, "remote_send: (%p) Got request.", hio);
1336 		ggio = &hio->hio_ggio;
1337 		switch (ggio->gctl_cmd) {
1338 		case BIO_READ:
1339 			cmd = HIO_READ;
1340 			data = NULL;
1341 			offset = ggio->gctl_offset;
1342 			length = ggio->gctl_length;
1343 			break;
1344 		case BIO_WRITE:
1345 			cmd = HIO_WRITE;
1346 			data = ggio->gctl_data;
1347 			offset = ggio->gctl_offset;
1348 			length = ggio->gctl_length;
1349 			break;
1350 		case BIO_DELETE:
1351 			cmd = HIO_DELETE;
1352 			data = NULL;
1353 			offset = ggio->gctl_offset;
1354 			length = ggio->gctl_length;
1355 			break;
1356 		case BIO_FLUSH:
1357 			cmd = HIO_FLUSH;
1358 			data = NULL;
1359 			offset = 0;
1360 			length = 0;
1361 			break;
1362 		default:
1363 			PJDLOG_ASSERT(!"invalid condition");
1364 			abort();
1365 		}
1366 		nv = nv_alloc();
1367 		nv_add_uint8(nv, cmd, "cmd");
1368 		nv_add_uint64(nv, (uint64_t)ggio->gctl_seq, "seq");
1369 		nv_add_uint64(nv, offset, "offset");
1370 		nv_add_uint64(nv, length, "length");
1371 		if (nv_error(nv) != 0) {
1372 			hio->hio_errors[ncomp] = nv_error(nv);
1373 			pjdlog_debug(2,
1374 			    "remote_send: (%p) Unable to prepare header to send.",
1375 			    hio);
1376 			reqlog(LOG_ERR, 0, ggio,
1377 			    "Unable to prepare header to send (%s): ",
1378 			    strerror(nv_error(nv)));
1379 			/* Move failed request immediately to the done queue. */
1380 			goto done_queue;
1381 		}
1382 		pjdlog_debug(2,
1383 		    "remote_send: (%p) Moving request to the recv queue.",
1384 		    hio);
1385 		/*
1386 		 * Protect connection from disappearing.
1387 		 */
1388 		rw_rlock(&hio_remote_lock[ncomp]);
1389 		if (!ISCONNECTED(res, ncomp)) {
1390 			rw_unlock(&hio_remote_lock[ncomp]);
1391 			hio->hio_errors[ncomp] = ENOTCONN;
1392 			goto done_queue;
1393 		}
1394 		/*
1395 		 * Move the request to recv queue before sending it, because
1396 		 * in different order we can get reply before we move request
1397 		 * to recv queue.
1398 		 */
1399 		mtx_lock(&hio_recv_list_lock[ncomp]);
1400 		wakeup = TAILQ_EMPTY(&hio_recv_list[ncomp]);
1401 		TAILQ_INSERT_TAIL(&hio_recv_list[ncomp], hio, hio_next[ncomp]);
1402 		mtx_unlock(&hio_recv_list_lock[ncomp]);
1403 		if (hast_proto_send(res, res->hr_remoteout, nv, data,
1404 		    data != NULL ? length : 0) < 0) {
1405 			hio->hio_errors[ncomp] = errno;
1406 			rw_unlock(&hio_remote_lock[ncomp]);
1407 			pjdlog_debug(2,
1408 			    "remote_send: (%p) Unable to send request.", hio);
1409 			reqlog(LOG_ERR, 0, ggio,
1410 			    "Unable to send request (%s): ",
1411 			    strerror(hio->hio_errors[ncomp]));
1412 			remote_close(res, ncomp);
1413 			/*
1414 			 * Take request back from the receive queue and move
1415 			 * it immediately to the done queue.
1416 			 */
1417 			mtx_lock(&hio_recv_list_lock[ncomp]);
1418 			TAILQ_REMOVE(&hio_recv_list[ncomp], hio, hio_next[ncomp]);
1419 			mtx_unlock(&hio_recv_list_lock[ncomp]);
1420 			goto done_queue;
1421 		}
1422 		rw_unlock(&hio_remote_lock[ncomp]);
1423 		nv_free(nv);
1424 		if (wakeup)
1425 			cv_signal(&hio_recv_list_cond[ncomp]);
1426 		continue;
1427 done_queue:
1428 		nv_free(nv);
1429 		if (ISSYNCREQ(hio)) {
1430 			if (!refcount_release(&hio->hio_countdown))
1431 				continue;
1432 			mtx_lock(&sync_lock);
1433 			SYNCREQDONE(hio);
1434 			mtx_unlock(&sync_lock);
1435 			cv_signal(&sync_cond);
1436 			continue;
1437 		}
1438 		if (ggio->gctl_cmd == BIO_WRITE) {
1439 			mtx_lock(&res->hr_amp_lock);
1440 			if (activemap_need_sync(res->hr_amp, ggio->gctl_offset,
1441 			    ggio->gctl_length)) {
1442 				(void)hast_activemap_flush(res);
1443 			}
1444 			mtx_unlock(&res->hr_amp_lock);
1445 		}
1446 		if (!refcount_release(&hio->hio_countdown))
1447 			continue;
1448 		pjdlog_debug(2,
1449 		    "remote_send: (%p) Moving request to the done queue.",
1450 		    hio);
1451 		QUEUE_INSERT2(hio, done);
1452 	}
1453 	/* NOTREACHED */
1454 	return (NULL);
1455 }
1456 
1457 /*
1458  * Thread receives answer from secondary node and passes it to ggate_send
1459  * thread.
1460  */
1461 static void *
1462 remote_recv_thread(void *arg)
1463 {
1464 	struct hast_resource *res = arg;
1465 	struct g_gate_ctl_io *ggio;
1466 	struct hio *hio;
1467 	struct nv *nv;
1468 	unsigned int ncomp;
1469 	uint64_t seq;
1470 	int error;
1471 
1472 	/* Remote component is 1 for now. */
1473 	ncomp = 1;
1474 
1475 	for (;;) {
1476 		/* Wait until there is anything to receive. */
1477 		mtx_lock(&hio_recv_list_lock[ncomp]);
1478 		while (TAILQ_EMPTY(&hio_recv_list[ncomp])) {
1479 			pjdlog_debug(2, "remote_recv: No requests, waiting.");
1480 			cv_wait(&hio_recv_list_cond[ncomp],
1481 			    &hio_recv_list_lock[ncomp]);
1482 		}
1483 		mtx_unlock(&hio_recv_list_lock[ncomp]);
1484 		rw_rlock(&hio_remote_lock[ncomp]);
1485 		if (!ISCONNECTED(res, ncomp)) {
1486 			rw_unlock(&hio_remote_lock[ncomp]);
1487 			/*
1488 			 * Connection is dead, so move all pending requests to
1489 			 * the done queue (one-by-one).
1490 			 */
1491 			mtx_lock(&hio_recv_list_lock[ncomp]);
1492 			hio = TAILQ_FIRST(&hio_recv_list[ncomp]);
1493 			PJDLOG_ASSERT(hio != NULL);
1494 			TAILQ_REMOVE(&hio_recv_list[ncomp], hio,
1495 			    hio_next[ncomp]);
1496 			mtx_unlock(&hio_recv_list_lock[ncomp]);
1497 			goto done_queue;
1498 		}
1499 		if (hast_proto_recv_hdr(res->hr_remotein, &nv) < 0) {
1500 			pjdlog_errno(LOG_ERR,
1501 			    "Unable to receive reply header");
1502 			rw_unlock(&hio_remote_lock[ncomp]);
1503 			remote_close(res, ncomp);
1504 			continue;
1505 		}
1506 		rw_unlock(&hio_remote_lock[ncomp]);
1507 		seq = nv_get_uint64(nv, "seq");
1508 		if (seq == 0) {
1509 			pjdlog_error("Header contains no 'seq' field.");
1510 			nv_free(nv);
1511 			continue;
1512 		}
1513 		mtx_lock(&hio_recv_list_lock[ncomp]);
1514 		TAILQ_FOREACH(hio, &hio_recv_list[ncomp], hio_next[ncomp]) {
1515 			if (hio->hio_ggio.gctl_seq == seq) {
1516 				TAILQ_REMOVE(&hio_recv_list[ncomp], hio,
1517 				    hio_next[ncomp]);
1518 				break;
1519 			}
1520 		}
1521 		mtx_unlock(&hio_recv_list_lock[ncomp]);
1522 		if (hio == NULL) {
1523 			pjdlog_error("Found no request matching received 'seq' field (%ju).",
1524 			    (uintmax_t)seq);
1525 			nv_free(nv);
1526 			continue;
1527 		}
1528 		error = nv_get_int16(nv, "error");
1529 		if (error != 0) {
1530 			/* Request failed on remote side. */
1531 			hio->hio_errors[ncomp] = error;
1532 			reqlog(LOG_WARNING, 0, &hio->hio_ggio,
1533 			    "Remote request failed (%s): ", strerror(error));
1534 			nv_free(nv);
1535 			goto done_queue;
1536 		}
1537 		ggio = &hio->hio_ggio;
1538 		switch (ggio->gctl_cmd) {
1539 		case BIO_READ:
1540 			rw_rlock(&hio_remote_lock[ncomp]);
1541 			if (!ISCONNECTED(res, ncomp)) {
1542 				rw_unlock(&hio_remote_lock[ncomp]);
1543 				nv_free(nv);
1544 				goto done_queue;
1545 			}
1546 			if (hast_proto_recv_data(res, res->hr_remotein, nv,
1547 			    ggio->gctl_data, ggio->gctl_length) < 0) {
1548 				hio->hio_errors[ncomp] = errno;
1549 				pjdlog_errno(LOG_ERR,
1550 				    "Unable to receive reply data");
1551 				rw_unlock(&hio_remote_lock[ncomp]);
1552 				nv_free(nv);
1553 				remote_close(res, ncomp);
1554 				goto done_queue;
1555 			}
1556 			rw_unlock(&hio_remote_lock[ncomp]);
1557 			break;
1558 		case BIO_WRITE:
1559 		case BIO_DELETE:
1560 		case BIO_FLUSH:
1561 			break;
1562 		default:
1563 			PJDLOG_ASSERT(!"invalid condition");
1564 			abort();
1565 		}
1566 		hio->hio_errors[ncomp] = 0;
1567 		nv_free(nv);
1568 done_queue:
1569 		if (refcount_release(&hio->hio_countdown)) {
1570 			if (ISSYNCREQ(hio)) {
1571 				mtx_lock(&sync_lock);
1572 				SYNCREQDONE(hio);
1573 				mtx_unlock(&sync_lock);
1574 				cv_signal(&sync_cond);
1575 			} else {
1576 				pjdlog_debug(2,
1577 				    "remote_recv: (%p) Moving request to the done queue.",
1578 				    hio);
1579 				QUEUE_INSERT2(hio, done);
1580 			}
1581 		}
1582 	}
1583 	/* NOTREACHED */
1584 	return (NULL);
1585 }
1586 
1587 /*
1588  * Thread sends answer to the kernel.
1589  */
1590 static void *
1591 ggate_send_thread(void *arg)
1592 {
1593 	struct hast_resource *res = arg;
1594 	struct g_gate_ctl_io *ggio;
1595 	struct hio *hio;
1596 	unsigned int ii, ncomp, ncomps;
1597 
1598 	ncomps = HAST_NCOMPONENTS;
1599 
1600 	for (;;) {
1601 		pjdlog_debug(2, "ggate_send: Taking request.");
1602 		QUEUE_TAKE2(hio, done);
1603 		pjdlog_debug(2, "ggate_send: (%p) Got request.", hio);
1604 		ggio = &hio->hio_ggio;
1605 		for (ii = 0; ii < ncomps; ii++) {
1606 			if (hio->hio_errors[ii] == 0) {
1607 				/*
1608 				 * One successful request is enough to declare
1609 				 * success.
1610 				 */
1611 				ggio->gctl_error = 0;
1612 				break;
1613 			}
1614 		}
1615 		if (ii == ncomps) {
1616 			/*
1617 			 * None of the requests were successful.
1618 			 * Use the error from local component except the
1619 			 * case when we did only remote request.
1620 			 */
1621 			if (ggio->gctl_cmd == BIO_READ &&
1622 			    res->hr_syncsrc == HAST_SYNCSRC_SECONDARY)
1623 				ggio->gctl_error = hio->hio_errors[1];
1624 			else
1625 				ggio->gctl_error = hio->hio_errors[0];
1626 		}
1627 		if (ggio->gctl_error == 0 && ggio->gctl_cmd == BIO_WRITE) {
1628 			mtx_lock(&res->hr_amp_lock);
1629 			activemap_write_complete(res->hr_amp,
1630 			    ggio->gctl_offset, ggio->gctl_length);
1631 			mtx_unlock(&res->hr_amp_lock);
1632 		}
1633 		if (ggio->gctl_cmd == BIO_WRITE) {
1634 			/*
1635 			 * Unlock range we locked.
1636 			 */
1637 			mtx_lock(&range_lock);
1638 			rangelock_del(range_regular, ggio->gctl_offset,
1639 			    ggio->gctl_length);
1640 			if (range_sync_wait)
1641 				cv_signal(&range_sync_cond);
1642 			mtx_unlock(&range_lock);
1643 			/*
1644 			 * Bump local count if this is first write after
1645 			 * connection failure with remote node.
1646 			 */
1647 			ncomp = 1;
1648 			rw_rlock(&hio_remote_lock[ncomp]);
1649 			if (!ISCONNECTED(res, ncomp)) {
1650 				mtx_lock(&metadata_lock);
1651 				if (res->hr_primary_localcnt ==
1652 				    res->hr_secondary_remotecnt) {
1653 					res->hr_primary_localcnt++;
1654 					pjdlog_debug(1,
1655 					    "Increasing localcnt to %ju.",
1656 					    (uintmax_t)res->hr_primary_localcnt);
1657 					(void)metadata_write(res);
1658 				}
1659 				mtx_unlock(&metadata_lock);
1660 			}
1661 			rw_unlock(&hio_remote_lock[ncomp]);
1662 		}
1663 		if (ioctl(res->hr_ggatefd, G_GATE_CMD_DONE, ggio) < 0)
1664 			primary_exit(EX_OSERR, "G_GATE_CMD_DONE failed");
1665 		pjdlog_debug(2,
1666 		    "ggate_send: (%p) Moving request to the free queue.", hio);
1667 		QUEUE_INSERT2(hio, free);
1668 	}
1669 	/* NOTREACHED */
1670 	return (NULL);
1671 }
1672 
1673 /*
1674  * Thread synchronize local and remote components.
1675  */
1676 static void *
1677 sync_thread(void *arg __unused)
1678 {
1679 	struct hast_resource *res = arg;
1680 	struct hio *hio;
1681 	struct g_gate_ctl_io *ggio;
1682 	struct timeval tstart, tend, tdiff;
1683 	unsigned int ii, ncomp, ncomps;
1684 	off_t offset, length, synced;
1685 	bool dorewind;
1686 	int syncext;
1687 
1688 	ncomps = HAST_NCOMPONENTS;
1689 	dorewind = true;
1690 	synced = 0;
1691 	offset = -1;
1692 
1693 	for (;;) {
1694 		mtx_lock(&sync_lock);
1695 		if (offset >= 0 && !sync_inprogress) {
1696 			gettimeofday(&tend, NULL);
1697 			timersub(&tend, &tstart, &tdiff);
1698 			pjdlog_info("Synchronization interrupted after %#.0T. "
1699 			    "%NB synchronized so far.", &tdiff,
1700 			    (intmax_t)synced);
1701 			event_send(res, EVENT_SYNCINTR);
1702 		}
1703 		while (!sync_inprogress) {
1704 			dorewind = true;
1705 			synced = 0;
1706 			cv_wait(&sync_cond, &sync_lock);
1707 		}
1708 		mtx_unlock(&sync_lock);
1709 		/*
1710 		 * Obtain offset at which we should synchronize.
1711 		 * Rewind synchronization if needed.
1712 		 */
1713 		mtx_lock(&res->hr_amp_lock);
1714 		if (dorewind)
1715 			activemap_sync_rewind(res->hr_amp);
1716 		offset = activemap_sync_offset(res->hr_amp, &length, &syncext);
1717 		if (syncext != -1) {
1718 			/*
1719 			 * We synchronized entire syncext extent, we can mark
1720 			 * it as clean now.
1721 			 */
1722 			if (activemap_extent_complete(res->hr_amp, syncext))
1723 				(void)hast_activemap_flush(res);
1724 		}
1725 		mtx_unlock(&res->hr_amp_lock);
1726 		if (dorewind) {
1727 			dorewind = false;
1728 			if (offset < 0)
1729 				pjdlog_info("Nodes are in sync.");
1730 			else {
1731 				pjdlog_info("Synchronization started. %NB to go.",
1732 				    (intmax_t)(res->hr_extentsize *
1733 				    activemap_ndirty(res->hr_amp)));
1734 				event_send(res, EVENT_SYNCSTART);
1735 				gettimeofday(&tstart, NULL);
1736 			}
1737 		}
1738 		if (offset < 0) {
1739 			sync_stop();
1740 			pjdlog_debug(1, "Nothing to synchronize.");
1741 			/*
1742 			 * Synchronization complete, make both localcnt and
1743 			 * remotecnt equal.
1744 			 */
1745 			ncomp = 1;
1746 			rw_rlock(&hio_remote_lock[ncomp]);
1747 			if (ISCONNECTED(res, ncomp)) {
1748 				if (synced > 0) {
1749 					int64_t bps;
1750 
1751 					gettimeofday(&tend, NULL);
1752 					timersub(&tend, &tstart, &tdiff);
1753 					bps = (int64_t)((double)synced /
1754 					    ((double)tdiff.tv_sec +
1755 					    (double)tdiff.tv_usec / 1000000));
1756 					pjdlog_info("Synchronization complete. "
1757 					    "%NB synchronized in %#.0lT (%NB/sec).",
1758 					    (intmax_t)synced, &tdiff,
1759 					    (intmax_t)bps);
1760 					event_send(res, EVENT_SYNCDONE);
1761 				}
1762 				mtx_lock(&metadata_lock);
1763 				res->hr_syncsrc = HAST_SYNCSRC_UNDEF;
1764 				res->hr_primary_localcnt =
1765 				    res->hr_secondary_remotecnt;
1766 				res->hr_primary_remotecnt =
1767 				    res->hr_secondary_localcnt;
1768 				pjdlog_debug(1,
1769 				    "Setting localcnt to %ju and remotecnt to %ju.",
1770 				    (uintmax_t)res->hr_primary_localcnt,
1771 				    (uintmax_t)res->hr_primary_remotecnt);
1772 				(void)metadata_write(res);
1773 				mtx_unlock(&metadata_lock);
1774 			}
1775 			rw_unlock(&hio_remote_lock[ncomp]);
1776 			continue;
1777 		}
1778 		pjdlog_debug(2, "sync: Taking free request.");
1779 		QUEUE_TAKE2(hio, free);
1780 		pjdlog_debug(2, "sync: (%p) Got free request.", hio);
1781 		/*
1782 		 * Lock the range we are going to synchronize. We don't want
1783 		 * race where someone writes between our read and write.
1784 		 */
1785 		for (;;) {
1786 			mtx_lock(&range_lock);
1787 			if (rangelock_islocked(range_regular, offset, length)) {
1788 				pjdlog_debug(2,
1789 				    "sync: Range offset=%jd length=%jd locked.",
1790 				    (intmax_t)offset, (intmax_t)length);
1791 				range_sync_wait = true;
1792 				cv_wait(&range_sync_cond, &range_lock);
1793 				range_sync_wait = false;
1794 				mtx_unlock(&range_lock);
1795 				continue;
1796 			}
1797 			if (rangelock_add(range_sync, offset, length) < 0) {
1798 				mtx_unlock(&range_lock);
1799 				pjdlog_debug(2,
1800 				    "sync: Range offset=%jd length=%jd is already locked, waiting.",
1801 				    (intmax_t)offset, (intmax_t)length);
1802 				sleep(1);
1803 				continue;
1804 			}
1805 			mtx_unlock(&range_lock);
1806 			break;
1807 		}
1808 		/*
1809 		 * First read the data from synchronization source.
1810 		 */
1811 		SYNCREQ(hio);
1812 		ggio = &hio->hio_ggio;
1813 		ggio->gctl_cmd = BIO_READ;
1814 		ggio->gctl_offset = offset;
1815 		ggio->gctl_length = length;
1816 		ggio->gctl_error = 0;
1817 		for (ii = 0; ii < ncomps; ii++)
1818 			hio->hio_errors[ii] = EINVAL;
1819 		reqlog(LOG_DEBUG, 2, ggio, "sync: (%p) Sending sync request: ",
1820 		    hio);
1821 		pjdlog_debug(2, "sync: (%p) Moving request to the send queue.",
1822 		    hio);
1823 		mtx_lock(&metadata_lock);
1824 		if (res->hr_syncsrc == HAST_SYNCSRC_PRIMARY) {
1825 			/*
1826 			 * This range is up-to-date on local component,
1827 			 * so handle request locally.
1828 			 */
1829 			 /* Local component is 0 for now. */
1830 			ncomp = 0;
1831 		} else /* if (res->hr_syncsrc == HAST_SYNCSRC_SECONDARY) */ {
1832 			PJDLOG_ASSERT(res->hr_syncsrc == HAST_SYNCSRC_SECONDARY);
1833 			/*
1834 			 * This range is out-of-date on local component,
1835 			 * so send request to the remote node.
1836 			 */
1837 			 /* Remote component is 1 for now. */
1838 			ncomp = 1;
1839 		}
1840 		mtx_unlock(&metadata_lock);
1841 		refcount_init(&hio->hio_countdown, 1);
1842 		QUEUE_INSERT1(hio, send, ncomp);
1843 
1844 		/*
1845 		 * Let's wait for READ to finish.
1846 		 */
1847 		mtx_lock(&sync_lock);
1848 		while (!ISSYNCREQDONE(hio))
1849 			cv_wait(&sync_cond, &sync_lock);
1850 		mtx_unlock(&sync_lock);
1851 
1852 		if (hio->hio_errors[ncomp] != 0) {
1853 			pjdlog_error("Unable to read synchronization data: %s.",
1854 			    strerror(hio->hio_errors[ncomp]));
1855 			goto free_queue;
1856 		}
1857 
1858 		/*
1859 		 * We read the data from synchronization source, now write it
1860 		 * to synchronization target.
1861 		 */
1862 		SYNCREQ(hio);
1863 		ggio->gctl_cmd = BIO_WRITE;
1864 		for (ii = 0; ii < ncomps; ii++)
1865 			hio->hio_errors[ii] = EINVAL;
1866 		reqlog(LOG_DEBUG, 2, ggio, "sync: (%p) Sending sync request: ",
1867 		    hio);
1868 		pjdlog_debug(2, "sync: (%p) Moving request to the send queue.",
1869 		    hio);
1870 		mtx_lock(&metadata_lock);
1871 		if (res->hr_syncsrc == HAST_SYNCSRC_PRIMARY) {
1872 			/*
1873 			 * This range is up-to-date on local component,
1874 			 * so we update remote component.
1875 			 */
1876 			 /* Remote component is 1 for now. */
1877 			ncomp = 1;
1878 		} else /* if (res->hr_syncsrc == HAST_SYNCSRC_SECONDARY) */ {
1879 			PJDLOG_ASSERT(res->hr_syncsrc == HAST_SYNCSRC_SECONDARY);
1880 			/*
1881 			 * This range is out-of-date on local component,
1882 			 * so we update it.
1883 			 */
1884 			 /* Local component is 0 for now. */
1885 			ncomp = 0;
1886 		}
1887 		mtx_unlock(&metadata_lock);
1888 
1889 		pjdlog_debug(2, "sync: (%p) Moving request to the send queues.",
1890 		    hio);
1891 		refcount_init(&hio->hio_countdown, 1);
1892 		QUEUE_INSERT1(hio, send, ncomp);
1893 
1894 		/*
1895 		 * Let's wait for WRITE to finish.
1896 		 */
1897 		mtx_lock(&sync_lock);
1898 		while (!ISSYNCREQDONE(hio))
1899 			cv_wait(&sync_cond, &sync_lock);
1900 		mtx_unlock(&sync_lock);
1901 
1902 		if (hio->hio_errors[ncomp] != 0) {
1903 			pjdlog_error("Unable to write synchronization data: %s.",
1904 			    strerror(hio->hio_errors[ncomp]));
1905 			goto free_queue;
1906 		}
1907 
1908 		synced += length;
1909 free_queue:
1910 		mtx_lock(&range_lock);
1911 		rangelock_del(range_sync, offset, length);
1912 		if (range_regular_wait)
1913 			cv_signal(&range_regular_cond);
1914 		mtx_unlock(&range_lock);
1915 		pjdlog_debug(2, "sync: (%p) Moving request to the free queue.",
1916 		    hio);
1917 		QUEUE_INSERT2(hio, free);
1918 	}
1919 	/* NOTREACHED */
1920 	return (NULL);
1921 }
1922 
1923 void
1924 primary_config_reload(struct hast_resource *res, struct nv *nv)
1925 {
1926 	unsigned int ii, ncomps;
1927 	int modified, vint;
1928 	const char *vstr;
1929 
1930 	pjdlog_info("Reloading configuration...");
1931 
1932 	PJDLOG_ASSERT(res->hr_role == HAST_ROLE_PRIMARY);
1933 	PJDLOG_ASSERT(gres == res);
1934 	nv_assert(nv, "remoteaddr");
1935 	nv_assert(nv, "sourceaddr");
1936 	nv_assert(nv, "replication");
1937 	nv_assert(nv, "checksum");
1938 	nv_assert(nv, "compression");
1939 	nv_assert(nv, "timeout");
1940 	nv_assert(nv, "exec");
1941 
1942 	ncomps = HAST_NCOMPONENTS;
1943 
1944 #define MODIFIED_REMOTEADDR	0x01
1945 #define MODIFIED_SOURCEADDR	0x02
1946 #define MODIFIED_REPLICATION	0x04
1947 #define MODIFIED_CHECKSUM	0x08
1948 #define MODIFIED_COMPRESSION	0x10
1949 #define MODIFIED_TIMEOUT	0x20
1950 #define MODIFIED_EXEC		0x40
1951 	modified = 0;
1952 
1953 	vstr = nv_get_string(nv, "remoteaddr");
1954 	if (strcmp(gres->hr_remoteaddr, vstr) != 0) {
1955 		/*
1956 		 * Don't copy res->hr_remoteaddr to gres just yet.
1957 		 * We want remote_close() to log disconnect from the old
1958 		 * addresses, not from the new ones.
1959 		 */
1960 		modified |= MODIFIED_REMOTEADDR;
1961 	}
1962 	vstr = nv_get_string(nv, "sourceaddr");
1963 	if (strcmp(gres->hr_sourceaddr, vstr) != 0) {
1964 		strlcpy(gres->hr_sourceaddr, vstr, sizeof(gres->hr_sourceaddr));
1965 		modified |= MODIFIED_SOURCEADDR;
1966 	}
1967 	vint = nv_get_int32(nv, "replication");
1968 	if (gres->hr_replication != vint) {
1969 		gres->hr_replication = vint;
1970 		modified |= MODIFIED_REPLICATION;
1971 	}
1972 	vint = nv_get_int32(nv, "checksum");
1973 	if (gres->hr_checksum != vint) {
1974 		gres->hr_checksum = vint;
1975 		modified |= MODIFIED_CHECKSUM;
1976 	}
1977 	vint = nv_get_int32(nv, "compression");
1978 	if (gres->hr_compression != vint) {
1979 		gres->hr_compression = vint;
1980 		modified |= MODIFIED_COMPRESSION;
1981 	}
1982 	vint = nv_get_int32(nv, "timeout");
1983 	if (gres->hr_timeout != vint) {
1984 		gres->hr_timeout = vint;
1985 		modified |= MODIFIED_TIMEOUT;
1986 	}
1987 	vstr = nv_get_string(nv, "exec");
1988 	if (strcmp(gres->hr_exec, vstr) != 0) {
1989 		strlcpy(gres->hr_exec, vstr, sizeof(gres->hr_exec));
1990 		modified |= MODIFIED_EXEC;
1991 	}
1992 
1993 	/*
1994 	 * Change timeout for connected sockets.
1995 	 * Don't bother if we need to reconnect.
1996 	 */
1997 	if ((modified & MODIFIED_TIMEOUT) != 0 &&
1998 	    (modified & (MODIFIED_REMOTEADDR | MODIFIED_SOURCEADDR |
1999 	    MODIFIED_REPLICATION)) == 0) {
2000 		for (ii = 0; ii < ncomps; ii++) {
2001 			if (!ISREMOTE(ii))
2002 				continue;
2003 			rw_rlock(&hio_remote_lock[ii]);
2004 			if (!ISCONNECTED(gres, ii)) {
2005 				rw_unlock(&hio_remote_lock[ii]);
2006 				continue;
2007 			}
2008 			rw_unlock(&hio_remote_lock[ii]);
2009 			if (proto_timeout(gres->hr_remotein,
2010 			    gres->hr_timeout) < 0) {
2011 				pjdlog_errno(LOG_WARNING,
2012 				    "Unable to set connection timeout");
2013 			}
2014 			if (proto_timeout(gres->hr_remoteout,
2015 			    gres->hr_timeout) < 0) {
2016 				pjdlog_errno(LOG_WARNING,
2017 				    "Unable to set connection timeout");
2018 			}
2019 		}
2020 	}
2021 	if ((modified & (MODIFIED_REMOTEADDR | MODIFIED_SOURCEADDR |
2022 	    MODIFIED_REPLICATION)) != 0) {
2023 		for (ii = 0; ii < ncomps; ii++) {
2024 			if (!ISREMOTE(ii))
2025 				continue;
2026 			remote_close(gres, ii);
2027 		}
2028 		if (modified & MODIFIED_REMOTEADDR) {
2029 			vstr = nv_get_string(nv, "remoteaddr");
2030 			strlcpy(gres->hr_remoteaddr, vstr,
2031 			    sizeof(gres->hr_remoteaddr));
2032 		}
2033 	}
2034 #undef	MODIFIED_REMOTEADDR
2035 #undef	MODIFIED_SOURCEADDR
2036 #undef	MODIFIED_REPLICATION
2037 #undef	MODIFIED_CHECKSUM
2038 #undef	MODIFIED_COMPRESSION
2039 #undef	MODIFIED_TIMEOUT
2040 #undef	MODIFIED_EXEC
2041 
2042 	pjdlog_info("Configuration reloaded successfully.");
2043 }
2044 
2045 static void
2046 guard_one(struct hast_resource *res, unsigned int ncomp)
2047 {
2048 	struct proto_conn *in, *out;
2049 
2050 	if (!ISREMOTE(ncomp))
2051 		return;
2052 
2053 	rw_rlock(&hio_remote_lock[ncomp]);
2054 
2055 	if (!real_remote(res)) {
2056 		rw_unlock(&hio_remote_lock[ncomp]);
2057 		return;
2058 	}
2059 
2060 	if (ISCONNECTED(res, ncomp)) {
2061 		PJDLOG_ASSERT(res->hr_remotein != NULL);
2062 		PJDLOG_ASSERT(res->hr_remoteout != NULL);
2063 		rw_unlock(&hio_remote_lock[ncomp]);
2064 		pjdlog_debug(2, "remote_guard: Connection to %s is ok.",
2065 		    res->hr_remoteaddr);
2066 		return;
2067 	}
2068 
2069 	PJDLOG_ASSERT(res->hr_remotein == NULL);
2070 	PJDLOG_ASSERT(res->hr_remoteout == NULL);
2071 	/*
2072 	 * Upgrade the lock. It doesn't have to be atomic as no other thread
2073 	 * can change connection status from disconnected to connected.
2074 	 */
2075 	rw_unlock(&hio_remote_lock[ncomp]);
2076 	pjdlog_debug(2, "remote_guard: Reconnecting to %s.",
2077 	    res->hr_remoteaddr);
2078 	in = out = NULL;
2079 	if (init_remote(res, &in, &out)) {
2080 		rw_wlock(&hio_remote_lock[ncomp]);
2081 		PJDLOG_ASSERT(res->hr_remotein == NULL);
2082 		PJDLOG_ASSERT(res->hr_remoteout == NULL);
2083 		PJDLOG_ASSERT(in != NULL && out != NULL);
2084 		res->hr_remotein = in;
2085 		res->hr_remoteout = out;
2086 		rw_unlock(&hio_remote_lock[ncomp]);
2087 		pjdlog_info("Successfully reconnected to %s.",
2088 		    res->hr_remoteaddr);
2089 		sync_start();
2090 	} else {
2091 		/* Both connections should be NULL. */
2092 		PJDLOG_ASSERT(res->hr_remotein == NULL);
2093 		PJDLOG_ASSERT(res->hr_remoteout == NULL);
2094 		PJDLOG_ASSERT(in == NULL && out == NULL);
2095 		pjdlog_debug(2, "remote_guard: Reconnect to %s failed.",
2096 		    res->hr_remoteaddr);
2097 	}
2098 }
2099 
2100 /*
2101  * Thread guards remote connections and reconnects when needed, handles
2102  * signals, etc.
2103  */
2104 static void *
2105 guard_thread(void *arg)
2106 {
2107 	struct hast_resource *res = arg;
2108 	unsigned int ii, ncomps;
2109 	struct timespec timeout;
2110 	time_t lastcheck, now;
2111 	sigset_t mask;
2112 	int signo;
2113 
2114 	ncomps = HAST_NCOMPONENTS;
2115 	lastcheck = time(NULL);
2116 
2117 	PJDLOG_VERIFY(sigemptyset(&mask) == 0);
2118 	PJDLOG_VERIFY(sigaddset(&mask, SIGINT) == 0);
2119 	PJDLOG_VERIFY(sigaddset(&mask, SIGTERM) == 0);
2120 
2121 	timeout.tv_sec = HAST_KEEPALIVE;
2122 	timeout.tv_nsec = 0;
2123 	signo = -1;
2124 
2125 	for (;;) {
2126 		switch (signo) {
2127 		case SIGINT:
2128 		case SIGTERM:
2129 			sigexit_received = true;
2130 			primary_exitx(EX_OK,
2131 			    "Termination signal received, exiting.");
2132 			break;
2133 		default:
2134 			break;
2135 		}
2136 
2137 		pjdlog_debug(2, "remote_guard: Checking connections.");
2138 		now = time(NULL);
2139 		if (lastcheck + HAST_KEEPALIVE <= now) {
2140 			for (ii = 0; ii < ncomps; ii++)
2141 				guard_one(res, ii);
2142 			lastcheck = now;
2143 		}
2144 		signo = sigtimedwait(&mask, NULL, &timeout);
2145 	}
2146 	/* NOTREACHED */
2147 	return (NULL);
2148 }
2149