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