secondary.c revision 222164
1252190Srpaulo/*-
2252190Srpaulo * Copyright (c) 2009-2010 The FreeBSD Foundation
3252190Srpaulo * Copyright (c) 2010 Pawel Jakub Dawidek <pjd@FreeBSD.org>
4252190Srpaulo * All rights reserved.
5252190Srpaulo *
6252190Srpaulo * This software was developed by Pawel Jakub Dawidek under sponsorship from
7252190Srpaulo * the FreeBSD Foundation.
8252190Srpaulo *
9252190Srpaulo * Redistribution and use in source and binary forms, with or without
10252190Srpaulo * modification, are permitted provided that the following conditions
11252190Srpaulo * are met:
12252190Srpaulo * 1. Redistributions of source code must retain the above copyright
13252190Srpaulo *    notice, this list of conditions and the following disclaimer.
14252190Srpaulo * 2. Redistributions in binary form must reproduce the above copyright
15252190Srpaulo *    notice, this list of conditions and the following disclaimer in the
16252190Srpaulo *    documentation and/or other materials provided with the distribution.
17252190Srpaulo *
18252190Srpaulo * THIS SOFTWARE IS PROVIDED BY THE AUTHORS AND CONTRIBUTORS ``AS IS'' AND
19252190Srpaulo * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20252190Srpaulo * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21252190Srpaulo * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE
22252190Srpaulo * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23252190Srpaulo * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24252190Srpaulo * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25252190Srpaulo * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26252190Srpaulo * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
27252190Srpaulo * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28252190Srpaulo * SUCH DAMAGE.
29 */
30
31#include <sys/cdefs.h>
32__FBSDID("$FreeBSD: head/sbin/hastd/secondary.c 222164 2011-05-21 20:21:20Z pjd $");
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
67struct 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
78static 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 */
84static TAILQ_HEAD(, hio) hio_free_list;
85static pthread_mutex_t hio_free_list_lock;
86static pthread_cond_t hio_free_list_cond;
87/*
88 * Disk thread (the one that do I/O requests) takes requests from this list.
89 */
90static TAILQ_HEAD(, hio) hio_disk_list;
91static pthread_mutex_t hio_disk_list_lock;
92static 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 */
97static TAILQ_HEAD(, hio) hio_send_list;
98static pthread_mutex_t hio_send_list_lock;
99static 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
106static void *recv_thread(void *arg);
107static void *disk_thread(void *arg);
108static 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
130static void
131init_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
170static void
171init_local(struct hast_resource *res)
172{
173
174	if (metadata_read(res, true) < 0)
175		exit(EX_NOINPUT);
176}
177
178static void
179init_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	/* Setup direction. */
187	if (proto_send(res->hr_remoteout, NULL, 0) == -1)
188		pjdlog_errno(LOG_WARNING, "Unable to set connection direction");
189
190	map = NULL;
191	mapsize = 0;
192	nvout = nv_alloc();
193	nv_add_int64(nvout, (int64_t)res->hr_datasize, "datasize");
194	nv_add_int32(nvout, (int32_t)res->hr_extentsize, "extentsize");
195	resuid = nv_get_uint64(nvin, "resuid");
196	res->hr_primary_localcnt = nv_get_uint64(nvin, "localcnt");
197	res->hr_primary_remotecnt = nv_get_uint64(nvin, "remotecnt");
198	nv_add_uint64(nvout, res->hr_secondary_localcnt, "localcnt");
199	nv_add_uint64(nvout, res->hr_secondary_remotecnt, "remotecnt");
200	mapsize = activemap_calc_ondisk_size(res->hr_local_mediasize -
201	    METADATA_SIZE, res->hr_extentsize, res->hr_local_sectorsize);
202	map = malloc(mapsize);
203	if (map == NULL) {
204		pjdlog_exitx(EX_TEMPFAIL,
205		    "Unable to allocate memory (%zu bytes) for activemap.",
206		    mapsize);
207	}
208	/*
209	 * When we work as primary and secondary is missing we will increase
210	 * localcnt in our metadata. When secondary is connected and synced
211	 * we make localcnt be equal to remotecnt, which means nodes are more
212	 * or less in sync.
213	 * Split-brain condition is when both nodes are not able to communicate
214	 * and are both configured as primary nodes. In turn, they can both
215	 * make incompatible changes to the data and we have to detect that.
216	 * Under split-brain condition we will increase our localcnt on first
217	 * write and remote node will increase its localcnt on first write.
218	 * When we connect we can see that primary's localcnt is greater than
219	 * our remotecnt (primary was modified while we weren't watching) and
220	 * our localcnt is greater than primary's remotecnt (we were modified
221	 * while primary wasn't watching).
222	 * There are many possible combinations which are all gathered below.
223	 * Don't pay too much attention to exact numbers, the more important
224	 * is to compare them. We compare secondary's local with primary's
225	 * remote and secondary's remote with primary's local.
226	 * Note that every case where primary's localcnt is smaller than
227	 * secondary's remotecnt and where secondary's localcnt is smaller than
228	 * primary's remotecnt should be impossible in practise. We will perform
229	 * full synchronization then. Those cases are marked with an asterisk.
230	 * Regular synchronization means that only extents marked as dirty are
231	 * synchronized (regular synchronization).
232	 *
233	 * SECONDARY METADATA PRIMARY METADATA
234	 * local=3 remote=3   local=2 remote=2*  ?! Full sync from secondary.
235	 * local=3 remote=3   local=2 remote=3*  ?! Full sync from primary.
236	 * local=3 remote=3   local=2 remote=4*  ?! Full sync from primary.
237	 * local=3 remote=3   local=3 remote=2   Primary is out-of-date,
238	 *                                       regular sync from secondary.
239	 * local=3 remote=3   local=3 remote=3   Regular sync just in case.
240	 * local=3 remote=3   local=3 remote=4*  ?! Full sync from primary.
241	 * local=3 remote=3   local=4 remote=2   Split-brain condition.
242	 * local=3 remote=3   local=4 remote=3   Secondary out-of-date,
243	 *                                       regular sync from primary.
244	 * local=3 remote=3   local=4 remote=4*  ?! Full sync from primary.
245	 */
246	if (res->hr_resuid == 0) {
247		/*
248		 * Provider is used for the first time. If primary node done no
249		 * writes yet as well (we will find "virgin" argument) then
250		 * there is no need to synchronize anything. If primary node
251		 * done any writes already we have to synchronize everything.
252		 */
253		PJDLOG_ASSERT(res->hr_secondary_localcnt == 0);
254		res->hr_resuid = resuid;
255		if (metadata_write(res) < 0)
256			exit(EX_NOINPUT);
257		if (nv_exists(nvin, "virgin")) {
258			free(map);
259			map = NULL;
260			mapsize = 0;
261		} else {
262			memset(map, 0xff, mapsize);
263		}
264		nv_add_int8(nvout, 1, "virgin");
265		nv_add_uint8(nvout, HAST_SYNCSRC_PRIMARY, "syncsrc");
266	} else if (res->hr_resuid != resuid) {
267		char errmsg[256];
268
269		(void)snprintf(errmsg, sizeof(errmsg),
270		    "Resource unique ID mismatch (primary=%ju, secondary=%ju).",
271		    (uintmax_t)resuid, (uintmax_t)res->hr_resuid);
272		pjdlog_error("%s", errmsg);
273		nv_add_string(nvout, errmsg, "errmsg");
274		if (hast_proto_send(res, res->hr_remotein, nvout, NULL, 0) < 0) {
275			pjdlog_exit(EX_TEMPFAIL, "Unable to send response to %s",
276			    res->hr_remoteaddr);
277		}
278		nv_free(nvout);
279		exit(EX_CONFIG);
280	} else if (
281	    /* Is primary is out-of-date? */
282	    (res->hr_secondary_localcnt > res->hr_primary_remotecnt &&
283	     res->hr_secondary_remotecnt == res->hr_primary_localcnt) ||
284	    /* Nodes are more or less in sync? */
285	    (res->hr_secondary_localcnt == res->hr_primary_remotecnt &&
286	     res->hr_secondary_remotecnt == res->hr_primary_localcnt) ||
287	    /* Is secondary is out-of-date? */
288	    (res->hr_secondary_localcnt == res->hr_primary_remotecnt &&
289	     res->hr_secondary_remotecnt < res->hr_primary_localcnt)) {
290		/*
291		 * Nodes are more or less in sync or one of the nodes is
292		 * out-of-date.
293		 * It doesn't matter at this point which one, we just have to
294		 * send out local bitmap to the remote node.
295		 */
296		if (pread(res->hr_localfd, map, mapsize, METADATA_SIZE) !=
297		    (ssize_t)mapsize) {
298			pjdlog_exit(LOG_ERR, "Unable to read activemap");
299		}
300		if (res->hr_secondary_localcnt > res->hr_primary_remotecnt &&
301		     res->hr_secondary_remotecnt == res->hr_primary_localcnt) {
302			/* Primary is out-of-date, sync from secondary. */
303			nv_add_uint8(nvout, HAST_SYNCSRC_SECONDARY, "syncsrc");
304		} else {
305			/*
306			 * Secondary is out-of-date or counts match.
307			 * Sync from primary.
308			 */
309			nv_add_uint8(nvout, HAST_SYNCSRC_PRIMARY, "syncsrc");
310		}
311	} else if (res->hr_secondary_localcnt > res->hr_primary_remotecnt &&
312	     res->hr_primary_localcnt > res->hr_secondary_remotecnt) {
313		/*
314		 * Not good, we have split-brain condition.
315		 */
316		pjdlog_error("Split-brain detected, exiting.");
317		nv_add_string(nvout, "Split-brain condition!", "errmsg");
318		free(map);
319		map = NULL;
320		mapsize = 0;
321	} else /* if (res->hr_secondary_localcnt < res->hr_primary_remotecnt ||
322	    res->hr_primary_localcnt < res->hr_secondary_remotecnt) */ {
323		/*
324		 * This should never happen in practise, but we will perform
325		 * full synchronization.
326		 */
327		PJDLOG_ASSERT(res->hr_secondary_localcnt < res->hr_primary_remotecnt ||
328		    res->hr_primary_localcnt < res->hr_secondary_remotecnt);
329		mapsize = activemap_calc_ondisk_size(res->hr_local_mediasize -
330		    METADATA_SIZE, res->hr_extentsize,
331		    res->hr_local_sectorsize);
332		memset(map, 0xff, mapsize);
333		if (res->hr_secondary_localcnt > res->hr_primary_remotecnt) {
334			/* In this one of five cases sync from secondary. */
335			nv_add_uint8(nvout, HAST_SYNCSRC_SECONDARY, "syncsrc");
336		} else {
337			/* For the rest four cases sync from primary. */
338			nv_add_uint8(nvout, HAST_SYNCSRC_PRIMARY, "syncsrc");
339		}
340		pjdlog_warning("This should never happen, asking for full synchronization (primary(local=%ju, remote=%ju), secondary(local=%ju, remote=%ju)).",
341		    (uintmax_t)res->hr_primary_localcnt,
342		    (uintmax_t)res->hr_primary_remotecnt,
343		    (uintmax_t)res->hr_secondary_localcnt,
344		    (uintmax_t)res->hr_secondary_remotecnt);
345	}
346	nv_add_uint32(nvout, (uint32_t)mapsize, "mapsize");
347	if (hast_proto_send(res, res->hr_remotein, nvout, map, mapsize) < 0) {
348		pjdlog_exit(EX_TEMPFAIL, "Unable to send activemap to %s",
349		    res->hr_remoteaddr);
350	}
351	if (map != NULL)
352		free(map);
353	nv_free(nvout);
354	/* Setup direction. */
355	if (proto_recv(res->hr_remotein, NULL, 0) == -1)
356		pjdlog_errno(LOG_WARNING, "Unable to set connection direction");
357	if (res->hr_secondary_localcnt > res->hr_primary_remotecnt &&
358	     res->hr_primary_localcnt > res->hr_secondary_remotecnt) {
359		/* Exit on split-brain. */
360		event_send(res, EVENT_SPLITBRAIN);
361		exit(EX_CONFIG);
362	}
363}
364
365void
366hastd_secondary(struct hast_resource *res, struct nv *nvin)
367{
368	sigset_t mask;
369	pthread_t td;
370	pid_t pid;
371	int error, mode, debuglevel;
372
373	/*
374	 * Create communication channel between parent and child.
375	 */
376	if (proto_client(NULL, "socketpair://", &res->hr_ctrl) < 0) {
377		KEEP_ERRNO((void)pidfile_remove(pfh));
378		pjdlog_exit(EX_OSERR,
379		    "Unable to create control sockets between parent and child");
380	}
381	/*
382	 * Create communication channel between child and parent.
383	 */
384	if (proto_client(NULL, "socketpair://", &res->hr_event) < 0) {
385		KEEP_ERRNO((void)pidfile_remove(pfh));
386		pjdlog_exit(EX_OSERR,
387		    "Unable to create event sockets between child and parent");
388	}
389
390	pid = fork();
391	if (pid < 0) {
392		KEEP_ERRNO((void)pidfile_remove(pfh));
393		pjdlog_exit(EX_OSERR, "Unable to fork");
394	}
395
396	if (pid > 0) {
397		/* This is parent. */
398		proto_close(res->hr_remotein);
399		res->hr_remotein = NULL;
400		proto_close(res->hr_remoteout);
401		res->hr_remoteout = NULL;
402		/* Declare that we are receiver. */
403		proto_recv(res->hr_event, NULL, 0);
404		/* Declare that we are sender. */
405		proto_send(res->hr_ctrl, NULL, 0);
406		res->hr_workerpid = pid;
407		return;
408	}
409
410	gres = res;
411	mode = pjdlog_mode_get();
412	debuglevel = pjdlog_debug_get();
413
414	/* Declare that we are sender. */
415	proto_send(res->hr_event, NULL, 0);
416	/* Declare that we are receiver. */
417	proto_recv(res->hr_ctrl, NULL, 0);
418	descriptors_cleanup(res);
419
420	descriptors_assert(res, mode);
421
422	pjdlog_init(mode);
423	pjdlog_debug_set(debuglevel);
424	pjdlog_prefix_set("[%s] (%s) ", res->hr_name, role2str(res->hr_role));
425	setproctitle("%s (%s)", res->hr_name, role2str(res->hr_role));
426
427	PJDLOG_VERIFY(sigemptyset(&mask) == 0);
428	PJDLOG_VERIFY(sigprocmask(SIG_SETMASK, &mask, NULL) == 0);
429
430	/* Error in setting timeout is not critical, but why should it fail? */
431	if (proto_timeout(res->hr_remotein, 2 * HAST_KEEPALIVE) < 0)
432		pjdlog_errno(LOG_WARNING, "Unable to set connection timeout");
433	if (proto_timeout(res->hr_remoteout, res->hr_timeout) < 0)
434		pjdlog_errno(LOG_WARNING, "Unable to set connection timeout");
435
436	init_local(res);
437	init_environment();
438
439	if (drop_privs(res) != 0)
440		exit(EX_CONFIG);
441	pjdlog_info("Privileges successfully dropped.");
442
443	/*
444	 * Create the control thread before sending any event to the parent,
445	 * as we can deadlock when parent sends control request to worker,
446	 * but worker has no control thread started yet, so parent waits.
447	 * In the meantime worker sends an event to the parent, but parent
448	 * is unable to handle the event, because it waits for control
449	 * request response.
450	 */
451	error = pthread_create(&td, NULL, ctrl_thread, res);
452	PJDLOG_ASSERT(error == 0);
453
454	init_remote(res, nvin);
455	event_send(res, EVENT_CONNECT);
456
457	error = pthread_create(&td, NULL, recv_thread, res);
458	PJDLOG_ASSERT(error == 0);
459	error = pthread_create(&td, NULL, disk_thread, res);
460	PJDLOG_ASSERT(error == 0);
461	(void)send_thread(res);
462}
463
464static void
465reqlog(int loglevel, int debuglevel, int error, struct hio *hio, const char *fmt, ...)
466{
467	char msg[1024];
468	va_list ap;
469	int len;
470
471	va_start(ap, fmt);
472	len = vsnprintf(msg, sizeof(msg), fmt, ap);
473	va_end(ap);
474	if ((size_t)len < sizeof(msg)) {
475		switch (hio->hio_cmd) {
476		case HIO_READ:
477			(void)snprintf(msg + len, sizeof(msg) - len,
478			    "READ(%ju, %ju).", (uintmax_t)hio->hio_offset,
479			    (uintmax_t)hio->hio_length);
480			break;
481		case HIO_DELETE:
482			(void)snprintf(msg + len, sizeof(msg) - len,
483			    "DELETE(%ju, %ju).", (uintmax_t)hio->hio_offset,
484			    (uintmax_t)hio->hio_length);
485			break;
486		case HIO_FLUSH:
487			(void)snprintf(msg + len, sizeof(msg) - len, "FLUSH.");
488			break;
489		case HIO_WRITE:
490			(void)snprintf(msg + len, sizeof(msg) - len,
491			    "WRITE(%ju, %ju).", (uintmax_t)hio->hio_offset,
492			    (uintmax_t)hio->hio_length);
493			break;
494		case HIO_KEEPALIVE:
495			(void)snprintf(msg + len, sizeof(msg) - len, "KEEPALIVE.");
496			break;
497		default:
498			(void)snprintf(msg + len, sizeof(msg) - len,
499			    "UNKNOWN(%u).", (unsigned int)hio->hio_cmd);
500			break;
501		}
502	}
503	pjdlog_common(loglevel, debuglevel, error, "%s", msg);
504}
505
506static int
507requnpack(struct hast_resource *res, struct hio *hio)
508{
509
510	hio->hio_cmd = nv_get_uint8(hio->hio_nv, "cmd");
511	if (hio->hio_cmd == 0) {
512		pjdlog_error("Header contains no 'cmd' field.");
513		hio->hio_error = EINVAL;
514		goto end;
515	}
516	switch (hio->hio_cmd) {
517	case HIO_FLUSH:
518	case HIO_KEEPALIVE:
519		break;
520	case HIO_READ:
521	case HIO_WRITE:
522	case HIO_DELETE:
523		hio->hio_offset = nv_get_uint64(hio->hio_nv, "offset");
524		if (nv_error(hio->hio_nv) != 0) {
525			pjdlog_error("Header is missing 'offset' field.");
526			hio->hio_error = EINVAL;
527			goto end;
528		}
529		hio->hio_length = nv_get_uint64(hio->hio_nv, "length");
530		if (nv_error(hio->hio_nv) != 0) {
531			pjdlog_error("Header is missing 'length' field.");
532			hio->hio_error = EINVAL;
533			goto end;
534		}
535		if (hio->hio_length == 0) {
536			pjdlog_error("Data length is zero.");
537			hio->hio_error = EINVAL;
538			goto end;
539		}
540		if (hio->hio_length > MAXPHYS) {
541			pjdlog_error("Data length is too large (%ju > %ju).",
542			    (uintmax_t)hio->hio_length, (uintmax_t)MAXPHYS);
543			hio->hio_error = EINVAL;
544			goto end;
545		}
546		if ((hio->hio_offset % res->hr_local_sectorsize) != 0) {
547			pjdlog_error("Offset %ju is not multiple of sector size.",
548			    (uintmax_t)hio->hio_offset);
549			hio->hio_error = EINVAL;
550			goto end;
551		}
552		if ((hio->hio_length % res->hr_local_sectorsize) != 0) {
553			pjdlog_error("Length %ju is not multiple of sector size.",
554			    (uintmax_t)hio->hio_length);
555			hio->hio_error = EINVAL;
556			goto end;
557		}
558		if (hio->hio_offset + hio->hio_length >
559		    (uint64_t)res->hr_datasize) {
560			pjdlog_error("Data offset is too large (%ju > %ju).",
561			    (uintmax_t)(hio->hio_offset + hio->hio_length),
562			    (uintmax_t)res->hr_datasize);
563			hio->hio_error = EINVAL;
564			goto end;
565		}
566		break;
567	default:
568		pjdlog_error("Header contains invalid 'cmd' (%hhu).",
569		    hio->hio_cmd);
570		hio->hio_error = EINVAL;
571		goto end;
572	}
573	hio->hio_error = 0;
574end:
575	return (hio->hio_error);
576}
577
578static __dead2 void
579secondary_exit(int exitcode, const char *fmt, ...)
580{
581	va_list ap;
582
583	PJDLOG_ASSERT(exitcode != EX_OK);
584	va_start(ap, fmt);
585	pjdlogv_errno(LOG_ERR, fmt, ap);
586	va_end(ap);
587	event_send(gres, EVENT_DISCONNECT);
588	exit(exitcode);
589}
590
591/*
592 * Thread receives requests from the primary node.
593 */
594static void *
595recv_thread(void *arg)
596{
597	struct hast_resource *res = arg;
598	struct hio *hio;
599
600	for (;;) {
601		pjdlog_debug(2, "recv: Taking free request.");
602		QUEUE_TAKE(free, hio);
603		pjdlog_debug(2, "recv: (%p) Got request.", hio);
604		if (hast_proto_recv_hdr(res->hr_remotein, &hio->hio_nv) < 0) {
605			secondary_exit(EX_TEMPFAIL,
606			    "Unable to receive request header");
607		}
608		if (requnpack(res, hio) != 0) {
609			pjdlog_debug(2,
610			    "recv: (%p) Moving request to the send queue.",
611			    hio);
612			QUEUE_INSERT(send, hio);
613			continue;
614		}
615		reqlog(LOG_DEBUG, 2, -1, hio,
616		    "recv: (%p) Got request header: ", hio);
617		if (hio->hio_cmd == HIO_KEEPALIVE) {
618			pjdlog_debug(2,
619			    "recv: (%p) Moving request to the free queue.",
620			    hio);
621			nv_free(hio->hio_nv);
622			QUEUE_INSERT(free, hio);
623			continue;
624		} else if (hio->hio_cmd == HIO_WRITE) {
625			if (hast_proto_recv_data(res, res->hr_remotein,
626			    hio->hio_nv, hio->hio_data, MAXPHYS) < 0) {
627				secondary_exit(EX_TEMPFAIL,
628				    "Unable to receive request data");
629			}
630		}
631		pjdlog_debug(2, "recv: (%p) Moving request to the disk queue.",
632		    hio);
633		QUEUE_INSERT(disk, hio);
634	}
635	/* NOTREACHED */
636	return (NULL);
637}
638
639/*
640 * Thread reads from or writes to local component and also handles DELETE and
641 * FLUSH requests.
642 */
643static void *
644disk_thread(void *arg)
645{
646	struct hast_resource *res = arg;
647	struct hio *hio;
648	ssize_t ret;
649	bool clear_activemap;
650
651	clear_activemap = true;
652
653	for (;;) {
654		pjdlog_debug(2, "disk: Taking request.");
655		QUEUE_TAKE(disk, hio);
656		while (clear_activemap) {
657			unsigned char *map;
658			size_t mapsize;
659
660			/*
661			 * When first request is received, it means that primary
662			 * already received our activemap, merged it and stored
663			 * locally. We can now safely clear our activemap.
664			 */
665			mapsize =
666			    activemap_calc_ondisk_size(res->hr_local_mediasize -
667			    METADATA_SIZE, res->hr_extentsize,
668			    res->hr_local_sectorsize);
669			map = calloc(1, mapsize);
670			if (map == NULL) {
671				pjdlog_warning("Unable to allocate memory to clear local activemap.");
672				break;
673			}
674			if (pwrite(res->hr_localfd, map, mapsize,
675			    METADATA_SIZE) != (ssize_t)mapsize) {
676				pjdlog_errno(LOG_WARNING,
677				    "Unable to store cleared activemap");
678				free(map);
679				break;
680			}
681			free(map);
682			clear_activemap = false;
683			pjdlog_debug(1, "Local activemap cleared.");
684		}
685		reqlog(LOG_DEBUG, 2, -1, hio, "disk: (%p) Got request: ", hio);
686		/* Handle the actual request. */
687		switch (hio->hio_cmd) {
688		case HIO_READ:
689			ret = pread(res->hr_localfd, hio->hio_data,
690			    hio->hio_length,
691			    hio->hio_offset + res->hr_localoff);
692			if (ret < 0)
693				hio->hio_error = errno;
694			else if (ret != (int64_t)hio->hio_length)
695				hio->hio_error = EIO;
696			else
697				hio->hio_error = 0;
698			break;
699		case HIO_WRITE:
700			ret = pwrite(res->hr_localfd, hio->hio_data,
701			    hio->hio_length,
702			    hio->hio_offset + res->hr_localoff);
703			if (ret < 0)
704				hio->hio_error = errno;
705			else if (ret != (int64_t)hio->hio_length)
706				hio->hio_error = EIO;
707			else
708				hio->hio_error = 0;
709			break;
710		case HIO_DELETE:
711			ret = g_delete(res->hr_localfd,
712			    hio->hio_offset + res->hr_localoff,
713			    hio->hio_length);
714			if (ret < 0)
715				hio->hio_error = errno;
716			else
717				hio->hio_error = 0;
718			break;
719		case HIO_FLUSH:
720			ret = g_flush(res->hr_localfd);
721			if (ret < 0)
722				hio->hio_error = errno;
723			else
724				hio->hio_error = 0;
725			break;
726		}
727		if (hio->hio_error != 0) {
728			reqlog(LOG_ERR, 0, hio->hio_error, hio,
729			    "Request failed: ");
730		}
731		pjdlog_debug(2, "disk: (%p) Moving request to the send queue.",
732		    hio);
733		QUEUE_INSERT(send, hio);
734	}
735	/* NOTREACHED */
736	return (NULL);
737}
738
739/*
740 * Thread sends requests back to primary node.
741 */
742static void *
743send_thread(void *arg)
744{
745	struct hast_resource *res = arg;
746	struct nv *nvout;
747	struct hio *hio;
748	void *data;
749	size_t length;
750
751	for (;;) {
752		pjdlog_debug(2, "send: Taking request.");
753		QUEUE_TAKE(send, hio);
754		reqlog(LOG_DEBUG, 2, -1, hio, "send: (%p) Got request: ", hio);
755		nvout = nv_alloc();
756		/* Copy sequence number. */
757		nv_add_uint64(nvout, nv_get_uint64(hio->hio_nv, "seq"), "seq");
758		switch (hio->hio_cmd) {
759		case HIO_READ:
760			if (hio->hio_error == 0) {
761				data = hio->hio_data;
762				length = hio->hio_length;
763				break;
764			}
765			/*
766			 * We send no data in case of an error.
767			 */
768			/* FALLTHROUGH */
769		case HIO_DELETE:
770		case HIO_FLUSH:
771		case HIO_WRITE:
772			data = NULL;
773			length = 0;
774			break;
775		default:
776			abort();
777			break;
778		}
779		if (hio->hio_error != 0)
780			nv_add_int16(nvout, hio->hio_error, "error");
781		if (hast_proto_send(res, res->hr_remoteout, nvout, data,
782		    length) < 0) {
783			secondary_exit(EX_TEMPFAIL, "Unable to send reply.");
784		}
785		nv_free(nvout);
786		pjdlog_debug(2, "send: (%p) Moving request to the free queue.",
787		    hio);
788		nv_free(hio->hio_nv);
789		hio->hio_error = 0;
790		QUEUE_INSERT(free, hio);
791	}
792	/* NOTREACHED */
793	return (NULL);
794}
795