secondary.c revision 246922
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: head/sbin/hastd/secondary.c 246922 2013-02-17 21:12:34Z pjd $");
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;
74246922Spjd	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 do 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 * There is one recv list for every component, although local components don't
95204076Spjd * use recv lists as local requests are done synchronously.
96204076Spjd */
97204076Spjdstatic TAILQ_HEAD(, hio) hio_send_list;
98204076Spjdstatic pthread_mutex_t hio_send_list_lock;
99204076Spjdstatic pthread_cond_t hio_send_list_cond;
100204076Spjd
101204076Spjd/*
102204076Spjd * Maximum number of outstanding I/O requests.
103204076Spjd */
104204076Spjd#define	HAST_HIO_MAX	256
105204076Spjd
106204076Spjdstatic void *recv_thread(void *arg);
107204076Spjdstatic void *disk_thread(void *arg);
108204076Spjdstatic void *send_thread(void *arg);
109204076Spjd
110211877Spjd#define	QUEUE_INSERT(name, hio)	do {					\
111211877Spjd	bool _wakeup;							\
112211877Spjd									\
113211877Spjd	mtx_lock(&hio_##name##_list_lock);				\
114211877Spjd	_wakeup = TAILQ_EMPTY(&hio_##name##_list);			\
115211877Spjd	TAILQ_INSERT_TAIL(&hio_##name##_list, (hio), hio_next);		\
116211877Spjd	mtx_unlock(&hio_##name##_list_lock);				\
117211877Spjd	if (_wakeup)							\
118211877Spjd		cv_signal(&hio_##name##_list_cond);			\
119211877Spjd} while (0)
120211877Spjd#define	QUEUE_TAKE(name, hio)	do {					\
121211877Spjd	mtx_lock(&hio_##name##_list_lock);				\
122211877Spjd	while (((hio) = TAILQ_FIRST(&hio_##name##_list)) == NULL) {	\
123211877Spjd		cv_wait(&hio_##name##_list_cond,			\
124211877Spjd		    &hio_##name##_list_lock);				\
125211877Spjd	}								\
126211877Spjd	TAILQ_REMOVE(&hio_##name##_list, (hio), hio_next);		\
127211877Spjd	mtx_unlock(&hio_##name##_list_lock);				\
128211877Spjd} while (0)
129226861Spjd
130226854Spjdstatic void
131226854Spjdhio_clear(struct hio *hio)
132226854Spjd{
133211877Spjd
134226854Spjd	hio->hio_seq = 0;
135226854Spjd	hio->hio_error = 0;
136226854Spjd	hio->hio_cmd = HIO_UNDEF;
137226854Spjd	hio->hio_offset = 0;
138226854Spjd	hio->hio_length = 0;
139246922Spjd	hio->hio_memsync = false;
140226854Spjd}
141226854Spjd
142204076Spjdstatic void
143246922Spjdhio_copy(const struct hio *srchio, struct hio *dsthio)
144246922Spjd{
145246922Spjd
146246922Spjd	/*
147246922Spjd	 * We don't copy hio_error, hio_data and hio_next fields.
148246922Spjd	 */
149246922Spjd
150246922Spjd	dsthio->hio_seq = srchio->hio_seq;
151246922Spjd	dsthio->hio_cmd = srchio->hio_cmd;
152246922Spjd	dsthio->hio_offset = srchio->hio_offset;
153246922Spjd	dsthio->hio_length = srchio->hio_length;
154246922Spjd	dsthio->hio_memsync = srchio->hio_memsync;
155246922Spjd}
156246922Spjd
157246922Spjdstatic void
158204076Spjdinit_environment(void)
159204076Spjd{
160204076Spjd	struct hio *hio;
161204076Spjd	unsigned int ii;
162204076Spjd
163204076Spjd	/*
164204076Spjd	 * Initialize lists, their locks and theirs condition variables.
165204076Spjd	 */
166204076Spjd	TAILQ_INIT(&hio_free_list);
167204076Spjd	mtx_init(&hio_free_list_lock);
168204076Spjd	cv_init(&hio_free_list_cond);
169204076Spjd	TAILQ_INIT(&hio_disk_list);
170204076Spjd	mtx_init(&hio_disk_list_lock);
171204076Spjd	cv_init(&hio_disk_list_cond);
172204076Spjd	TAILQ_INIT(&hio_send_list);
173204076Spjd	mtx_init(&hio_send_list_lock);
174204076Spjd	cv_init(&hio_send_list_cond);
175204076Spjd
176204076Spjd	/*
177204076Spjd	 * Allocate requests pool and initialize requests.
178204076Spjd	 */
179204076Spjd	for (ii = 0; ii < HAST_HIO_MAX; ii++) {
180204076Spjd		hio = malloc(sizeof(*hio));
181204076Spjd		if (hio == NULL) {
182210879Spjd			pjdlog_exitx(EX_TEMPFAIL,
183210879Spjd			    "Unable to allocate memory (%zu bytes) for hio request.",
184210879Spjd			    sizeof(*hio));
185204076Spjd		}
186204076Spjd		hio->hio_data = malloc(MAXPHYS);
187204076Spjd		if (hio->hio_data == NULL) {
188210879Spjd			pjdlog_exitx(EX_TEMPFAIL,
189210879Spjd			    "Unable to allocate memory (%zu bytes) for gctl_data.",
190210879Spjd			    (size_t)MAXPHYS);
191204076Spjd		}
192226854Spjd		hio_clear(hio);
193204076Spjd		TAILQ_INSERT_HEAD(&hio_free_list, hio, hio_next);
194204076Spjd	}
195204076Spjd}
196204076Spjd
197204076Spjdstatic void
198204076Spjdinit_local(struct hast_resource *res)
199204076Spjd{
200204076Spjd
201229945Spjd	if (metadata_read(res, true) == -1)
202204076Spjd		exit(EX_NOINPUT);
203204076Spjd}
204204076Spjd
205204076Spjdstatic void
206204076Spjdinit_remote(struct hast_resource *res, struct nv *nvin)
207204076Spjd{
208204076Spjd	uint64_t resuid;
209204076Spjd	struct nv *nvout;
210204076Spjd	unsigned char *map;
211204076Spjd	size_t mapsize;
212204076Spjd
213223181Strociny#ifdef notyet
214220271Spjd	/* Setup direction. */
215220271Spjd	if (proto_send(res->hr_remoteout, NULL, 0) == -1)
216220271Spjd		pjdlog_errno(LOG_WARNING, "Unable to set connection direction");
217223181Strociny#endif
218220271Spjd
219204076Spjd	nvout = nv_alloc();
220204076Spjd	nv_add_int64(nvout, (int64_t)res->hr_datasize, "datasize");
221204076Spjd	nv_add_int32(nvout, (int32_t)res->hr_extentsize, "extentsize");
222204076Spjd	resuid = nv_get_uint64(nvin, "resuid");
223204076Spjd	res->hr_primary_localcnt = nv_get_uint64(nvin, "localcnt");
224204076Spjd	res->hr_primary_remotecnt = nv_get_uint64(nvin, "remotecnt");
225204076Spjd	nv_add_uint64(nvout, res->hr_secondary_localcnt, "localcnt");
226204076Spjd	nv_add_uint64(nvout, res->hr_secondary_remotecnt, "remotecnt");
227204076Spjd	mapsize = activemap_calc_ondisk_size(res->hr_local_mediasize -
228204076Spjd	    METADATA_SIZE, res->hr_extentsize, res->hr_local_sectorsize);
229204076Spjd	map = malloc(mapsize);
230204076Spjd	if (map == NULL) {
231204076Spjd		pjdlog_exitx(EX_TEMPFAIL,
232204076Spjd		    "Unable to allocate memory (%zu bytes) for activemap.",
233204076Spjd		    mapsize);
234204076Spjd	}
235204076Spjd	/*
236204076Spjd	 * When we work as primary and secondary is missing we will increase
237204076Spjd	 * localcnt in our metadata. When secondary is connected and synced
238204076Spjd	 * we make localcnt be equal to remotecnt, which means nodes are more
239204076Spjd	 * or less in sync.
240204076Spjd	 * Split-brain condition is when both nodes are not able to communicate
241204076Spjd	 * and are both configured as primary nodes. In turn, they can both
242204076Spjd	 * make incompatible changes to the data and we have to detect that.
243204076Spjd	 * Under split-brain condition we will increase our localcnt on first
244204076Spjd	 * write and remote node will increase its localcnt on first write.
245204076Spjd	 * When we connect we can see that primary's localcnt is greater than
246204076Spjd	 * our remotecnt (primary was modified while we weren't watching) and
247204076Spjd	 * our localcnt is greater than primary's remotecnt (we were modified
248204076Spjd	 * while primary wasn't watching).
249204076Spjd	 * There are many possible combinations which are all gathered below.
250204076Spjd	 * Don't pay too much attention to exact numbers, the more important
251204076Spjd	 * is to compare them. We compare secondary's local with primary's
252204076Spjd	 * remote and secondary's remote with primary's local.
253204076Spjd	 * Note that every case where primary's localcnt is smaller than
254204076Spjd	 * secondary's remotecnt and where secondary's localcnt is smaller than
255204076Spjd	 * primary's remotecnt should be impossible in practise. We will perform
256204076Spjd	 * full synchronization then. Those cases are marked with an asterisk.
257204076Spjd	 * Regular synchronization means that only extents marked as dirty are
258204076Spjd	 * synchronized (regular synchronization).
259204076Spjd	 *
260204076Spjd	 * SECONDARY METADATA PRIMARY METADATA
261204076Spjd	 * local=3 remote=3   local=2 remote=2*  ?! Full sync from secondary.
262204076Spjd	 * local=3 remote=3   local=2 remote=3*  ?! Full sync from primary.
263204076Spjd	 * local=3 remote=3   local=2 remote=4*  ?! Full sync from primary.
264204076Spjd	 * local=3 remote=3   local=3 remote=2   Primary is out-of-date,
265204076Spjd	 *                                       regular sync from secondary.
266204076Spjd	 * local=3 remote=3   local=3 remote=3   Regular sync just in case.
267204076Spjd	 * local=3 remote=3   local=3 remote=4*  ?! Full sync from primary.
268204076Spjd	 * local=3 remote=3   local=4 remote=2   Split-brain condition.
269204076Spjd	 * local=3 remote=3   local=4 remote=3   Secondary out-of-date,
270204076Spjd	 *                                       regular sync from primary.
271204076Spjd	 * local=3 remote=3   local=4 remote=4*  ?! Full sync from primary.
272204076Spjd	 */
273204076Spjd	if (res->hr_resuid == 0) {
274204076Spjd		/*
275214284Spjd		 * Provider is used for the first time. If primary node done no
276214284Spjd		 * writes yet as well (we will find "virgin" argument) then
277214284Spjd		 * there is no need to synchronize anything. If primary node
278214284Spjd		 * done any writes already we have to synchronize everything.
279204076Spjd		 */
280218138Spjd		PJDLOG_ASSERT(res->hr_secondary_localcnt == 0);
281204076Spjd		res->hr_resuid = resuid;
282229945Spjd		if (metadata_write(res) == -1)
283204076Spjd			exit(EX_NOINPUT);
284214284Spjd		if (nv_exists(nvin, "virgin")) {
285214284Spjd			free(map);
286214284Spjd			map = NULL;
287214284Spjd			mapsize = 0;
288214284Spjd		} else {
289214284Spjd			memset(map, 0xff, mapsize);
290214284Spjd		}
291220865Spjd		nv_add_int8(nvout, 1, "virgin");
292204076Spjd		nv_add_uint8(nvout, HAST_SYNCSRC_PRIMARY, "syncsrc");
293219830Spjd	} else if (res->hr_resuid != resuid) {
294219830Spjd		char errmsg[256];
295219830Spjd
296226854Spjd		free(map);
297219830Spjd		(void)snprintf(errmsg, sizeof(errmsg),
298219830Spjd		    "Resource unique ID mismatch (primary=%ju, secondary=%ju).",
299219830Spjd		    (uintmax_t)resuid, (uintmax_t)res->hr_resuid);
300219830Spjd		pjdlog_error("%s", errmsg);
301219830Spjd		nv_add_string(nvout, errmsg, "errmsg");
302230092Spjd		if (hast_proto_send(res, res->hr_remotein, nvout,
303230092Spjd		    NULL, 0) == -1) {
304230092Spjd			pjdlog_exit(EX_TEMPFAIL,
305230092Spjd			    "Unable to send response to %s",
306219830Spjd			    res->hr_remoteaddr);
307219830Spjd		}
308219831Spjd		nv_free(nvout);
309219830Spjd		exit(EX_CONFIG);
310204076Spjd	} else if (
311226842Spjd	    /* Is primary out-of-date? */
312204076Spjd	    (res->hr_secondary_localcnt > res->hr_primary_remotecnt &&
313204076Spjd	     res->hr_secondary_remotecnt == res->hr_primary_localcnt) ||
314226842Spjd	    /* Are the nodes more or less in sync? */
315204076Spjd	    (res->hr_secondary_localcnt == res->hr_primary_remotecnt &&
316204076Spjd	     res->hr_secondary_remotecnt == res->hr_primary_localcnt) ||
317226842Spjd	    /* Is secondary out-of-date? */
318204076Spjd	    (res->hr_secondary_localcnt == res->hr_primary_remotecnt &&
319204076Spjd	     res->hr_secondary_remotecnt < res->hr_primary_localcnt)) {
320204076Spjd		/*
321204076Spjd		 * Nodes are more or less in sync or one of the nodes is
322204076Spjd		 * out-of-date.
323204076Spjd		 * It doesn't matter at this point which one, we just have to
324204076Spjd		 * send out local bitmap to the remote node.
325204076Spjd		 */
326204076Spjd		if (pread(res->hr_localfd, map, mapsize, METADATA_SIZE) !=
327204076Spjd		    (ssize_t)mapsize) {
328204076Spjd			pjdlog_exit(LOG_ERR, "Unable to read activemap");
329204076Spjd		}
330204076Spjd		if (res->hr_secondary_localcnt > res->hr_primary_remotecnt &&
331204076Spjd		     res->hr_secondary_remotecnt == res->hr_primary_localcnt) {
332204076Spjd			/* Primary is out-of-date, sync from secondary. */
333204076Spjd			nv_add_uint8(nvout, HAST_SYNCSRC_SECONDARY, "syncsrc");
334204076Spjd		} else {
335204076Spjd			/*
336204076Spjd			 * Secondary is out-of-date or counts match.
337204076Spjd			 * Sync from primary.
338204076Spjd			 */
339204076Spjd			nv_add_uint8(nvout, HAST_SYNCSRC_PRIMARY, "syncsrc");
340204076Spjd		}
341204076Spjd	} else if (res->hr_secondary_localcnt > res->hr_primary_remotecnt &&
342204076Spjd	     res->hr_primary_localcnt > res->hr_secondary_remotecnt) {
343204076Spjd		/*
344204076Spjd		 * Not good, we have split-brain condition.
345204076Spjd		 */
346226854Spjd		free(map);
347204076Spjd		pjdlog_error("Split-brain detected, exiting.");
348204076Spjd		nv_add_string(nvout, "Split-brain condition!", "errmsg");
349230092Spjd		if (hast_proto_send(res, res->hr_remotein, nvout,
350230092Spjd		    NULL, 0) == -1) {
351230092Spjd			pjdlog_exit(EX_TEMPFAIL,
352230092Spjd			    "Unable to send response to %s",
353226854Spjd			    res->hr_remoteaddr);
354226854Spjd		}
355226854Spjd		nv_free(nvout);
356226854Spjd		/* Exit on split-brain. */
357226854Spjd		event_send(res, EVENT_SPLITBRAIN);
358226854Spjd		exit(EX_CONFIG);
359204076Spjd	} else /* if (res->hr_secondary_localcnt < res->hr_primary_remotecnt ||
360204076Spjd	    res->hr_primary_localcnt < res->hr_secondary_remotecnt) */ {
361204076Spjd		/*
362204076Spjd		 * This should never happen in practise, but we will perform
363204076Spjd		 * full synchronization.
364204076Spjd		 */
365218138Spjd		PJDLOG_ASSERT(res->hr_secondary_localcnt < res->hr_primary_remotecnt ||
366204076Spjd		    res->hr_primary_localcnt < res->hr_secondary_remotecnt);
367204076Spjd		mapsize = activemap_calc_ondisk_size(res->hr_local_mediasize -
368204076Spjd		    METADATA_SIZE, res->hr_extentsize,
369204076Spjd		    res->hr_local_sectorsize);
370204076Spjd		memset(map, 0xff, mapsize);
371204076Spjd		if (res->hr_secondary_localcnt > res->hr_primary_remotecnt) {
372204076Spjd			/* In this one of five cases sync from secondary. */
373204076Spjd			nv_add_uint8(nvout, HAST_SYNCSRC_SECONDARY, "syncsrc");
374204076Spjd		} else {
375204076Spjd			/* For the rest four cases sync from primary. */
376204076Spjd			nv_add_uint8(nvout, HAST_SYNCSRC_PRIMARY, "syncsrc");
377204076Spjd		}
378204076Spjd		pjdlog_warning("This should never happen, asking for full synchronization (primary(local=%ju, remote=%ju), secondary(local=%ju, remote=%ju)).",
379204076Spjd		    (uintmax_t)res->hr_primary_localcnt,
380204076Spjd		    (uintmax_t)res->hr_primary_remotecnt,
381204076Spjd		    (uintmax_t)res->hr_secondary_localcnt,
382204076Spjd		    (uintmax_t)res->hr_secondary_remotecnt);
383204076Spjd	}
384220007Spjd	nv_add_uint32(nvout, (uint32_t)mapsize, "mapsize");
385229945Spjd	if (hast_proto_send(res, res->hr_remotein, nvout, map, mapsize) == -1) {
386214276Spjd		pjdlog_exit(EX_TEMPFAIL, "Unable to send activemap to %s",
387204076Spjd		    res->hr_remoteaddr);
388204076Spjd	}
389214275Spjd	if (map != NULL)
390214275Spjd		free(map);
391209182Spjd	nv_free(nvout);
392223181Strociny#ifdef notyet
393220271Spjd	/* Setup direction. */
394220271Spjd	if (proto_recv(res->hr_remotein, NULL, 0) == -1)
395220271Spjd		pjdlog_errno(LOG_WARNING, "Unable to set connection direction");
396223181Strociny#endif
397204076Spjd}
398204076Spjd
399204076Spjdvoid
400204076Spjdhastd_secondary(struct hast_resource *res, struct nv *nvin)
401204076Spjd{
402213009Spjd	sigset_t mask;
403204076Spjd	pthread_t td;
404204076Spjd	pid_t pid;
405219482Strociny	int error, mode, debuglevel;
406204076Spjd
407204076Spjd	/*
408204076Spjd	 * Create communication channel between parent and child.
409204076Spjd	 */
410229945Spjd	if (proto_client(NULL, "socketpair://", &res->hr_ctrl) == -1) {
411204076Spjd		KEEP_ERRNO((void)pidfile_remove(pfh));
412204076Spjd		pjdlog_exit(EX_OSERR,
413204076Spjd		    "Unable to create control sockets between parent and child");
414204076Spjd	}
415212038Spjd	/*
416212038Spjd	 * Create communication channel between child and parent.
417212038Spjd	 */
418229945Spjd	if (proto_client(NULL, "socketpair://", &res->hr_event) == -1) {
419212038Spjd		KEEP_ERRNO((void)pidfile_remove(pfh));
420212038Spjd		pjdlog_exit(EX_OSERR,
421212038Spjd		    "Unable to create event sockets between child and parent");
422212038Spjd	}
423204076Spjd
424204076Spjd	pid = fork();
425229744Spjd	if (pid == -1) {
426204076Spjd		KEEP_ERRNO((void)pidfile_remove(pfh));
427204076Spjd		pjdlog_exit(EX_OSERR, "Unable to fork");
428204076Spjd	}
429204076Spjd
430204076Spjd	if (pid > 0) {
431204076Spjd		/* This is parent. */
432204076Spjd		proto_close(res->hr_remotein);
433204076Spjd		res->hr_remotein = NULL;
434204076Spjd		proto_close(res->hr_remoteout);
435204076Spjd		res->hr_remoteout = NULL;
436212038Spjd		/* Declare that we are receiver. */
437212038Spjd		proto_recv(res->hr_event, NULL, 0);
438218043Spjd		/* Declare that we are sender. */
439218043Spjd		proto_send(res->hr_ctrl, NULL, 0);
440204076Spjd		res->hr_workerpid = pid;
441204076Spjd		return;
442204076Spjd	}
443211977Spjd
444211984Spjd	gres = res;
445218043Spjd	mode = pjdlog_mode_get();
446219482Strociny	debuglevel = pjdlog_debug_get();
447211984Spjd
448218043Spjd	/* Declare that we are sender. */
449218043Spjd	proto_send(res->hr_event, NULL, 0);
450218043Spjd	/* Declare that we are receiver. */
451218043Spjd	proto_recv(res->hr_ctrl, NULL, 0);
452218043Spjd	descriptors_cleanup(res);
453204076Spjd
454218045Spjd	descriptors_assert(res, mode);
455218045Spjd
456218043Spjd	pjdlog_init(mode);
457219482Strociny	pjdlog_debug_set(debuglevel);
458218043Spjd	pjdlog_prefix_set("[%s] (%s) ", res->hr_name, role2str(res->hr_role));
459220005Spjd	setproctitle("%s (%s)", res->hr_name, role2str(res->hr_role));
460204076Spjd
461213009Spjd	PJDLOG_VERIFY(sigemptyset(&mask) == 0);
462213009Spjd	PJDLOG_VERIFY(sigprocmask(SIG_SETMASK, &mask, NULL) == 0);
463210880Spjd
464207371Spjd	/* Error in setting timeout is not critical, but why should it fail? */
465229945Spjd	if (proto_timeout(res->hr_remotein, 2 * HAST_KEEPALIVE) == -1)
466207371Spjd		pjdlog_errno(LOG_WARNING, "Unable to set connection timeout");
467229945Spjd	if (proto_timeout(res->hr_remoteout, res->hr_timeout) == -1)
468207371Spjd		pjdlog_errno(LOG_WARNING, "Unable to set connection timeout");
469207371Spjd
470204076Spjd	init_local(res);
471213007Spjd	init_environment();
472213007Spjd
473221899Spjd	if (drop_privs(res) != 0)
474218049Spjd		exit(EX_CONFIG);
475218214Spjd	pjdlog_info("Privileges successfully dropped.");
476218049Spjd
477213007Spjd	/*
478213007Spjd	 * Create the control thread before sending any event to the parent,
479213007Spjd	 * as we can deadlock when parent sends control request to worker,
480213007Spjd	 * but worker has no control thread started yet, so parent waits.
481213007Spjd	 * In the meantime worker sends an event to the parent, but parent
482213007Spjd	 * is unable to handle the event, because it waits for control
483213007Spjd	 * request response.
484213007Spjd	 */
485213007Spjd	error = pthread_create(&td, NULL, ctrl_thread, res);
486218138Spjd	PJDLOG_ASSERT(error == 0);
487213007Spjd
488204076Spjd	init_remote(res, nvin);
489212038Spjd	event_send(res, EVENT_CONNECT);
490204076Spjd
491204076Spjd	error = pthread_create(&td, NULL, recv_thread, res);
492218138Spjd	PJDLOG_ASSERT(error == 0);
493204076Spjd	error = pthread_create(&td, NULL, disk_thread, res);
494218138Spjd	PJDLOG_ASSERT(error == 0);
495213007Spjd	(void)send_thread(res);
496204076Spjd}
497204076Spjd
498204076Spjdstatic void
499230092Spjdreqlog(int loglevel, int debuglevel, int error, struct hio *hio,
500230092Spjd    const char *fmt, ...)
501204076Spjd{
502204076Spjd	char msg[1024];
503204076Spjd	va_list ap;
504204076Spjd	int len;
505204076Spjd
506204076Spjd	va_start(ap, fmt);
507204076Spjd	len = vsnprintf(msg, sizeof(msg), fmt, ap);
508204076Spjd	va_end(ap);
509204076Spjd	if ((size_t)len < sizeof(msg)) {
510204076Spjd		switch (hio->hio_cmd) {
511204076Spjd		case HIO_READ:
512204076Spjd			(void)snprintf(msg + len, sizeof(msg) - len,
513204076Spjd			    "READ(%ju, %ju).", (uintmax_t)hio->hio_offset,
514204076Spjd			    (uintmax_t)hio->hio_length);
515204076Spjd			break;
516204076Spjd		case HIO_DELETE:
517204076Spjd			(void)snprintf(msg + len, sizeof(msg) - len,
518204076Spjd			    "DELETE(%ju, %ju).", (uintmax_t)hio->hio_offset,
519204076Spjd			    (uintmax_t)hio->hio_length);
520204076Spjd			break;
521204076Spjd		case HIO_FLUSH:
522204076Spjd			(void)snprintf(msg + len, sizeof(msg) - len, "FLUSH.");
523204076Spjd			break;
524204076Spjd		case HIO_WRITE:
525204076Spjd			(void)snprintf(msg + len, sizeof(msg) - len,
526204076Spjd			    "WRITE(%ju, %ju).", (uintmax_t)hio->hio_offset,
527204076Spjd			    (uintmax_t)hio->hio_length);
528204076Spjd			break;
529211882Spjd		case HIO_KEEPALIVE:
530211882Spjd			(void)snprintf(msg + len, sizeof(msg) - len, "KEEPALIVE.");
531211882Spjd			break;
532204076Spjd		default:
533204076Spjd			(void)snprintf(msg + len, sizeof(msg) - len,
534204076Spjd			    "UNKNOWN(%u).", (unsigned int)hio->hio_cmd);
535204076Spjd			break;
536204076Spjd		}
537204076Spjd	}
538204076Spjd	pjdlog_common(loglevel, debuglevel, error, "%s", msg);
539204076Spjd}
540204076Spjd
541204076Spjdstatic int
542226854Spjdrequnpack(struct hast_resource *res, struct hio *hio, struct nv *nv)
543204076Spjd{
544204076Spjd
545226854Spjd	hio->hio_cmd = nv_get_uint8(nv, "cmd");
546204076Spjd	if (hio->hio_cmd == 0) {
547204076Spjd		pjdlog_error("Header contains no 'cmd' field.");
548204076Spjd		hio->hio_error = EINVAL;
549204076Spjd		goto end;
550204076Spjd	}
551226854Spjd	if (hio->hio_cmd != HIO_KEEPALIVE) {
552226854Spjd		hio->hio_seq = nv_get_uint64(nv, "seq");
553226854Spjd		if (hio->hio_seq == 0) {
554226854Spjd			pjdlog_error("Header contains no 'seq' field.");
555226854Spjd			hio->hio_error = EINVAL;
556226854Spjd			goto end;
557226854Spjd		}
558226854Spjd	}
559204076Spjd	switch (hio->hio_cmd) {
560222164Spjd	case HIO_FLUSH:
561211882Spjd	case HIO_KEEPALIVE:
562211882Spjd		break;
563246922Spjd	case HIO_WRITE:
564246922Spjd		hio->hio_memsync = nv_exists(nv, "memsync");
565246922Spjd		/* FALLTHROUGH */
566204076Spjd	case HIO_READ:
567204076Spjd	case HIO_DELETE:
568226854Spjd		hio->hio_offset = nv_get_uint64(nv, "offset");
569226854Spjd		if (nv_error(nv) != 0) {
570204076Spjd			pjdlog_error("Header is missing 'offset' field.");
571204076Spjd			hio->hio_error = EINVAL;
572204076Spjd			goto end;
573204076Spjd		}
574226854Spjd		hio->hio_length = nv_get_uint64(nv, "length");
575226854Spjd		if (nv_error(nv) != 0) {
576204076Spjd			pjdlog_error("Header is missing 'length' field.");
577204076Spjd			hio->hio_error = EINVAL;
578204076Spjd			goto end;
579204076Spjd		}
580204076Spjd		if (hio->hio_length == 0) {
581204076Spjd			pjdlog_error("Data length is zero.");
582204076Spjd			hio->hio_error = EINVAL;
583204076Spjd			goto end;
584204076Spjd		}
585204076Spjd		if (hio->hio_length > MAXPHYS) {
586204076Spjd			pjdlog_error("Data length is too large (%ju > %ju).",
587204076Spjd			    (uintmax_t)hio->hio_length, (uintmax_t)MAXPHYS);
588204076Spjd			hio->hio_error = EINVAL;
589204076Spjd			goto end;
590204076Spjd		}
591204076Spjd		if ((hio->hio_offset % res->hr_local_sectorsize) != 0) {
592204076Spjd			pjdlog_error("Offset %ju is not multiple of sector size.",
593204076Spjd			    (uintmax_t)hio->hio_offset);
594204076Spjd			hio->hio_error = EINVAL;
595204076Spjd			goto end;
596204076Spjd		}
597204076Spjd		if ((hio->hio_length % res->hr_local_sectorsize) != 0) {
598204076Spjd			pjdlog_error("Length %ju is not multiple of sector size.",
599204076Spjd			    (uintmax_t)hio->hio_length);
600204076Spjd			hio->hio_error = EINVAL;
601204076Spjd			goto end;
602204076Spjd		}
603204076Spjd		if (hio->hio_offset + hio->hio_length >
604204076Spjd		    (uint64_t)res->hr_datasize) {
605204076Spjd			pjdlog_error("Data offset is too large (%ju > %ju).",
606204076Spjd			    (uintmax_t)(hio->hio_offset + hio->hio_length),
607204076Spjd			    (uintmax_t)res->hr_datasize);
608204076Spjd			hio->hio_error = EINVAL;
609204076Spjd			goto end;
610204076Spjd		}
611204076Spjd		break;
612204076Spjd	default:
613204076Spjd		pjdlog_error("Header contains invalid 'cmd' (%hhu).",
614204076Spjd		    hio->hio_cmd);
615204076Spjd		hio->hio_error = EINVAL;
616204076Spjd		goto end;
617204076Spjd	}
618204076Spjd	hio->hio_error = 0;
619204076Spjdend:
620204076Spjd	return (hio->hio_error);
621204076Spjd}
622204076Spjd
623212899Spjdstatic __dead2 void
624211984Spjdsecondary_exit(int exitcode, const char *fmt, ...)
625211984Spjd{
626211984Spjd	va_list ap;
627211984Spjd
628218138Spjd	PJDLOG_ASSERT(exitcode != EX_OK);
629211984Spjd	va_start(ap, fmt);
630211984Spjd	pjdlogv_errno(LOG_ERR, fmt, ap);
631211984Spjd	va_end(ap);
632212038Spjd	event_send(gres, EVENT_DISCONNECT);
633211984Spjd	exit(exitcode);
634211984Spjd}
635211984Spjd
636204076Spjd/*
637204076Spjd * Thread receives requests from the primary node.
638204076Spjd */
639204076Spjdstatic void *
640204076Spjdrecv_thread(void *arg)
641204076Spjd{
642204076Spjd	struct hast_resource *res = arg;
643246922Spjd	struct hio *hio, *mshio;
644226854Spjd	struct nv *nv;
645204076Spjd
646204076Spjd	for (;;) {
647204076Spjd		pjdlog_debug(2, "recv: Taking free request.");
648211877Spjd		QUEUE_TAKE(free, hio);
649204076Spjd		pjdlog_debug(2, "recv: (%p) Got request.", hio);
650229945Spjd		if (hast_proto_recv_hdr(res->hr_remotein, &nv) == -1) {
651211984Spjd			secondary_exit(EX_TEMPFAIL,
652204076Spjd			    "Unable to receive request header");
653204076Spjd		}
654226854Spjd		if (requnpack(res, hio, nv) != 0) {
655226854Spjd			nv_free(nv);
656211877Spjd			pjdlog_debug(2,
657211877Spjd			    "recv: (%p) Moving request to the send queue.",
658211877Spjd			    hio);
659211877Spjd			QUEUE_INSERT(send, hio);
660211877Spjd			continue;
661211877Spjd		}
662222228Spjd		switch (hio->hio_cmd) {
663222228Spjd		case HIO_READ:
664222228Spjd			res->hr_stat_read++;
665222228Spjd			break;
666222228Spjd		case HIO_WRITE:
667222228Spjd			res->hr_stat_write++;
668222228Spjd			break;
669222228Spjd		case HIO_DELETE:
670222228Spjd			res->hr_stat_delete++;
671222228Spjd			break;
672222228Spjd		case HIO_FLUSH:
673222228Spjd			res->hr_stat_flush++;
674222228Spjd			break;
675226854Spjd		case HIO_KEEPALIVE:
676226854Spjd			break;
677226854Spjd		default:
678226854Spjd			PJDLOG_ABORT("Unexpected command (cmd=%hhu).",
679226854Spjd			    hio->hio_cmd);
680222228Spjd		}
681204076Spjd		reqlog(LOG_DEBUG, 2, -1, hio,
682204076Spjd		    "recv: (%p) Got request header: ", hio);
683211882Spjd		if (hio->hio_cmd == HIO_KEEPALIVE) {
684226854Spjd			nv_free(nv);
685211882Spjd			pjdlog_debug(2,
686211882Spjd			    "recv: (%p) Moving request to the free queue.",
687211882Spjd			    hio);
688226854Spjd			hio_clear(hio);
689211882Spjd			QUEUE_INSERT(free, hio);
690211882Spjd			continue;
691211882Spjd		} else if (hio->hio_cmd == HIO_WRITE) {
692226854Spjd			if (hast_proto_recv_data(res, res->hr_remotein, nv,
693229945Spjd			    hio->hio_data, MAXPHYS) == -1) {
694211984Spjd				secondary_exit(EX_TEMPFAIL,
695212051Spjd				    "Unable to receive request data");
696204076Spjd			}
697246922Spjd			if (hio->hio_memsync) {
698246922Spjd				/*
699246922Spjd				 * For memsync requests we expect two replies.
700246922Spjd				 * Clone the hio so we can handle both of them.
701246922Spjd				 */
702246922Spjd				pjdlog_debug(2, "recv: Taking free request.");
703246922Spjd				QUEUE_TAKE(free, mshio);
704246922Spjd				pjdlog_debug(2, "recv: (%p) Got request.",
705246922Spjd				    mshio);
706246922Spjd				hio_copy(hio, mshio);
707246922Spjd				mshio->hio_error = 0;
708246922Spjd				/*
709246922Spjd				 * We want to keep 'memsync' tag only on the
710246922Spjd				 * request going onto send queue (mshio).
711246922Spjd				 */
712246922Spjd				hio->hio_memsync = false;
713246922Spjd				pjdlog_debug(2,
714246922Spjd				    "recv: (%p) Moving memsync request to the send queue.",
715246922Spjd				    mshio);
716246922Spjd				QUEUE_INSERT(send, mshio);
717246922Spjd			}
718204076Spjd		}
719226854Spjd		nv_free(nv);
720204076Spjd		pjdlog_debug(2, "recv: (%p) Moving request to the disk queue.",
721204076Spjd		    hio);
722211877Spjd		QUEUE_INSERT(disk, hio);
723204076Spjd	}
724204076Spjd	/* NOTREACHED */
725204076Spjd	return (NULL);
726204076Spjd}
727204076Spjd
728204076Spjd/*
729204076Spjd * Thread reads from or writes to local component and also handles DELETE and
730204076Spjd * FLUSH requests.
731204076Spjd */
732204076Spjdstatic void *
733204076Spjddisk_thread(void *arg)
734204076Spjd{
735204076Spjd	struct hast_resource *res = arg;
736204076Spjd	struct hio *hio;
737204076Spjd	ssize_t ret;
738225832Spjd	bool clear_activemap, logerror;
739204076Spjd
740204076Spjd	clear_activemap = true;
741204076Spjd
742204076Spjd	for (;;) {
743204076Spjd		pjdlog_debug(2, "disk: Taking request.");
744211877Spjd		QUEUE_TAKE(disk, hio);
745204076Spjd		while (clear_activemap) {
746204076Spjd			unsigned char *map;
747204076Spjd			size_t mapsize;
748204076Spjd
749204076Spjd			/*
750204076Spjd			 * When first request is received, it means that primary
751204076Spjd			 * already received our activemap, merged it and stored
752204076Spjd			 * locally. We can now safely clear our activemap.
753204076Spjd			 */
754204076Spjd			mapsize =
755204076Spjd			    activemap_calc_ondisk_size(res->hr_local_mediasize -
756204076Spjd			    METADATA_SIZE, res->hr_extentsize,
757204076Spjd			    res->hr_local_sectorsize);
758204076Spjd			map = calloc(1, mapsize);
759204076Spjd			if (map == NULL) {
760204076Spjd				pjdlog_warning("Unable to allocate memory to clear local activemap.");
761204076Spjd				break;
762204076Spjd			}
763204076Spjd			if (pwrite(res->hr_localfd, map, mapsize,
764204076Spjd			    METADATA_SIZE) != (ssize_t)mapsize) {
765204076Spjd				pjdlog_errno(LOG_WARNING,
766204076Spjd				    "Unable to store cleared activemap");
767204076Spjd				free(map);
768204076Spjd				break;
769204076Spjd			}
770204076Spjd			free(map);
771204076Spjd			clear_activemap = false;
772204076Spjd			pjdlog_debug(1, "Local activemap cleared.");
773225831Spjd			break;
774204076Spjd		}
775204076Spjd		reqlog(LOG_DEBUG, 2, -1, hio, "disk: (%p) Got request: ", hio);
776225832Spjd		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);
783229945Spjd			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);
794229945Spjd			if (ret == -1)
795204076Spjd				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;
801204076Spjd		case HIO_DELETE:
802204076Spjd			ret = g_delete(res->hr_localfd,
803204076Spjd			    hio->hio_offset + res->hr_localoff,
804204076Spjd			    hio->hio_length);
805229945Spjd			if (ret == -1)
806204076Spjd				hio->hio_error = errno;
807204076Spjd			else
808204076Spjd				hio->hio_error = 0;
809204076Spjd			break;
810204076Spjd		case HIO_FLUSH:
811225832Spjd			if (!res->hr_localflush) {
812225832Spjd				ret = -1;
813225832Spjd				hio->hio_error = EOPNOTSUPP;
814225832Spjd				logerror = false;
815225832Spjd				break;
816225832Spjd			}
817204076Spjd			ret = g_flush(res->hr_localfd);
818229945Spjd			if (ret == -1) {
819225832Spjd				if (errno == EOPNOTSUPP)
820225832Spjd					res->hr_localflush = false;
821204076Spjd				hio->hio_error = errno;
822225832Spjd			} else {
823204076Spjd				hio->hio_error = 0;
824225832Spjd			}
825204076Spjd			break;
826226854Spjd		default:
827226854Spjd			PJDLOG_ABORT("Unexpected command (cmd=%hhu).",
828226854Spjd			    hio->hio_cmd);
829204076Spjd		}
830225832Spjd		if (logerror && hio->hio_error != 0) {
831204076Spjd			reqlog(LOG_ERR, 0, hio->hio_error, hio,
832204076Spjd			    "Request failed: ");
833204076Spjd		}
834204076Spjd		pjdlog_debug(2, "disk: (%p) Moving request to the send queue.",
835204076Spjd		    hio);
836211877Spjd		QUEUE_INSERT(send, hio);
837204076Spjd	}
838204076Spjd	/* NOTREACHED */
839204076Spjd	return (NULL);
840204076Spjd}
841204076Spjd
842204076Spjd/*
843204076Spjd * Thread sends requests back to primary node.
844204076Spjd */
845204076Spjdstatic void *
846204076Spjdsend_thread(void *arg)
847204076Spjd{
848204076Spjd	struct hast_resource *res = arg;
849204076Spjd	struct nv *nvout;
850204076Spjd	struct hio *hio;
851204076Spjd	void *data;
852204076Spjd	size_t length;
853204076Spjd
854204076Spjd	for (;;) {
855204076Spjd		pjdlog_debug(2, "send: Taking request.");
856211877Spjd		QUEUE_TAKE(send, hio);
857204076Spjd		reqlog(LOG_DEBUG, 2, -1, hio, "send: (%p) Got request: ", hio);
858204076Spjd		nvout = nv_alloc();
859204076Spjd		/* Copy sequence number. */
860226854Spjd		nv_add_uint64(nvout, hio->hio_seq, "seq");
861246922Spjd		if (hio->hio_memsync) {
862246922Spjd			PJDLOG_ASSERT(hio->hio_cmd == HIO_WRITE);
863246922Spjd			nv_add_int8(nvout, 1, "received");
864246922Spjd		}
865204076Spjd		switch (hio->hio_cmd) {
866204076Spjd		case HIO_READ:
867204076Spjd			if (hio->hio_error == 0) {
868204076Spjd				data = hio->hio_data;
869204076Spjd				length = hio->hio_length;
870204076Spjd				break;
871204076Spjd			}
872204076Spjd			/*
873204076Spjd			 * We send no data in case of an error.
874204076Spjd			 */
875204076Spjd			/* FALLTHROUGH */
876204076Spjd		case HIO_DELETE:
877204076Spjd		case HIO_FLUSH:
878204076Spjd		case HIO_WRITE:
879204076Spjd			data = NULL;
880204076Spjd			length = 0;
881204076Spjd			break;
882204076Spjd		default:
883225782Spjd			PJDLOG_ABORT("Unexpected command (cmd=%hhu).",
884225782Spjd			    hio->hio_cmd);
885204076Spjd		}
886204076Spjd		if (hio->hio_error != 0)
887204076Spjd			nv_add_int16(nvout, hio->hio_error, "error");
888204076Spjd		if (hast_proto_send(res, res->hr_remoteout, nvout, data,
889229945Spjd		    length) == -1) {
890230092Spjd			secondary_exit(EX_TEMPFAIL, "Unable to send reply");
891204076Spjd		}
892204076Spjd		nv_free(nvout);
893209185Spjd		pjdlog_debug(2, "send: (%p) Moving request to the free queue.",
894204076Spjd		    hio);
895226854Spjd		hio_clear(hio);
896211877Spjd		QUEUE_INSERT(free, hio);
897204076Spjd	}
898204076Spjd	/* NOTREACHED */
899204076Spjd	return (NULL);
900204076Spjd}
901