xref: /freebsd/sbin/hastd/secondary.c (revision 5dcd9c10612684d1c823670cbb5b4715028784e7)
1 /*-
2  * Copyright (c) 2009-2010 The FreeBSD Foundation
3  * Copyright (c) 2010 Pawel Jakub Dawidek <pjd@FreeBSD.org>
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/param.h>
35 #include <sys/time.h>
36 #include <sys/bio.h>
37 #include <sys/disk.h>
38 #include <sys/stat.h>
39 
40 #include <err.h>
41 #include <errno.h>
42 #include <fcntl.h>
43 #include <libgeom.h>
44 #include <pthread.h>
45 #include <signal.h>
46 #include <stdint.h>
47 #include <stdio.h>
48 #include <string.h>
49 #include <sysexits.h>
50 #include <unistd.h>
51 
52 #include <activemap.h>
53 #include <nv.h>
54 #include <pjdlog.h>
55 
56 #include "control.h"
57 #include "event.h"
58 #include "hast.h"
59 #include "hast_proto.h"
60 #include "hastd.h"
61 #include "hooks.h"
62 #include "metadata.h"
63 #include "proto.h"
64 #include "subr.h"
65 #include "synch.h"
66 
67 struct hio {
68 	uint64_t 	 hio_seq;
69 	int	 	 hio_error;
70 	struct nv	*hio_nv;
71 	void		*hio_data;
72 	uint8_t		 hio_cmd;
73 	uint64_t	 hio_offset;
74 	uint64_t	 hio_length;
75 	TAILQ_ENTRY(hio) hio_next;
76 };
77 
78 static struct hast_resource *gres;
79 
80 /*
81  * Free list holds unused structures. When free list is empty, we have to wait
82  * until some in-progress requests are freed.
83  */
84 static TAILQ_HEAD(, hio) hio_free_list;
85 static pthread_mutex_t hio_free_list_lock;
86 static pthread_cond_t hio_free_list_cond;
87 /*
88  * Disk thread (the one that do I/O requests) takes requests from this list.
89  */
90 static TAILQ_HEAD(, hio) hio_disk_list;
91 static pthread_mutex_t hio_disk_list_lock;
92 static pthread_cond_t hio_disk_list_cond;
93 /*
94  * There is one recv list for every component, although local components don't
95  * use recv lists as local requests are done synchronously.
96  */
97 static TAILQ_HEAD(, hio) hio_send_list;
98 static pthread_mutex_t hio_send_list_lock;
99 static pthread_cond_t hio_send_list_cond;
100 
101 /*
102  * Maximum number of outstanding I/O requests.
103  */
104 #define	HAST_HIO_MAX	256
105 
106 static void *recv_thread(void *arg);
107 static void *disk_thread(void *arg);
108 static void *send_thread(void *arg);
109 
110 #define	QUEUE_INSERT(name, hio)	do {					\
111 	bool _wakeup;							\
112 									\
113 	mtx_lock(&hio_##name##_list_lock);				\
114 	_wakeup = TAILQ_EMPTY(&hio_##name##_list);			\
115 	TAILQ_INSERT_TAIL(&hio_##name##_list, (hio), hio_next);		\
116 	mtx_unlock(&hio_##name##_list_lock);				\
117 	if (_wakeup)							\
118 		cv_signal(&hio_##name##_list_cond);			\
119 } while (0)
120 #define	QUEUE_TAKE(name, hio)	do {					\
121 	mtx_lock(&hio_##name##_list_lock);				\
122 	while (((hio) = TAILQ_FIRST(&hio_##name##_list)) == NULL) {	\
123 		cv_wait(&hio_##name##_list_cond,			\
124 		    &hio_##name##_list_lock);				\
125 	}								\
126 	TAILQ_REMOVE(&hio_##name##_list, (hio), hio_next);		\
127 	mtx_unlock(&hio_##name##_list_lock);				\
128 } while (0)
129 
130 static void
131 init_environment(void)
132 {
133 	struct hio *hio;
134 	unsigned int ii;
135 
136 	/*
137 	 * Initialize lists, their locks and theirs condition variables.
138 	 */
139 	TAILQ_INIT(&hio_free_list);
140 	mtx_init(&hio_free_list_lock);
141 	cv_init(&hio_free_list_cond);
142 	TAILQ_INIT(&hio_disk_list);
143 	mtx_init(&hio_disk_list_lock);
144 	cv_init(&hio_disk_list_cond);
145 	TAILQ_INIT(&hio_send_list);
146 	mtx_init(&hio_send_list_lock);
147 	cv_init(&hio_send_list_cond);
148 
149 	/*
150 	 * Allocate requests pool and initialize requests.
151 	 */
152 	for (ii = 0; ii < HAST_HIO_MAX; ii++) {
153 		hio = malloc(sizeof(*hio));
154 		if (hio == NULL) {
155 			pjdlog_exitx(EX_TEMPFAIL,
156 			    "Unable to allocate memory (%zu bytes) for hio request.",
157 			    sizeof(*hio));
158 		}
159 		hio->hio_error = 0;
160 		hio->hio_data = malloc(MAXPHYS);
161 		if (hio->hio_data == NULL) {
162 			pjdlog_exitx(EX_TEMPFAIL,
163 			    "Unable to allocate memory (%zu bytes) for gctl_data.",
164 			    (size_t)MAXPHYS);
165 		}
166 		TAILQ_INSERT_HEAD(&hio_free_list, hio, hio_next);
167 	}
168 }
169 
170 static void
171 init_local(struct hast_resource *res)
172 {
173 
174 	if (metadata_read(res, true) < 0)
175 		exit(EX_NOINPUT);
176 }
177 
178 static void
179 init_remote(struct hast_resource *res, struct nv *nvin)
180 {
181 	uint64_t resuid;
182 	struct nv *nvout;
183 	unsigned char *map;
184 	size_t mapsize;
185 
186 	map = NULL;
187 	mapsize = 0;
188 	nvout = nv_alloc();
189 	nv_add_int64(nvout, (int64_t)res->hr_datasize, "datasize");
190 	nv_add_int32(nvout, (int32_t)res->hr_extentsize, "extentsize");
191 	resuid = nv_get_uint64(nvin, "resuid");
192 	res->hr_primary_localcnt = nv_get_uint64(nvin, "localcnt");
193 	res->hr_primary_remotecnt = nv_get_uint64(nvin, "remotecnt");
194 	nv_add_uint64(nvout, res->hr_secondary_localcnt, "localcnt");
195 	nv_add_uint64(nvout, res->hr_secondary_remotecnt, "remotecnt");
196 	mapsize = activemap_calc_ondisk_size(res->hr_local_mediasize -
197 	    METADATA_SIZE, res->hr_extentsize, res->hr_local_sectorsize);
198 	map = malloc(mapsize);
199 	if (map == NULL) {
200 		pjdlog_exitx(EX_TEMPFAIL,
201 		    "Unable to allocate memory (%zu bytes) for activemap.",
202 		    mapsize);
203 	}
204 	nv_add_uint32(nvout, (uint32_t)mapsize, "mapsize");
205 	/*
206 	 * When we work as primary and secondary is missing we will increase
207 	 * localcnt in our metadata. When secondary is connected and synced
208 	 * we make localcnt be equal to remotecnt, which means nodes are more
209 	 * or less in sync.
210 	 * Split-brain condition is when both nodes are not able to communicate
211 	 * and are both configured as primary nodes. In turn, they can both
212 	 * make incompatible changes to the data and we have to detect that.
213 	 * Under split-brain condition we will increase our localcnt on first
214 	 * write and remote node will increase its localcnt on first write.
215 	 * When we connect we can see that primary's localcnt is greater than
216 	 * our remotecnt (primary was modified while we weren't watching) and
217 	 * our localcnt is greater than primary's remotecnt (we were modified
218 	 * while primary wasn't watching).
219 	 * There are many possible combinations which are all gathered below.
220 	 * Don't pay too much attention to exact numbers, the more important
221 	 * is to compare them. We compare secondary's local with primary's
222 	 * remote and secondary's remote with primary's local.
223 	 * Note that every case where primary's localcnt is smaller than
224 	 * secondary's remotecnt and where secondary's localcnt is smaller than
225 	 * primary's remotecnt should be impossible in practise. We will perform
226 	 * full synchronization then. Those cases are marked with an asterisk.
227 	 * Regular synchronization means that only extents marked as dirty are
228 	 * synchronized (regular synchronization).
229 	 *
230 	 * SECONDARY METADATA PRIMARY METADATA
231 	 * local=3 remote=3   local=2 remote=2*  ?! Full sync from secondary.
232 	 * local=3 remote=3   local=2 remote=3*  ?! Full sync from primary.
233 	 * local=3 remote=3   local=2 remote=4*  ?! Full sync from primary.
234 	 * local=3 remote=3   local=3 remote=2   Primary is out-of-date,
235 	 *                                       regular sync from secondary.
236 	 * local=3 remote=3   local=3 remote=3   Regular sync just in case.
237 	 * local=3 remote=3   local=3 remote=4*  ?! Full sync from primary.
238 	 * local=3 remote=3   local=4 remote=2   Split-brain condition.
239 	 * local=3 remote=3   local=4 remote=3   Secondary out-of-date,
240 	 *                                       regular sync from primary.
241 	 * local=3 remote=3   local=4 remote=4*  ?! Full sync from primary.
242 	 */
243 	if (res->hr_resuid == 0) {
244 		/*
245 		 * Provider is used for the first time. If primary node done no
246 		 * writes yet as well (we will find "virgin" argument) then
247 		 * there is no need to synchronize anything. If primary node
248 		 * done any writes already we have to synchronize everything.
249 		 */
250 		PJDLOG_ASSERT(res->hr_secondary_localcnt == 0);
251 		res->hr_resuid = resuid;
252 		if (metadata_write(res) < 0)
253 			exit(EX_NOINPUT);
254 		if (nv_exists(nvin, "virgin")) {
255 			free(map);
256 			map = NULL;
257 			mapsize = 0;
258 		} else {
259 			memset(map, 0xff, mapsize);
260 		}
261 		nv_add_uint8(nvout, HAST_SYNCSRC_PRIMARY, "syncsrc");
262 	} else if (
263 	    /* Is primary is out-of-date? */
264 	    (res->hr_secondary_localcnt > res->hr_primary_remotecnt &&
265 	     res->hr_secondary_remotecnt == res->hr_primary_localcnt) ||
266 	    /* Node are more or less in sync? */
267 	    (res->hr_secondary_localcnt == res->hr_primary_remotecnt &&
268 	     res->hr_secondary_remotecnt == res->hr_primary_localcnt) ||
269 	    /* Is secondary is out-of-date? */
270 	    (res->hr_secondary_localcnt == res->hr_primary_remotecnt &&
271 	     res->hr_secondary_remotecnt < res->hr_primary_localcnt)) {
272 		/*
273 		 * Nodes are more or less in sync or one of the nodes is
274 		 * out-of-date.
275 		 * It doesn't matter at this point which one, we just have to
276 		 * send out local bitmap to the remote node.
277 		 */
278 		if (pread(res->hr_localfd, map, mapsize, METADATA_SIZE) !=
279 		    (ssize_t)mapsize) {
280 			pjdlog_exit(LOG_ERR, "Unable to read activemap");
281 		}
282 		if (res->hr_secondary_localcnt > res->hr_primary_remotecnt &&
283 		     res->hr_secondary_remotecnt == res->hr_primary_localcnt) {
284 			/* Primary is out-of-date, sync from secondary. */
285 			nv_add_uint8(nvout, HAST_SYNCSRC_SECONDARY, "syncsrc");
286 		} else {
287 			/*
288 			 * Secondary is out-of-date or counts match.
289 			 * Sync from primary.
290 			 */
291 			nv_add_uint8(nvout, HAST_SYNCSRC_PRIMARY, "syncsrc");
292 		}
293 	} else if (res->hr_secondary_localcnt > res->hr_primary_remotecnt &&
294 	     res->hr_primary_localcnt > res->hr_secondary_remotecnt) {
295 		/*
296 		 * Not good, we have split-brain condition.
297 		 */
298 		pjdlog_error("Split-brain detected, exiting.");
299 		nv_add_string(nvout, "Split-brain condition!", "errmsg");
300 		free(map);
301 		map = NULL;
302 		mapsize = 0;
303 	} else /* if (res->hr_secondary_localcnt < res->hr_primary_remotecnt ||
304 	    res->hr_primary_localcnt < res->hr_secondary_remotecnt) */ {
305 		/*
306 		 * This should never happen in practise, but we will perform
307 		 * full synchronization.
308 		 */
309 		PJDLOG_ASSERT(res->hr_secondary_localcnt < res->hr_primary_remotecnt ||
310 		    res->hr_primary_localcnt < res->hr_secondary_remotecnt);
311 		mapsize = activemap_calc_ondisk_size(res->hr_local_mediasize -
312 		    METADATA_SIZE, res->hr_extentsize,
313 		    res->hr_local_sectorsize);
314 		memset(map, 0xff, mapsize);
315 		if (res->hr_secondary_localcnt > res->hr_primary_remotecnt) {
316 			/* In this one of five cases sync from secondary. */
317 			nv_add_uint8(nvout, HAST_SYNCSRC_SECONDARY, "syncsrc");
318 		} else {
319 			/* For the rest four cases sync from primary. */
320 			nv_add_uint8(nvout, HAST_SYNCSRC_PRIMARY, "syncsrc");
321 		}
322 		pjdlog_warning("This should never happen, asking for full synchronization (primary(local=%ju, remote=%ju), secondary(local=%ju, remote=%ju)).",
323 		    (uintmax_t)res->hr_primary_localcnt,
324 		    (uintmax_t)res->hr_primary_remotecnt,
325 		    (uintmax_t)res->hr_secondary_localcnt,
326 		    (uintmax_t)res->hr_secondary_remotecnt);
327 	}
328 	if (hast_proto_send(res, res->hr_remotein, nvout, map, mapsize) < 0) {
329 		pjdlog_exit(EX_TEMPFAIL, "Unable to send activemap to %s",
330 		    res->hr_remoteaddr);
331 	}
332 	if (map != NULL)
333 		free(map);
334 	nv_free(nvout);
335 	if (res->hr_secondary_localcnt > res->hr_primary_remotecnt &&
336 	     res->hr_primary_localcnt > res->hr_secondary_remotecnt) {
337 		/* Exit on split-brain. */
338 		event_send(res, EVENT_SPLITBRAIN);
339 		exit(EX_CONFIG);
340 	}
341 }
342 
343 void
344 hastd_secondary(struct hast_resource *res, struct nv *nvin)
345 {
346 	sigset_t mask;
347 	pthread_t td;
348 	pid_t pid;
349 	int error, mode;
350 
351 	/*
352 	 * Create communication channel between parent and child.
353 	 */
354 	if (proto_client("socketpair://", &res->hr_ctrl) < 0) {
355 		KEEP_ERRNO((void)pidfile_remove(pfh));
356 		pjdlog_exit(EX_OSERR,
357 		    "Unable to create control sockets between parent and child");
358 	}
359 	/*
360 	 * Create communication channel between child and parent.
361 	 */
362 	if (proto_client("socketpair://", &res->hr_event) < 0) {
363 		KEEP_ERRNO((void)pidfile_remove(pfh));
364 		pjdlog_exit(EX_OSERR,
365 		    "Unable to create event sockets between child and parent");
366 	}
367 	/*
368 	 * Create communication channel for sending connection requests from
369 	 * parent to child.
370 	 */
371 	if (proto_client("socketpair://", &res->hr_conn) < 0) {
372 		/* TODO: There's no need for this to be fatal error. */
373 		KEEP_ERRNO((void)pidfile_remove(pfh));
374 		pjdlog_exit(EX_OSERR,
375 		    "Unable to create connection sockets between parent and child");
376 	}
377 
378 	pid = fork();
379 	if (pid < 0) {
380 		KEEP_ERRNO((void)pidfile_remove(pfh));
381 		pjdlog_exit(EX_OSERR, "Unable to fork");
382 	}
383 
384 	if (pid > 0) {
385 		/* This is parent. */
386 		proto_close(res->hr_remotein);
387 		res->hr_remotein = NULL;
388 		proto_close(res->hr_remoteout);
389 		res->hr_remoteout = NULL;
390 		/* Declare that we are receiver. */
391 		proto_recv(res->hr_event, NULL, 0);
392 		/* Declare that we are sender. */
393 		proto_send(res->hr_ctrl, NULL, 0);
394 		proto_send(res->hr_conn, NULL, 0);
395 		res->hr_workerpid = pid;
396 		return;
397 	}
398 
399 	gres = res;
400 	mode = pjdlog_mode_get();
401 
402 	/* Declare that we are sender. */
403 	proto_send(res->hr_event, NULL, 0);
404 	/* Declare that we are receiver. */
405 	proto_recv(res->hr_ctrl, NULL, 0);
406 	proto_recv(res->hr_conn, NULL, 0);
407 	descriptors_cleanup(res);
408 
409 	descriptors_assert(res, mode);
410 
411 	pjdlog_init(mode);
412 	pjdlog_prefix_set("[%s] (%s) ", res->hr_name, role2str(res->hr_role));
413 	setproctitle("%s (secondary)", res->hr_name);
414 
415 	PJDLOG_VERIFY(sigemptyset(&mask) == 0);
416 	PJDLOG_VERIFY(sigprocmask(SIG_SETMASK, &mask, NULL) == 0);
417 
418 	/* Error in setting timeout is not critical, but why should it fail? */
419 	if (proto_timeout(res->hr_remotein, 0) < 0)
420 		pjdlog_errno(LOG_WARNING, "Unable to set connection timeout");
421 	if (proto_timeout(res->hr_remoteout, res->hr_timeout) < 0)
422 		pjdlog_errno(LOG_WARNING, "Unable to set connection timeout");
423 
424 	init_local(res);
425 	init_environment();
426 
427 	if (drop_privs() != 0)
428 		exit(EX_CONFIG);
429 	pjdlog_info("Privileges successfully dropped.");
430 
431 	/*
432 	 * Create the control thread before sending any event to the parent,
433 	 * as we can deadlock when parent sends control request to worker,
434 	 * but worker has no control thread started yet, so parent waits.
435 	 * In the meantime worker sends an event to the parent, but parent
436 	 * is unable to handle the event, because it waits for control
437 	 * request response.
438 	 */
439 	error = pthread_create(&td, NULL, ctrl_thread, res);
440 	PJDLOG_ASSERT(error == 0);
441 
442 	init_remote(res, nvin);
443 	event_send(res, EVENT_CONNECT);
444 
445 	error = pthread_create(&td, NULL, recv_thread, res);
446 	PJDLOG_ASSERT(error == 0);
447 	error = pthread_create(&td, NULL, disk_thread, res);
448 	PJDLOG_ASSERT(error == 0);
449 	(void)send_thread(res);
450 }
451 
452 static void
453 reqlog(int loglevel, int debuglevel, int error, struct hio *hio, const char *fmt, ...)
454 {
455 	char msg[1024];
456 	va_list ap;
457 	int len;
458 
459 	va_start(ap, fmt);
460 	len = vsnprintf(msg, sizeof(msg), fmt, ap);
461 	va_end(ap);
462 	if ((size_t)len < sizeof(msg)) {
463 		switch (hio->hio_cmd) {
464 		case HIO_READ:
465 			(void)snprintf(msg + len, sizeof(msg) - len,
466 			    "READ(%ju, %ju).", (uintmax_t)hio->hio_offset,
467 			    (uintmax_t)hio->hio_length);
468 			break;
469 		case HIO_DELETE:
470 			(void)snprintf(msg + len, sizeof(msg) - len,
471 			    "DELETE(%ju, %ju).", (uintmax_t)hio->hio_offset,
472 			    (uintmax_t)hio->hio_length);
473 			break;
474 		case HIO_FLUSH:
475 			(void)snprintf(msg + len, sizeof(msg) - len, "FLUSH.");
476 			break;
477 		case HIO_WRITE:
478 			(void)snprintf(msg + len, sizeof(msg) - len,
479 			    "WRITE(%ju, %ju).", (uintmax_t)hio->hio_offset,
480 			    (uintmax_t)hio->hio_length);
481 			break;
482 		case HIO_KEEPALIVE:
483 			(void)snprintf(msg + len, sizeof(msg) - len, "KEEPALIVE.");
484 			break;
485 		default:
486 			(void)snprintf(msg + len, sizeof(msg) - len,
487 			    "UNKNOWN(%u).", (unsigned int)hio->hio_cmd);
488 			break;
489 		}
490 	}
491 	pjdlog_common(loglevel, debuglevel, error, "%s", msg);
492 }
493 
494 static int
495 requnpack(struct hast_resource *res, struct hio *hio)
496 {
497 
498 	hio->hio_cmd = nv_get_uint8(hio->hio_nv, "cmd");
499 	if (hio->hio_cmd == 0) {
500 		pjdlog_error("Header contains no 'cmd' field.");
501 		hio->hio_error = EINVAL;
502 		goto end;
503 	}
504 	switch (hio->hio_cmd) {
505 	case HIO_KEEPALIVE:
506 		break;
507 	case HIO_READ:
508 	case HIO_WRITE:
509 	case HIO_DELETE:
510 		hio->hio_offset = nv_get_uint64(hio->hio_nv, "offset");
511 		if (nv_error(hio->hio_nv) != 0) {
512 			pjdlog_error("Header is missing 'offset' field.");
513 			hio->hio_error = EINVAL;
514 			goto end;
515 		}
516 		hio->hio_length = nv_get_uint64(hio->hio_nv, "length");
517 		if (nv_error(hio->hio_nv) != 0) {
518 			pjdlog_error("Header is missing 'length' field.");
519 			hio->hio_error = EINVAL;
520 			goto end;
521 		}
522 		if (hio->hio_length == 0) {
523 			pjdlog_error("Data length is zero.");
524 			hio->hio_error = EINVAL;
525 			goto end;
526 		}
527 		if (hio->hio_length > MAXPHYS) {
528 			pjdlog_error("Data length is too large (%ju > %ju).",
529 			    (uintmax_t)hio->hio_length, (uintmax_t)MAXPHYS);
530 			hio->hio_error = EINVAL;
531 			goto end;
532 		}
533 		if ((hio->hio_offset % res->hr_local_sectorsize) != 0) {
534 			pjdlog_error("Offset %ju is not multiple of sector size.",
535 			    (uintmax_t)hio->hio_offset);
536 			hio->hio_error = EINVAL;
537 			goto end;
538 		}
539 		if ((hio->hio_length % res->hr_local_sectorsize) != 0) {
540 			pjdlog_error("Length %ju is not multiple of sector size.",
541 			    (uintmax_t)hio->hio_length);
542 			hio->hio_error = EINVAL;
543 			goto end;
544 		}
545 		if (hio->hio_offset + hio->hio_length >
546 		    (uint64_t)res->hr_datasize) {
547 			pjdlog_error("Data offset is too large (%ju > %ju).",
548 			    (uintmax_t)(hio->hio_offset + hio->hio_length),
549 			    (uintmax_t)res->hr_datasize);
550 			hio->hio_error = EINVAL;
551 			goto end;
552 		}
553 		break;
554 	default:
555 		pjdlog_error("Header contains invalid 'cmd' (%hhu).",
556 		    hio->hio_cmd);
557 		hio->hio_error = EINVAL;
558 		goto end;
559 	}
560 	hio->hio_error = 0;
561 end:
562 	return (hio->hio_error);
563 }
564 
565 static __dead2 void
566 secondary_exit(int exitcode, const char *fmt, ...)
567 {
568 	va_list ap;
569 
570 	PJDLOG_ASSERT(exitcode != EX_OK);
571 	va_start(ap, fmt);
572 	pjdlogv_errno(LOG_ERR, fmt, ap);
573 	va_end(ap);
574 	event_send(gres, EVENT_DISCONNECT);
575 	exit(exitcode);
576 }
577 
578 /*
579  * Thread receives requests from the primary node.
580  */
581 static void *
582 recv_thread(void *arg)
583 {
584 	struct hast_resource *res = arg;
585 	struct hio *hio;
586 
587 	for (;;) {
588 		pjdlog_debug(2, "recv: Taking free request.");
589 		QUEUE_TAKE(free, hio);
590 		pjdlog_debug(2, "recv: (%p) Got request.", hio);
591 		if (hast_proto_recv_hdr(res->hr_remotein, &hio->hio_nv) < 0) {
592 			secondary_exit(EX_TEMPFAIL,
593 			    "Unable to receive request header");
594 		}
595 		if (requnpack(res, hio) != 0) {
596 			pjdlog_debug(2,
597 			    "recv: (%p) Moving request to the send queue.",
598 			    hio);
599 			QUEUE_INSERT(send, hio);
600 			continue;
601 		}
602 		reqlog(LOG_DEBUG, 2, -1, hio,
603 		    "recv: (%p) Got request header: ", hio);
604 		if (hio->hio_cmd == HIO_KEEPALIVE) {
605 			pjdlog_debug(2,
606 			    "recv: (%p) Moving request to the free queue.",
607 			    hio);
608 			nv_free(hio->hio_nv);
609 			QUEUE_INSERT(free, hio);
610 			continue;
611 		} else if (hio->hio_cmd == HIO_WRITE) {
612 			if (hast_proto_recv_data(res, res->hr_remotein,
613 			    hio->hio_nv, hio->hio_data, MAXPHYS) < 0) {
614 				secondary_exit(EX_TEMPFAIL,
615 				    "Unable to receive request data");
616 			}
617 		}
618 		pjdlog_debug(2, "recv: (%p) Moving request to the disk queue.",
619 		    hio);
620 		QUEUE_INSERT(disk, hio);
621 	}
622 	/* NOTREACHED */
623 	return (NULL);
624 }
625 
626 /*
627  * Thread reads from or writes to local component and also handles DELETE and
628  * FLUSH requests.
629  */
630 static void *
631 disk_thread(void *arg)
632 {
633 	struct hast_resource *res = arg;
634 	struct hio *hio;
635 	ssize_t ret;
636 	bool clear_activemap;
637 
638 	clear_activemap = true;
639 
640 	for (;;) {
641 		pjdlog_debug(2, "disk: Taking request.");
642 		QUEUE_TAKE(disk, hio);
643 		while (clear_activemap) {
644 			unsigned char *map;
645 			size_t mapsize;
646 
647 			/*
648 			 * When first request is received, it means that primary
649 			 * already received our activemap, merged it and stored
650 			 * locally. We can now safely clear our activemap.
651 			 */
652 			mapsize =
653 			    activemap_calc_ondisk_size(res->hr_local_mediasize -
654 			    METADATA_SIZE, res->hr_extentsize,
655 			    res->hr_local_sectorsize);
656 			map = calloc(1, mapsize);
657 			if (map == NULL) {
658 				pjdlog_warning("Unable to allocate memory to clear local activemap.");
659 				break;
660 			}
661 			if (pwrite(res->hr_localfd, map, mapsize,
662 			    METADATA_SIZE) != (ssize_t)mapsize) {
663 				pjdlog_errno(LOG_WARNING,
664 				    "Unable to store cleared activemap");
665 				free(map);
666 				break;
667 			}
668 			free(map);
669 			clear_activemap = false;
670 			pjdlog_debug(1, "Local activemap cleared.");
671 		}
672 		reqlog(LOG_DEBUG, 2, -1, hio, "disk: (%p) Got request: ", hio);
673 		/* Handle the actual request. */
674 		switch (hio->hio_cmd) {
675 		case HIO_READ:
676 			ret = pread(res->hr_localfd, hio->hio_data,
677 			    hio->hio_length,
678 			    hio->hio_offset + res->hr_localoff);
679 			if (ret < 0)
680 				hio->hio_error = errno;
681 			else if (ret != (int64_t)hio->hio_length)
682 				hio->hio_error = EIO;
683 			else
684 				hio->hio_error = 0;
685 			break;
686 		case HIO_WRITE:
687 			ret = pwrite(res->hr_localfd, hio->hio_data,
688 			    hio->hio_length,
689 			    hio->hio_offset + res->hr_localoff);
690 			if (ret < 0)
691 				hio->hio_error = errno;
692 			else if (ret != (int64_t)hio->hio_length)
693 				hio->hio_error = EIO;
694 			else
695 				hio->hio_error = 0;
696 			break;
697 		case HIO_DELETE:
698 			ret = g_delete(res->hr_localfd,
699 			    hio->hio_offset + res->hr_localoff,
700 			    hio->hio_length);
701 			if (ret < 0)
702 				hio->hio_error = errno;
703 			else
704 				hio->hio_error = 0;
705 			break;
706 		case HIO_FLUSH:
707 			ret = g_flush(res->hr_localfd);
708 			if (ret < 0)
709 				hio->hio_error = errno;
710 			else
711 				hio->hio_error = 0;
712 			break;
713 		}
714 		if (hio->hio_error != 0) {
715 			reqlog(LOG_ERR, 0, hio->hio_error, hio,
716 			    "Request failed: ");
717 		}
718 		pjdlog_debug(2, "disk: (%p) Moving request to the send queue.",
719 		    hio);
720 		QUEUE_INSERT(send, hio);
721 	}
722 	/* NOTREACHED */
723 	return (NULL);
724 }
725 
726 /*
727  * Thread sends requests back to primary node.
728  */
729 static void *
730 send_thread(void *arg)
731 {
732 	struct hast_resource *res = arg;
733 	struct nv *nvout;
734 	struct hio *hio;
735 	void *data;
736 	size_t length;
737 
738 	for (;;) {
739 		pjdlog_debug(2, "send: Taking request.");
740 		QUEUE_TAKE(send, hio);
741 		reqlog(LOG_DEBUG, 2, -1, hio, "send: (%p) Got request: ", hio);
742 		nvout = nv_alloc();
743 		/* Copy sequence number. */
744 		nv_add_uint64(nvout, nv_get_uint64(hio->hio_nv, "seq"), "seq");
745 		switch (hio->hio_cmd) {
746 		case HIO_READ:
747 			if (hio->hio_error == 0) {
748 				data = hio->hio_data;
749 				length = hio->hio_length;
750 				break;
751 			}
752 			/*
753 			 * We send no data in case of an error.
754 			 */
755 			/* FALLTHROUGH */
756 		case HIO_DELETE:
757 		case HIO_FLUSH:
758 		case HIO_WRITE:
759 			data = NULL;
760 			length = 0;
761 			break;
762 		default:
763 			abort();
764 			break;
765 		}
766 		if (hio->hio_error != 0)
767 			nv_add_int16(nvout, hio->hio_error, "error");
768 		if (hast_proto_send(res, res->hr_remoteout, nvout, data,
769 		    length) < 0) {
770 			secondary_exit(EX_TEMPFAIL, "Unable to send reply.");
771 		}
772 		nv_free(nvout);
773 		pjdlog_debug(2, "send: (%p) Moving request to the free queue.",
774 		    hio);
775 		nv_free(hio->hio_nv);
776 		hio->hio_error = 0;
777 		QUEUE_INSERT(free, hio);
778 	}
779 	/* NOTREACHED */
780 	return (NULL);
781 }
782