secondary.c revision 256027
1204076Spjd/*-
2204076Spjd * Copyright (c) 2009-2010 The FreeBSD Foundation
3211877Spjd * Copyright (c) 2010 Pawel Jakub Dawidek <pjd@FreeBSD.org>
4204076Spjd * All rights reserved.
5204076Spjd *
6204076Spjd * This software was developed by Pawel Jakub Dawidek under sponsorship from
7204076Spjd * the FreeBSD Foundation.
8204076Spjd *
9204076Spjd * Redistribution and use in source and binary forms, with or without
10204076Spjd * modification, are permitted provided that the following conditions
11204076Spjd * are met:
12204076Spjd * 1. Redistributions of source code must retain the above copyright
13204076Spjd *    notice, this list of conditions and the following disclaimer.
14204076Spjd * 2. Redistributions in binary form must reproduce the above copyright
15204076Spjd *    notice, this list of conditions and the following disclaimer in the
16204076Spjd *    documentation and/or other materials provided with the distribution.
17204076Spjd *
18204076Spjd * THIS SOFTWARE IS PROVIDED BY THE AUTHORS AND CONTRIBUTORS ``AS IS'' AND
19204076Spjd * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20204076Spjd * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21204076Spjd * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE
22204076Spjd * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23204076Spjd * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24204076Spjd * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25204076Spjd * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26204076Spjd * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
27204076Spjd * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28204076Spjd * SUCH DAMAGE.
29204076Spjd */
30204076Spjd
31204076Spjd#include <sys/cdefs.h>
32204076Spjd__FBSDID("$FreeBSD: stable/9/sbin/hastd/secondary.c 256027 2013-10-03 18:52:04Z trociny $");
33204076Spjd
34204076Spjd#include <sys/param.h>
35204076Spjd#include <sys/time.h>
36204076Spjd#include <sys/bio.h>
37204076Spjd#include <sys/disk.h>
38204076Spjd#include <sys/stat.h>
39204076Spjd
40204076Spjd#include <err.h>
41204076Spjd#include <errno.h>
42204076Spjd#include <fcntl.h>
43204076Spjd#include <libgeom.h>
44204076Spjd#include <pthread.h>
45213009Spjd#include <signal.h>
46204076Spjd#include <stdint.h>
47204076Spjd#include <stdio.h>
48204076Spjd#include <string.h>
49204076Spjd#include <sysexits.h>
50204076Spjd#include <unistd.h>
51204076Spjd
52204076Spjd#include <activemap.h>
53204076Spjd#include <nv.h>
54204076Spjd#include <pjdlog.h>
55204076Spjd
56204076Spjd#include "control.h"
57212038Spjd#include "event.h"
58204076Spjd#include "hast.h"
59204076Spjd#include "hast_proto.h"
60204076Spjd#include "hastd.h"
61211977Spjd#include "hooks.h"
62204076Spjd#include "metadata.h"
63204076Spjd#include "proto.h"
64204076Spjd#include "subr.h"
65204076Spjd#include "synch.h"
66204076Spjd
67204076Spjdstruct hio {
68219864Spjd	uint64_t	 hio_seq;
69219864Spjd	int		 hio_error;
70204076Spjd	void		*hio_data;
71204076Spjd	uint8_t		 hio_cmd;
72204076Spjd	uint64_t	 hio_offset;
73204076Spjd	uint64_t	 hio_length;
74204076Spjd	bool		 hio_memsync;
75204076Spjd	TAILQ_ENTRY(hio) hio_next;
76204076Spjd};
77204076Spjd
78211984Spjdstatic struct hast_resource *gres;
79211984Spjd
80204076Spjd/*
81204076Spjd * Free list holds unused structures. When free list is empty, we have to wait
82204076Spjd * until some in-progress requests are freed.
83204076Spjd */
84204076Spjdstatic TAILQ_HEAD(, hio) hio_free_list;
85204076Spjdstatic pthread_mutex_t hio_free_list_lock;
86204076Spjdstatic pthread_cond_t hio_free_list_cond;
87204076Spjd/*
88204076Spjd * Disk thread (the one that does I/O requests) takes requests from this list.
89204076Spjd */
90204076Spjdstatic TAILQ_HEAD(, hio) hio_disk_list;
91204076Spjdstatic pthread_mutex_t hio_disk_list_lock;
92204076Spjdstatic pthread_cond_t hio_disk_list_cond;
93204076Spjd/*
94204076Spjd * Thread that sends requests back to primary takes requests from this list.
95204076Spjd */
96204076Spjdstatic TAILQ_HEAD(, hio) hio_send_list;
97204076Spjdstatic pthread_mutex_t hio_send_list_lock;
98204076Spjdstatic pthread_cond_t hio_send_list_cond;
99204076Spjd
100204076Spjd/*
101204076Spjd * Maximum number of outstanding I/O requests.
102204076Spjd */
103204076Spjd#define	HAST_HIO_MAX	256
104204076Spjd
105204076Spjdstatic void *recv_thread(void *arg);
106204076Spjdstatic void *disk_thread(void *arg);
107204076Spjdstatic void *send_thread(void *arg);
108204076Spjd
109204076Spjd#define	QUEUE_INSERT(name, hio)	do {					\
110211877Spjd	bool _wakeup;							\
111211877Spjd									\
112211877Spjd	mtx_lock(&hio_##name##_list_lock);				\
113211877Spjd	_wakeup = TAILQ_EMPTY(&hio_##name##_list);			\
114211877Spjd	TAILQ_INSERT_TAIL(&hio_##name##_list, (hio), hio_next);		\
115211877Spjd	mtx_unlock(&hio_##name##_list_lock);				\
116211877Spjd	if (_wakeup)							\
117211877Spjd		cv_broadcast(&hio_##name##_list_cond);			\
118211877Spjd} while (0)
119211877Spjd#define	QUEUE_TAKE(name, hio)	do {					\
120211877Spjd	mtx_lock(&hio_##name##_list_lock);				\
121211877Spjd	while (((hio) = TAILQ_FIRST(&hio_##name##_list)) == NULL) {	\
122211877Spjd		cv_wait(&hio_##name##_list_cond,			\
123211877Spjd		    &hio_##name##_list_lock);				\
124211877Spjd	}								\
125211877Spjd	TAILQ_REMOVE(&hio_##name##_list, (hio), hio_next);		\
126211877Spjd	mtx_unlock(&hio_##name##_list_lock);				\
127211877Spjd} while (0)
128211877Spjd
129211877Spjdstatic void
130204076Spjdhio_clear(struct hio *hio)
131204076Spjd{
132204076Spjd
133204076Spjd	hio->hio_seq = 0;
134204076Spjd	hio->hio_error = 0;
135204076Spjd	hio->hio_cmd = HIO_UNDEF;
136204076Spjd	hio->hio_offset = 0;
137204076Spjd	hio->hio_length = 0;
138204076Spjd	hio->hio_memsync = false;
139204076Spjd}
140204076Spjd
141204076Spjdstatic void
142204076Spjdhio_copy(const struct hio *srchio, struct hio *dsthio)
143204076Spjd{
144204076Spjd
145204076Spjd	/*
146204076Spjd	 * We don't copy hio_error, hio_data and hio_next fields.
147204076Spjd	 */
148204076Spjd
149204076Spjd	dsthio->hio_seq = srchio->hio_seq;
150204076Spjd	dsthio->hio_cmd = srchio->hio_cmd;
151204076Spjd	dsthio->hio_offset = srchio->hio_offset;
152204076Spjd	dsthio->hio_length = srchio->hio_length;
153204076Spjd	dsthio->hio_memsync = srchio->hio_memsync;
154204076Spjd}
155210879Spjd
156210879Spjdstatic void
157210879Spjdinit_environment(void)
158204076Spjd{
159204076Spjd	struct hio *hio;
160204076Spjd	unsigned int ii;
161204076Spjd
162210879Spjd	/*
163210879Spjd	 * Initialize lists, their locks and theirs condition variables.
164210879Spjd	 */
165204076Spjd	TAILQ_INIT(&hio_free_list);
166204076Spjd	mtx_init(&hio_free_list_lock);
167204076Spjd	cv_init(&hio_free_list_cond);
168204076Spjd	TAILQ_INIT(&hio_disk_list);
169204076Spjd	mtx_init(&hio_disk_list_lock);
170204076Spjd	cv_init(&hio_disk_list_cond);
171204076Spjd	TAILQ_INIT(&hio_send_list);
172204076Spjd	mtx_init(&hio_send_list_lock);
173204076Spjd	cv_init(&hio_send_list_cond);
174204076Spjd
175204076Spjd	/*
176204076Spjd	 * Allocate requests pool and initialize requests.
177204076Spjd	 */
178204076Spjd	for (ii = 0; ii < HAST_HIO_MAX; ii++) {
179204076Spjd		hio = malloc(sizeof(*hio));
180204076Spjd		if (hio == NULL) {
181204076Spjd			pjdlog_exitx(EX_TEMPFAIL,
182204076Spjd			    "Unable to allocate memory (%zu bytes) for hio request.",
183204076Spjd			    sizeof(*hio));
184204076Spjd		}
185204076Spjd		hio->hio_data = malloc(MAXPHYS);
186223181Strociny		if (hio->hio_data == NULL) {
187220271Spjd			pjdlog_exitx(EX_TEMPFAIL,
188220271Spjd			    "Unable to allocate memory (%zu bytes) for gctl_data.",
189220271Spjd			    (size_t)MAXPHYS);
190223181Strociny		}
191220271Spjd		hio_clear(hio);
192204076Spjd		TAILQ_INSERT_HEAD(&hio_free_list, hio, hio_next);
193204076Spjd	}
194204076Spjd}
195204076Spjd
196204076Spjdstatic void
197204076Spjdinit_local(struct hast_resource *res)
198204076Spjd{
199204076Spjd
200204076Spjd	if (metadata_read(res, true) == -1)
201204076Spjd		exit(EX_NOINPUT);
202204076Spjd}
203204076Spjd
204204076Spjdstatic void
205204076Spjdinit_remote(struct hast_resource *res, struct nv *nvin)
206204076Spjd{
207204076Spjd	uint64_t resuid;
208204076Spjd	struct nv *nvout;
209204076Spjd	unsigned char *map;
210204076Spjd	size_t mapsize;
211204076Spjd
212204076Spjd#ifdef notyet
213204076Spjd	/* Setup direction. */
214204076Spjd	if (proto_send(res->hr_remoteout, NULL, 0) == -1)
215204076Spjd		pjdlog_errno(LOG_WARNING, "Unable to set connection direction");
216204076Spjd#endif
217204076Spjd
218204076Spjd	nvout = nv_alloc();
219204076Spjd	nv_add_int64(nvout, (int64_t)res->hr_datasize, "datasize");
220204076Spjd	nv_add_int32(nvout, (int32_t)res->hr_extentsize, "extentsize");
221204076Spjd	resuid = nv_get_uint64(nvin, "resuid");
222204076Spjd	res->hr_primary_localcnt = nv_get_uint64(nvin, "localcnt");
223204076Spjd	res->hr_primary_remotecnt = nv_get_uint64(nvin, "remotecnt");
224204076Spjd	nv_add_uint64(nvout, res->hr_secondary_localcnt, "localcnt");
225204076Spjd	nv_add_uint64(nvout, res->hr_secondary_remotecnt, "remotecnt");
226204076Spjd	mapsize = activemap_calc_ondisk_size(res->hr_local_mediasize -
227204076Spjd	    METADATA_SIZE, res->hr_extentsize, res->hr_local_sectorsize);
228204076Spjd	map = malloc(mapsize);
229204076Spjd	if (map == NULL) {
230204076Spjd		pjdlog_exitx(EX_TEMPFAIL,
231204076Spjd		    "Unable to allocate memory (%zu bytes) for activemap.",
232204076Spjd		    mapsize);
233204076Spjd	}
234204076Spjd	/*
235204076Spjd	 * When we work as primary and secondary is missing we will increase
236204076Spjd	 * localcnt in our metadata. When secondary is connected and synced
237204076Spjd	 * we make localcnt be equal to remotecnt, which means nodes are more
238204076Spjd	 * or less in sync.
239204076Spjd	 * Split-brain condition is when both nodes are not able to communicate
240204076Spjd	 * and are both configured as primary nodes. In turn, they can both
241204076Spjd	 * make incompatible changes to the data and we have to detect that.
242204076Spjd	 * Under split-brain condition we will increase our localcnt on first
243204076Spjd	 * write and remote node will increase its localcnt on first write.
244204076Spjd	 * When we connect we can see that primary's localcnt is greater than
245204076Spjd	 * our remotecnt (primary was modified while we weren't watching) and
246204076Spjd	 * our localcnt is greater than primary's remotecnt (we were modified
247204076Spjd	 * while primary wasn't watching).
248204076Spjd	 * There are many possible combinations which are all gathered below.
249204076Spjd	 * Don't pay too much attention to exact numbers, the more important
250214284Spjd	 * is to compare them. We compare secondary's local with primary's
251214284Spjd	 * remote and secondary's remote with primary's local.
252214284Spjd	 * Note that every case where primary's localcnt is smaller than
253214284Spjd	 * secondary's remotecnt and where secondary's localcnt is smaller than
254204076Spjd	 * primary's remotecnt should be impossible in practise. We will perform
255218138Spjd	 * full synchronization then. Those cases are marked with an asterisk.
256204076Spjd	 * Regular synchronization means that only extents marked as dirty are
257204076Spjd	 * synchronized (regular synchronization).
258204076Spjd	 *
259214284Spjd	 * SECONDARY METADATA PRIMARY METADATA
260214284Spjd	 * local=3 remote=3   local=2 remote=2*  ?! Full sync from secondary.
261214284Spjd	 * local=3 remote=3   local=2 remote=3*  ?! Full sync from primary.
262214284Spjd	 * local=3 remote=3   local=2 remote=4*  ?! Full sync from primary.
263214284Spjd	 * local=3 remote=3   local=3 remote=2   Primary is out-of-date,
264214284Spjd	 *                                       regular sync from secondary.
265214284Spjd	 * local=3 remote=3   local=3 remote=3   Regular sync just in case.
266220865Spjd	 * local=3 remote=3   local=3 remote=4*  ?! Full sync from primary.
267204076Spjd	 * local=3 remote=3   local=4 remote=2   Split-brain condition.
268219830Spjd	 * local=3 remote=3   local=4 remote=3   Secondary out-of-date,
269219830Spjd	 *                                       regular sync from primary.
270219830Spjd	 * local=3 remote=3   local=4 remote=4*  ?! Full sync from primary.
271219830Spjd	 */
272219830Spjd	if (res->hr_resuid == 0) {
273219830Spjd		/*
274219830Spjd		 * Provider is used for the first time. If primary node done no
275219830Spjd		 * writes yet as well (we will find "virgin" argument) then
276219830Spjd		 * there is no need to synchronize anything. If primary node
277219830Spjd		 * done any writes already we have to synchronize everything.
278219830Spjd		 */
279219830Spjd		PJDLOG_ASSERT(res->hr_secondary_localcnt == 0);
280219831Spjd		res->hr_resuid = resuid;
281219830Spjd		if (metadata_write(res) == -1)
282204076Spjd			exit(EX_NOINPUT);
283204076Spjd		if (nv_exists(nvin, "virgin")) {
284204076Spjd			free(map);
285204076Spjd			map = NULL;
286219843Spjd			mapsize = 0;
287204076Spjd		} else {
288204076Spjd			memset(map, 0xff, mapsize);
289204076Spjd		}
290204076Spjd		nv_add_int8(nvout, 1, "virgin");
291204076Spjd		nv_add_uint8(nvout, HAST_SYNCSRC_PRIMARY, "syncsrc");
292204076Spjd	} else if (res->hr_resuid != resuid) {
293204076Spjd		char errmsg[256];
294204076Spjd
295204076Spjd		free(map);
296204076Spjd		(void)snprintf(errmsg, sizeof(errmsg),
297204076Spjd		    "Resource unique ID mismatch (primary=%ju, secondary=%ju).",
298204076Spjd		    (uintmax_t)resuid, (uintmax_t)res->hr_resuid);
299204076Spjd		pjdlog_error("%s", errmsg);
300204076Spjd		nv_add_string(nvout, errmsg, "errmsg");
301204076Spjd		if (hast_proto_send(res, res->hr_remotein, nvout,
302204076Spjd		    NULL, 0) == -1) {
303204076Spjd			pjdlog_exit(EX_TEMPFAIL,
304204076Spjd			    "Unable to send response to %s",
305204076Spjd			    res->hr_remoteaddr);
306204076Spjd		}
307204076Spjd		nv_free(nvout);
308204076Spjd		exit(EX_CONFIG);
309204076Spjd	} else if (
310204076Spjd	    /* Is primary out-of-date? */
311204076Spjd	    (res->hr_secondary_localcnt > res->hr_primary_remotecnt &&
312204076Spjd	     res->hr_secondary_remotecnt == res->hr_primary_localcnt) ||
313204076Spjd	    /* Are the nodes more or less in sync? */
314204076Spjd	    (res->hr_secondary_localcnt == res->hr_primary_remotecnt &&
315204076Spjd	     res->hr_secondary_remotecnt == res->hr_primary_localcnt) ||
316204076Spjd	    /* Is secondary out-of-date? */
317204076Spjd	    (res->hr_secondary_localcnt == res->hr_primary_remotecnt &&
318204076Spjd	     res->hr_secondary_remotecnt < res->hr_primary_localcnt)) {
319204076Spjd		/*
320204076Spjd		 * Nodes are more or less in sync or one of the nodes is
321204076Spjd		 * out-of-date.
322204076Spjd		 * It doesn't matter at this point which one, we just have to
323204076Spjd		 * send out local bitmap to the remote node.
324204076Spjd		 */
325204076Spjd		if (pread(res->hr_localfd, map, mapsize, METADATA_SIZE) !=
326204076Spjd		    (ssize_t)mapsize) {
327204076Spjd			pjdlog_exit(LOG_ERR, "Unable to read activemap");
328204076Spjd		}
329218138Spjd		if (res->hr_secondary_localcnt > res->hr_primary_remotecnt &&
330204076Spjd		     res->hr_secondary_remotecnt == res->hr_primary_localcnt) {
331204076Spjd			/* Primary is out-of-date, sync from secondary. */
332204076Spjd			nv_add_uint8(nvout, HAST_SYNCSRC_SECONDARY, "syncsrc");
333204076Spjd		} else {
334204076Spjd			/*
335204076Spjd			 * Secondary is out-of-date or counts match.
336204076Spjd			 * Sync from primary.
337204076Spjd			 */
338204076Spjd			nv_add_uint8(nvout, HAST_SYNCSRC_PRIMARY, "syncsrc");
339204076Spjd		}
340204076Spjd	} else if (res->hr_secondary_localcnt > res->hr_primary_remotecnt &&
341204076Spjd	     res->hr_primary_localcnt > res->hr_secondary_remotecnt) {
342204076Spjd		/*
343204076Spjd		 * Not good, we have split-brain condition.
344204076Spjd		 */
345204076Spjd		free(map);
346204076Spjd		pjdlog_error("Split-brain detected, exiting.");
347204076Spjd		nv_add_string(nvout, "Split-brain condition!", "errmsg");
348220007Spjd		if (hast_proto_send(res, res->hr_remotein, nvout,
349204076Spjd		    NULL, 0) == -1) {
350214276Spjd			pjdlog_exit(EX_TEMPFAIL,
351204076Spjd			    "Unable to send response to %s",
352204076Spjd			    res->hr_remoteaddr);
353214275Spjd		}
354214275Spjd		nv_free(nvout);
355209182Spjd		/* Exit on split-brain. */
356223181Strociny		event_send(res, EVENT_SPLITBRAIN);
357220271Spjd		exit(EX_CONFIG);
358220271Spjd	} else /* if (res->hr_secondary_localcnt < res->hr_primary_remotecnt ||
359220271Spjd	    res->hr_primary_localcnt < res->hr_secondary_remotecnt) */ {
360223181Strociny		/*
361204076Spjd		 * This should never happen in practise, but we will perform
362204076Spjd		 * full synchronization.
363204076Spjd		 */
364212038Spjd		PJDLOG_ASSERT(res->hr_secondary_localcnt < res->hr_primary_remotecnt ||
365204076Spjd		    res->hr_primary_localcnt < res->hr_secondary_remotecnt);
366204076Spjd		mapsize = activemap_calc_ondisk_size(res->hr_local_mediasize -
367204076Spjd		    METADATA_SIZE, res->hr_extentsize,
368204076Spjd		    res->hr_local_sectorsize);
369204076Spjd		memset(map, 0xff, mapsize);
370204076Spjd		if (res->hr_secondary_localcnt > res->hr_primary_remotecnt) {
371204076Spjd			/* In this one of five cases sync from secondary. */
372213009Spjd			nv_add_uint8(nvout, HAST_SYNCSRC_SECONDARY, "syncsrc");
373204076Spjd		} else {
374204076Spjd			/* For the rest four cases sync from primary. */
375219482Strociny			nv_add_uint8(nvout, HAST_SYNCSRC_PRIMARY, "syncsrc");
376204076Spjd		}
377204076Spjd		pjdlog_warning("This should never happen, asking for full synchronization (primary(local=%ju, remote=%ju), secondary(local=%ju, remote=%ju)).",
378204076Spjd		    (uintmax_t)res->hr_primary_localcnt,
379204076Spjd		    (uintmax_t)res->hr_primary_remotecnt,
380219818Spjd		    (uintmax_t)res->hr_secondary_localcnt,
381204076Spjd		    (uintmax_t)res->hr_secondary_remotecnt);
382204076Spjd	}
383204076Spjd	nv_add_uint32(nvout, (uint32_t)mapsize, "mapsize");
384204076Spjd	if (hast_proto_send(res, res->hr_remotein, nvout, map, mapsize) == -1) {
385212038Spjd		pjdlog_exit(EX_TEMPFAIL, "Unable to send activemap to %s",
386212038Spjd		    res->hr_remoteaddr);
387212038Spjd	}
388219818Spjd	if (map != NULL)
389212038Spjd		free(map);
390212038Spjd	nv_free(nvout);
391212038Spjd#ifdef notyet
392212038Spjd	/* Setup direction. */
393204076Spjd	if (proto_recv(res->hr_remotein, NULL, 0) == -1)
394204076Spjd		pjdlog_errno(LOG_WARNING, "Unable to set connection direction");
395204076Spjd#endif
396204076Spjd}
397204076Spjd
398204076Spjdvoid
399204076Spjdhastd_secondary(struct hast_resource *res, struct nv *nvin)
400204076Spjd{
401204076Spjd	sigset_t mask;
402204076Spjd	pthread_t td;
403204076Spjd	pid_t pid;
404204076Spjd	int error, mode, debuglevel;
405204076Spjd
406212038Spjd	/*
407212038Spjd	 * Create communication channel between parent and child.
408218043Spjd	 */
409218043Spjd	if (proto_client(NULL, "socketpair://", &res->hr_ctrl) == -1) {
410204076Spjd		KEEP_ERRNO((void)pidfile_remove(pfh));
411204076Spjd		pjdlog_exit(EX_OSERR,
412204076Spjd		    "Unable to create control sockets between parent and child");
413211977Spjd	}
414211984Spjd	/*
415218043Spjd	 * Create communication channel between child and parent.
416219482Strociny	 */
417211984Spjd	if (proto_client(NULL, "socketpair://", &res->hr_event) == -1) {
418218043Spjd		KEEP_ERRNO((void)pidfile_remove(pfh));
419218043Spjd		pjdlog_exit(EX_OSERR,
420218043Spjd		    "Unable to create event sockets between child and parent");
421218043Spjd	}
422218043Spjd
423204076Spjd	pid = fork();
424218045Spjd	if (pid == -1) {
425218045Spjd		KEEP_ERRNO((void)pidfile_remove(pfh));
426218043Spjd		pjdlog_exit(EX_OSERR, "Unable to fork");
427219482Strociny	}
428218043Spjd
429220005Spjd	if (pid > 0) {
430204076Spjd		/* This is parent. */
431213009Spjd		proto_close(res->hr_remotein);
432213009Spjd		res->hr_remotein = NULL;
433210880Spjd		proto_close(res->hr_remoteout);
434207371Spjd		res->hr_remoteout = NULL;
435219721Strociny		/* Declare that we are receiver. */
436207371Spjd		proto_recv(res->hr_event, NULL, 0);
437207371Spjd		/* Declare that we are sender. */
438207371Spjd		proto_send(res->hr_ctrl, NULL, 0);
439207371Spjd		res->hr_workerpid = pid;
440204076Spjd		return;
441213007Spjd	}
442213007Spjd
443221899Spjd	gres = res;
444218049Spjd	mode = pjdlog_mode_get();
445218214Spjd	debuglevel = pjdlog_debug_get();
446218049Spjd
447213007Spjd	/* Declare that we are sender. */
448213007Spjd	proto_send(res->hr_event, NULL, 0);
449213007Spjd	/* Declare that we are receiver. */
450213007Spjd	proto_recv(res->hr_ctrl, NULL, 0);
451213007Spjd	descriptors_cleanup(res);
452213007Spjd
453213007Spjd	descriptors_assert(res, mode);
454213007Spjd
455213007Spjd	pjdlog_init(mode);
456218138Spjd	pjdlog_debug_set(debuglevel);
457213007Spjd	pjdlog_prefix_set("[%s] (%s) ", res->hr_name, role2str(res->hr_role));
458204076Spjd	setproctitle("%s (%s)", res->hr_name, role2str(res->hr_role));
459212038Spjd
460204076Spjd	PJDLOG_VERIFY(sigemptyset(&mask) == 0);
461204076Spjd	PJDLOG_VERIFY(sigprocmask(SIG_SETMASK, &mask, NULL) == 0);
462218138Spjd
463204076Spjd	/* Error in setting timeout is not critical, but why should it fail? */
464218138Spjd	if (proto_timeout(res->hr_remotein, 2 * HAST_KEEPALIVE) == -1)
465213007Spjd		pjdlog_errno(LOG_WARNING, "Unable to set connection timeout");
466204076Spjd	if (proto_timeout(res->hr_remoteout, res->hr_timeout) == -1)
467204076Spjd		pjdlog_errno(LOG_WARNING, "Unable to set connection timeout");
468204076Spjd
469204076Spjd	init_local(res);
470204076Spjd	init_environment();
471204076Spjd
472204076Spjd	if (drop_privs(res) != 0)
473204076Spjd		exit(EX_CONFIG);
474204076Spjd	pjdlog_info("Privileges successfully dropped.");
475204076Spjd
476204076Spjd	/*
477204076Spjd	 * Create the control thread before sending any event to the parent,
478204076Spjd	 * as we can deadlock when parent sends control request to worker,
479204076Spjd	 * but worker has no control thread started yet, so parent waits.
480204076Spjd	 * In the meantime worker sends an event to the parent, but parent
481204076Spjd	 * is unable to handle the event, because it waits for control
482204076Spjd	 * request response.
483204076Spjd	 */
484204076Spjd	error = pthread_create(&td, NULL, ctrl_thread, res);
485204076Spjd	PJDLOG_ASSERT(error == 0);
486204076Spjd
487204076Spjd	init_remote(res, nvin);
488204076Spjd	event_send(res, EVENT_CONNECT);
489204076Spjd
490204076Spjd	error = pthread_create(&td, NULL, recv_thread, res);
491204076Spjd	PJDLOG_ASSERT(error == 0);
492204076Spjd	error = pthread_create(&td, NULL, disk_thread, res);
493204076Spjd	PJDLOG_ASSERT(error == 0);
494204076Spjd	(void)send_thread(res);
495204076Spjd}
496204076Spjd
497204076Spjdstatic void
498211882Spjdreqlog(int loglevel, int debuglevel, int error, struct hio *hio,
499211882Spjd    const char *fmt, ...)
500211882Spjd{
501204076Spjd	char msg[1024];
502204076Spjd	va_list ap;
503204076Spjd	int len;
504204076Spjd
505204076Spjd	va_start(ap, fmt);
506204076Spjd	len = vsnprintf(msg, sizeof(msg), fmt, ap);
507204076Spjd	va_end(ap);
508204076Spjd	if ((size_t)len < sizeof(msg)) {
509204076Spjd		switch (hio->hio_cmd) {
510204076Spjd		case HIO_READ:
511204076Spjd			(void)snprintf(msg + len, sizeof(msg) - len,
512204076Spjd			    "READ(%ju, %ju).", (uintmax_t)hio->hio_offset,
513204076Spjd			    (uintmax_t)hio->hio_length);
514204076Spjd			break;
515204076Spjd		case HIO_DELETE:
516204076Spjd			(void)snprintf(msg + len, sizeof(msg) - len,
517204076Spjd			    "DELETE(%ju, %ju).", (uintmax_t)hio->hio_offset,
518204076Spjd			    (uintmax_t)hio->hio_length);
519204076Spjd			break;
520204076Spjd		case HIO_FLUSH:
521222164Spjd			(void)snprintf(msg + len, sizeof(msg) - len, "FLUSH.");
522211882Spjd			break;
523211882Spjd		case HIO_WRITE:
524204076Spjd			(void)snprintf(msg + len, sizeof(msg) - len,
525204076Spjd			    "WRITE(%ju, %ju).", (uintmax_t)hio->hio_offset,
526204076Spjd			    (uintmax_t)hio->hio_length);
527204076Spjd			break;
528204076Spjd		case HIO_KEEPALIVE:
529204076Spjd			(void)snprintf(msg + len, sizeof(msg) - len, "KEEPALIVE.");
530204076Spjd			break;
531204076Spjd		default:
532204076Spjd			(void)snprintf(msg + len, sizeof(msg) - len,
533204076Spjd			    "UNKNOWN(%u).", (unsigned int)hio->hio_cmd);
534204076Spjd			break;
535204076Spjd		}
536204076Spjd	}
537204076Spjd	pjdlog_common(loglevel, debuglevel, error, "%s", msg);
538204076Spjd}
539204076Spjd
540204076Spjdstatic int
541204076Spjdrequnpack(struct hast_resource *res, struct hio *hio, struct nv *nv)
542204076Spjd{
543204076Spjd
544204076Spjd	hio->hio_cmd = nv_get_uint8(nv, "cmd");
545204076Spjd	if (hio->hio_cmd == 0) {
546204076Spjd		pjdlog_error("Header contains no 'cmd' field.");
547204076Spjd		hio->hio_error = EINVAL;
548204076Spjd		goto end;
549204076Spjd	}
550204076Spjd	if (hio->hio_cmd != HIO_KEEPALIVE) {
551204076Spjd		hio->hio_seq = nv_get_uint64(nv, "seq");
552204076Spjd		if (hio->hio_seq == 0) {
553204076Spjd			pjdlog_error("Header contains no 'seq' field.");
554204076Spjd			hio->hio_error = EINVAL;
555204076Spjd			goto end;
556204076Spjd		}
557204076Spjd	}
558204076Spjd	switch (hio->hio_cmd) {
559204076Spjd	case HIO_FLUSH:
560204076Spjd	case HIO_KEEPALIVE:
561204076Spjd		break;
562204076Spjd	case HIO_WRITE:
563204076Spjd		hio->hio_memsync = nv_exists(nv, "memsync");
564204076Spjd		/* FALLTHROUGH */
565204076Spjd	case HIO_READ:
566204076Spjd	case HIO_DELETE:
567204076Spjd		hio->hio_offset = nv_get_uint64(nv, "offset");
568204076Spjd		if (nv_error(nv) != 0) {
569204076Spjd			pjdlog_error("Header is missing 'offset' field.");
570204076Spjd			hio->hio_error = EINVAL;
571204076Spjd			goto end;
572204076Spjd		}
573204076Spjd		hio->hio_length = nv_get_uint64(nv, "length");
574204076Spjd		if (nv_error(nv) != 0) {
575204076Spjd			pjdlog_error("Header is missing 'length' field.");
576204076Spjd			hio->hio_error = EINVAL;
577204076Spjd			goto end;
578204076Spjd		}
579204076Spjd		if (hio->hio_length == 0) {
580204076Spjd			pjdlog_error("Data length is zero.");
581204076Spjd			hio->hio_error = EINVAL;
582212899Spjd			goto end;
583211984Spjd		}
584211984Spjd		if (hio->hio_cmd != HIO_DELETE && hio->hio_length > MAXPHYS) {
585211984Spjd			pjdlog_error("Data length is too large (%ju > %ju).",
586211984Spjd			    (uintmax_t)hio->hio_length, (uintmax_t)MAXPHYS);
587218138Spjd			hio->hio_error = EINVAL;
588211984Spjd			goto end;
589211984Spjd		}
590211984Spjd		if ((hio->hio_offset % res->hr_local_sectorsize) != 0) {
591212038Spjd			pjdlog_error("Offset %ju is not multiple of sector size.",
592211984Spjd			    (uintmax_t)hio->hio_offset);
593211984Spjd			hio->hio_error = EINVAL;
594211984Spjd			goto end;
595204076Spjd		}
596204076Spjd		if ((hio->hio_length % res->hr_local_sectorsize) != 0) {
597204076Spjd			pjdlog_error("Length %ju is not multiple of sector size.",
598204076Spjd			    (uintmax_t)hio->hio_length);
599204076Spjd			hio->hio_error = EINVAL;
600204076Spjd			goto end;
601204076Spjd		}
602204076Spjd		if (hio->hio_offset + hio->hio_length >
603204076Spjd		    (uint64_t)res->hr_datasize) {
604204076Spjd			pjdlog_error("Data offset is too large (%ju > %ju).",
605204076Spjd			    (uintmax_t)(hio->hio_offset + hio->hio_length),
606211877Spjd			    (uintmax_t)res->hr_datasize);
607204076Spjd			hio->hio_error = EINVAL;
608204076Spjd			goto end;
609211984Spjd		}
610204076Spjd		break;
611204076Spjd	default:
612211877Spjd		pjdlog_error("Header contains invalid 'cmd' (%hhu).",
613211877Spjd		    hio->hio_cmd);
614211877Spjd		hio->hio_error = EINVAL;
615211877Spjd		goto end;
616211877Spjd	}
617211877Spjd	hio->hio_error = 0;
618211877Spjdend:
619222228Spjd	return (hio->hio_error);
620222228Spjd}
621222228Spjd
622222228Spjdstatic __dead2 void
623222228Spjdsecondary_exit(int exitcode, const char *fmt, ...)
624222228Spjd{
625222228Spjd	va_list ap;
626222228Spjd
627222228Spjd	PJDLOG_ASSERT(exitcode != EX_OK);
628222228Spjd	va_start(ap, fmt);
629222228Spjd	pjdlogv_errno(LOG_ERR, fmt, ap);
630222228Spjd	va_end(ap);
631222228Spjd	event_send(gres, EVENT_DISCONNECT);
632222228Spjd	exit(exitcode);
633204076Spjd}
634204076Spjd
635211882Spjd/*
636211882Spjd * Thread receives requests from the primary node.
637211882Spjd */
638211882Spjdstatic void *
639211882Spjdrecv_thread(void *arg)
640211882Spjd{
641211882Spjd	struct hast_resource *res = arg;
642211882Spjd	struct hio *hio, *mshio;
643204076Spjd	struct nv *nv;
644204076Spjd
645211984Spjd	for (;;) {
646212051Spjd		pjdlog_debug(2, "recv: Taking free request.");
647204076Spjd		QUEUE_TAKE(free, hio);
648204076Spjd		pjdlog_debug(2, "recv: (%p) Got request.", hio);
649204076Spjd		if (hast_proto_recv_hdr(res->hr_remotein, &nv) == -1) {
650204076Spjd			secondary_exit(EX_TEMPFAIL,
651211877Spjd			    "Unable to receive request header");
652204076Spjd		}
653204076Spjd		if (requnpack(res, hio, nv) != 0) {
654204076Spjd			nv_free(nv);
655204076Spjd			pjdlog_debug(2,
656204076Spjd			    "recv: (%p) Moving request to the send queue.",
657204076Spjd			    hio);
658204076Spjd			QUEUE_INSERT(send, hio);
659204076Spjd			continue;
660204076Spjd		}
661204076Spjd		switch (hio->hio_cmd) {
662204076Spjd		case HIO_READ:
663204076Spjd			res->hr_stat_read++;
664204076Spjd			break;
665204076Spjd		case HIO_WRITE:
666204076Spjd			res->hr_stat_write++;
667211877Spjd			break;
668204076Spjd		case HIO_DELETE:
669204076Spjd			res->hr_stat_delete++;
670204076Spjd			break;
671204076Spjd		case HIO_FLUSH:
672204076Spjd			res->hr_stat_flush++;
673211877Spjd			break;
674204076Spjd		case HIO_KEEPALIVE:
675204076Spjd			break;
676204076Spjd		default:
677204076Spjd			PJDLOG_ABORT("Unexpected command (cmd=%hhu).",
678204076Spjd			    hio->hio_cmd);
679204076Spjd		}
680204076Spjd		reqlog(LOG_DEBUG, 2, -1, hio,
681204076Spjd		    "recv: (%p) Got request header: ", hio);
682204076Spjd		if (hio->hio_cmd == HIO_KEEPALIVE) {
683204076Spjd			nv_free(nv);
684204076Spjd			pjdlog_debug(2,
685204076Spjd			    "recv: (%p) Moving request to the free queue.",
686204076Spjd			    hio);
687204076Spjd			hio_clear(hio);
688204076Spjd			QUEUE_INSERT(free, hio);
689204076Spjd			continue;
690204076Spjd		} else if (hio->hio_cmd == HIO_WRITE) {
691204076Spjd			if (hast_proto_recv_data(res, res->hr_remotein, nv,
692204076Spjd			    hio->hio_data, MAXPHYS) == -1) {
693204076Spjd				secondary_exit(EX_TEMPFAIL,
694204076Spjd				    "Unable to receive request data");
695204076Spjd			}
696204076Spjd			if (hio->hio_memsync) {
697204076Spjd				/*
698204076Spjd				 * For memsync requests we expect two replies.
699204076Spjd				 * Clone the hio so we can handle both of them.
700204076Spjd				 */
701204076Spjd				pjdlog_debug(2, "recv: Taking free request.");
702204076Spjd				QUEUE_TAKE(free, mshio);
703204076Spjd				pjdlog_debug(2, "recv: (%p) Got request.",
704204076Spjd				    mshio);
705204076Spjd				hio_copy(hio, mshio);
706204076Spjd				mshio->hio_error = 0;
707204076Spjd				/*
708204076Spjd				 * We want to keep 'memsync' tag only on the
709204076Spjd				 * request going onto send queue (mshio).
710204076Spjd				 */
711204076Spjd				hio->hio_memsync = false;
712204076Spjd				pjdlog_debug(2,
713204076Spjd				    "recv: (%p) Moving memsync request to the send queue.",
714204076Spjd				    mshio);
715204076Spjd				QUEUE_INSERT(send, mshio);
716204076Spjd			}
717204076Spjd		}
718204076Spjd		nv_free(nv);
719204076Spjd		pjdlog_debug(2, "recv: (%p) Moving request to the disk queue.",
720204076Spjd		    hio);
721204076Spjd		QUEUE_INSERT(disk, hio);
722204076Spjd	}
723204076Spjd	/* NOTREACHED */
724204076Spjd	return (NULL);
725204076Spjd}
726204076Spjd
727204076Spjd/*
728204076Spjd * Thread reads from or writes to local component and also handles DELETE and
729204076Spjd * FLUSH requests.
730204076Spjd */
731204076Spjdstatic void *
732204076Spjddisk_thread(void *arg)
733204076Spjd{
734204076Spjd	struct hast_resource *res = arg;
735204076Spjd	struct hio *hio;
736204076Spjd	ssize_t ret;
737204076Spjd	bool clear_activemap, logerror;
738204076Spjd
739204076Spjd	clear_activemap = true;
740204076Spjd
741204076Spjd	for (;;) {
742204076Spjd		pjdlog_debug(2, "disk: Taking request.");
743204076Spjd		QUEUE_TAKE(disk, hio);
744204076Spjd		while (clear_activemap) {
745204076Spjd			unsigned char *map;
746204076Spjd			size_t mapsize;
747204076Spjd
748204076Spjd			/*
749204076Spjd			 * When first request is received, it means that primary
750204076Spjd			 * already received our activemap, merged it and stored
751211877Spjd			 * locally. We can now safely clear our activemap.
752204076Spjd			 */
753204076Spjd			mapsize =
754204076Spjd			    activemap_calc_ondisk_size(res->hr_local_mediasize -
755204076Spjd			    METADATA_SIZE, res->hr_extentsize,
756204076Spjd			    res->hr_local_sectorsize);
757204076Spjd			map = calloc(1, mapsize);
758204076Spjd			if (map == NULL) {
759204076Spjd				pjdlog_warning("Unable to allocate memory to clear local activemap.");
760204076Spjd				break;
761204076Spjd			}
762204076Spjd			if (pwrite(res->hr_localfd, map, mapsize,
763204076Spjd			    METADATA_SIZE) != (ssize_t)mapsize) {
764204076Spjd				pjdlog_errno(LOG_WARNING,
765204076Spjd				    "Unable to store cleared activemap");
766204076Spjd				free(map);
767204076Spjd				res->hr_stat_activemap_write_error++;
768204076Spjd				break;
769204076Spjd			}
770204076Spjd			free(map);
771211877Spjd			clear_activemap = false;
772204076Spjd			pjdlog_debug(1, "Local activemap cleared.");
773204076Spjd			break;
774204076Spjd		}
775204076Spjd		reqlog(LOG_DEBUG, 2, -1, hio, "disk: (%p) Got request: ", hio);
776204076Spjd		logerror = true;
777204076Spjd		/* Handle the actual request. */
778204076Spjd		switch (hio->hio_cmd) {
779204076Spjd		case HIO_READ:
780204076Spjd			ret = pread(res->hr_localfd, hio->hio_data,
781204076Spjd			    hio->hio_length,
782204076Spjd			    hio->hio_offset + res->hr_localoff);
783204076Spjd			if (ret == -1)
784204076Spjd				hio->hio_error = errno;
785204076Spjd			else if (ret != (int64_t)hio->hio_length)
786204076Spjd				hio->hio_error = EIO;
787204076Spjd			else
788204076Spjd				hio->hio_error = 0;
789204076Spjd			break;
790204076Spjd		case HIO_WRITE:
791204076Spjd			ret = pwrite(res->hr_localfd, hio->hio_data,
792204076Spjd			    hio->hio_length,
793204076Spjd			    hio->hio_offset + res->hr_localoff);
794225782Spjd			if (ret == -1)
795225782Spjd				hio->hio_error = errno;
796204076Spjd			else if (ret != (int64_t)hio->hio_length)
797204076Spjd				hio->hio_error = EIO;
798204076Spjd			else
799204076Spjd				hio->hio_error = 0;
800204076Spjd			break;
801211984Spjd		case HIO_DELETE:
802204076Spjd			ret = g_delete(res->hr_localfd,
803204076Spjd			    hio->hio_offset + res->hr_localoff,
804209185Spjd			    hio->hio_length);
805204076Spjd			if (ret == -1)
806204076Spjd				hio->hio_error = errno;
807204076Spjd			else
808211877Spjd				hio->hio_error = 0;
809204076Spjd			break;
810204076Spjd		case HIO_FLUSH:
811204076Spjd			if (!res->hr_localflush) {
812204076Spjd				ret = -1;
813				hio->hio_error = EOPNOTSUPP;
814				logerror = false;
815				break;
816			}
817			ret = g_flush(res->hr_localfd);
818			if (ret == -1) {
819				if (errno == EOPNOTSUPP)
820					res->hr_localflush = false;
821				hio->hio_error = errno;
822			} else {
823				hio->hio_error = 0;
824			}
825			break;
826		default:
827			PJDLOG_ABORT("Unexpected command (cmd=%hhu).",
828			    hio->hio_cmd);
829		}
830		if (logerror && hio->hio_error != 0) {
831			reqlog(LOG_ERR, 0, hio->hio_error, hio,
832			    "Request failed: ");
833		}
834		pjdlog_debug(2, "disk: (%p) Moving request to the send queue.",
835		    hio);
836		QUEUE_INSERT(send, hio);
837	}
838	/* NOTREACHED */
839	return (NULL);
840}
841
842/*
843 * Thread sends requests back to primary node.
844 */
845static void *
846send_thread(void *arg)
847{
848	struct hast_resource *res = arg;
849	struct nv *nvout;
850	struct hio *hio;
851	void *data;
852	size_t length;
853
854	for (;;) {
855		pjdlog_debug(2, "send: Taking request.");
856		QUEUE_TAKE(send, hio);
857		reqlog(LOG_DEBUG, 2, -1, hio, "send: (%p) Got request: ", hio);
858		nvout = nv_alloc();
859		/* Copy sequence number. */
860		nv_add_uint64(nvout, hio->hio_seq, "seq");
861		if (hio->hio_memsync) {
862			PJDLOG_ASSERT(hio->hio_cmd == HIO_WRITE);
863			nv_add_int8(nvout, 1, "received");
864		}
865		switch (hio->hio_cmd) {
866		case HIO_READ:
867			if (hio->hio_error == 0) {
868				data = hio->hio_data;
869				length = hio->hio_length;
870				break;
871			}
872			/*
873			 * We send no data in case of an error.
874			 */
875			/* FALLTHROUGH */
876		case HIO_DELETE:
877		case HIO_FLUSH:
878		case HIO_WRITE:
879			data = NULL;
880			length = 0;
881			break;
882		default:
883			PJDLOG_ABORT("Unexpected command (cmd=%hhu).",
884			    hio->hio_cmd);
885		}
886		if (hio->hio_error != 0) {
887			switch (hio->hio_cmd) {
888			case HIO_READ:
889				res->hr_stat_read_error++;
890				break;
891			case HIO_WRITE:
892				res->hr_stat_write_error++;
893				break;
894			case HIO_DELETE:
895				res->hr_stat_delete_error++;
896				break;
897			case HIO_FLUSH:
898				res->hr_stat_flush_error++;
899				break;
900			}
901			nv_add_int16(nvout, hio->hio_error, "error");
902		}
903		if (hast_proto_send(res, res->hr_remoteout, nvout, data,
904		    length) == -1) {
905			secondary_exit(EX_TEMPFAIL, "Unable to send reply");
906		}
907		nv_free(nvout);
908		pjdlog_debug(2, "send: (%p) Moving request to the free queue.",
909		    hio);
910		hio_clear(hio);
911		QUEUE_INSERT(free, hio);
912	}
913	/* NOTREACHED */
914	return (NULL);
915}
916