secondary.c revision 226861
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 226861 2011-10-27 20:36:35Z 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
184204076Spjd	if (metadata_read(res, true) < 0)
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	map = NULL;
203204076Spjd	mapsize = 0;
204204076Spjd	nvout = nv_alloc();
205204076Spjd	nv_add_int64(nvout, (int64_t)res->hr_datasize, "datasize");
206204076Spjd	nv_add_int32(nvout, (int32_t)res->hr_extentsize, "extentsize");
207204076Spjd	resuid = nv_get_uint64(nvin, "resuid");
208204076Spjd	res->hr_primary_localcnt = nv_get_uint64(nvin, "localcnt");
209204076Spjd	res->hr_primary_remotecnt = nv_get_uint64(nvin, "remotecnt");
210204076Spjd	nv_add_uint64(nvout, res->hr_secondary_localcnt, "localcnt");
211204076Spjd	nv_add_uint64(nvout, res->hr_secondary_remotecnt, "remotecnt");
212204076Spjd	mapsize = activemap_calc_ondisk_size(res->hr_local_mediasize -
213204076Spjd	    METADATA_SIZE, res->hr_extentsize, res->hr_local_sectorsize);
214204076Spjd	map = malloc(mapsize);
215204076Spjd	if (map == NULL) {
216204076Spjd		pjdlog_exitx(EX_TEMPFAIL,
217204076Spjd		    "Unable to allocate memory (%zu bytes) for activemap.",
218204076Spjd		    mapsize);
219204076Spjd	}
220204076Spjd	/*
221204076Spjd	 * When we work as primary and secondary is missing we will increase
222204076Spjd	 * localcnt in our metadata. When secondary is connected and synced
223204076Spjd	 * we make localcnt be equal to remotecnt, which means nodes are more
224204076Spjd	 * or less in sync.
225204076Spjd	 * Split-brain condition is when both nodes are not able to communicate
226204076Spjd	 * and are both configured as primary nodes. In turn, they can both
227204076Spjd	 * make incompatible changes to the data and we have to detect that.
228204076Spjd	 * Under split-brain condition we will increase our localcnt on first
229204076Spjd	 * write and remote node will increase its localcnt on first write.
230204076Spjd	 * When we connect we can see that primary's localcnt is greater than
231204076Spjd	 * our remotecnt (primary was modified while we weren't watching) and
232204076Spjd	 * our localcnt is greater than primary's remotecnt (we were modified
233204076Spjd	 * while primary wasn't watching).
234204076Spjd	 * There are many possible combinations which are all gathered below.
235204076Spjd	 * Don't pay too much attention to exact numbers, the more important
236204076Spjd	 * is to compare them. We compare secondary's local with primary's
237204076Spjd	 * remote and secondary's remote with primary's local.
238204076Spjd	 * Note that every case where primary's localcnt is smaller than
239204076Spjd	 * secondary's remotecnt and where secondary's localcnt is smaller than
240204076Spjd	 * primary's remotecnt should be impossible in practise. We will perform
241204076Spjd	 * full synchronization then. Those cases are marked with an asterisk.
242204076Spjd	 * Regular synchronization means that only extents marked as dirty are
243204076Spjd	 * synchronized (regular synchronization).
244204076Spjd	 *
245204076Spjd	 * SECONDARY METADATA PRIMARY METADATA
246204076Spjd	 * local=3 remote=3   local=2 remote=2*  ?! Full sync from secondary.
247204076Spjd	 * local=3 remote=3   local=2 remote=3*  ?! Full sync from primary.
248204076Spjd	 * local=3 remote=3   local=2 remote=4*  ?! Full sync from primary.
249204076Spjd	 * local=3 remote=3   local=3 remote=2   Primary is out-of-date,
250204076Spjd	 *                                       regular sync from secondary.
251204076Spjd	 * local=3 remote=3   local=3 remote=3   Regular sync just in case.
252204076Spjd	 * local=3 remote=3   local=3 remote=4*  ?! Full sync from primary.
253204076Spjd	 * local=3 remote=3   local=4 remote=2   Split-brain condition.
254204076Spjd	 * local=3 remote=3   local=4 remote=3   Secondary out-of-date,
255204076Spjd	 *                                       regular sync from primary.
256204076Spjd	 * local=3 remote=3   local=4 remote=4*  ?! Full sync from primary.
257204076Spjd	 */
258204076Spjd	if (res->hr_resuid == 0) {
259204076Spjd		/*
260214284Spjd		 * Provider is used for the first time. If primary node done no
261214284Spjd		 * writes yet as well (we will find "virgin" argument) then
262214284Spjd		 * there is no need to synchronize anything. If primary node
263214284Spjd		 * done any writes already we have to synchronize everything.
264204076Spjd		 */
265218138Spjd		PJDLOG_ASSERT(res->hr_secondary_localcnt == 0);
266204076Spjd		res->hr_resuid = resuid;
267204076Spjd		if (metadata_write(res) < 0)
268204076Spjd			exit(EX_NOINPUT);
269214284Spjd		if (nv_exists(nvin, "virgin")) {
270214284Spjd			free(map);
271214284Spjd			map = NULL;
272214284Spjd			mapsize = 0;
273214284Spjd		} else {
274214284Spjd			memset(map, 0xff, mapsize);
275214284Spjd		}
276220865Spjd		nv_add_int8(nvout, 1, "virgin");
277204076Spjd		nv_add_uint8(nvout, HAST_SYNCSRC_PRIMARY, "syncsrc");
278219830Spjd	} else if (res->hr_resuid != resuid) {
279219830Spjd		char errmsg[256];
280219830Spjd
281226854Spjd		free(map);
282219830Spjd		(void)snprintf(errmsg, sizeof(errmsg),
283219830Spjd		    "Resource unique ID mismatch (primary=%ju, secondary=%ju).",
284219830Spjd		    (uintmax_t)resuid, (uintmax_t)res->hr_resuid);
285219830Spjd		pjdlog_error("%s", errmsg);
286219830Spjd		nv_add_string(nvout, errmsg, "errmsg");
287219830Spjd		if (hast_proto_send(res, res->hr_remotein, nvout, NULL, 0) < 0) {
288219830Spjd			pjdlog_exit(EX_TEMPFAIL, "Unable to send response to %s",
289219830Spjd			    res->hr_remoteaddr);
290219830Spjd		}
291219831Spjd		nv_free(nvout);
292219830Spjd		exit(EX_CONFIG);
293204076Spjd	} else if (
294226842Spjd	    /* Is primary out-of-date? */
295204076Spjd	    (res->hr_secondary_localcnt > res->hr_primary_remotecnt &&
296204076Spjd	     res->hr_secondary_remotecnt == res->hr_primary_localcnt) ||
297226842Spjd	    /* Are the nodes more or less in sync? */
298204076Spjd	    (res->hr_secondary_localcnt == res->hr_primary_remotecnt &&
299204076Spjd	     res->hr_secondary_remotecnt == res->hr_primary_localcnt) ||
300226842Spjd	    /* Is secondary out-of-date? */
301204076Spjd	    (res->hr_secondary_localcnt == res->hr_primary_remotecnt &&
302204076Spjd	     res->hr_secondary_remotecnt < res->hr_primary_localcnt)) {
303204076Spjd		/*
304204076Spjd		 * Nodes are more or less in sync or one of the nodes is
305204076Spjd		 * out-of-date.
306204076Spjd		 * It doesn't matter at this point which one, we just have to
307204076Spjd		 * send out local bitmap to the remote node.
308204076Spjd		 */
309204076Spjd		if (pread(res->hr_localfd, map, mapsize, METADATA_SIZE) !=
310204076Spjd		    (ssize_t)mapsize) {
311204076Spjd			pjdlog_exit(LOG_ERR, "Unable to read activemap");
312204076Spjd		}
313204076Spjd		if (res->hr_secondary_localcnt > res->hr_primary_remotecnt &&
314204076Spjd		     res->hr_secondary_remotecnt == res->hr_primary_localcnt) {
315204076Spjd			/* Primary is out-of-date, sync from secondary. */
316204076Spjd			nv_add_uint8(nvout, HAST_SYNCSRC_SECONDARY, "syncsrc");
317204076Spjd		} else {
318204076Spjd			/*
319204076Spjd			 * Secondary is out-of-date or counts match.
320204076Spjd			 * Sync from primary.
321204076Spjd			 */
322204076Spjd			nv_add_uint8(nvout, HAST_SYNCSRC_PRIMARY, "syncsrc");
323204076Spjd		}
324204076Spjd	} else if (res->hr_secondary_localcnt > res->hr_primary_remotecnt &&
325204076Spjd	     res->hr_primary_localcnt > res->hr_secondary_remotecnt) {
326204076Spjd		/*
327204076Spjd		 * Not good, we have split-brain condition.
328204076Spjd		 */
329226854Spjd		free(map);
330204076Spjd		pjdlog_error("Split-brain detected, exiting.");
331204076Spjd		nv_add_string(nvout, "Split-brain condition!", "errmsg");
332226854Spjd		if (hast_proto_send(res, res->hr_remotein, nvout, NULL, 0) < 0) {
333226854Spjd			pjdlog_exit(EX_TEMPFAIL, "Unable to send response to %s",
334226854Spjd			    res->hr_remoteaddr);
335226854Spjd		}
336226854Spjd		nv_free(nvout);
337226854Spjd		/* Exit on split-brain. */
338226854Spjd		event_send(res, EVENT_SPLITBRAIN);
339226854Spjd		exit(EX_CONFIG);
340204076Spjd	} else /* if (res->hr_secondary_localcnt < res->hr_primary_remotecnt ||
341204076Spjd	    res->hr_primary_localcnt < res->hr_secondary_remotecnt) */ {
342204076Spjd		/*
343204076Spjd		 * This should never happen in practise, but we will perform
344204076Spjd		 * full synchronization.
345204076Spjd		 */
346218138Spjd		PJDLOG_ASSERT(res->hr_secondary_localcnt < res->hr_primary_remotecnt ||
347204076Spjd		    res->hr_primary_localcnt < res->hr_secondary_remotecnt);
348204076Spjd		mapsize = activemap_calc_ondisk_size(res->hr_local_mediasize -
349204076Spjd		    METADATA_SIZE, res->hr_extentsize,
350204076Spjd		    res->hr_local_sectorsize);
351204076Spjd		memset(map, 0xff, mapsize);
352204076Spjd		if (res->hr_secondary_localcnt > res->hr_primary_remotecnt) {
353204076Spjd			/* In this one of five cases sync from secondary. */
354204076Spjd			nv_add_uint8(nvout, HAST_SYNCSRC_SECONDARY, "syncsrc");
355204076Spjd		} else {
356204076Spjd			/* For the rest four cases sync from primary. */
357204076Spjd			nv_add_uint8(nvout, HAST_SYNCSRC_PRIMARY, "syncsrc");
358204076Spjd		}
359204076Spjd		pjdlog_warning("This should never happen, asking for full synchronization (primary(local=%ju, remote=%ju), secondary(local=%ju, remote=%ju)).",
360204076Spjd		    (uintmax_t)res->hr_primary_localcnt,
361204076Spjd		    (uintmax_t)res->hr_primary_remotecnt,
362204076Spjd		    (uintmax_t)res->hr_secondary_localcnt,
363204076Spjd		    (uintmax_t)res->hr_secondary_remotecnt);
364204076Spjd	}
365220007Spjd	nv_add_uint32(nvout, (uint32_t)mapsize, "mapsize");
366204076Spjd	if (hast_proto_send(res, res->hr_remotein, nvout, map, mapsize) < 0) {
367214276Spjd		pjdlog_exit(EX_TEMPFAIL, "Unable to send activemap to %s",
368204076Spjd		    res->hr_remoteaddr);
369204076Spjd	}
370214275Spjd	if (map != NULL)
371214275Spjd		free(map);
372209182Spjd	nv_free(nvout);
373223181Strociny#ifdef notyet
374220271Spjd	/* Setup direction. */
375220271Spjd	if (proto_recv(res->hr_remotein, NULL, 0) == -1)
376220271Spjd		pjdlog_errno(LOG_WARNING, "Unable to set connection direction");
377223181Strociny#endif
378204076Spjd}
379204076Spjd
380204076Spjdvoid
381204076Spjdhastd_secondary(struct hast_resource *res, struct nv *nvin)
382204076Spjd{
383213009Spjd	sigset_t mask;
384204076Spjd	pthread_t td;
385204076Spjd	pid_t pid;
386219482Strociny	int error, mode, debuglevel;
387204076Spjd
388204076Spjd	/*
389204076Spjd	 * Create communication channel between parent and child.
390204076Spjd	 */
391219818Spjd	if (proto_client(NULL, "socketpair://", &res->hr_ctrl) < 0) {
392204076Spjd		KEEP_ERRNO((void)pidfile_remove(pfh));
393204076Spjd		pjdlog_exit(EX_OSERR,
394204076Spjd		    "Unable to create control sockets between parent and child");
395204076Spjd	}
396212038Spjd	/*
397212038Spjd	 * Create communication channel between child and parent.
398212038Spjd	 */
399219818Spjd	if (proto_client(NULL, "socketpair://", &res->hr_event) < 0) {
400212038Spjd		KEEP_ERRNO((void)pidfile_remove(pfh));
401212038Spjd		pjdlog_exit(EX_OSERR,
402212038Spjd		    "Unable to create event sockets between child and parent");
403212038Spjd	}
404204076Spjd
405204076Spjd	pid = fork();
406204076Spjd	if (pid < 0) {
407204076Spjd		KEEP_ERRNO((void)pidfile_remove(pfh));
408204076Spjd		pjdlog_exit(EX_OSERR, "Unable to fork");
409204076Spjd	}
410204076Spjd
411204076Spjd	if (pid > 0) {
412204076Spjd		/* This is parent. */
413204076Spjd		proto_close(res->hr_remotein);
414204076Spjd		res->hr_remotein = NULL;
415204076Spjd		proto_close(res->hr_remoteout);
416204076Spjd		res->hr_remoteout = NULL;
417212038Spjd		/* Declare that we are receiver. */
418212038Spjd		proto_recv(res->hr_event, NULL, 0);
419218043Spjd		/* Declare that we are sender. */
420218043Spjd		proto_send(res->hr_ctrl, NULL, 0);
421204076Spjd		res->hr_workerpid = pid;
422204076Spjd		return;
423204076Spjd	}
424211977Spjd
425211984Spjd	gres = res;
426218043Spjd	mode = pjdlog_mode_get();
427219482Strociny	debuglevel = pjdlog_debug_get();
428211984Spjd
429218043Spjd	/* Declare that we are sender. */
430218043Spjd	proto_send(res->hr_event, NULL, 0);
431218043Spjd	/* Declare that we are receiver. */
432218043Spjd	proto_recv(res->hr_ctrl, NULL, 0);
433218043Spjd	descriptors_cleanup(res);
434204076Spjd
435218045Spjd	descriptors_assert(res, mode);
436218045Spjd
437218043Spjd	pjdlog_init(mode);
438219482Strociny	pjdlog_debug_set(debuglevel);
439218043Spjd	pjdlog_prefix_set("[%s] (%s) ", res->hr_name, role2str(res->hr_role));
440220005Spjd	setproctitle("%s (%s)", res->hr_name, role2str(res->hr_role));
441204076Spjd
442213009Spjd	PJDLOG_VERIFY(sigemptyset(&mask) == 0);
443213009Spjd	PJDLOG_VERIFY(sigprocmask(SIG_SETMASK, &mask, NULL) == 0);
444210880Spjd
445207371Spjd	/* Error in setting timeout is not critical, but why should it fail? */
446219721Strociny	if (proto_timeout(res->hr_remotein, 2 * HAST_KEEPALIVE) < 0)
447207371Spjd		pjdlog_errno(LOG_WARNING, "Unable to set connection timeout");
448207371Spjd	if (proto_timeout(res->hr_remoteout, res->hr_timeout) < 0)
449207371Spjd		pjdlog_errno(LOG_WARNING, "Unable to set connection timeout");
450207371Spjd
451204076Spjd	init_local(res);
452213007Spjd	init_environment();
453213007Spjd
454221899Spjd	if (drop_privs(res) != 0)
455218049Spjd		exit(EX_CONFIG);
456218214Spjd	pjdlog_info("Privileges successfully dropped.");
457218049Spjd
458213007Spjd	/*
459213007Spjd	 * Create the control thread before sending any event to the parent,
460213007Spjd	 * as we can deadlock when parent sends control request to worker,
461213007Spjd	 * but worker has no control thread started yet, so parent waits.
462213007Spjd	 * In the meantime worker sends an event to the parent, but parent
463213007Spjd	 * is unable to handle the event, because it waits for control
464213007Spjd	 * request response.
465213007Spjd	 */
466213007Spjd	error = pthread_create(&td, NULL, ctrl_thread, res);
467218138Spjd	PJDLOG_ASSERT(error == 0);
468213007Spjd
469204076Spjd	init_remote(res, nvin);
470212038Spjd	event_send(res, EVENT_CONNECT);
471204076Spjd
472204076Spjd	error = pthread_create(&td, NULL, recv_thread, res);
473218138Spjd	PJDLOG_ASSERT(error == 0);
474204076Spjd	error = pthread_create(&td, NULL, disk_thread, res);
475218138Spjd	PJDLOG_ASSERT(error == 0);
476213007Spjd	(void)send_thread(res);
477204076Spjd}
478204076Spjd
479204076Spjdstatic void
480204076Spjdreqlog(int loglevel, int debuglevel, int error, struct hio *hio, const char *fmt, ...)
481204076Spjd{
482204076Spjd	char msg[1024];
483204076Spjd	va_list ap;
484204076Spjd	int len;
485204076Spjd
486204076Spjd	va_start(ap, fmt);
487204076Spjd	len = vsnprintf(msg, sizeof(msg), fmt, ap);
488204076Spjd	va_end(ap);
489204076Spjd	if ((size_t)len < sizeof(msg)) {
490204076Spjd		switch (hio->hio_cmd) {
491204076Spjd		case HIO_READ:
492204076Spjd			(void)snprintf(msg + len, sizeof(msg) - len,
493204076Spjd			    "READ(%ju, %ju).", (uintmax_t)hio->hio_offset,
494204076Spjd			    (uintmax_t)hio->hio_length);
495204076Spjd			break;
496204076Spjd		case HIO_DELETE:
497204076Spjd			(void)snprintf(msg + len, sizeof(msg) - len,
498204076Spjd			    "DELETE(%ju, %ju).", (uintmax_t)hio->hio_offset,
499204076Spjd			    (uintmax_t)hio->hio_length);
500204076Spjd			break;
501204076Spjd		case HIO_FLUSH:
502204076Spjd			(void)snprintf(msg + len, sizeof(msg) - len, "FLUSH.");
503204076Spjd			break;
504204076Spjd		case HIO_WRITE:
505204076Spjd			(void)snprintf(msg + len, sizeof(msg) - len,
506204076Spjd			    "WRITE(%ju, %ju).", (uintmax_t)hio->hio_offset,
507204076Spjd			    (uintmax_t)hio->hio_length);
508204076Spjd			break;
509211882Spjd		case HIO_KEEPALIVE:
510211882Spjd			(void)snprintf(msg + len, sizeof(msg) - len, "KEEPALIVE.");
511211882Spjd			break;
512204076Spjd		default:
513204076Spjd			(void)snprintf(msg + len, sizeof(msg) - len,
514204076Spjd			    "UNKNOWN(%u).", (unsigned int)hio->hio_cmd);
515204076Spjd			break;
516204076Spjd		}
517204076Spjd	}
518204076Spjd	pjdlog_common(loglevel, debuglevel, error, "%s", msg);
519204076Spjd}
520204076Spjd
521204076Spjdstatic int
522226854Spjdrequnpack(struct hast_resource *res, struct hio *hio, struct nv *nv)
523204076Spjd{
524204076Spjd
525226854Spjd	hio->hio_cmd = nv_get_uint8(nv, "cmd");
526204076Spjd	if (hio->hio_cmd == 0) {
527204076Spjd		pjdlog_error("Header contains no 'cmd' field.");
528204076Spjd		hio->hio_error = EINVAL;
529204076Spjd		goto end;
530204076Spjd	}
531226854Spjd	if (hio->hio_cmd != HIO_KEEPALIVE) {
532226854Spjd		hio->hio_seq = nv_get_uint64(nv, "seq");
533226854Spjd		if (hio->hio_seq == 0) {
534226854Spjd			pjdlog_error("Header contains no 'seq' field.");
535226854Spjd			hio->hio_error = EINVAL;
536226854Spjd			goto end;
537226854Spjd		}
538226854Spjd	}
539204076Spjd	switch (hio->hio_cmd) {
540222164Spjd	case HIO_FLUSH:
541211882Spjd	case HIO_KEEPALIVE:
542211882Spjd		break;
543204076Spjd	case HIO_READ:
544204076Spjd	case HIO_WRITE:
545204076Spjd	case HIO_DELETE:
546226854Spjd		hio->hio_offset = nv_get_uint64(nv, "offset");
547226854Spjd		if (nv_error(nv) != 0) {
548204076Spjd			pjdlog_error("Header is missing 'offset' field.");
549204076Spjd			hio->hio_error = EINVAL;
550204076Spjd			goto end;
551204076Spjd		}
552226854Spjd		hio->hio_length = nv_get_uint64(nv, "length");
553226854Spjd		if (nv_error(nv) != 0) {
554204076Spjd			pjdlog_error("Header is missing 'length' field.");
555204076Spjd			hio->hio_error = EINVAL;
556204076Spjd			goto end;
557204076Spjd		}
558204076Spjd		if (hio->hio_length == 0) {
559204076Spjd			pjdlog_error("Data length is zero.");
560204076Spjd			hio->hio_error = EINVAL;
561204076Spjd			goto end;
562204076Spjd		}
563204076Spjd		if (hio->hio_length > MAXPHYS) {
564204076Spjd			pjdlog_error("Data length is too large (%ju > %ju).",
565204076Spjd			    (uintmax_t)hio->hio_length, (uintmax_t)MAXPHYS);
566204076Spjd			hio->hio_error = EINVAL;
567204076Spjd			goto end;
568204076Spjd		}
569204076Spjd		if ((hio->hio_offset % res->hr_local_sectorsize) != 0) {
570204076Spjd			pjdlog_error("Offset %ju is not multiple of sector size.",
571204076Spjd			    (uintmax_t)hio->hio_offset);
572204076Spjd			hio->hio_error = EINVAL;
573204076Spjd			goto end;
574204076Spjd		}
575204076Spjd		if ((hio->hio_length % res->hr_local_sectorsize) != 0) {
576204076Spjd			pjdlog_error("Length %ju is not multiple of sector size.",
577204076Spjd			    (uintmax_t)hio->hio_length);
578204076Spjd			hio->hio_error = EINVAL;
579204076Spjd			goto end;
580204076Spjd		}
581204076Spjd		if (hio->hio_offset + hio->hio_length >
582204076Spjd		    (uint64_t)res->hr_datasize) {
583204076Spjd			pjdlog_error("Data offset is too large (%ju > %ju).",
584204076Spjd			    (uintmax_t)(hio->hio_offset + hio->hio_length),
585204076Spjd			    (uintmax_t)res->hr_datasize);
586204076Spjd			hio->hio_error = EINVAL;
587204076Spjd			goto end;
588204076Spjd		}
589204076Spjd		break;
590204076Spjd	default:
591204076Spjd		pjdlog_error("Header contains invalid 'cmd' (%hhu).",
592204076Spjd		    hio->hio_cmd);
593204076Spjd		hio->hio_error = EINVAL;
594204076Spjd		goto end;
595204076Spjd	}
596204076Spjd	hio->hio_error = 0;
597204076Spjdend:
598204076Spjd	return (hio->hio_error);
599204076Spjd}
600204076Spjd
601212899Spjdstatic __dead2 void
602211984Spjdsecondary_exit(int exitcode, const char *fmt, ...)
603211984Spjd{
604211984Spjd	va_list ap;
605211984Spjd
606218138Spjd	PJDLOG_ASSERT(exitcode != EX_OK);
607211984Spjd	va_start(ap, fmt);
608211984Spjd	pjdlogv_errno(LOG_ERR, fmt, ap);
609211984Spjd	va_end(ap);
610212038Spjd	event_send(gres, EVENT_DISCONNECT);
611211984Spjd	exit(exitcode);
612211984Spjd}
613211984Spjd
614204076Spjd/*
615204076Spjd * Thread receives requests from the primary node.
616204076Spjd */
617204076Spjdstatic void *
618204076Spjdrecv_thread(void *arg)
619204076Spjd{
620204076Spjd	struct hast_resource *res = arg;
621204076Spjd	struct hio *hio;
622226854Spjd	struct nv *nv;
623204076Spjd
624204076Spjd	for (;;) {
625204076Spjd		pjdlog_debug(2, "recv: Taking free request.");
626211877Spjd		QUEUE_TAKE(free, hio);
627204076Spjd		pjdlog_debug(2, "recv: (%p) Got request.", hio);
628226854Spjd		if (hast_proto_recv_hdr(res->hr_remotein, &nv) < 0) {
629211984Spjd			secondary_exit(EX_TEMPFAIL,
630204076Spjd			    "Unable to receive request header");
631204076Spjd		}
632226854Spjd		if (requnpack(res, hio, nv) != 0) {
633226854Spjd			nv_free(nv);
634211877Spjd			pjdlog_debug(2,
635211877Spjd			    "recv: (%p) Moving request to the send queue.",
636211877Spjd			    hio);
637211877Spjd			QUEUE_INSERT(send, hio);
638211877Spjd			continue;
639211877Spjd		}
640222228Spjd		switch (hio->hio_cmd) {
641222228Spjd		case HIO_READ:
642222228Spjd			res->hr_stat_read++;
643222228Spjd			break;
644222228Spjd		case HIO_WRITE:
645222228Spjd			res->hr_stat_write++;
646222228Spjd			break;
647222228Spjd		case HIO_DELETE:
648222228Spjd			res->hr_stat_delete++;
649222228Spjd			break;
650222228Spjd		case HIO_FLUSH:
651222228Spjd			res->hr_stat_flush++;
652222228Spjd			break;
653226854Spjd		case HIO_KEEPALIVE:
654226854Spjd			break;
655226854Spjd		default:
656226854Spjd			PJDLOG_ABORT("Unexpected command (cmd=%hhu).",
657226854Spjd			    hio->hio_cmd);
658222228Spjd		}
659204076Spjd		reqlog(LOG_DEBUG, 2, -1, hio,
660204076Spjd		    "recv: (%p) Got request header: ", hio);
661211882Spjd		if (hio->hio_cmd == HIO_KEEPALIVE) {
662226854Spjd			nv_free(nv);
663211882Spjd			pjdlog_debug(2,
664211882Spjd			    "recv: (%p) Moving request to the free queue.",
665211882Spjd			    hio);
666226854Spjd			hio_clear(hio);
667211882Spjd			QUEUE_INSERT(free, hio);
668211882Spjd			continue;
669211882Spjd		} else if (hio->hio_cmd == HIO_WRITE) {
670226854Spjd			if (hast_proto_recv_data(res, res->hr_remotein, nv,
671226854Spjd			    hio->hio_data, MAXPHYS) < 0) {
672211984Spjd				secondary_exit(EX_TEMPFAIL,
673212051Spjd				    "Unable to receive request data");
674204076Spjd			}
675204076Spjd		}
676226854Spjd		nv_free(nv);
677204076Spjd		pjdlog_debug(2, "recv: (%p) Moving request to the disk queue.",
678204076Spjd		    hio);
679211877Spjd		QUEUE_INSERT(disk, hio);
680204076Spjd	}
681204076Spjd	/* NOTREACHED */
682204076Spjd	return (NULL);
683204076Spjd}
684204076Spjd
685204076Spjd/*
686204076Spjd * Thread reads from or writes to local component and also handles DELETE and
687204076Spjd * FLUSH requests.
688204076Spjd */
689204076Spjdstatic void *
690204076Spjddisk_thread(void *arg)
691204076Spjd{
692204076Spjd	struct hast_resource *res = arg;
693204076Spjd	struct hio *hio;
694204076Spjd	ssize_t ret;
695225832Spjd	bool clear_activemap, logerror;
696204076Spjd
697204076Spjd	clear_activemap = true;
698204076Spjd
699204076Spjd	for (;;) {
700204076Spjd		pjdlog_debug(2, "disk: Taking request.");
701211877Spjd		QUEUE_TAKE(disk, hio);
702204076Spjd		while (clear_activemap) {
703204076Spjd			unsigned char *map;
704204076Spjd			size_t mapsize;
705204076Spjd
706204076Spjd			/*
707204076Spjd			 * When first request is received, it means that primary
708204076Spjd			 * already received our activemap, merged it and stored
709204076Spjd			 * locally. We can now safely clear our activemap.
710204076Spjd			 */
711204076Spjd			mapsize =
712204076Spjd			    activemap_calc_ondisk_size(res->hr_local_mediasize -
713204076Spjd			    METADATA_SIZE, res->hr_extentsize,
714204076Spjd			    res->hr_local_sectorsize);
715204076Spjd			map = calloc(1, mapsize);
716204076Spjd			if (map == NULL) {
717204076Spjd				pjdlog_warning("Unable to allocate memory to clear local activemap.");
718204076Spjd				break;
719204076Spjd			}
720204076Spjd			if (pwrite(res->hr_localfd, map, mapsize,
721204076Spjd			    METADATA_SIZE) != (ssize_t)mapsize) {
722204076Spjd				pjdlog_errno(LOG_WARNING,
723204076Spjd				    "Unable to store cleared activemap");
724204076Spjd				free(map);
725204076Spjd				break;
726204076Spjd			}
727204076Spjd			free(map);
728204076Spjd			clear_activemap = false;
729204076Spjd			pjdlog_debug(1, "Local activemap cleared.");
730225831Spjd			break;
731204076Spjd		}
732204076Spjd		reqlog(LOG_DEBUG, 2, -1, hio, "disk: (%p) Got request: ", hio);
733225832Spjd		logerror = true;
734204076Spjd		/* Handle the actual request. */
735204076Spjd		switch (hio->hio_cmd) {
736204076Spjd		case HIO_READ:
737204076Spjd			ret = pread(res->hr_localfd, hio->hio_data,
738204076Spjd			    hio->hio_length,
739204076Spjd			    hio->hio_offset + res->hr_localoff);
740204076Spjd			if (ret < 0)
741204076Spjd				hio->hio_error = errno;
742204076Spjd			else if (ret != (int64_t)hio->hio_length)
743204076Spjd				hio->hio_error = EIO;
744204076Spjd			else
745204076Spjd				hio->hio_error = 0;
746204076Spjd			break;
747204076Spjd		case HIO_WRITE:
748204076Spjd			ret = pwrite(res->hr_localfd, hio->hio_data,
749204076Spjd			    hio->hio_length,
750204076Spjd			    hio->hio_offset + res->hr_localoff);
751204076Spjd			if (ret < 0)
752204076Spjd				hio->hio_error = errno;
753204076Spjd			else if (ret != (int64_t)hio->hio_length)
754204076Spjd				hio->hio_error = EIO;
755204076Spjd			else
756204076Spjd				hio->hio_error = 0;
757204076Spjd			break;
758204076Spjd		case HIO_DELETE:
759204076Spjd			ret = g_delete(res->hr_localfd,
760204076Spjd			    hio->hio_offset + res->hr_localoff,
761204076Spjd			    hio->hio_length);
762204076Spjd			if (ret < 0)
763204076Spjd				hio->hio_error = errno;
764204076Spjd			else
765204076Spjd				hio->hio_error = 0;
766204076Spjd			break;
767204076Spjd		case HIO_FLUSH:
768225832Spjd			if (!res->hr_localflush) {
769225832Spjd				ret = -1;
770225832Spjd				hio->hio_error = EOPNOTSUPP;
771225832Spjd				logerror = false;
772225832Spjd				break;
773225832Spjd			}
774204076Spjd			ret = g_flush(res->hr_localfd);
775225832Spjd			if (ret < 0) {
776225832Spjd				if (errno == EOPNOTSUPP)
777225832Spjd					res->hr_localflush = false;
778204076Spjd				hio->hio_error = errno;
779225832Spjd			} else {
780204076Spjd				hio->hio_error = 0;
781225832Spjd			}
782204076Spjd			break;
783226854Spjd		default:
784226854Spjd			PJDLOG_ABORT("Unexpected command (cmd=%hhu).",
785226854Spjd			    hio->hio_cmd);
786204076Spjd		}
787225832Spjd		if (logerror && hio->hio_error != 0) {
788204076Spjd			reqlog(LOG_ERR, 0, hio->hio_error, hio,
789204076Spjd			    "Request failed: ");
790204076Spjd		}
791204076Spjd		pjdlog_debug(2, "disk: (%p) Moving request to the send queue.",
792204076Spjd		    hio);
793211877Spjd		QUEUE_INSERT(send, hio);
794204076Spjd	}
795204076Spjd	/* NOTREACHED */
796204076Spjd	return (NULL);
797204076Spjd}
798204076Spjd
799204076Spjd/*
800204076Spjd * Thread sends requests back to primary node.
801204076Spjd */
802204076Spjdstatic void *
803204076Spjdsend_thread(void *arg)
804204076Spjd{
805204076Spjd	struct hast_resource *res = arg;
806204076Spjd	struct nv *nvout;
807204076Spjd	struct hio *hio;
808204076Spjd	void *data;
809204076Spjd	size_t length;
810204076Spjd
811204076Spjd	for (;;) {
812204076Spjd		pjdlog_debug(2, "send: Taking request.");
813211877Spjd		QUEUE_TAKE(send, hio);
814204076Spjd		reqlog(LOG_DEBUG, 2, -1, hio, "send: (%p) Got request: ", hio);
815204076Spjd		nvout = nv_alloc();
816204076Spjd		/* Copy sequence number. */
817226854Spjd		nv_add_uint64(nvout, hio->hio_seq, "seq");
818204076Spjd		switch (hio->hio_cmd) {
819204076Spjd		case HIO_READ:
820204076Spjd			if (hio->hio_error == 0) {
821204076Spjd				data = hio->hio_data;
822204076Spjd				length = hio->hio_length;
823204076Spjd				break;
824204076Spjd			}
825204076Spjd			/*
826204076Spjd			 * We send no data in case of an error.
827204076Spjd			 */
828204076Spjd			/* FALLTHROUGH */
829204076Spjd		case HIO_DELETE:
830204076Spjd		case HIO_FLUSH:
831204076Spjd		case HIO_WRITE:
832204076Spjd			data = NULL;
833204076Spjd			length = 0;
834204076Spjd			break;
835204076Spjd		default:
836225782Spjd			PJDLOG_ABORT("Unexpected command (cmd=%hhu).",
837225782Spjd			    hio->hio_cmd);
838204076Spjd		}
839204076Spjd		if (hio->hio_error != 0)
840204076Spjd			nv_add_int16(nvout, hio->hio_error, "error");
841204076Spjd		if (hast_proto_send(res, res->hr_remoteout, nvout, data,
842204076Spjd		    length) < 0) {
843211984Spjd			secondary_exit(EX_TEMPFAIL, "Unable to send reply.");
844204076Spjd		}
845204076Spjd		nv_free(nvout);
846209185Spjd		pjdlog_debug(2, "send: (%p) Moving request to the free queue.",
847204076Spjd		    hio);
848226854Spjd		hio_clear(hio);
849211877Spjd		QUEUE_INSERT(free, hio);
850204076Spjd	}
851204076Spjd	/* NOTREACHED */
852204076Spjd	return (NULL);
853204076Spjd}
854