secondary.c revision 219830
1127128Snectar/*-
2127128Snectar * Copyright (c) 2009-2010 The FreeBSD Foundation
3127128Snectar * Copyright (c) 2010 Pawel Jakub Dawidek <pjd@FreeBSD.org>
4127128Snectar * All rights reserved.
5127128Snectar *
6127128Snectar * This software was developed by Pawel Jakub Dawidek under sponsorship from
7127128Snectar * the FreeBSD Foundation.
8127128Snectar *
9127128Snectar * Redistribution and use in source and binary forms, with or without
10127128Snectar * modification, are permitted provided that the following conditions
11127128Snectar * are met:
12127128Snectar * 1. Redistributions of source code must retain the above copyright
13127128Snectar *    notice, this list of conditions and the following disclaimer.
14127128Snectar * 2. Redistributions in binary form must reproduce the above copyright
15127128Snectar *    notice, this list of conditions and the following disclaimer in the
16127128Snectar *    documentation and/or other materials provided with the distribution.
17127128Snectar *
18296341Sdelphij * THIS SOFTWARE IS PROVIDED BY THE AUTHORS AND CONTRIBUTORS ``AS IS'' AND
19296341Sdelphij * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20296341Sdelphij * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21296341Sdelphij * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE
22127128Snectar * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23127128Snectar * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24127128Snectar * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25127128Snectar * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26127128Snectar * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
27127128Snectar * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28296341Sdelphij * SUCH DAMAGE.
29296341Sdelphij */
30296341Sdelphij
31296341Sdelphij#include <sys/cdefs.h>
32296341Sdelphij__FBSDID("$FreeBSD: head/sbin/hastd/secondary.c 219830 2011-03-21 14:50:12Z pjd $");
33296341Sdelphij
34296341Sdelphij#include <sys/param.h>
35296341Sdelphij#include <sys/time.h>
36127128Snectar#include <sys/bio.h>
37127128Snectar#include <sys/disk.h>
38127128Snectar#include <sys/stat.h>
39127128Snectar
40127128Snectar#include <err.h>
41127128Snectar#include <errno.h>
42127128Snectar#include <fcntl.h>
43127128Snectar#include <libgeom.h>
44127128Snectar#include <pthread.h>
45127128Snectar#include <signal.h>
46127128Snectar#include <stdint.h>
47127128Snectar#include <stdio.h>
48127128Snectar#include <string.h>
49127128Snectar#include <sysexits.h>
50127128Snectar#include <unistd.h>
51127128Snectar
52127128Snectar#include <activemap.h>
53127128Snectar#include <nv.h>
54127128Snectar#include <pjdlog.h>
55127128Snectar
56127128Snectar#include "control.h"
57127128Snectar#include "event.h"
58127128Snectar#include "hast.h"
59127128Snectar#include "hast_proto.h"
60127128Snectar#include "hastd.h"
61127128Snectar#include "hooks.h"
62127128Snectar#include "metadata.h"
63127128Snectar#include "proto.h"
64127128Snectar#include "subr.h"
65127128Snectar#include "synch.h"
66127128Snectar
67127128Snectarstruct hio {
68127128Snectar	uint64_t 	 hio_seq;
69267258Sjkim	int	 	 hio_error;
70127128Snectar	struct nv	*hio_nv;
71127128Snectar	void		*hio_data;
72127128Snectar	uint8_t		 hio_cmd;
73127128Snectar	uint64_t	 hio_offset;
74127128Snectar	uint64_t	 hio_length;
75127128Snectar	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	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 (res->hr_resuid != resuid) {
263		char errmsg[256];
264
265		(void)snprintf(errmsg, sizeof(errmsg),
266		    "Resource unique ID mismatch (primary=%ju, secondary=%ju).",
267		    (uintmax_t)resuid, (uintmax_t)res->hr_resuid);
268		pjdlog_error("%s", errmsg);
269		nv_add_string(nvout, errmsg, "errmsg");
270		if (hast_proto_send(res, res->hr_remotein, nvout, NULL, 0) < 0) {
271			pjdlog_exit(EX_TEMPFAIL, "Unable to send response to %s",
272			    res->hr_remoteaddr);
273		}
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	    /* Node 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	if (hast_proto_send(res, res->hr_remotein, nvout, map, mapsize) < 0) {
342		pjdlog_exit(EX_TEMPFAIL, "Unable to send activemap to %s",
343		    res->hr_remoteaddr);
344	}
345	if (map != NULL)
346		free(map);
347	nv_free(nvout);
348	if (res->hr_secondary_localcnt > res->hr_primary_remotecnt &&
349	     res->hr_primary_localcnt > res->hr_secondary_remotecnt) {
350		/* Exit on split-brain. */
351		event_send(res, EVENT_SPLITBRAIN);
352		exit(EX_CONFIG);
353	}
354}
355
356void
357hastd_secondary(struct hast_resource *res, struct nv *nvin)
358{
359	sigset_t mask;
360	pthread_t td;
361	pid_t pid;
362	int error, mode, debuglevel;
363
364	/*
365	 * Create communication channel between parent and child.
366	 */
367	if (proto_client(NULL, "socketpair://", &res->hr_ctrl) < 0) {
368		KEEP_ERRNO((void)pidfile_remove(pfh));
369		pjdlog_exit(EX_OSERR,
370		    "Unable to create control sockets between parent and child");
371	}
372	/*
373	 * Create communication channel between child and parent.
374	 */
375	if (proto_client(NULL, "socketpair://", &res->hr_event) < 0) {
376		KEEP_ERRNO((void)pidfile_remove(pfh));
377		pjdlog_exit(EX_OSERR,
378		    "Unable to create event sockets between child and parent");
379	}
380	/*
381	 * Create communication channel for sending connection requests from
382	 * parent to child.
383	 */
384	if (proto_client(NULL, "socketpair://", &res->hr_conn) < 0) {
385		/* TODO: There's no need for this to be fatal error. */
386		KEEP_ERRNO((void)pidfile_remove(pfh));
387		pjdlog_exit(EX_OSERR,
388		    "Unable to create connection sockets between parent and child");
389	}
390
391	pid = fork();
392	if (pid < 0) {
393		KEEP_ERRNO((void)pidfile_remove(pfh));
394		pjdlog_exit(EX_OSERR, "Unable to fork");
395	}
396
397	if (pid > 0) {
398		/* This is parent. */
399		proto_close(res->hr_remotein);
400		res->hr_remotein = NULL;
401		proto_close(res->hr_remoteout);
402		res->hr_remoteout = NULL;
403		/* Declare that we are receiver. */
404		proto_recv(res->hr_event, NULL, 0);
405		/* Declare that we are sender. */
406		proto_send(res->hr_ctrl, NULL, 0);
407		proto_send(res->hr_conn, NULL, 0);
408		res->hr_workerpid = pid;
409		return;
410	}
411
412	gres = res;
413	mode = pjdlog_mode_get();
414	debuglevel = pjdlog_debug_get();
415
416	/* Declare that we are sender. */
417	proto_send(res->hr_event, NULL, 0);
418	/* Declare that we are receiver. */
419	proto_recv(res->hr_ctrl, NULL, 0);
420	proto_recv(res->hr_conn, NULL, 0);
421	descriptors_cleanup(res);
422
423	descriptors_assert(res, mode);
424
425	pjdlog_init(mode);
426	pjdlog_debug_set(debuglevel);
427	pjdlog_prefix_set("[%s] (%s) ", res->hr_name, role2str(res->hr_role));
428	setproctitle("%s (secondary)", res->hr_name);
429
430	PJDLOG_VERIFY(sigemptyset(&mask) == 0);
431	PJDLOG_VERIFY(sigprocmask(SIG_SETMASK, &mask, NULL) == 0);
432
433	/* Error in setting timeout is not critical, but why should it fail? */
434	if (proto_timeout(res->hr_remotein, 2 * HAST_KEEPALIVE) < 0)
435		pjdlog_errno(LOG_WARNING, "Unable to set connection timeout");
436	if (proto_timeout(res->hr_remoteout, res->hr_timeout) < 0)
437		pjdlog_errno(LOG_WARNING, "Unable to set connection timeout");
438
439	init_local(res);
440	init_environment();
441
442	if (drop_privs() != 0)
443		exit(EX_CONFIG);
444	pjdlog_info("Privileges successfully dropped.");
445
446	/*
447	 * Create the control thread before sending any event to the parent,
448	 * as we can deadlock when parent sends control request to worker,
449	 * but worker has no control thread started yet, so parent waits.
450	 * In the meantime worker sends an event to the parent, but parent
451	 * is unable to handle the event, because it waits for control
452	 * request response.
453	 */
454	error = pthread_create(&td, NULL, ctrl_thread, res);
455	PJDLOG_ASSERT(error == 0);
456
457	init_remote(res, nvin);
458	event_send(res, EVENT_CONNECT);
459
460	error = pthread_create(&td, NULL, recv_thread, res);
461	PJDLOG_ASSERT(error == 0);
462	error = pthread_create(&td, NULL, disk_thread, res);
463	PJDLOG_ASSERT(error == 0);
464	(void)send_thread(res);
465}
466
467static void
468reqlog(int loglevel, int debuglevel, int error, struct hio *hio, const char *fmt, ...)
469{
470	char msg[1024];
471	va_list ap;
472	int len;
473
474	va_start(ap, fmt);
475	len = vsnprintf(msg, sizeof(msg), fmt, ap);
476	va_end(ap);
477	if ((size_t)len < sizeof(msg)) {
478		switch (hio->hio_cmd) {
479		case HIO_READ:
480			(void)snprintf(msg + len, sizeof(msg) - len,
481			    "READ(%ju, %ju).", (uintmax_t)hio->hio_offset,
482			    (uintmax_t)hio->hio_length);
483			break;
484		case HIO_DELETE:
485			(void)snprintf(msg + len, sizeof(msg) - len,
486			    "DELETE(%ju, %ju).", (uintmax_t)hio->hio_offset,
487			    (uintmax_t)hio->hio_length);
488			break;
489		case HIO_FLUSH:
490			(void)snprintf(msg + len, sizeof(msg) - len, "FLUSH.");
491			break;
492		case HIO_WRITE:
493			(void)snprintf(msg + len, sizeof(msg) - len,
494			    "WRITE(%ju, %ju).", (uintmax_t)hio->hio_offset,
495			    (uintmax_t)hio->hio_length);
496			break;
497		case HIO_KEEPALIVE:
498			(void)snprintf(msg + len, sizeof(msg) - len, "KEEPALIVE.");
499			break;
500		default:
501			(void)snprintf(msg + len, sizeof(msg) - len,
502			    "UNKNOWN(%u).", (unsigned int)hio->hio_cmd);
503			break;
504		}
505	}
506	pjdlog_common(loglevel, debuglevel, error, "%s", msg);
507}
508
509static int
510requnpack(struct hast_resource *res, struct hio *hio)
511{
512
513	hio->hio_cmd = nv_get_uint8(hio->hio_nv, "cmd");
514	if (hio->hio_cmd == 0) {
515		pjdlog_error("Header contains no 'cmd' field.");
516		hio->hio_error = EINVAL;
517		goto end;
518	}
519	switch (hio->hio_cmd) {
520	case HIO_KEEPALIVE:
521		break;
522	case HIO_READ:
523	case HIO_WRITE:
524	case HIO_DELETE:
525		hio->hio_offset = nv_get_uint64(hio->hio_nv, "offset");
526		if (nv_error(hio->hio_nv) != 0) {
527			pjdlog_error("Header is missing 'offset' field.");
528			hio->hio_error = EINVAL;
529			goto end;
530		}
531		hio->hio_length = nv_get_uint64(hio->hio_nv, "length");
532		if (nv_error(hio->hio_nv) != 0) {
533			pjdlog_error("Header is missing 'length' field.");
534			hio->hio_error = EINVAL;
535			goto end;
536		}
537		if (hio->hio_length == 0) {
538			pjdlog_error("Data length is zero.");
539			hio->hio_error = EINVAL;
540			goto end;
541		}
542		if (hio->hio_length > MAXPHYS) {
543			pjdlog_error("Data length is too large (%ju > %ju).",
544			    (uintmax_t)hio->hio_length, (uintmax_t)MAXPHYS);
545			hio->hio_error = EINVAL;
546			goto end;
547		}
548		if ((hio->hio_offset % res->hr_local_sectorsize) != 0) {
549			pjdlog_error("Offset %ju is not multiple of sector size.",
550			    (uintmax_t)hio->hio_offset);
551			hio->hio_error = EINVAL;
552			goto end;
553		}
554		if ((hio->hio_length % res->hr_local_sectorsize) != 0) {
555			pjdlog_error("Length %ju is not multiple of sector size.",
556			    (uintmax_t)hio->hio_length);
557			hio->hio_error = EINVAL;
558			goto end;
559		}
560		if (hio->hio_offset + hio->hio_length >
561		    (uint64_t)res->hr_datasize) {
562			pjdlog_error("Data offset is too large (%ju > %ju).",
563			    (uintmax_t)(hio->hio_offset + hio->hio_length),
564			    (uintmax_t)res->hr_datasize);
565			hio->hio_error = EINVAL;
566			goto end;
567		}
568		break;
569	default:
570		pjdlog_error("Header contains invalid 'cmd' (%hhu).",
571		    hio->hio_cmd);
572		hio->hio_error = EINVAL;
573		goto end;
574	}
575	hio->hio_error = 0;
576end:
577	return (hio->hio_error);
578}
579
580static __dead2 void
581secondary_exit(int exitcode, const char *fmt, ...)
582{
583	va_list ap;
584
585	PJDLOG_ASSERT(exitcode != EX_OK);
586	va_start(ap, fmt);
587	pjdlogv_errno(LOG_ERR, fmt, ap);
588	va_end(ap);
589	event_send(gres, EVENT_DISCONNECT);
590	exit(exitcode);
591}
592
593/*
594 * Thread receives requests from the primary node.
595 */
596static void *
597recv_thread(void *arg)
598{
599	struct hast_resource *res = arg;
600	struct hio *hio;
601
602	for (;;) {
603		pjdlog_debug(2, "recv: Taking free request.");
604		QUEUE_TAKE(free, hio);
605		pjdlog_debug(2, "recv: (%p) Got request.", hio);
606		if (hast_proto_recv_hdr(res->hr_remotein, &hio->hio_nv) < 0) {
607			secondary_exit(EX_TEMPFAIL,
608			    "Unable to receive request header");
609		}
610		if (requnpack(res, hio) != 0) {
611			pjdlog_debug(2,
612			    "recv: (%p) Moving request to the send queue.",
613			    hio);
614			QUEUE_INSERT(send, hio);
615			continue;
616		}
617		reqlog(LOG_DEBUG, 2, -1, hio,
618		    "recv: (%p) Got request header: ", hio);
619		if (hio->hio_cmd == HIO_KEEPALIVE) {
620			pjdlog_debug(2,
621			    "recv: (%p) Moving request to the free queue.",
622			    hio);
623			nv_free(hio->hio_nv);
624			QUEUE_INSERT(free, hio);
625			continue;
626		} else if (hio->hio_cmd == HIO_WRITE) {
627			if (hast_proto_recv_data(res, res->hr_remotein,
628			    hio->hio_nv, hio->hio_data, MAXPHYS) < 0) {
629				secondary_exit(EX_TEMPFAIL,
630				    "Unable to receive request data");
631			}
632		}
633		pjdlog_debug(2, "recv: (%p) Moving request to the disk queue.",
634		    hio);
635		QUEUE_INSERT(disk, hio);
636	}
637	/* NOTREACHED */
638	return (NULL);
639}
640
641/*
642 * Thread reads from or writes to local component and also handles DELETE and
643 * FLUSH requests.
644 */
645static void *
646disk_thread(void *arg)
647{
648	struct hast_resource *res = arg;
649	struct hio *hio;
650	ssize_t ret;
651	bool clear_activemap;
652
653	clear_activemap = true;
654
655	for (;;) {
656		pjdlog_debug(2, "disk: Taking request.");
657		QUEUE_TAKE(disk, hio);
658		while (clear_activemap) {
659			unsigned char *map;
660			size_t mapsize;
661
662			/*
663			 * When first request is received, it means that primary
664			 * already received our activemap, merged it and stored
665			 * locally. We can now safely clear our activemap.
666			 */
667			mapsize =
668			    activemap_calc_ondisk_size(res->hr_local_mediasize -
669			    METADATA_SIZE, res->hr_extentsize,
670			    res->hr_local_sectorsize);
671			map = calloc(1, mapsize);
672			if (map == NULL) {
673				pjdlog_warning("Unable to allocate memory to clear local activemap.");
674				break;
675			}
676			if (pwrite(res->hr_localfd, map, mapsize,
677			    METADATA_SIZE) != (ssize_t)mapsize) {
678				pjdlog_errno(LOG_WARNING,
679				    "Unable to store cleared activemap");
680				free(map);
681				break;
682			}
683			free(map);
684			clear_activemap = false;
685			pjdlog_debug(1, "Local activemap cleared.");
686		}
687		reqlog(LOG_DEBUG, 2, -1, hio, "disk: (%p) Got request: ", hio);
688		/* Handle the actual request. */
689		switch (hio->hio_cmd) {
690		case HIO_READ:
691			ret = pread(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_WRITE:
702			ret = pwrite(res->hr_localfd, hio->hio_data,
703			    hio->hio_length,
704			    hio->hio_offset + res->hr_localoff);
705			if (ret < 0)
706				hio->hio_error = errno;
707			else if (ret != (int64_t)hio->hio_length)
708				hio->hio_error = EIO;
709			else
710				hio->hio_error = 0;
711			break;
712		case HIO_DELETE:
713			ret = g_delete(res->hr_localfd,
714			    hio->hio_offset + res->hr_localoff,
715			    hio->hio_length);
716			if (ret < 0)
717				hio->hio_error = errno;
718			else
719				hio->hio_error = 0;
720			break;
721		case HIO_FLUSH:
722			ret = g_flush(res->hr_localfd);
723			if (ret < 0)
724				hio->hio_error = errno;
725			else
726				hio->hio_error = 0;
727			break;
728		}
729		if (hio->hio_error != 0) {
730			reqlog(LOG_ERR, 0, hio->hio_error, hio,
731			    "Request failed: ");
732		}
733		pjdlog_debug(2, "disk: (%p) Moving request to the send queue.",
734		    hio);
735		QUEUE_INSERT(send, hio);
736	}
737	/* NOTREACHED */
738	return (NULL);
739}
740
741/*
742 * Thread sends requests back to primary node.
743 */
744static void *
745send_thread(void *arg)
746{
747	struct hast_resource *res = arg;
748	struct nv *nvout;
749	struct hio *hio;
750	void *data;
751	size_t length;
752
753	for (;;) {
754		pjdlog_debug(2, "send: Taking request.");
755		QUEUE_TAKE(send, hio);
756		reqlog(LOG_DEBUG, 2, -1, hio, "send: (%p) Got request: ", hio);
757		nvout = nv_alloc();
758		/* Copy sequence number. */
759		nv_add_uint64(nvout, nv_get_uint64(hio->hio_nv, "seq"), "seq");
760		switch (hio->hio_cmd) {
761		case HIO_READ:
762			if (hio->hio_error == 0) {
763				data = hio->hio_data;
764				length = hio->hio_length;
765				break;
766			}
767			/*
768			 * We send no data in case of an error.
769			 */
770			/* FALLTHROUGH */
771		case HIO_DELETE:
772		case HIO_FLUSH:
773		case HIO_WRITE:
774			data = NULL;
775			length = 0;
776			break;
777		default:
778			abort();
779			break;
780		}
781		if (hio->hio_error != 0)
782			nv_add_int16(nvout, hio->hio_error, "error");
783		if (hast_proto_send(res, res->hr_remoteout, nvout, data,
784		    length) < 0) {
785			secondary_exit(EX_TEMPFAIL, "Unable to send reply.");
786		}
787		nv_free(nvout);
788		pjdlog_debug(2, "send: (%p) Moving request to the free queue.",
789		    hio);
790		nv_free(hio->hio_nv);
791		hio->hio_error = 0;
792		QUEUE_INSERT(free, hio);
793	}
794	/* NOTREACHED */
795	return (NULL);
796}
797