secondary.c revision 219864
1228753Smm/*-
2228753Smm * Copyright (c) 2009-2010 The FreeBSD Foundation
3228753Smm * Copyright (c) 2010 Pawel Jakub Dawidek <pjd@FreeBSD.org>
4228753Smm * All rights reserved.
5228753Smm *
6228753Smm * This software was developed by Pawel Jakub Dawidek under sponsorship from
7228753Smm * the FreeBSD Foundation.
8228753Smm *
9228753Smm * Redistribution and use in source and binary forms, with or without
10228753Smm * modification, are permitted provided that the following conditions
11228753Smm * are met:
12228753Smm * 1. Redistributions of source code must retain the above copyright
13228753Smm *    notice, this list of conditions and the following disclaimer.
14228753Smm * 2. Redistributions in binary form must reproduce the above copyright
15228753Smm *    notice, this list of conditions and the following disclaimer in the
16228753Smm *    documentation and/or other materials provided with the distribution.
17228753Smm *
18228753Smm * THIS SOFTWARE IS PROVIDED BY THE AUTHORS AND CONTRIBUTORS ``AS IS'' AND
19228753Smm * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20228753Smm * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21228753Smm * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE
22228753Smm * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23228753Smm * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24228753Smm * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25228753Smm * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26228753Smm * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
27229592Smm * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28228753Smm * SUCH DAMAGE.
29228753Smm */
30228753Smm
31228753Smm#include <sys/cdefs.h>
32228753Smm__FBSDID("$FreeBSD: head/sbin/hastd/secondary.c 219864 2011-03-22 10:39:34Z pjd $");
33228753Smm
34228753Smm#include <sys/param.h>
35228753Smm#include <sys/time.h>
36228753Smm#include <sys/bio.h>
37228753Smm#include <sys/disk.h>
38228753Smm#include <sys/stat.h>
39228753Smm
40228753Smm#include <err.h>
41228753Smm#include <errno.h>
42228753Smm#include <fcntl.h>
43228753Smm#include <libgeom.h>
44228753Smm#include <pthread.h>
45228753Smm#include <signal.h>
46228753Smm#include <stdint.h>
47228753Smm#include <stdio.h>
48228753Smm#include <string.h>
49228753Smm#include <sysexits.h>
50228753Smm#include <unistd.h>
51228753Smm
52228753Smm#include <activemap.h>
53228753Smm#include <nv.h>
54228753Smm#include <pjdlog.h>
55228753Smm
56228753Smm#include "control.h"
57228753Smm#include "event.h"
58228753Smm#include "hast.h"
59228753Smm#include "hast_proto.h"
60228753Smm#include "hastd.h"
61228753Smm#include "hooks.h"
62228753Smm#include "metadata.h"
63228753Smm#include "proto.h"
64228753Smm#include "subr.h"
65228753Smm#include "synch.h"
66228753Smm
67228753Smmstruct hio {
68228753Smm	uint64_t	 hio_seq;
69228753Smm	int		 hio_error;
70228753Smm	struct nv	*hio_nv;
71228753Smm	void		*hio_data;
72228753Smm	uint8_t		 hio_cmd;
73228753Smm	uint64_t	 hio_offset;
74228753Smm	uint64_t	 hio_length;
75228753Smm	TAILQ_ENTRY(hio) hio_next;
76228753Smm};
77228753Smm
78228753Smmstatic struct hast_resource *gres;
79228753Smm
80228753Smm/*
81228753Smm * Free list holds unused structures. When free list is empty, we have to wait
82228753Smm * until some in-progress requests are freed.
83228753Smm */
84228753Smmstatic TAILQ_HEAD(, hio) hio_free_list;
85228753Smmstatic pthread_mutex_t hio_free_list_lock;
86228753Smmstatic pthread_cond_t hio_free_list_cond;
87228753Smm/*
88228753Smm * Disk thread (the one that do I/O requests) takes requests from this list.
89228753Smm */
90228753Smmstatic TAILQ_HEAD(, hio) hio_disk_list;
91228753Smmstatic pthread_mutex_t hio_disk_list_lock;
92228753Smmstatic pthread_cond_t hio_disk_list_cond;
93228753Smm/*
94228753Smm * There is one recv list for every component, although local components don't
95228753Smm * use recv lists as local requests are done synchronously.
96228753Smm */
97228753Smmstatic TAILQ_HEAD(, hio) hio_send_list;
98228753Smmstatic pthread_mutex_t hio_send_list_lock;
99228753Smmstatic pthread_cond_t hio_send_list_cond;
100228753Smm
101228753Smm/*
102228753Smm * Maximum number of outstanding I/O requests.
103228753Smm */
104228753Smm#define	HAST_HIO_MAX	256
105228753Smm
106229592Smmstatic void *recv_thread(void *arg);
107228753Smmstatic void *disk_thread(void *arg);
108228753Smmstatic void *send_thread(void *arg);
109228753Smm
110228753Smm#define	QUEUE_INSERT(name, hio)	do {					\
111228753Smm	bool _wakeup;							\
112228753Smm									\
113228753Smm	mtx_lock(&hio_##name##_list_lock);				\
114228753Smm	_wakeup = TAILQ_EMPTY(&hio_##name##_list);			\
115228753Smm	TAILQ_INSERT_TAIL(&hio_##name##_list, (hio), hio_next);		\
116229592Smm	mtx_unlock(&hio_##name##_list_lock);				\
117229592Smm	if (_wakeup)							\
118229592Smm		cv_signal(&hio_##name##_list_cond);			\
119229592Smm} while (0)
120228753Smm#define	QUEUE_TAKE(name, hio)	do {					\
121228753Smm	mtx_lock(&hio_##name##_list_lock);				\
122229592Smm	while (((hio) = TAILQ_FIRST(&hio_##name##_list)) == NULL) {	\
123228753Smm		cv_wait(&hio_##name##_list_cond,			\
124228753Smm		    &hio_##name##_list_lock);				\
125228753Smm	}								\
126228753Smm	TAILQ_REMOVE(&hio_##name##_list, (hio), hio_next);		\
127228753Smm	mtx_unlock(&hio_##name##_list_lock);				\
128228753Smm} while (0)
129228753Smm
130228753Smmstatic void
131228753Smminit_environment(void)
132228753Smm{
133228753Smm	struct hio *hio;
134228753Smm	unsigned int ii;
135228753Smm
136228753Smm	/*
137228753Smm	 * Initialize lists, their locks and theirs condition variables.
138228753Smm	 */
139228753Smm	TAILQ_INIT(&hio_free_list);
140228753Smm	mtx_init(&hio_free_list_lock);
141228753Smm	cv_init(&hio_free_list_cond);
142228753Smm	TAILQ_INIT(&hio_disk_list);
143228753Smm	mtx_init(&hio_disk_list_lock);
144228753Smm	cv_init(&hio_disk_list_cond);
145228753Smm	TAILQ_INIT(&hio_send_list);
146228753Smm	mtx_init(&hio_send_list_lock);
147228753Smm	cv_init(&hio_send_list_cond);
148228753Smm
149228753Smm	/*
150228753Smm	 * Allocate requests pool and initialize requests.
151228753Smm	 */
152228753Smm	for (ii = 0; ii < HAST_HIO_MAX; ii++) {
153228753Smm		hio = malloc(sizeof(*hio));
154228753Smm		if (hio == NULL) {
155228753Smm			pjdlog_exitx(EX_TEMPFAIL,
156228753Smm			    "Unable to allocate memory (%zu bytes) for hio request.",
157228753Smm			    sizeof(*hio));
158228753Smm		}
159228753Smm		hio->hio_error = 0;
160228753Smm		hio->hio_data = malloc(MAXPHYS);
161228753Smm		if (hio->hio_data == NULL) {
162228753Smm			pjdlog_exitx(EX_TEMPFAIL,
163228753Smm			    "Unable to allocate memory (%zu bytes) for gctl_data.",
164228753Smm			    (size_t)MAXPHYS);
165228753Smm		}
166228753Smm		TAILQ_INSERT_HEAD(&hio_free_list, hio, hio_next);
167228753Smm	}
168228753Smm}
169228753Smm
170228753Smmstatic void
171228753Smminit_local(struct hast_resource *res)
172228753Smm{
173228753Smm
174228753Smm	if (metadata_read(res, true) < 0)
175228753Smm		exit(EX_NOINPUT);
176228753Smm}
177228753Smm
178228753Smmstatic void
179228753Smminit_remote(struct hast_resource *res, struct nv *nvin)
180228753Smm{
181228753Smm	uint64_t resuid;
182228753Smm	struct nv *nvout;
183228753Smm	unsigned char *map;
184228753Smm	size_t mapsize;
185228753Smm
186228753Smm	map = NULL;
187228753Smm	mapsize = 0;
188228753Smm	nvout = nv_alloc();
189228753Smm	nv_add_int64(nvout, (int64_t)res->hr_datasize, "datasize");
190228753Smm	nv_add_int32(nvout, (int32_t)res->hr_extentsize, "extentsize");
191228753Smm	resuid = nv_get_uint64(nvin, "resuid");
192228753Smm	res->hr_primary_localcnt = nv_get_uint64(nvin, "localcnt");
193228753Smm	res->hr_primary_remotecnt = nv_get_uint64(nvin, "remotecnt");
194228753Smm	nv_add_uint64(nvout, res->hr_secondary_localcnt, "localcnt");
195228753Smm	nv_add_uint64(nvout, res->hr_secondary_remotecnt, "remotecnt");
196228753Smm	mapsize = activemap_calc_ondisk_size(res->hr_local_mediasize -
197228753Smm	    METADATA_SIZE, res->hr_extentsize, res->hr_local_sectorsize);
198228753Smm	map = malloc(mapsize);
199228753Smm	if (map == NULL) {
200228753Smm		pjdlog_exitx(EX_TEMPFAIL,
201228753Smm		    "Unable to allocate memory (%zu bytes) for activemap.",
202228753Smm		    mapsize);
203228753Smm	}
204228753Smm	nv_add_uint32(nvout, (uint32_t)mapsize, "mapsize");
205228753Smm	/*
206228753Smm	 * When we work as primary and secondary is missing we will increase
207228753Smm	 * localcnt in our metadata. When secondary is connected and synced
208228753Smm	 * we make localcnt be equal to remotecnt, which means nodes are more
209228753Smm	 * or less in sync.
210228753Smm	 * Split-brain condition is when both nodes are not able to communicate
211228753Smm	 * and are both configured as primary nodes. In turn, they can both
212228753Smm	 * make incompatible changes to the data and we have to detect that.
213228753Smm	 * Under split-brain condition we will increase our localcnt on first
214228753Smm	 * write and remote node will increase its localcnt on first write.
215228753Smm	 * When we connect we can see that primary's localcnt is greater than
216228753Smm	 * our remotecnt (primary was modified while we weren't watching) and
217228753Smm	 * our localcnt is greater than primary's remotecnt (we were modified
218228753Smm	 * while primary wasn't watching).
219228753Smm	 * There are many possible combinations which are all gathered below.
220228753Smm	 * Don't pay too much attention to exact numbers, the more important
221228753Smm	 * is to compare them. We compare secondary's local with primary's
222229592Smm	 * remote and secondary's remote with primary's local.
223228753Smm	 * Note that every case where primary's localcnt is smaller than
224228753Smm	 * secondary's remotecnt and where secondary's localcnt is smaller than
225228753Smm	 * primary's remotecnt should be impossible in practise. We will perform
226228753Smm	 * full synchronization then. Those cases are marked with an asterisk.
227228753Smm	 * Regular synchronization means that only extents marked as dirty are
228228753Smm	 * synchronized (regular synchronization).
229228753Smm	 *
230228753Smm	 * SECONDARY METADATA PRIMARY METADATA
231228753Smm	 * local=3 remote=3   local=2 remote=2*  ?! Full sync from secondary.
232228753Smm	 * local=3 remote=3   local=2 remote=3*  ?! Full sync from primary.
233228753Smm	 * local=3 remote=3   local=2 remote=4*  ?! Full sync from primary.
234228753Smm	 * local=3 remote=3   local=3 remote=2   Primary is out-of-date,
235228753Smm	 *                                       regular sync from secondary.
236228753Smm	 * local=3 remote=3   local=3 remote=3   Regular sync just in case.
237228753Smm	 * local=3 remote=3   local=3 remote=4*  ?! Full sync from primary.
238228753Smm	 * local=3 remote=3   local=4 remote=2   Split-brain condition.
239228753Smm	 * local=3 remote=3   local=4 remote=3   Secondary out-of-date,
240228753Smm	 *                                       regular sync from primary.
241228753Smm	 * local=3 remote=3   local=4 remote=4*  ?! Full sync from primary.
242228753Smm	 */
243228753Smm	if (res->hr_resuid == 0) {
244228753Smm		/*
245228753Smm		 * Provider is used for the first time. If primary node done no
246228753Smm		 * writes yet as well (we will find "virgin" argument) then
247228753Smm		 * there is no need to synchronize anything. If primary node
248228753Smm		 * done any writes already we have to synchronize everything.
249228753Smm		 */
250228753Smm		PJDLOG_ASSERT(res->hr_secondary_localcnt == 0);
251228753Smm		res->hr_resuid = resuid;
252228753Smm		if (metadata_write(res) < 0)
253228753Smm			exit(EX_NOINPUT);
254228753Smm		if (nv_exists(nvin, "virgin")) {
255228753Smm			free(map);
256228753Smm			map = NULL;
257228753Smm			mapsize = 0;
258228753Smm		} else {
259228753Smm			memset(map, 0xff, mapsize);
260228753Smm		}
261228753Smm		nv_add_uint8(nvout, HAST_SYNCSRC_PRIMARY, "syncsrc");
262228753Smm	} else if (res->hr_resuid != resuid) {
263228753Smm		char errmsg[256];
264228753Smm
265228753Smm		(void)snprintf(errmsg, sizeof(errmsg),
266228753Smm		    "Resource unique ID mismatch (primary=%ju, secondary=%ju).",
267228753Smm		    (uintmax_t)resuid, (uintmax_t)res->hr_resuid);
268228753Smm		pjdlog_error("%s", errmsg);
269228753Smm		nv_add_string(nvout, errmsg, "errmsg");
270228753Smm		if (hast_proto_send(res, res->hr_remotein, nvout, NULL, 0) < 0) {
271228753Smm			pjdlog_exit(EX_TEMPFAIL, "Unable to send response to %s",
272228753Smm			    res->hr_remoteaddr);
273228753Smm		}
274228753Smm		nv_free(nvout);
275228753Smm		exit(EX_CONFIG);
276228753Smm	} else if (
277228753Smm	    /* Is primary is out-of-date? */
278228753Smm	    (res->hr_secondary_localcnt > res->hr_primary_remotecnt &&
279228753Smm	     res->hr_secondary_remotecnt == res->hr_primary_localcnt) ||
280228753Smm	    /* Nodes are more or less in sync? */
281228753Smm	    (res->hr_secondary_localcnt == res->hr_primary_remotecnt &&
282228753Smm	     res->hr_secondary_remotecnt == res->hr_primary_localcnt) ||
283228753Smm	    /* Is secondary is out-of-date? */
284228753Smm	    (res->hr_secondary_localcnt == res->hr_primary_remotecnt &&
285228753Smm	     res->hr_secondary_remotecnt < res->hr_primary_localcnt)) {
286228753Smm		/*
287228753Smm		 * Nodes are more or less in sync or one of the nodes is
288228753Smm		 * out-of-date.
289228753Smm		 * It doesn't matter at this point which one, we just have to
290228753Smm		 * send out local bitmap to the remote node.
291228753Smm		 */
292228753Smm		if (pread(res->hr_localfd, map, mapsize, METADATA_SIZE) !=
293228753Smm		    (ssize_t)mapsize) {
294228753Smm			pjdlog_exit(LOG_ERR, "Unable to read activemap");
295228753Smm		}
296228753Smm		if (res->hr_secondary_localcnt > res->hr_primary_remotecnt &&
297228753Smm		     res->hr_secondary_remotecnt == res->hr_primary_localcnt) {
298228753Smm			/* Primary is out-of-date, sync from secondary. */
299228753Smm			nv_add_uint8(nvout, HAST_SYNCSRC_SECONDARY, "syncsrc");
300228753Smm		} else {
301228753Smm			/*
302228753Smm			 * Secondary is out-of-date or counts match.
303228753Smm			 * Sync from primary.
304228753Smm			 */
305228753Smm			nv_add_uint8(nvout, HAST_SYNCSRC_PRIMARY, "syncsrc");
306228753Smm		}
307228753Smm	} else if (res->hr_secondary_localcnt > res->hr_primary_remotecnt &&
308228753Smm	     res->hr_primary_localcnt > res->hr_secondary_remotecnt) {
309228753Smm		/*
310228753Smm		 * Not good, we have split-brain condition.
311228753Smm		 */
312228753Smm		pjdlog_error("Split-brain detected, exiting.");
313228753Smm		nv_add_string(nvout, "Split-brain condition!", "errmsg");
314228753Smm		free(map);
315228753Smm		map = NULL;
316228753Smm		mapsize = 0;
317228753Smm	} else /* if (res->hr_secondary_localcnt < res->hr_primary_remotecnt ||
318228753Smm	    res->hr_primary_localcnt < res->hr_secondary_remotecnt) */ {
319228753Smm		/*
320228753Smm		 * This should never happen in practise, but we will perform
321228753Smm		 * full synchronization.
322228753Smm		 */
323228753Smm		PJDLOG_ASSERT(res->hr_secondary_localcnt < res->hr_primary_remotecnt ||
324228753Smm		    res->hr_primary_localcnt < res->hr_secondary_remotecnt);
325228753Smm		mapsize = activemap_calc_ondisk_size(res->hr_local_mediasize -
326228753Smm		    METADATA_SIZE, res->hr_extentsize,
327228753Smm		    res->hr_local_sectorsize);
328228753Smm		memset(map, 0xff, mapsize);
329228753Smm		if (res->hr_secondary_localcnt > res->hr_primary_remotecnt) {
330228753Smm			/* In this one of five cases sync from secondary. */
331228753Smm			nv_add_uint8(nvout, HAST_SYNCSRC_SECONDARY, "syncsrc");
332228753Smm		} else {
333228753Smm			/* For the rest four cases sync from primary. */
334228753Smm			nv_add_uint8(nvout, HAST_SYNCSRC_PRIMARY, "syncsrc");
335228753Smm		}
336228753Smm		pjdlog_warning("This should never happen, asking for full synchronization (primary(local=%ju, remote=%ju), secondary(local=%ju, remote=%ju)).",
337228753Smm		    (uintmax_t)res->hr_primary_localcnt,
338228753Smm		    (uintmax_t)res->hr_primary_remotecnt,
339228753Smm		    (uintmax_t)res->hr_secondary_localcnt,
340228753Smm		    (uintmax_t)res->hr_secondary_remotecnt);
341228753Smm	}
342228753Smm	if (hast_proto_send(res, res->hr_remotein, nvout, map, mapsize) < 0) {
343228753Smm		pjdlog_exit(EX_TEMPFAIL, "Unable to send activemap to %s",
344228753Smm		    res->hr_remoteaddr);
345228753Smm	}
346228753Smm	if (map != NULL)
347228753Smm		free(map);
348228753Smm	nv_free(nvout);
349228753Smm	if (res->hr_secondary_localcnt > res->hr_primary_remotecnt &&
350228753Smm	     res->hr_primary_localcnt > res->hr_secondary_remotecnt) {
351228753Smm		/* Exit on split-brain. */
352228753Smm		event_send(res, EVENT_SPLITBRAIN);
353228753Smm		exit(EX_CONFIG);
354228753Smm	}
355228753Smm}
356228753Smm
357228753Smmvoid
358228753Smmhastd_secondary(struct hast_resource *res, struct nv *nvin)
359228753Smm{
360228753Smm	sigset_t mask;
361228753Smm	pthread_t td;
362228753Smm	pid_t pid;
363228753Smm	int error, mode, debuglevel;
364228753Smm
365228753Smm	/*
366228753Smm	 * Create communication channel between parent and child.
367228753Smm	 */
368228753Smm	if (proto_client(NULL, "socketpair://", &res->hr_ctrl) < 0) {
369228753Smm		KEEP_ERRNO((void)pidfile_remove(pfh));
370228753Smm		pjdlog_exit(EX_OSERR,
371228753Smm		    "Unable to create control sockets between parent and child");
372228753Smm	}
373228753Smm	/*
374228753Smm	 * Create communication channel between child and parent.
375228753Smm	 */
376228753Smm	if (proto_client(NULL, "socketpair://", &res->hr_event) < 0) {
377228753Smm		KEEP_ERRNO((void)pidfile_remove(pfh));
378228753Smm		pjdlog_exit(EX_OSERR,
379228753Smm		    "Unable to create event sockets between child and parent");
380228753Smm	}
381228753Smm	/*
382228753Smm	 * Create communication channel for sending connection requests from
383228753Smm	 * parent to child.
384228753Smm	 */
385228753Smm	if (proto_client(NULL, "socketpair://", &res->hr_conn) < 0) {
386228753Smm		/* TODO: There's no need for this to be fatal error. */
387228753Smm		KEEP_ERRNO((void)pidfile_remove(pfh));
388228753Smm		pjdlog_exit(EX_OSERR,
389228753Smm		    "Unable to create connection sockets between parent and child");
390228753Smm	}
391228753Smm
392228753Smm	pid = fork();
393228753Smm	if (pid < 0) {
394228753Smm		KEEP_ERRNO((void)pidfile_remove(pfh));
395228753Smm		pjdlog_exit(EX_OSERR, "Unable to fork");
396228753Smm	}
397228753Smm
398228753Smm	if (pid > 0) {
399228753Smm		/* This is parent. */
400228753Smm		proto_close(res->hr_remotein);
401228753Smm		res->hr_remotein = NULL;
402228753Smm		proto_close(res->hr_remoteout);
403228753Smm		res->hr_remoteout = NULL;
404228753Smm		/* Declare that we are receiver. */
405228753Smm		proto_recv(res->hr_event, NULL, 0);
406228753Smm		/* Declare that we are sender. */
407228753Smm		proto_send(res->hr_ctrl, NULL, 0);
408228753Smm		proto_send(res->hr_conn, NULL, 0);
409228753Smm		res->hr_workerpid = pid;
410228753Smm		return;
411228753Smm	}
412228753Smm
413228753Smm	gres = res;
414228753Smm	mode = pjdlog_mode_get();
415228753Smm	debuglevel = pjdlog_debug_get();
416228753Smm
417228753Smm	/* Declare that we are sender. */
418228753Smm	proto_send(res->hr_event, NULL, 0);
419228753Smm	/* Declare that we are receiver. */
420228753Smm	proto_recv(res->hr_ctrl, NULL, 0);
421228753Smm	proto_recv(res->hr_conn, NULL, 0);
422228753Smm	descriptors_cleanup(res);
423228753Smm
424228753Smm	descriptors_assert(res, mode);
425228753Smm
426228753Smm	pjdlog_init(mode);
427228753Smm	pjdlog_debug_set(debuglevel);
428228753Smm	pjdlog_prefix_set("[%s] (%s) ", res->hr_name, role2str(res->hr_role));
429228753Smm	setproctitle("%s (secondary)", res->hr_name);
430228753Smm
431228753Smm	PJDLOG_VERIFY(sigemptyset(&mask) == 0);
432228753Smm	PJDLOG_VERIFY(sigprocmask(SIG_SETMASK, &mask, NULL) == 0);
433228753Smm
434228753Smm	/* Error in setting timeout is not critical, but why should it fail? */
435228753Smm	if (proto_timeout(res->hr_remotein, 2 * HAST_KEEPALIVE) < 0)
436228753Smm		pjdlog_errno(LOG_WARNING, "Unable to set connection timeout");
437228753Smm	if (proto_timeout(res->hr_remoteout, res->hr_timeout) < 0)
438228753Smm		pjdlog_errno(LOG_WARNING, "Unable to set connection timeout");
439228753Smm
440228753Smm	init_local(res);
441228753Smm	init_environment();
442228753Smm
443228753Smm	if (drop_privs(true) != 0)
444228753Smm		exit(EX_CONFIG);
445228753Smm	pjdlog_info("Privileges successfully dropped.");
446228753Smm
447228753Smm	/*
448228753Smm	 * Create the control thread before sending any event to the parent,
449228753Smm	 * as we can deadlock when parent sends control request to worker,
450228753Smm	 * but worker has no control thread started yet, so parent waits.
451	 * In the meantime worker sends an event to the parent, but parent
452	 * is unable to handle the event, because it waits for control
453	 * request response.
454	 */
455	error = pthread_create(&td, NULL, ctrl_thread, res);
456	PJDLOG_ASSERT(error == 0);
457
458	init_remote(res, nvin);
459	event_send(res, EVENT_CONNECT);
460
461	error = pthread_create(&td, NULL, recv_thread, res);
462	PJDLOG_ASSERT(error == 0);
463	error = pthread_create(&td, NULL, disk_thread, res);
464	PJDLOG_ASSERT(error == 0);
465	(void)send_thread(res);
466}
467
468static void
469reqlog(int loglevel, int debuglevel, int error, struct hio *hio, const char *fmt, ...)
470{
471	char msg[1024];
472	va_list ap;
473	int len;
474
475	va_start(ap, fmt);
476	len = vsnprintf(msg, sizeof(msg), fmt, ap);
477	va_end(ap);
478	if ((size_t)len < sizeof(msg)) {
479		switch (hio->hio_cmd) {
480		case HIO_READ:
481			(void)snprintf(msg + len, sizeof(msg) - len,
482			    "READ(%ju, %ju).", (uintmax_t)hio->hio_offset,
483			    (uintmax_t)hio->hio_length);
484			break;
485		case HIO_DELETE:
486			(void)snprintf(msg + len, sizeof(msg) - len,
487			    "DELETE(%ju, %ju).", (uintmax_t)hio->hio_offset,
488			    (uintmax_t)hio->hio_length);
489			break;
490		case HIO_FLUSH:
491			(void)snprintf(msg + len, sizeof(msg) - len, "FLUSH.");
492			break;
493		case HIO_WRITE:
494			(void)snprintf(msg + len, sizeof(msg) - len,
495			    "WRITE(%ju, %ju).", (uintmax_t)hio->hio_offset,
496			    (uintmax_t)hio->hio_length);
497			break;
498		case HIO_KEEPALIVE:
499			(void)snprintf(msg + len, sizeof(msg) - len, "KEEPALIVE.");
500			break;
501		default:
502			(void)snprintf(msg + len, sizeof(msg) - len,
503			    "UNKNOWN(%u).", (unsigned int)hio->hio_cmd);
504			break;
505		}
506	}
507	pjdlog_common(loglevel, debuglevel, error, "%s", msg);
508}
509
510static int
511requnpack(struct hast_resource *res, struct hio *hio)
512{
513
514	hio->hio_cmd = nv_get_uint8(hio->hio_nv, "cmd");
515	if (hio->hio_cmd == 0) {
516		pjdlog_error("Header contains no 'cmd' field.");
517		hio->hio_error = EINVAL;
518		goto end;
519	}
520	switch (hio->hio_cmd) {
521	case HIO_KEEPALIVE:
522		break;
523	case HIO_READ:
524	case HIO_WRITE:
525	case HIO_DELETE:
526		hio->hio_offset = nv_get_uint64(hio->hio_nv, "offset");
527		if (nv_error(hio->hio_nv) != 0) {
528			pjdlog_error("Header is missing 'offset' field.");
529			hio->hio_error = EINVAL;
530			goto end;
531		}
532		hio->hio_length = nv_get_uint64(hio->hio_nv, "length");
533		if (nv_error(hio->hio_nv) != 0) {
534			pjdlog_error("Header is missing 'length' field.");
535			hio->hio_error = EINVAL;
536			goto end;
537		}
538		if (hio->hio_length == 0) {
539			pjdlog_error("Data length is zero.");
540			hio->hio_error = EINVAL;
541			goto end;
542		}
543		if (hio->hio_length > MAXPHYS) {
544			pjdlog_error("Data length is too large (%ju > %ju).",
545			    (uintmax_t)hio->hio_length, (uintmax_t)MAXPHYS);
546			hio->hio_error = EINVAL;
547			goto end;
548		}
549		if ((hio->hio_offset % res->hr_local_sectorsize) != 0) {
550			pjdlog_error("Offset %ju is not multiple of sector size.",
551			    (uintmax_t)hio->hio_offset);
552			hio->hio_error = EINVAL;
553			goto end;
554		}
555		if ((hio->hio_length % res->hr_local_sectorsize) != 0) {
556			pjdlog_error("Length %ju is not multiple of sector size.",
557			    (uintmax_t)hio->hio_length);
558			hio->hio_error = EINVAL;
559			goto end;
560		}
561		if (hio->hio_offset + hio->hio_length >
562		    (uint64_t)res->hr_datasize) {
563			pjdlog_error("Data offset is too large (%ju > %ju).",
564			    (uintmax_t)(hio->hio_offset + hio->hio_length),
565			    (uintmax_t)res->hr_datasize);
566			hio->hio_error = EINVAL;
567			goto end;
568		}
569		break;
570	default:
571		pjdlog_error("Header contains invalid 'cmd' (%hhu).",
572		    hio->hio_cmd);
573		hio->hio_error = EINVAL;
574		goto end;
575	}
576	hio->hio_error = 0;
577end:
578	return (hio->hio_error);
579}
580
581static __dead2 void
582secondary_exit(int exitcode, const char *fmt, ...)
583{
584	va_list ap;
585
586	PJDLOG_ASSERT(exitcode != EX_OK);
587	va_start(ap, fmt);
588	pjdlogv_errno(LOG_ERR, fmt, ap);
589	va_end(ap);
590	event_send(gres, EVENT_DISCONNECT);
591	exit(exitcode);
592}
593
594/*
595 * Thread receives requests from the primary node.
596 */
597static void *
598recv_thread(void *arg)
599{
600	struct hast_resource *res = arg;
601	struct hio *hio;
602
603	for (;;) {
604		pjdlog_debug(2, "recv: Taking free request.");
605		QUEUE_TAKE(free, hio);
606		pjdlog_debug(2, "recv: (%p) Got request.", hio);
607		if (hast_proto_recv_hdr(res->hr_remotein, &hio->hio_nv) < 0) {
608			secondary_exit(EX_TEMPFAIL,
609			    "Unable to receive request header");
610		}
611		if (requnpack(res, hio) != 0) {
612			pjdlog_debug(2,
613			    "recv: (%p) Moving request to the send queue.",
614			    hio);
615			QUEUE_INSERT(send, hio);
616			continue;
617		}
618		reqlog(LOG_DEBUG, 2, -1, hio,
619		    "recv: (%p) Got request header: ", hio);
620		if (hio->hio_cmd == HIO_KEEPALIVE) {
621			pjdlog_debug(2,
622			    "recv: (%p) Moving request to the free queue.",
623			    hio);
624			nv_free(hio->hio_nv);
625			QUEUE_INSERT(free, hio);
626			continue;
627		} else if (hio->hio_cmd == HIO_WRITE) {
628			if (hast_proto_recv_data(res, res->hr_remotein,
629			    hio->hio_nv, hio->hio_data, MAXPHYS) < 0) {
630				secondary_exit(EX_TEMPFAIL,
631				    "Unable to receive request data");
632			}
633		}
634		pjdlog_debug(2, "recv: (%p) Moving request to the disk queue.",
635		    hio);
636		QUEUE_INSERT(disk, hio);
637	}
638	/* NOTREACHED */
639	return (NULL);
640}
641
642/*
643 * Thread reads from or writes to local component and also handles DELETE and
644 * FLUSH requests.
645 */
646static void *
647disk_thread(void *arg)
648{
649	struct hast_resource *res = arg;
650	struct hio *hio;
651	ssize_t ret;
652	bool clear_activemap;
653
654	clear_activemap = true;
655
656	for (;;) {
657		pjdlog_debug(2, "disk: Taking request.");
658		QUEUE_TAKE(disk, hio);
659		while (clear_activemap) {
660			unsigned char *map;
661			size_t mapsize;
662
663			/*
664			 * When first request is received, it means that primary
665			 * already received our activemap, merged it and stored
666			 * locally. We can now safely clear our activemap.
667			 */
668			mapsize =
669			    activemap_calc_ondisk_size(res->hr_local_mediasize -
670			    METADATA_SIZE, res->hr_extentsize,
671			    res->hr_local_sectorsize);
672			map = calloc(1, mapsize);
673			if (map == NULL) {
674				pjdlog_warning("Unable to allocate memory to clear local activemap.");
675				break;
676			}
677			if (pwrite(res->hr_localfd, map, mapsize,
678			    METADATA_SIZE) != (ssize_t)mapsize) {
679				pjdlog_errno(LOG_WARNING,
680				    "Unable to store cleared activemap");
681				free(map);
682				break;
683			}
684			free(map);
685			clear_activemap = false;
686			pjdlog_debug(1, "Local activemap cleared.");
687		}
688		reqlog(LOG_DEBUG, 2, -1, hio, "disk: (%p) Got request: ", hio);
689		/* Handle the actual request. */
690		switch (hio->hio_cmd) {
691		case HIO_READ:
692			ret = pread(res->hr_localfd, hio->hio_data,
693			    hio->hio_length,
694			    hio->hio_offset + res->hr_localoff);
695			if (ret < 0)
696				hio->hio_error = errno;
697			else if (ret != (int64_t)hio->hio_length)
698				hio->hio_error = EIO;
699			else
700				hio->hio_error = 0;
701			break;
702		case HIO_WRITE:
703			ret = pwrite(res->hr_localfd, hio->hio_data,
704			    hio->hio_length,
705			    hio->hio_offset + res->hr_localoff);
706			if (ret < 0)
707				hio->hio_error = errno;
708			else if (ret != (int64_t)hio->hio_length)
709				hio->hio_error = EIO;
710			else
711				hio->hio_error = 0;
712			break;
713		case HIO_DELETE:
714			ret = g_delete(res->hr_localfd,
715			    hio->hio_offset + res->hr_localoff,
716			    hio->hio_length);
717			if (ret < 0)
718				hio->hio_error = errno;
719			else
720				hio->hio_error = 0;
721			break;
722		case HIO_FLUSH:
723			ret = g_flush(res->hr_localfd);
724			if (ret < 0)
725				hio->hio_error = errno;
726			else
727				hio->hio_error = 0;
728			break;
729		}
730		if (hio->hio_error != 0) {
731			reqlog(LOG_ERR, 0, hio->hio_error, hio,
732			    "Request failed: ");
733		}
734		pjdlog_debug(2, "disk: (%p) Moving request to the send queue.",
735		    hio);
736		QUEUE_INSERT(send, hio);
737	}
738	/* NOTREACHED */
739	return (NULL);
740}
741
742/*
743 * Thread sends requests back to primary node.
744 */
745static void *
746send_thread(void *arg)
747{
748	struct hast_resource *res = arg;
749	struct nv *nvout;
750	struct hio *hio;
751	void *data;
752	size_t length;
753
754	for (;;) {
755		pjdlog_debug(2, "send: Taking request.");
756		QUEUE_TAKE(send, hio);
757		reqlog(LOG_DEBUG, 2, -1, hio, "send: (%p) Got request: ", hio);
758		nvout = nv_alloc();
759		/* Copy sequence number. */
760		nv_add_uint64(nvout, nv_get_uint64(hio->hio_nv, "seq"), "seq");
761		switch (hio->hio_cmd) {
762		case HIO_READ:
763			if (hio->hio_error == 0) {
764				data = hio->hio_data;
765				length = hio->hio_length;
766				break;
767			}
768			/*
769			 * We send no data in case of an error.
770			 */
771			/* FALLTHROUGH */
772		case HIO_DELETE:
773		case HIO_FLUSH:
774		case HIO_WRITE:
775			data = NULL;
776			length = 0;
777			break;
778		default:
779			abort();
780			break;
781		}
782		if (hio->hio_error != 0)
783			nv_add_int16(nvout, hio->hio_error, "error");
784		if (hast_proto_send(res, res->hr_remoteout, nvout, data,
785		    length) < 0) {
786			secondary_exit(EX_TEMPFAIL, "Unable to send reply.");
787		}
788		nv_free(nvout);
789		pjdlog_debug(2, "send: (%p) Moving request to the free queue.",
790		    hio);
791		nv_free(hio->hio_nv);
792		hio->hio_error = 0;
793		QUEUE_INSERT(free, hio);
794	}
795	/* NOTREACHED */
796	return (NULL);
797}
798