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