secondary.c revision 229945
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 229945 2012-01-10 22:39:07Z 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;
74204076Spjd	TAILQ_ENTRY(hio) hio_next;
75204076Spjd};
76204076Spjd
77211984Spjdstatic struct hast_resource *gres;
78211984Spjd
79204076Spjd/*
80204076Spjd * Free list holds unused structures. When free list is empty, we have to wait
81204076Spjd * until some in-progress requests are freed.
82204076Spjd */
83204076Spjdstatic TAILQ_HEAD(, hio) hio_free_list;
84204076Spjdstatic pthread_mutex_t hio_free_list_lock;
85204076Spjdstatic pthread_cond_t hio_free_list_cond;
86204076Spjd/*
87204076Spjd * Disk thread (the one that do I/O requests) takes requests from this list.
88204076Spjd */
89204076Spjdstatic TAILQ_HEAD(, hio) hio_disk_list;
90204076Spjdstatic pthread_mutex_t hio_disk_list_lock;
91204076Spjdstatic pthread_cond_t hio_disk_list_cond;
92204076Spjd/*
93204076Spjd * There is one recv list for every component, although local components don't
94204076Spjd * use recv lists as local requests are done synchronously.
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
109211877Spjd#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_signal(&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)
128226861Spjd
129226854Spjdstatic void
130226854Spjdhio_clear(struct hio *hio)
131226854Spjd{
132211877Spjd
133226854Spjd	hio->hio_seq = 0;
134226854Spjd	hio->hio_error = 0;
135226854Spjd	hio->hio_cmd = HIO_UNDEF;
136226854Spjd	hio->hio_offset = 0;
137226854Spjd	hio->hio_length = 0;
138226854Spjd}
139226854Spjd
140204076Spjdstatic void
141204076Spjdinit_environment(void)
142204076Spjd{
143204076Spjd	struct hio *hio;
144204076Spjd	unsigned int ii;
145204076Spjd
146204076Spjd	/*
147204076Spjd	 * Initialize lists, their locks and theirs condition variables.
148204076Spjd	 */
149204076Spjd	TAILQ_INIT(&hio_free_list);
150204076Spjd	mtx_init(&hio_free_list_lock);
151204076Spjd	cv_init(&hio_free_list_cond);
152204076Spjd	TAILQ_INIT(&hio_disk_list);
153204076Spjd	mtx_init(&hio_disk_list_lock);
154204076Spjd	cv_init(&hio_disk_list_cond);
155204076Spjd	TAILQ_INIT(&hio_send_list);
156204076Spjd	mtx_init(&hio_send_list_lock);
157204076Spjd	cv_init(&hio_send_list_cond);
158204076Spjd
159204076Spjd	/*
160204076Spjd	 * Allocate requests pool and initialize requests.
161204076Spjd	 */
162204076Spjd	for (ii = 0; ii < HAST_HIO_MAX; ii++) {
163204076Spjd		hio = malloc(sizeof(*hio));
164204076Spjd		if (hio == NULL) {
165210879Spjd			pjdlog_exitx(EX_TEMPFAIL,
166210879Spjd			    "Unable to allocate memory (%zu bytes) for hio request.",
167210879Spjd			    sizeof(*hio));
168204076Spjd		}
169204076Spjd		hio->hio_data = malloc(MAXPHYS);
170204076Spjd		if (hio->hio_data == NULL) {
171210879Spjd			pjdlog_exitx(EX_TEMPFAIL,
172210879Spjd			    "Unable to allocate memory (%zu bytes) for gctl_data.",
173210879Spjd			    (size_t)MAXPHYS);
174204076Spjd		}
175226854Spjd		hio_clear(hio);
176204076Spjd		TAILQ_INSERT_HEAD(&hio_free_list, hio, hio_next);
177204076Spjd	}
178204076Spjd}
179204076Spjd
180204076Spjdstatic void
181204076Spjdinit_local(struct hast_resource *res)
182204076Spjd{
183204076Spjd
184229945Spjd	if (metadata_read(res, true) == -1)
185204076Spjd		exit(EX_NOINPUT);
186204076Spjd}
187204076Spjd
188204076Spjdstatic void
189204076Spjdinit_remote(struct hast_resource *res, struct nv *nvin)
190204076Spjd{
191204076Spjd	uint64_t resuid;
192204076Spjd	struct nv *nvout;
193204076Spjd	unsigned char *map;
194204076Spjd	size_t mapsize;
195204076Spjd
196223181Strociny#ifdef notyet
197220271Spjd	/* Setup direction. */
198220271Spjd	if (proto_send(res->hr_remoteout, NULL, 0) == -1)
199220271Spjd		pjdlog_errno(LOG_WARNING, "Unable to set connection direction");
200223181Strociny#endif
201220271Spjd
202204076Spjd	nvout = nv_alloc();
203204076Spjd	nv_add_int64(nvout, (int64_t)res->hr_datasize, "datasize");
204204076Spjd	nv_add_int32(nvout, (int32_t)res->hr_extentsize, "extentsize");
205204076Spjd	resuid = nv_get_uint64(nvin, "resuid");
206204076Spjd	res->hr_primary_localcnt = nv_get_uint64(nvin, "localcnt");
207204076Spjd	res->hr_primary_remotecnt = nv_get_uint64(nvin, "remotecnt");
208204076Spjd	nv_add_uint64(nvout, res->hr_secondary_localcnt, "localcnt");
209204076Spjd	nv_add_uint64(nvout, res->hr_secondary_remotecnt, "remotecnt");
210204076Spjd	mapsize = activemap_calc_ondisk_size(res->hr_local_mediasize -
211204076Spjd	    METADATA_SIZE, res->hr_extentsize, res->hr_local_sectorsize);
212204076Spjd	map = malloc(mapsize);
213204076Spjd	if (map == NULL) {
214204076Spjd		pjdlog_exitx(EX_TEMPFAIL,
215204076Spjd		    "Unable to allocate memory (%zu bytes) for activemap.",
216204076Spjd		    mapsize);
217204076Spjd	}
218204076Spjd	/*
219204076Spjd	 * When we work as primary and secondary is missing we will increase
220204076Spjd	 * localcnt in our metadata. When secondary is connected and synced
221204076Spjd	 * we make localcnt be equal to remotecnt, which means nodes are more
222204076Spjd	 * or less in sync.
223204076Spjd	 * Split-brain condition is when both nodes are not able to communicate
224204076Spjd	 * and are both configured as primary nodes. In turn, they can both
225204076Spjd	 * make incompatible changes to the data and we have to detect that.
226204076Spjd	 * Under split-brain condition we will increase our localcnt on first
227204076Spjd	 * write and remote node will increase its localcnt on first write.
228204076Spjd	 * When we connect we can see that primary's localcnt is greater than
229204076Spjd	 * our remotecnt (primary was modified while we weren't watching) and
230204076Spjd	 * our localcnt is greater than primary's remotecnt (we were modified
231204076Spjd	 * while primary wasn't watching).
232204076Spjd	 * There are many possible combinations which are all gathered below.
233204076Spjd	 * Don't pay too much attention to exact numbers, the more important
234204076Spjd	 * is to compare them. We compare secondary's local with primary's
235204076Spjd	 * remote and secondary's remote with primary's local.
236204076Spjd	 * Note that every case where primary's localcnt is smaller than
237204076Spjd	 * secondary's remotecnt and where secondary's localcnt is smaller than
238204076Spjd	 * primary's remotecnt should be impossible in practise. We will perform
239204076Spjd	 * full synchronization then. Those cases are marked with an asterisk.
240204076Spjd	 * Regular synchronization means that only extents marked as dirty are
241204076Spjd	 * synchronized (regular synchronization).
242204076Spjd	 *
243204076Spjd	 * SECONDARY METADATA PRIMARY METADATA
244204076Spjd	 * local=3 remote=3   local=2 remote=2*  ?! Full sync from secondary.
245204076Spjd	 * local=3 remote=3   local=2 remote=3*  ?! Full sync from primary.
246204076Spjd	 * local=3 remote=3   local=2 remote=4*  ?! Full sync from primary.
247204076Spjd	 * local=3 remote=3   local=3 remote=2   Primary is out-of-date,
248204076Spjd	 *                                       regular sync from secondary.
249204076Spjd	 * local=3 remote=3   local=3 remote=3   Regular sync just in case.
250204076Spjd	 * local=3 remote=3   local=3 remote=4*  ?! Full sync from primary.
251204076Spjd	 * local=3 remote=3   local=4 remote=2   Split-brain condition.
252204076Spjd	 * local=3 remote=3   local=4 remote=3   Secondary out-of-date,
253204076Spjd	 *                                       regular sync from primary.
254204076Spjd	 * local=3 remote=3   local=4 remote=4*  ?! Full sync from primary.
255204076Spjd	 */
256204076Spjd	if (res->hr_resuid == 0) {
257204076Spjd		/*
258214284Spjd		 * Provider is used for the first time. If primary node done no
259214284Spjd		 * writes yet as well (we will find "virgin" argument) then
260214284Spjd		 * there is no need to synchronize anything. If primary node
261214284Spjd		 * done any writes already we have to synchronize everything.
262204076Spjd		 */
263218138Spjd		PJDLOG_ASSERT(res->hr_secondary_localcnt == 0);
264204076Spjd		res->hr_resuid = resuid;
265229945Spjd		if (metadata_write(res) == -1)
266204076Spjd			exit(EX_NOINPUT);
267214284Spjd		if (nv_exists(nvin, "virgin")) {
268214284Spjd			free(map);
269214284Spjd			map = NULL;
270214284Spjd			mapsize = 0;
271214284Spjd		} else {
272214284Spjd			memset(map, 0xff, mapsize);
273214284Spjd		}
274220865Spjd		nv_add_int8(nvout, 1, "virgin");
275204076Spjd		nv_add_uint8(nvout, HAST_SYNCSRC_PRIMARY, "syncsrc");
276219830Spjd	} else if (res->hr_resuid != resuid) {
277219830Spjd		char errmsg[256];
278219830Spjd
279226854Spjd		free(map);
280219830Spjd		(void)snprintf(errmsg, sizeof(errmsg),
281219830Spjd		    "Resource unique ID mismatch (primary=%ju, secondary=%ju).",
282219830Spjd		    (uintmax_t)resuid, (uintmax_t)res->hr_resuid);
283219830Spjd		pjdlog_error("%s", errmsg);
284219830Spjd		nv_add_string(nvout, errmsg, "errmsg");
285229945Spjd		if (hast_proto_send(res, res->hr_remotein, nvout, NULL, 0) == -1) {
286219830Spjd			pjdlog_exit(EX_TEMPFAIL, "Unable to send response to %s",
287219830Spjd			    res->hr_remoteaddr);
288219830Spjd		}
289219831Spjd		nv_free(nvout);
290219830Spjd		exit(EX_CONFIG);
291204076Spjd	} else if (
292226842Spjd	    /* Is primary out-of-date? */
293204076Spjd	    (res->hr_secondary_localcnt > res->hr_primary_remotecnt &&
294204076Spjd	     res->hr_secondary_remotecnt == res->hr_primary_localcnt) ||
295226842Spjd	    /* Are the nodes more or less in sync? */
296204076Spjd	    (res->hr_secondary_localcnt == res->hr_primary_remotecnt &&
297204076Spjd	     res->hr_secondary_remotecnt == res->hr_primary_localcnt) ||
298226842Spjd	    /* Is secondary out-of-date? */
299204076Spjd	    (res->hr_secondary_localcnt == res->hr_primary_remotecnt &&
300204076Spjd	     res->hr_secondary_remotecnt < res->hr_primary_localcnt)) {
301204076Spjd		/*
302204076Spjd		 * Nodes are more or less in sync or one of the nodes is
303204076Spjd		 * out-of-date.
304204076Spjd		 * It doesn't matter at this point which one, we just have to
305204076Spjd		 * send out local bitmap to the remote node.
306204076Spjd		 */
307204076Spjd		if (pread(res->hr_localfd, map, mapsize, METADATA_SIZE) !=
308204076Spjd		    (ssize_t)mapsize) {
309204076Spjd			pjdlog_exit(LOG_ERR, "Unable to read activemap");
310204076Spjd		}
311204076Spjd		if (res->hr_secondary_localcnt > res->hr_primary_remotecnt &&
312204076Spjd		     res->hr_secondary_remotecnt == res->hr_primary_localcnt) {
313204076Spjd			/* Primary is out-of-date, sync from secondary. */
314204076Spjd			nv_add_uint8(nvout, HAST_SYNCSRC_SECONDARY, "syncsrc");
315204076Spjd		} else {
316204076Spjd			/*
317204076Spjd			 * Secondary is out-of-date or counts match.
318204076Spjd			 * Sync from primary.
319204076Spjd			 */
320204076Spjd			nv_add_uint8(nvout, HAST_SYNCSRC_PRIMARY, "syncsrc");
321204076Spjd		}
322204076Spjd	} else if (res->hr_secondary_localcnt > res->hr_primary_remotecnt &&
323204076Spjd	     res->hr_primary_localcnt > res->hr_secondary_remotecnt) {
324204076Spjd		/*
325204076Spjd		 * Not good, we have split-brain condition.
326204076Spjd		 */
327226854Spjd		free(map);
328204076Spjd		pjdlog_error("Split-brain detected, exiting.");
329204076Spjd		nv_add_string(nvout, "Split-brain condition!", "errmsg");
330229945Spjd		if (hast_proto_send(res, res->hr_remotein, nvout, NULL, 0) == -1) {
331226854Spjd			pjdlog_exit(EX_TEMPFAIL, "Unable to send response to %s",
332226854Spjd			    res->hr_remoteaddr);
333226854Spjd		}
334226854Spjd		nv_free(nvout);
335226854Spjd		/* Exit on split-brain. */
336226854Spjd		event_send(res, EVENT_SPLITBRAIN);
337226854Spjd		exit(EX_CONFIG);
338204076Spjd	} else /* if (res->hr_secondary_localcnt < res->hr_primary_remotecnt ||
339204076Spjd	    res->hr_primary_localcnt < res->hr_secondary_remotecnt) */ {
340204076Spjd		/*
341204076Spjd		 * This should never happen in practise, but we will perform
342204076Spjd		 * full synchronization.
343204076Spjd		 */
344218138Spjd		PJDLOG_ASSERT(res->hr_secondary_localcnt < res->hr_primary_remotecnt ||
345204076Spjd		    res->hr_primary_localcnt < res->hr_secondary_remotecnt);
346204076Spjd		mapsize = activemap_calc_ondisk_size(res->hr_local_mediasize -
347204076Spjd		    METADATA_SIZE, res->hr_extentsize,
348204076Spjd		    res->hr_local_sectorsize);
349204076Spjd		memset(map, 0xff, mapsize);
350204076Spjd		if (res->hr_secondary_localcnt > res->hr_primary_remotecnt) {
351204076Spjd			/* In this one of five cases sync from secondary. */
352204076Spjd			nv_add_uint8(nvout, HAST_SYNCSRC_SECONDARY, "syncsrc");
353204076Spjd		} else {
354204076Spjd			/* For the rest four cases sync from primary. */
355204076Spjd			nv_add_uint8(nvout, HAST_SYNCSRC_PRIMARY, "syncsrc");
356204076Spjd		}
357204076Spjd		pjdlog_warning("This should never happen, asking for full synchronization (primary(local=%ju, remote=%ju), secondary(local=%ju, remote=%ju)).",
358204076Spjd		    (uintmax_t)res->hr_primary_localcnt,
359204076Spjd		    (uintmax_t)res->hr_primary_remotecnt,
360204076Spjd		    (uintmax_t)res->hr_secondary_localcnt,
361204076Spjd		    (uintmax_t)res->hr_secondary_remotecnt);
362204076Spjd	}
363220007Spjd	nv_add_uint32(nvout, (uint32_t)mapsize, "mapsize");
364229945Spjd	if (hast_proto_send(res, res->hr_remotein, nvout, map, mapsize) == -1) {
365214276Spjd		pjdlog_exit(EX_TEMPFAIL, "Unable to send activemap to %s",
366204076Spjd		    res->hr_remoteaddr);
367204076Spjd	}
368214275Spjd	if (map != NULL)
369214275Spjd		free(map);
370209182Spjd	nv_free(nvout);
371223181Strociny#ifdef notyet
372220271Spjd	/* Setup direction. */
373220271Spjd	if (proto_recv(res->hr_remotein, NULL, 0) == -1)
374220271Spjd		pjdlog_errno(LOG_WARNING, "Unable to set connection direction");
375223181Strociny#endif
376204076Spjd}
377204076Spjd
378204076Spjdvoid
379204076Spjdhastd_secondary(struct hast_resource *res, struct nv *nvin)
380204076Spjd{
381213009Spjd	sigset_t mask;
382204076Spjd	pthread_t td;
383204076Spjd	pid_t pid;
384219482Strociny	int error, mode, debuglevel;
385204076Spjd
386204076Spjd	/*
387204076Spjd	 * Create communication channel between parent and child.
388204076Spjd	 */
389229945Spjd	if (proto_client(NULL, "socketpair://", &res->hr_ctrl) == -1) {
390204076Spjd		KEEP_ERRNO((void)pidfile_remove(pfh));
391204076Spjd		pjdlog_exit(EX_OSERR,
392204076Spjd		    "Unable to create control sockets between parent and child");
393204076Spjd	}
394212038Spjd	/*
395212038Spjd	 * Create communication channel between child and parent.
396212038Spjd	 */
397229945Spjd	if (proto_client(NULL, "socketpair://", &res->hr_event) == -1) {
398212038Spjd		KEEP_ERRNO((void)pidfile_remove(pfh));
399212038Spjd		pjdlog_exit(EX_OSERR,
400212038Spjd		    "Unable to create event sockets between child and parent");
401212038Spjd	}
402204076Spjd
403204076Spjd	pid = fork();
404229744Spjd	if (pid == -1) {
405204076Spjd		KEEP_ERRNO((void)pidfile_remove(pfh));
406204076Spjd		pjdlog_exit(EX_OSERR, "Unable to fork");
407204076Spjd	}
408204076Spjd
409204076Spjd	if (pid > 0) {
410204076Spjd		/* This is parent. */
411204076Spjd		proto_close(res->hr_remotein);
412204076Spjd		res->hr_remotein = NULL;
413204076Spjd		proto_close(res->hr_remoteout);
414204076Spjd		res->hr_remoteout = NULL;
415212038Spjd		/* Declare that we are receiver. */
416212038Spjd		proto_recv(res->hr_event, NULL, 0);
417218043Spjd		/* Declare that we are sender. */
418218043Spjd		proto_send(res->hr_ctrl, NULL, 0);
419204076Spjd		res->hr_workerpid = pid;
420204076Spjd		return;
421204076Spjd	}
422211977Spjd
423211984Spjd	gres = res;
424218043Spjd	mode = pjdlog_mode_get();
425219482Strociny	debuglevel = pjdlog_debug_get();
426211984Spjd
427218043Spjd	/* Declare that we are sender. */
428218043Spjd	proto_send(res->hr_event, NULL, 0);
429218043Spjd	/* Declare that we are receiver. */
430218043Spjd	proto_recv(res->hr_ctrl, NULL, 0);
431218043Spjd	descriptors_cleanup(res);
432204076Spjd
433218045Spjd	descriptors_assert(res, mode);
434218045Spjd
435218043Spjd	pjdlog_init(mode);
436219482Strociny	pjdlog_debug_set(debuglevel);
437218043Spjd	pjdlog_prefix_set("[%s] (%s) ", res->hr_name, role2str(res->hr_role));
438220005Spjd	setproctitle("%s (%s)", res->hr_name, role2str(res->hr_role));
439204076Spjd
440213009Spjd	PJDLOG_VERIFY(sigemptyset(&mask) == 0);
441213009Spjd	PJDLOG_VERIFY(sigprocmask(SIG_SETMASK, &mask, NULL) == 0);
442210880Spjd
443207371Spjd	/* Error in setting timeout is not critical, but why should it fail? */
444229945Spjd	if (proto_timeout(res->hr_remotein, 2 * HAST_KEEPALIVE) == -1)
445207371Spjd		pjdlog_errno(LOG_WARNING, "Unable to set connection timeout");
446229945Spjd	if (proto_timeout(res->hr_remoteout, res->hr_timeout) == -1)
447207371Spjd		pjdlog_errno(LOG_WARNING, "Unable to set connection timeout");
448207371Spjd
449204076Spjd	init_local(res);
450213007Spjd	init_environment();
451213007Spjd
452221899Spjd	if (drop_privs(res) != 0)
453218049Spjd		exit(EX_CONFIG);
454218214Spjd	pjdlog_info("Privileges successfully dropped.");
455218049Spjd
456213007Spjd	/*
457213007Spjd	 * Create the control thread before sending any event to the parent,
458213007Spjd	 * as we can deadlock when parent sends control request to worker,
459213007Spjd	 * but worker has no control thread started yet, so parent waits.
460213007Spjd	 * In the meantime worker sends an event to the parent, but parent
461213007Spjd	 * is unable to handle the event, because it waits for control
462213007Spjd	 * request response.
463213007Spjd	 */
464213007Spjd	error = pthread_create(&td, NULL, ctrl_thread, res);
465218138Spjd	PJDLOG_ASSERT(error == 0);
466213007Spjd
467204076Spjd	init_remote(res, nvin);
468212038Spjd	event_send(res, EVENT_CONNECT);
469204076Spjd
470204076Spjd	error = pthread_create(&td, NULL, recv_thread, res);
471218138Spjd	PJDLOG_ASSERT(error == 0);
472204076Spjd	error = pthread_create(&td, NULL, disk_thread, res);
473218138Spjd	PJDLOG_ASSERT(error == 0);
474213007Spjd	(void)send_thread(res);
475204076Spjd}
476204076Spjd
477204076Spjdstatic void
478204076Spjdreqlog(int loglevel, int debuglevel, int error, struct hio *hio, const char *fmt, ...)
479204076Spjd{
480204076Spjd	char msg[1024];
481204076Spjd	va_list ap;
482204076Spjd	int len;
483204076Spjd
484204076Spjd	va_start(ap, fmt);
485204076Spjd	len = vsnprintf(msg, sizeof(msg), fmt, ap);
486204076Spjd	va_end(ap);
487204076Spjd	if ((size_t)len < sizeof(msg)) {
488204076Spjd		switch (hio->hio_cmd) {
489204076Spjd		case HIO_READ:
490204076Spjd			(void)snprintf(msg + len, sizeof(msg) - len,
491204076Spjd			    "READ(%ju, %ju).", (uintmax_t)hio->hio_offset,
492204076Spjd			    (uintmax_t)hio->hio_length);
493204076Spjd			break;
494204076Spjd		case HIO_DELETE:
495204076Spjd			(void)snprintf(msg + len, sizeof(msg) - len,
496204076Spjd			    "DELETE(%ju, %ju).", (uintmax_t)hio->hio_offset,
497204076Spjd			    (uintmax_t)hio->hio_length);
498204076Spjd			break;
499204076Spjd		case HIO_FLUSH:
500204076Spjd			(void)snprintf(msg + len, sizeof(msg) - len, "FLUSH.");
501204076Spjd			break;
502204076Spjd		case HIO_WRITE:
503204076Spjd			(void)snprintf(msg + len, sizeof(msg) - len,
504204076Spjd			    "WRITE(%ju, %ju).", (uintmax_t)hio->hio_offset,
505204076Spjd			    (uintmax_t)hio->hio_length);
506204076Spjd			break;
507211882Spjd		case HIO_KEEPALIVE:
508211882Spjd			(void)snprintf(msg + len, sizeof(msg) - len, "KEEPALIVE.");
509211882Spjd			break;
510204076Spjd		default:
511204076Spjd			(void)snprintf(msg + len, sizeof(msg) - len,
512204076Spjd			    "UNKNOWN(%u).", (unsigned int)hio->hio_cmd);
513204076Spjd			break;
514204076Spjd		}
515204076Spjd	}
516204076Spjd	pjdlog_common(loglevel, debuglevel, error, "%s", msg);
517204076Spjd}
518204076Spjd
519204076Spjdstatic int
520226854Spjdrequnpack(struct hast_resource *res, struct hio *hio, struct nv *nv)
521204076Spjd{
522204076Spjd
523226854Spjd	hio->hio_cmd = nv_get_uint8(nv, "cmd");
524204076Spjd	if (hio->hio_cmd == 0) {
525204076Spjd		pjdlog_error("Header contains no 'cmd' field.");
526204076Spjd		hio->hio_error = EINVAL;
527204076Spjd		goto end;
528204076Spjd	}
529226854Spjd	if (hio->hio_cmd != HIO_KEEPALIVE) {
530226854Spjd		hio->hio_seq = nv_get_uint64(nv, "seq");
531226854Spjd		if (hio->hio_seq == 0) {
532226854Spjd			pjdlog_error("Header contains no 'seq' field.");
533226854Spjd			hio->hio_error = EINVAL;
534226854Spjd			goto end;
535226854Spjd		}
536226854Spjd	}
537204076Spjd	switch (hio->hio_cmd) {
538222164Spjd	case HIO_FLUSH:
539211882Spjd	case HIO_KEEPALIVE:
540211882Spjd		break;
541204076Spjd	case HIO_READ:
542204076Spjd	case HIO_WRITE:
543204076Spjd	case HIO_DELETE:
544226854Spjd		hio->hio_offset = nv_get_uint64(nv, "offset");
545226854Spjd		if (nv_error(nv) != 0) {
546204076Spjd			pjdlog_error("Header is missing 'offset' field.");
547204076Spjd			hio->hio_error = EINVAL;
548204076Spjd			goto end;
549204076Spjd		}
550226854Spjd		hio->hio_length = nv_get_uint64(nv, "length");
551226854Spjd		if (nv_error(nv) != 0) {
552204076Spjd			pjdlog_error("Header is missing 'length' field.");
553204076Spjd			hio->hio_error = EINVAL;
554204076Spjd			goto end;
555204076Spjd		}
556204076Spjd		if (hio->hio_length == 0) {
557204076Spjd			pjdlog_error("Data length is zero.");
558204076Spjd			hio->hio_error = EINVAL;
559204076Spjd			goto end;
560204076Spjd		}
561204076Spjd		if (hio->hio_length > MAXPHYS) {
562204076Spjd			pjdlog_error("Data length is too large (%ju > %ju).",
563204076Spjd			    (uintmax_t)hio->hio_length, (uintmax_t)MAXPHYS);
564204076Spjd			hio->hio_error = EINVAL;
565204076Spjd			goto end;
566204076Spjd		}
567204076Spjd		if ((hio->hio_offset % res->hr_local_sectorsize) != 0) {
568204076Spjd			pjdlog_error("Offset %ju is not multiple of sector size.",
569204076Spjd			    (uintmax_t)hio->hio_offset);
570204076Spjd			hio->hio_error = EINVAL;
571204076Spjd			goto end;
572204076Spjd		}
573204076Spjd		if ((hio->hio_length % res->hr_local_sectorsize) != 0) {
574204076Spjd			pjdlog_error("Length %ju is not multiple of sector size.",
575204076Spjd			    (uintmax_t)hio->hio_length);
576204076Spjd			hio->hio_error = EINVAL;
577204076Spjd			goto end;
578204076Spjd		}
579204076Spjd		if (hio->hio_offset + hio->hio_length >
580204076Spjd		    (uint64_t)res->hr_datasize) {
581204076Spjd			pjdlog_error("Data offset is too large (%ju > %ju).",
582204076Spjd			    (uintmax_t)(hio->hio_offset + hio->hio_length),
583204076Spjd			    (uintmax_t)res->hr_datasize);
584204076Spjd			hio->hio_error = EINVAL;
585204076Spjd			goto end;
586204076Spjd		}
587204076Spjd		break;
588204076Spjd	default:
589204076Spjd		pjdlog_error("Header contains invalid 'cmd' (%hhu).",
590204076Spjd		    hio->hio_cmd);
591204076Spjd		hio->hio_error = EINVAL;
592204076Spjd		goto end;
593204076Spjd	}
594204076Spjd	hio->hio_error = 0;
595204076Spjdend:
596204076Spjd	return (hio->hio_error);
597204076Spjd}
598204076Spjd
599212899Spjdstatic __dead2 void
600211984Spjdsecondary_exit(int exitcode, const char *fmt, ...)
601211984Spjd{
602211984Spjd	va_list ap;
603211984Spjd
604218138Spjd	PJDLOG_ASSERT(exitcode != EX_OK);
605211984Spjd	va_start(ap, fmt);
606211984Spjd	pjdlogv_errno(LOG_ERR, fmt, ap);
607211984Spjd	va_end(ap);
608212038Spjd	event_send(gres, EVENT_DISCONNECT);
609211984Spjd	exit(exitcode);
610211984Spjd}
611211984Spjd
612204076Spjd/*
613204076Spjd * Thread receives requests from the primary node.
614204076Spjd */
615204076Spjdstatic void *
616204076Spjdrecv_thread(void *arg)
617204076Spjd{
618204076Spjd	struct hast_resource *res = arg;
619204076Spjd	struct hio *hio;
620226854Spjd	struct nv *nv;
621204076Spjd
622204076Spjd	for (;;) {
623204076Spjd		pjdlog_debug(2, "recv: Taking free request.");
624211877Spjd		QUEUE_TAKE(free, hio);
625204076Spjd		pjdlog_debug(2, "recv: (%p) Got request.", hio);
626229945Spjd		if (hast_proto_recv_hdr(res->hr_remotein, &nv) == -1) {
627211984Spjd			secondary_exit(EX_TEMPFAIL,
628204076Spjd			    "Unable to receive request header");
629204076Spjd		}
630226854Spjd		if (requnpack(res, hio, nv) != 0) {
631226854Spjd			nv_free(nv);
632211877Spjd			pjdlog_debug(2,
633211877Spjd			    "recv: (%p) Moving request to the send queue.",
634211877Spjd			    hio);
635211877Spjd			QUEUE_INSERT(send, hio);
636211877Spjd			continue;
637211877Spjd		}
638222228Spjd		switch (hio->hio_cmd) {
639222228Spjd		case HIO_READ:
640222228Spjd			res->hr_stat_read++;
641222228Spjd			break;
642222228Spjd		case HIO_WRITE:
643222228Spjd			res->hr_stat_write++;
644222228Spjd			break;
645222228Spjd		case HIO_DELETE:
646222228Spjd			res->hr_stat_delete++;
647222228Spjd			break;
648222228Spjd		case HIO_FLUSH:
649222228Spjd			res->hr_stat_flush++;
650222228Spjd			break;
651226854Spjd		case HIO_KEEPALIVE:
652226854Spjd			break;
653226854Spjd		default:
654226854Spjd			PJDLOG_ABORT("Unexpected command (cmd=%hhu).",
655226854Spjd			    hio->hio_cmd);
656222228Spjd		}
657204076Spjd		reqlog(LOG_DEBUG, 2, -1, hio,
658204076Spjd		    "recv: (%p) Got request header: ", hio);
659211882Spjd		if (hio->hio_cmd == HIO_KEEPALIVE) {
660226854Spjd			nv_free(nv);
661211882Spjd			pjdlog_debug(2,
662211882Spjd			    "recv: (%p) Moving request to the free queue.",
663211882Spjd			    hio);
664226854Spjd			hio_clear(hio);
665211882Spjd			QUEUE_INSERT(free, hio);
666211882Spjd			continue;
667211882Spjd		} else if (hio->hio_cmd == HIO_WRITE) {
668226854Spjd			if (hast_proto_recv_data(res, res->hr_remotein, nv,
669229945Spjd			    hio->hio_data, MAXPHYS) == -1) {
670211984Spjd				secondary_exit(EX_TEMPFAIL,
671212051Spjd				    "Unable to receive request data");
672204076Spjd			}
673204076Spjd		}
674226854Spjd		nv_free(nv);
675204076Spjd		pjdlog_debug(2, "recv: (%p) Moving request to the disk queue.",
676204076Spjd		    hio);
677211877Spjd		QUEUE_INSERT(disk, hio);
678204076Spjd	}
679204076Spjd	/* NOTREACHED */
680204076Spjd	return (NULL);
681204076Spjd}
682204076Spjd
683204076Spjd/*
684204076Spjd * Thread reads from or writes to local component and also handles DELETE and
685204076Spjd * FLUSH requests.
686204076Spjd */
687204076Spjdstatic void *
688204076Spjddisk_thread(void *arg)
689204076Spjd{
690204076Spjd	struct hast_resource *res = arg;
691204076Spjd	struct hio *hio;
692204076Spjd	ssize_t ret;
693225832Spjd	bool clear_activemap, logerror;
694204076Spjd
695204076Spjd	clear_activemap = true;
696204076Spjd
697204076Spjd	for (;;) {
698204076Spjd		pjdlog_debug(2, "disk: Taking request.");
699211877Spjd		QUEUE_TAKE(disk, hio);
700204076Spjd		while (clear_activemap) {
701204076Spjd			unsigned char *map;
702204076Spjd			size_t mapsize;
703204076Spjd
704204076Spjd			/*
705204076Spjd			 * When first request is received, it means that primary
706204076Spjd			 * already received our activemap, merged it and stored
707204076Spjd			 * locally. We can now safely clear our activemap.
708204076Spjd			 */
709204076Spjd			mapsize =
710204076Spjd			    activemap_calc_ondisk_size(res->hr_local_mediasize -
711204076Spjd			    METADATA_SIZE, res->hr_extentsize,
712204076Spjd			    res->hr_local_sectorsize);
713204076Spjd			map = calloc(1, mapsize);
714204076Spjd			if (map == NULL) {
715204076Spjd				pjdlog_warning("Unable to allocate memory to clear local activemap.");
716204076Spjd				break;
717204076Spjd			}
718204076Spjd			if (pwrite(res->hr_localfd, map, mapsize,
719204076Spjd			    METADATA_SIZE) != (ssize_t)mapsize) {
720204076Spjd				pjdlog_errno(LOG_WARNING,
721204076Spjd				    "Unable to store cleared activemap");
722204076Spjd				free(map);
723204076Spjd				break;
724204076Spjd			}
725204076Spjd			free(map);
726204076Spjd			clear_activemap = false;
727204076Spjd			pjdlog_debug(1, "Local activemap cleared.");
728225831Spjd			break;
729204076Spjd		}
730204076Spjd		reqlog(LOG_DEBUG, 2, -1, hio, "disk: (%p) Got request: ", hio);
731225832Spjd		logerror = true;
732204076Spjd		/* Handle the actual request. */
733204076Spjd		switch (hio->hio_cmd) {
734204076Spjd		case HIO_READ:
735204076Spjd			ret = pread(res->hr_localfd, hio->hio_data,
736204076Spjd			    hio->hio_length,
737204076Spjd			    hio->hio_offset + res->hr_localoff);
738229945Spjd			if (ret == -1)
739204076Spjd				hio->hio_error = errno;
740204076Spjd			else if (ret != (int64_t)hio->hio_length)
741204076Spjd				hio->hio_error = EIO;
742204076Spjd			else
743204076Spjd				hio->hio_error = 0;
744204076Spjd			break;
745204076Spjd		case HIO_WRITE:
746204076Spjd			ret = pwrite(res->hr_localfd, hio->hio_data,
747204076Spjd			    hio->hio_length,
748204076Spjd			    hio->hio_offset + res->hr_localoff);
749229945Spjd			if (ret == -1)
750204076Spjd				hio->hio_error = errno;
751204076Spjd			else if (ret != (int64_t)hio->hio_length)
752204076Spjd				hio->hio_error = EIO;
753204076Spjd			else
754204076Spjd				hio->hio_error = 0;
755204076Spjd			break;
756204076Spjd		case HIO_DELETE:
757204076Spjd			ret = g_delete(res->hr_localfd,
758204076Spjd			    hio->hio_offset + res->hr_localoff,
759204076Spjd			    hio->hio_length);
760229945Spjd			if (ret == -1)
761204076Spjd				hio->hio_error = errno;
762204076Spjd			else
763204076Spjd				hio->hio_error = 0;
764204076Spjd			break;
765204076Spjd		case HIO_FLUSH:
766225832Spjd			if (!res->hr_localflush) {
767225832Spjd				ret = -1;
768225832Spjd				hio->hio_error = EOPNOTSUPP;
769225832Spjd				logerror = false;
770225832Spjd				break;
771225832Spjd			}
772204076Spjd			ret = g_flush(res->hr_localfd);
773229945Spjd			if (ret == -1) {
774225832Spjd				if (errno == EOPNOTSUPP)
775225832Spjd					res->hr_localflush = false;
776204076Spjd				hio->hio_error = errno;
777225832Spjd			} else {
778204076Spjd				hio->hio_error = 0;
779225832Spjd			}
780204076Spjd			break;
781226854Spjd		default:
782226854Spjd			PJDLOG_ABORT("Unexpected command (cmd=%hhu).",
783226854Spjd			    hio->hio_cmd);
784204076Spjd		}
785225832Spjd		if (logerror && hio->hio_error != 0) {
786204076Spjd			reqlog(LOG_ERR, 0, hio->hio_error, hio,
787204076Spjd			    "Request failed: ");
788204076Spjd		}
789204076Spjd		pjdlog_debug(2, "disk: (%p) Moving request to the send queue.",
790204076Spjd		    hio);
791211877Spjd		QUEUE_INSERT(send, hio);
792204076Spjd	}
793204076Spjd	/* NOTREACHED */
794204076Spjd	return (NULL);
795204076Spjd}
796204076Spjd
797204076Spjd/*
798204076Spjd * Thread sends requests back to primary node.
799204076Spjd */
800204076Spjdstatic void *
801204076Spjdsend_thread(void *arg)
802204076Spjd{
803204076Spjd	struct hast_resource *res = arg;
804204076Spjd	struct nv *nvout;
805204076Spjd	struct hio *hio;
806204076Spjd	void *data;
807204076Spjd	size_t length;
808204076Spjd
809204076Spjd	for (;;) {
810204076Spjd		pjdlog_debug(2, "send: Taking request.");
811211877Spjd		QUEUE_TAKE(send, hio);
812204076Spjd		reqlog(LOG_DEBUG, 2, -1, hio, "send: (%p) Got request: ", hio);
813204076Spjd		nvout = nv_alloc();
814204076Spjd		/* Copy sequence number. */
815226854Spjd		nv_add_uint64(nvout, hio->hio_seq, "seq");
816204076Spjd		switch (hio->hio_cmd) {
817204076Spjd		case HIO_READ:
818204076Spjd			if (hio->hio_error == 0) {
819204076Spjd				data = hio->hio_data;
820204076Spjd				length = hio->hio_length;
821204076Spjd				break;
822204076Spjd			}
823204076Spjd			/*
824204076Spjd			 * We send no data in case of an error.
825204076Spjd			 */
826204076Spjd			/* FALLTHROUGH */
827204076Spjd		case HIO_DELETE:
828204076Spjd		case HIO_FLUSH:
829204076Spjd		case HIO_WRITE:
830204076Spjd			data = NULL;
831204076Spjd			length = 0;
832204076Spjd			break;
833204076Spjd		default:
834225782Spjd			PJDLOG_ABORT("Unexpected command (cmd=%hhu).",
835225782Spjd			    hio->hio_cmd);
836204076Spjd		}
837204076Spjd		if (hio->hio_error != 0)
838204076Spjd			nv_add_int16(nvout, hio->hio_error, "error");
839204076Spjd		if (hast_proto_send(res, res->hr_remoteout, nvout, data,
840229945Spjd		    length) == -1) {
841211984Spjd			secondary_exit(EX_TEMPFAIL, "Unable to send reply.");
842204076Spjd		}
843204076Spjd		nv_free(nvout);
844209185Spjd		pjdlog_debug(2, "send: (%p) Moving request to the free queue.",
845204076Spjd		    hio);
846226854Spjd		hio_clear(hio);
847211877Spjd		QUEUE_INSERT(free, hio);
848204076Spjd	}
849204076Spjd	/* NOTREACHED */
850204076Spjd	return (NULL);
851204076Spjd}
852