secondary.c revision 222164
1283625Sdim/*-
2283625Sdim * Copyright (c) 2009-2010 The FreeBSD Foundation
3283625Sdim * Copyright (c) 2010 Pawel Jakub Dawidek <pjd@FreeBSD.org>
4283625Sdim * All rights reserved.
5283625Sdim *
6283625Sdim * This software was developed by Pawel Jakub Dawidek under sponsorship from
7283625Sdim * the FreeBSD Foundation.
8283625Sdim *
9283625Sdim * Redistribution and use in source and binary forms, with or without
10283625Sdim * modification, are permitted provided that the following conditions
11283625Sdim * are met:
12283625Sdim * 1. Redistributions of source code must retain the above copyright
13283625Sdim *    notice, this list of conditions and the following disclaimer.
14283625Sdim * 2. Redistributions in binary form must reproduce the above copyright
15283625Sdim *    notice, this list of conditions and the following disclaimer in the
16283625Sdim *    documentation and/or other materials provided with the distribution.
17283625Sdim *
18283625Sdim * THIS SOFTWARE IS PROVIDED BY THE AUTHORS AND CONTRIBUTORS ``AS IS'' AND
19283625Sdim * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20283625Sdim * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21283625Sdim * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE
22283625Sdim * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23283625Sdim * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24283625Sdim * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25283625Sdim * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26283625Sdim * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
27283625Sdim * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28283625Sdim * SUCH DAMAGE.
29283625Sdim */
30283625Sdim
31283625Sdim#include <sys/cdefs.h>
32283625Sdim__FBSDID("$FreeBSD: head/sbin/hastd/secondary.c 222164 2011-05-21 20:21:20Z pjd $");
33283625Sdim
34283625Sdim#include <sys/param.h>
35283625Sdim#include <sys/time.h>
36283625Sdim#include <sys/bio.h>
37283625Sdim#include <sys/disk.h>
38283625Sdim#include <sys/stat.h>
39283625Sdim
40283625Sdim#include <err.h>
41283625Sdim#include <errno.h>
42283625Sdim#include <fcntl.h>
43283625Sdim#include <libgeom.h>
44283625Sdim#include <pthread.h>
45283625Sdim#include <signal.h>
46296417Sdim#include <stdint.h>
47296417Sdim#include <stdio.h>
48283625Sdim#include <string.h>
49296417Sdim#include <sysexits.h>
50296417Sdim#include <unistd.h>
51296417Sdim
52283625Sdim#include <activemap.h>
53283625Sdim#include <nv.h>
54283625Sdim#include <pjdlog.h>
55283625Sdim
56283625Sdim#include "control.h"
57283625Sdim#include "event.h"
58283625Sdim#include "hast.h"
59283625Sdim#include "hast_proto.h"
60283625Sdim#include "hastd.h"
61283625Sdim#include "hooks.h"
62283625Sdim#include "metadata.h"
63283625Sdim#include "proto.h"
64283625Sdim#include "subr.h"
65283625Sdim#include "synch.h"
66283625Sdim
67296417Sdimstruct hio {
68296417Sdim	uint64_t	 hio_seq;
69283625Sdim	int		 hio_error;
70283625Sdim	struct nv	*hio_nv;
71283625Sdim	void		*hio_data;
72283625Sdim	uint8_t		 hio_cmd;
73283625Sdim	uint64_t	 hio_offset;
74296417Sdim	uint64_t	 hio_length;
75283625Sdim	TAILQ_ENTRY(hio) hio_next;
76283625Sdim};
77283625Sdim
78283625Sdimstatic struct hast_resource *gres;
79283625Sdim
80283625Sdim/*
81283625Sdim * Free list holds unused structures. When free list is empty, we have to wait
82283625Sdim * until some in-progress requests are freed.
83283625Sdim */
84283625Sdimstatic TAILQ_HEAD(, hio) hio_free_list;
85283625Sdimstatic pthread_mutex_t hio_free_list_lock;
86283625Sdimstatic pthread_cond_t hio_free_list_cond;
87296417Sdim/*
88296417Sdim * Disk thread (the one that do I/O requests) takes requests from this list.
89296417Sdim */
90296417Sdimstatic TAILQ_HEAD(, hio) hio_disk_list;
91283625Sdimstatic pthread_mutex_t hio_disk_list_lock;
92283625Sdimstatic pthread_cond_t hio_disk_list_cond;
93283625Sdim/*
94283625Sdim * There is one recv list for every component, although local components don't
95283625Sdim * use recv lists as local requests are done synchronously.
96283625Sdim */
97283625Sdimstatic TAILQ_HEAD(, hio) hio_send_list;
98283625Sdimstatic pthread_mutex_t hio_send_list_lock;
99283625Sdimstatic pthread_cond_t hio_send_list_cond;
100283625Sdim
101283625Sdim/*
102283625Sdim * Maximum number of outstanding I/O requests.
103283625Sdim */
104283625Sdim#define	HAST_HIO_MAX	256
105283625Sdim
106283625Sdimstatic void *recv_thread(void *arg);
107283625Sdimstatic void *disk_thread(void *arg);
108283625Sdimstatic void *send_thread(void *arg);
109283625Sdim
110283625Sdim#define	QUEUE_INSERT(name, hio)	do {					\
111283625Sdim	bool _wakeup;							\
112283625Sdim									\
113283625Sdim	mtx_lock(&hio_##name##_list_lock);				\
114283625Sdim	_wakeup = TAILQ_EMPTY(&hio_##name##_list);			\
115283625Sdim	TAILQ_INSERT_TAIL(&hio_##name##_list, (hio), hio_next);		\
116283625Sdim	mtx_unlock(&hio_##name##_list_lock);				\
117283625Sdim	if (_wakeup)							\
118283625Sdim		cv_signal(&hio_##name##_list_cond);			\
119283625Sdim} while (0)
120283625Sdim#define	QUEUE_TAKE(name, hio)	do {					\
121283625Sdim	mtx_lock(&hio_##name##_list_lock);				\
122283625Sdim	while (((hio) = TAILQ_FIRST(&hio_##name##_list)) == NULL) {	\
123283625Sdim		cv_wait(&hio_##name##_list_cond,			\
124283625Sdim		    &hio_##name##_list_lock);				\
125283625Sdim	}								\
126296417Sdim	TAILQ_REMOVE(&hio_##name##_list, (hio), hio_next);		\
127296417Sdim	mtx_unlock(&hio_##name##_list_lock);				\
128296417Sdim} while (0)
129296417Sdim
130296417Sdimstatic void
131283625Sdiminit_environment(void)
132283625Sdim{
133283625Sdim	struct hio *hio;
134283625Sdim	unsigned int ii;
135296417Sdim
136283625Sdim	/*
137296417Sdim	 * Initialize lists, their locks and theirs condition variables.
138296417Sdim	 */
139296417Sdim	TAILQ_INIT(&hio_free_list);
140296417Sdim	mtx_init(&hio_free_list_lock);
141296417Sdim	cv_init(&hio_free_list_cond);
142296417Sdim	TAILQ_INIT(&hio_disk_list);
143296417Sdim	mtx_init(&hio_disk_list_lock);
144296417Sdim	cv_init(&hio_disk_list_cond);
145296417Sdim	TAILQ_INIT(&hio_send_list);
146296417Sdim	mtx_init(&hio_send_list_lock);
147296417Sdim	cv_init(&hio_send_list_cond);
148296417Sdim
149296417Sdim	/*
150296417Sdim	 * Allocate requests pool and initialize requests.
151296417Sdim	 */
152283625Sdim	for (ii = 0; ii < HAST_HIO_MAX; ii++) {
153283625Sdim		hio = malloc(sizeof(*hio));
154283625Sdim		if (hio == NULL) {
155283625Sdim			pjdlog_exitx(EX_TEMPFAIL,
156283625Sdim			    "Unable to allocate memory (%zu bytes) for hio request.",
157296417Sdim			    sizeof(*hio));
158283625Sdim		}
159283625Sdim		hio->hio_error = 0;
160283625Sdim		hio->hio_data = malloc(MAXPHYS);
161283625Sdim		if (hio->hio_data == NULL) {
162283625Sdim			pjdlog_exitx(EX_TEMPFAIL,
163283625Sdim			    "Unable to allocate memory (%zu bytes) for gctl_data.",
164283625Sdim			    (size_t)MAXPHYS);
165283625Sdim		}
166283625Sdim		TAILQ_INSERT_HEAD(&hio_free_list, hio, hio_next);
167283625Sdim	}
168283625Sdim}
169283625Sdim
170283625Sdimstatic void
171283625Sdiminit_local(struct hast_resource *res)
172283625Sdim{
173296417Sdim
174296417Sdim	if (metadata_read(res, true) < 0)
175283625Sdim		exit(EX_NOINPUT);
176283625Sdim}
177283625Sdim
178283625Sdimstatic void
179283625Sdiminit_remote(struct hast_resource *res, struct nv *nvin)
180283625Sdim{
181283625Sdim	uint64_t resuid;
182283625Sdim	struct nv *nvout;
183296417Sdim	unsigned char *map;
184296417Sdim	size_t mapsize;
185296417Sdim
186283625Sdim	/* Setup direction. */
187283625Sdim	if (proto_send(res->hr_remoteout, NULL, 0) == -1)
188283625Sdim		pjdlog_errno(LOG_WARNING, "Unable to set connection direction");
189283625Sdim
190283625Sdim	map = NULL;
191283625Sdim	mapsize = 0;
192283625Sdim	nvout = nv_alloc();
193283625Sdim	nv_add_int64(nvout, (int64_t)res->hr_datasize, "datasize");
194283625Sdim	nv_add_int32(nvout, (int32_t)res->hr_extentsize, "extentsize");
195283625Sdim	resuid = nv_get_uint64(nvin, "resuid");
196283625Sdim	res->hr_primary_localcnt = nv_get_uint64(nvin, "localcnt");
197283625Sdim	res->hr_primary_remotecnt = nv_get_uint64(nvin, "remotecnt");
198283625Sdim	nv_add_uint64(nvout, res->hr_secondary_localcnt, "localcnt");
199283625Sdim	nv_add_uint64(nvout, res->hr_secondary_remotecnt, "remotecnt");
200283625Sdim	mapsize = activemap_calc_ondisk_size(res->hr_local_mediasize -
201283625Sdim	    METADATA_SIZE, res->hr_extentsize, res->hr_local_sectorsize);
202283625Sdim	map = malloc(mapsize);
203283625Sdim	if (map == NULL) {
204283625Sdim		pjdlog_exitx(EX_TEMPFAIL,
205283625Sdim		    "Unable to allocate memory (%zu bytes) for activemap.",
206283625Sdim		    mapsize);
207283625Sdim	}
208283625Sdim	/*
209283625Sdim	 * When we work as primary and secondary is missing we will increase
210283625Sdim	 * localcnt in our metadata. When secondary is connected and synced
211283625Sdim	 * we make localcnt be equal to remotecnt, which means nodes are more
212283625Sdim	 * or less in sync.
213283625Sdim	 * Split-brain condition is when both nodes are not able to communicate
214283625Sdim	 * and are both configured as primary nodes. In turn, they can both
215283625Sdim	 * make incompatible changes to the data and we have to detect that.
216283625Sdim	 * Under split-brain condition we will increase our localcnt on first
217283625Sdim	 * write and remote node will increase its localcnt on first write.
218283625Sdim	 * When we connect we can see that primary's localcnt is greater than
219283625Sdim	 * our remotecnt (primary was modified while we weren't watching) and
220283625Sdim	 * our localcnt is greater than primary's remotecnt (we were modified
221283625Sdim	 * while primary wasn't watching).
222283625Sdim	 * There are many possible combinations which are all gathered below.
223296417Sdim	 * Don't pay too much attention to exact numbers, the more important
224296417Sdim	 * is to compare them. We compare secondary's local with primary's
225283625Sdim	 * remote and secondary's remote with primary's local.
226283625Sdim	 * Note that every case where primary's localcnt is smaller than
227283625Sdim	 * secondary's remotecnt and where secondary's localcnt is smaller than
228283625Sdim	 * primary's remotecnt should be impossible in practise. We will perform
229283625Sdim	 * full synchronization then. Those cases are marked with an asterisk.
230283625Sdim	 * Regular synchronization means that only extents marked as dirty are
231296417Sdim	 * synchronized (regular synchronization).
232283625Sdim	 *
233283625Sdim	 * SECONDARY METADATA PRIMARY METADATA
234283625Sdim	 * local=3 remote=3   local=2 remote=2*  ?! Full sync from secondary.
235283625Sdim	 * local=3 remote=3   local=2 remote=3*  ?! Full sync from primary.
236283625Sdim	 * local=3 remote=3   local=2 remote=4*  ?! Full sync from primary.
237283625Sdim	 * local=3 remote=3   local=3 remote=2   Primary is out-of-date,
238296417Sdim	 *                                       regular sync from secondary.
239296417Sdim	 * local=3 remote=3   local=3 remote=3   Regular sync just in case.
240296417Sdim	 * local=3 remote=3   local=3 remote=4*  ?! Full sync from primary.
241296417Sdim	 * local=3 remote=3   local=4 remote=2   Split-brain condition.
242296417Sdim	 * local=3 remote=3   local=4 remote=3   Secondary out-of-date,
243296417Sdim	 *                                       regular sync from primary.
244296417Sdim	 * local=3 remote=3   local=4 remote=4*  ?! Full sync from primary.
245296417Sdim	 */
246296417Sdim	if (res->hr_resuid == 0) {
247283625Sdim		/*
248296417Sdim		 * Provider is used for the first time. If primary node done no
249296417Sdim		 * writes yet as well (we will find "virgin" argument) then
250296417Sdim		 * there is no need to synchronize anything. If primary node
251283625Sdim		 * done any writes already we have to synchronize everything.
252283625Sdim		 */
253283625Sdim		PJDLOG_ASSERT(res->hr_secondary_localcnt == 0);
254283625Sdim		res->hr_resuid = resuid;
255283625Sdim		if (metadata_write(res) < 0)
256283625Sdim			exit(EX_NOINPUT);
257283625Sdim		if (nv_exists(nvin, "virgin")) {
258283625Sdim			free(map);
259283625Sdim			map = NULL;
260283625Sdim			mapsize = 0;
261283625Sdim		} else {
262283625Sdim			memset(map, 0xff, mapsize);
263283625Sdim		}
264283625Sdim		nv_add_int8(nvout, 1, "virgin");
265283625Sdim		nv_add_uint8(nvout, HAST_SYNCSRC_PRIMARY, "syncsrc");
266283625Sdim	} else if (res->hr_resuid != resuid) {
267296417Sdim		char errmsg[256];
268296417Sdim
269283625Sdim		(void)snprintf(errmsg, sizeof(errmsg),
270283625Sdim		    "Resource unique ID mismatch (primary=%ju, secondary=%ju).",
271283625Sdim		    (uintmax_t)resuid, (uintmax_t)res->hr_resuid);
272296417Sdim		pjdlog_error("%s", errmsg);
273296417Sdim		nv_add_string(nvout, errmsg, "errmsg");
274283625Sdim		if (hast_proto_send(res, res->hr_remotein, nvout, NULL, 0) < 0) {
275283625Sdim			pjdlog_exit(EX_TEMPFAIL, "Unable to send response to %s",
276283625Sdim			    res->hr_remoteaddr);
277283625Sdim		}
278283625Sdim		nv_free(nvout);
279283625Sdim		exit(EX_CONFIG);
280283625Sdim	} else if (
281283625Sdim	    /* Is primary is out-of-date? */
282283625Sdim	    (res->hr_secondary_localcnt > res->hr_primary_remotecnt &&
283283625Sdim	     res->hr_secondary_remotecnt == res->hr_primary_localcnt) ||
284283625Sdim	    /* Nodes are more or less in sync? */
285283625Sdim	    (res->hr_secondary_localcnt == res->hr_primary_remotecnt &&
286283625Sdim	     res->hr_secondary_remotecnt == res->hr_primary_localcnt) ||
287283625Sdim	    /* Is secondary is out-of-date? */
288283625Sdim	    (res->hr_secondary_localcnt == res->hr_primary_remotecnt &&
289283625Sdim	     res->hr_secondary_remotecnt < res->hr_primary_localcnt)) {
290283625Sdim		/*
291283625Sdim		 * Nodes are more or less in sync or one of the nodes is
292283625Sdim		 * out-of-date.
293283625Sdim		 * It doesn't matter at this point which one, we just have to
294296417Sdim		 * send out local bitmap to the remote node.
295283625Sdim		 */
296283625Sdim		if (pread(res->hr_localfd, map, mapsize, METADATA_SIZE) !=
297283625Sdim		    (ssize_t)mapsize) {
298283625Sdim			pjdlog_exit(LOG_ERR, "Unable to read activemap");
299283625Sdim		}
300283625Sdim		if (res->hr_secondary_localcnt > res->hr_primary_remotecnt &&
301283625Sdim		     res->hr_secondary_remotecnt == res->hr_primary_localcnt) {
302283625Sdim			/* Primary is out-of-date, sync from secondary. */
303283625Sdim			nv_add_uint8(nvout, HAST_SYNCSRC_SECONDARY, "syncsrc");
304283625Sdim		} else {
305283625Sdim			/*
306283625Sdim			 * Secondary is out-of-date or counts match.
307283625Sdim			 * Sync from primary.
308283625Sdim			 */
309283625Sdim			nv_add_uint8(nvout, HAST_SYNCSRC_PRIMARY, "syncsrc");
310283625Sdim		}
311283625Sdim	} else if (res->hr_secondary_localcnt > res->hr_primary_remotecnt &&
312283625Sdim	     res->hr_primary_localcnt > res->hr_secondary_remotecnt) {
313283625Sdim		/*
314283625Sdim		 * Not good, we have split-brain condition.
315283625Sdim		 */
316283625Sdim		pjdlog_error("Split-brain detected, exiting.");
317283625Sdim		nv_add_string(nvout, "Split-brain condition!", "errmsg");
318283625Sdim		free(map);
319283625Sdim		map = NULL;
320283625Sdim		mapsize = 0;
321283625Sdim	} else /* if (res->hr_secondary_localcnt < res->hr_primary_remotecnt ||
322283625Sdim	    res->hr_primary_localcnt < res->hr_secondary_remotecnt) */ {
323283625Sdim		/*
324283625Sdim		 * This should never happen in practise, but we will perform
325296417Sdim		 * full synchronization.
326296417Sdim		 */
327296417Sdim		PJDLOG_ASSERT(res->hr_secondary_localcnt < res->hr_primary_remotecnt ||
328296417Sdim		    res->hr_primary_localcnt < res->hr_secondary_remotecnt);
329296417Sdim		mapsize = activemap_calc_ondisk_size(res->hr_local_mediasize -
330296417Sdim		    METADATA_SIZE, res->hr_extentsize,
331296417Sdim		    res->hr_local_sectorsize);
332296417Sdim		memset(map, 0xff, mapsize);
333296417Sdim		if (res->hr_secondary_localcnt > res->hr_primary_remotecnt) {
334296417Sdim			/* In this one of five cases sync from secondary. */
335296417Sdim			nv_add_uint8(nvout, HAST_SYNCSRC_SECONDARY, "syncsrc");
336296417Sdim		} else {
337296417Sdim			/* For the rest four cases sync from primary. */
338296417Sdim			nv_add_uint8(nvout, HAST_SYNCSRC_PRIMARY, "syncsrc");
339296417Sdim		}
340296417Sdim		pjdlog_warning("This should never happen, asking for full synchronization (primary(local=%ju, remote=%ju), secondary(local=%ju, remote=%ju)).",
341296417Sdim		    (uintmax_t)res->hr_primary_localcnt,
342296417Sdim		    (uintmax_t)res->hr_primary_remotecnt,
343283625Sdim		    (uintmax_t)res->hr_secondary_localcnt,
344283625Sdim		    (uintmax_t)res->hr_secondary_remotecnt);
345283625Sdim	}
346283625Sdim	nv_add_uint32(nvout, (uint32_t)mapsize, "mapsize");
347283625Sdim	if (hast_proto_send(res, res->hr_remotein, nvout, map, mapsize) < 0) {
348283625Sdim		pjdlog_exit(EX_TEMPFAIL, "Unable to send activemap to %s",
349283625Sdim		    res->hr_remoteaddr);
350283625Sdim	}
351283625Sdim	if (map != NULL)
352283625Sdim		free(map);
353296417Sdim	nv_free(nvout);
354296417Sdim	/* Setup direction. */
355296417Sdim	if (proto_recv(res->hr_remotein, NULL, 0) == -1)
356296417Sdim		pjdlog_errno(LOG_WARNING, "Unable to set connection direction");
357296417Sdim	if (res->hr_secondary_localcnt > res->hr_primary_remotecnt &&
358283625Sdim	     res->hr_primary_localcnt > res->hr_secondary_remotecnt) {
359296417Sdim		/* Exit on split-brain. */
360296417Sdim		event_send(res, EVENT_SPLITBRAIN);
361296417Sdim		exit(EX_CONFIG);
362296417Sdim	}
363296417Sdim}
364296417Sdim
365296417Sdimvoid
366283625Sdimhastd_secondary(struct hast_resource *res, struct nv *nvin)
367296417Sdim{
368296417Sdim	sigset_t mask;
369296417Sdim	pthread_t td;
370296417Sdim	pid_t pid;
371296417Sdim	int error, mode, debuglevel;
372296417Sdim
373296417Sdim	/*
374296417Sdim	 * Create communication channel between parent and child.
375296417Sdim	 */
376296417Sdim	if (proto_client(NULL, "socketpair://", &res->hr_ctrl) < 0) {
377296417Sdim		KEEP_ERRNO((void)pidfile_remove(pfh));
378296417Sdim		pjdlog_exit(EX_OSERR,
379296417Sdim		    "Unable to create control sockets between parent and child");
380296417Sdim	}
381296417Sdim	/*
382296417Sdim	 * Create communication channel between child and parent.
383296417Sdim	 */
384283625Sdim	if (proto_client(NULL, "socketpair://", &res->hr_event) < 0) {
385283625Sdim		KEEP_ERRNO((void)pidfile_remove(pfh));
386283625Sdim		pjdlog_exit(EX_OSERR,
387283625Sdim		    "Unable to create event sockets between child and parent");
388296417Sdim	}
389296417Sdim
390296417Sdim	pid = fork();
391296417Sdim	if (pid < 0) {
392296417Sdim		KEEP_ERRNO((void)pidfile_remove(pfh));
393296417Sdim		pjdlog_exit(EX_OSERR, "Unable to fork");
394296417Sdim	}
395296417Sdim
396296417Sdim	if (pid > 0) {
397296417Sdim		/* This is parent. */
398296417Sdim		proto_close(res->hr_remotein);
399296417Sdim		res->hr_remotein = NULL;
400296417Sdim		proto_close(res->hr_remoteout);
401296417Sdim		res->hr_remoteout = NULL;
402296417Sdim		/* Declare that we are receiver. */
403296417Sdim		proto_recv(res->hr_event, NULL, 0);
404296417Sdim		/* Declare that we are sender. */
405296417Sdim		proto_send(res->hr_ctrl, NULL, 0);
406296417Sdim		res->hr_workerpid = pid;
407296417Sdim		return;
408296417Sdim	}
409296417Sdim
410296417Sdim	gres = res;
411296417Sdim	mode = pjdlog_mode_get();
412296417Sdim	debuglevel = pjdlog_debug_get();
413296417Sdim
414296417Sdim	/* Declare that we are sender. */
415296417Sdim	proto_send(res->hr_event, NULL, 0);
416296417Sdim	/* Declare that we are receiver. */
417296417Sdim	proto_recv(res->hr_ctrl, NULL, 0);
418296417Sdim	descriptors_cleanup(res);
419296417Sdim
420296417Sdim	descriptors_assert(res, mode);
421296417Sdim
422296417Sdim	pjdlog_init(mode);
423283625Sdim	pjdlog_debug_set(debuglevel);
424296417Sdim	pjdlog_prefix_set("[%s] (%s) ", res->hr_name, role2str(res->hr_role));
425283625Sdim	setproctitle("%s (%s)", res->hr_name, role2str(res->hr_role));
426296417Sdim
427283625Sdim	PJDLOG_VERIFY(sigemptyset(&mask) == 0);
428283625Sdim	PJDLOG_VERIFY(sigprocmask(SIG_SETMASK, &mask, NULL) == 0);
429283625Sdim
430283625Sdim	/* Error in setting timeout is not critical, but why should it fail? */
431296417Sdim	if (proto_timeout(res->hr_remotein, 2 * HAST_KEEPALIVE) < 0)
432296417Sdim		pjdlog_errno(LOG_WARNING, "Unable to set connection timeout");
433296417Sdim	if (proto_timeout(res->hr_remoteout, res->hr_timeout) < 0)
434296417Sdim		pjdlog_errno(LOG_WARNING, "Unable to set connection timeout");
435296417Sdim
436296417Sdim	init_local(res);
437296417Sdim	init_environment();
438296417Sdim
439296417Sdim	if (drop_privs(res) != 0)
440296417Sdim		exit(EX_CONFIG);
441296417Sdim	pjdlog_info("Privileges successfully dropped.");
442296417Sdim
443296417Sdim	/*
444296417Sdim	 * Create the control thread before sending any event to the parent,
445296417Sdim	 * as we can deadlock when parent sends control request to worker,
446283625Sdim	 * but worker has no control thread started yet, so parent waits.
447283625Sdim	 * In the meantime worker sends an event to the parent, but parent
448283625Sdim	 * is unable to handle the event, because it waits for control
449283625Sdim	 * request response.
450296417Sdim	 */
451296417Sdim	error = pthread_create(&td, NULL, ctrl_thread, res);
452296417Sdim	PJDLOG_ASSERT(error == 0);
453296417Sdim
454296417Sdim	init_remote(res, nvin);
455283625Sdim	event_send(res, EVENT_CONNECT);
456296417Sdim
457283625Sdim	error = pthread_create(&td, NULL, recv_thread, res);
458283625Sdim	PJDLOG_ASSERT(error == 0);
459283625Sdim	error = pthread_create(&td, NULL, disk_thread, res);
460296417Sdim	PJDLOG_ASSERT(error == 0);
461283625Sdim	(void)send_thread(res);
462283625Sdim}
463283625Sdim
464283625Sdimstatic void
465283625Sdimreqlog(int loglevel, int debuglevel, int error, struct hio *hio, const char *fmt, ...)
466283625Sdim{
467283625Sdim	char msg[1024];
468283625Sdim	va_list ap;
469283625Sdim	int len;
470283625Sdim
471283625Sdim	va_start(ap, fmt);
472283625Sdim	len = vsnprintf(msg, sizeof(msg), fmt, ap);
473283625Sdim	va_end(ap);
474283625Sdim	if ((size_t)len < sizeof(msg)) {
475283625Sdim		switch (hio->hio_cmd) {
476283625Sdim		case HIO_READ:
477283625Sdim			(void)snprintf(msg + len, sizeof(msg) - len,
478283625Sdim			    "READ(%ju, %ju).", (uintmax_t)hio->hio_offset,
479283625Sdim			    (uintmax_t)hio->hio_length);
480283625Sdim			break;
481283625Sdim		case HIO_DELETE:
482283625Sdim			(void)snprintf(msg + len, sizeof(msg) - len,
483283625Sdim			    "DELETE(%ju, %ju).", (uintmax_t)hio->hio_offset,
484283625Sdim			    (uintmax_t)hio->hio_length);
485283625Sdim			break;
486283625Sdim		case HIO_FLUSH:
487283625Sdim			(void)snprintf(msg + len, sizeof(msg) - len, "FLUSH.");
488283625Sdim			break;
489283625Sdim		case HIO_WRITE:
490283625Sdim			(void)snprintf(msg + len, sizeof(msg) - len,
491283625Sdim			    "WRITE(%ju, %ju).", (uintmax_t)hio->hio_offset,
492283625Sdim			    (uintmax_t)hio->hio_length);
493283625Sdim			break;
494283625Sdim		case HIO_KEEPALIVE:
495283625Sdim			(void)snprintf(msg + len, sizeof(msg) - len, "KEEPALIVE.");
496283625Sdim			break;
497283625Sdim		default:
498283625Sdim			(void)snprintf(msg + len, sizeof(msg) - len,
499283625Sdim			    "UNKNOWN(%u).", (unsigned int)hio->hio_cmd);
500283625Sdim			break;
501283625Sdim		}
502283625Sdim	}
503283625Sdim	pjdlog_common(loglevel, debuglevel, error, "%s", msg);
504283625Sdim}
505283625Sdim
506283625Sdimstatic int
507283625Sdimrequnpack(struct hast_resource *res, struct hio *hio)
508283625Sdim{
509283625Sdim
510283625Sdim	hio->hio_cmd = nv_get_uint8(hio->hio_nv, "cmd");
511283625Sdim	if (hio->hio_cmd == 0) {
512296417Sdim		pjdlog_error("Header contains no 'cmd' field.");
513283625Sdim		hio->hio_error = EINVAL;
514283625Sdim		goto end;
515283625Sdim	}
516283625Sdim	switch (hio->hio_cmd) {
517283625Sdim	case HIO_FLUSH:
518283625Sdim	case HIO_KEEPALIVE:
519283625Sdim		break;
520283625Sdim	case HIO_READ:
521283625Sdim	case HIO_WRITE:
522283625Sdim	case HIO_DELETE:
523283625Sdim		hio->hio_offset = nv_get_uint64(hio->hio_nv, "offset");
524283625Sdim		if (nv_error(hio->hio_nv) != 0) {
525283625Sdim			pjdlog_error("Header is missing 'offset' field.");
526283625Sdim			hio->hio_error = EINVAL;
527283625Sdim			goto end;
528283625Sdim		}
529283625Sdim		hio->hio_length = nv_get_uint64(hio->hio_nv, "length");
530296417Sdim		if (nv_error(hio->hio_nv) != 0) {
531296417Sdim			pjdlog_error("Header is missing 'length' field.");
532296417Sdim			hio->hio_error = EINVAL;
533296417Sdim			goto end;
534296417Sdim		}
535296417Sdim		if (hio->hio_length == 0) {
536296417Sdim			pjdlog_error("Data length is zero.");
537296417Sdim			hio->hio_error = EINVAL;
538296417Sdim			goto end;
539296417Sdim		}
540296417Sdim		if (hio->hio_length > MAXPHYS) {
541296417Sdim			pjdlog_error("Data length is too large (%ju > %ju).",
542296417Sdim			    (uintmax_t)hio->hio_length, (uintmax_t)MAXPHYS);
543296417Sdim			hio->hio_error = EINVAL;
544296417Sdim			goto end;
545296417Sdim		}
546296417Sdim		if ((hio->hio_offset % res->hr_local_sectorsize) != 0) {
547296417Sdim			pjdlog_error("Offset %ju is not multiple of sector size.",
548296417Sdim			    (uintmax_t)hio->hio_offset);
549296417Sdim			hio->hio_error = EINVAL;
550296417Sdim			goto end;
551296417Sdim		}
552296417Sdim		if ((hio->hio_length % res->hr_local_sectorsize) != 0) {
553296417Sdim			pjdlog_error("Length %ju is not multiple of sector size.",
554296417Sdim			    (uintmax_t)hio->hio_length);
555296417Sdim			hio->hio_error = EINVAL;
556296417Sdim			goto end;
557		}
558		if (hio->hio_offset + hio->hio_length >
559		    (uint64_t)res->hr_datasize) {
560			pjdlog_error("Data offset is too large (%ju > %ju).",
561			    (uintmax_t)(hio->hio_offset + hio->hio_length),
562			    (uintmax_t)res->hr_datasize);
563			hio->hio_error = EINVAL;
564			goto end;
565		}
566		break;
567	default:
568		pjdlog_error("Header contains invalid 'cmd' (%hhu).",
569		    hio->hio_cmd);
570		hio->hio_error = EINVAL;
571		goto end;
572	}
573	hio->hio_error = 0;
574end:
575	return (hio->hio_error);
576}
577
578static __dead2 void
579secondary_exit(int exitcode, const char *fmt, ...)
580{
581	va_list ap;
582
583	PJDLOG_ASSERT(exitcode != EX_OK);
584	va_start(ap, fmt);
585	pjdlogv_errno(LOG_ERR, fmt, ap);
586	va_end(ap);
587	event_send(gres, EVENT_DISCONNECT);
588	exit(exitcode);
589}
590
591/*
592 * Thread receives requests from the primary node.
593 */
594static void *
595recv_thread(void *arg)
596{
597	struct hast_resource *res = arg;
598	struct hio *hio;
599
600	for (;;) {
601		pjdlog_debug(2, "recv: Taking free request.");
602		QUEUE_TAKE(free, hio);
603		pjdlog_debug(2, "recv: (%p) Got request.", hio);
604		if (hast_proto_recv_hdr(res->hr_remotein, &hio->hio_nv) < 0) {
605			secondary_exit(EX_TEMPFAIL,
606			    "Unable to receive request header");
607		}
608		if (requnpack(res, hio) != 0) {
609			pjdlog_debug(2,
610			    "recv: (%p) Moving request to the send queue.",
611			    hio);
612			QUEUE_INSERT(send, hio);
613			continue;
614		}
615		reqlog(LOG_DEBUG, 2, -1, hio,
616		    "recv: (%p) Got request header: ", hio);
617		if (hio->hio_cmd == HIO_KEEPALIVE) {
618			pjdlog_debug(2,
619			    "recv: (%p) Moving request to the free queue.",
620			    hio);
621			nv_free(hio->hio_nv);
622			QUEUE_INSERT(free, hio);
623			continue;
624		} else if (hio->hio_cmd == HIO_WRITE) {
625			if (hast_proto_recv_data(res, res->hr_remotein,
626			    hio->hio_nv, hio->hio_data, MAXPHYS) < 0) {
627				secondary_exit(EX_TEMPFAIL,
628				    "Unable to receive request data");
629			}
630		}
631		pjdlog_debug(2, "recv: (%p) Moving request to the disk queue.",
632		    hio);
633		QUEUE_INSERT(disk, hio);
634	}
635	/* NOTREACHED */
636	return (NULL);
637}
638
639/*
640 * Thread reads from or writes to local component and also handles DELETE and
641 * FLUSH requests.
642 */
643static void *
644disk_thread(void *arg)
645{
646	struct hast_resource *res = arg;
647	struct hio *hio;
648	ssize_t ret;
649	bool clear_activemap;
650
651	clear_activemap = true;
652
653	for (;;) {
654		pjdlog_debug(2, "disk: Taking request.");
655		QUEUE_TAKE(disk, hio);
656		while (clear_activemap) {
657			unsigned char *map;
658			size_t mapsize;
659
660			/*
661			 * When first request is received, it means that primary
662			 * already received our activemap, merged it and stored
663			 * locally. We can now safely clear our activemap.
664			 */
665			mapsize =
666			    activemap_calc_ondisk_size(res->hr_local_mediasize -
667			    METADATA_SIZE, res->hr_extentsize,
668			    res->hr_local_sectorsize);
669			map = calloc(1, mapsize);
670			if (map == NULL) {
671				pjdlog_warning("Unable to allocate memory to clear local activemap.");
672				break;
673			}
674			if (pwrite(res->hr_localfd, map, mapsize,
675			    METADATA_SIZE) != (ssize_t)mapsize) {
676				pjdlog_errno(LOG_WARNING,
677				    "Unable to store cleared activemap");
678				free(map);
679				break;
680			}
681			free(map);
682			clear_activemap = false;
683			pjdlog_debug(1, "Local activemap cleared.");
684		}
685		reqlog(LOG_DEBUG, 2, -1, hio, "disk: (%p) Got request: ", hio);
686		/* Handle the actual request. */
687		switch (hio->hio_cmd) {
688		case HIO_READ:
689			ret = pread(res->hr_localfd, hio->hio_data,
690			    hio->hio_length,
691			    hio->hio_offset + res->hr_localoff);
692			if (ret < 0)
693				hio->hio_error = errno;
694			else if (ret != (int64_t)hio->hio_length)
695				hio->hio_error = EIO;
696			else
697				hio->hio_error = 0;
698			break;
699		case HIO_WRITE:
700			ret = pwrite(res->hr_localfd, hio->hio_data,
701			    hio->hio_length,
702			    hio->hio_offset + res->hr_localoff);
703			if (ret < 0)
704				hio->hio_error = errno;
705			else if (ret != (int64_t)hio->hio_length)
706				hio->hio_error = EIO;
707			else
708				hio->hio_error = 0;
709			break;
710		case HIO_DELETE:
711			ret = g_delete(res->hr_localfd,
712			    hio->hio_offset + res->hr_localoff,
713			    hio->hio_length);
714			if (ret < 0)
715				hio->hio_error = errno;
716			else
717				hio->hio_error = 0;
718			break;
719		case HIO_FLUSH:
720			ret = g_flush(res->hr_localfd);
721			if (ret < 0)
722				hio->hio_error = errno;
723			else
724				hio->hio_error = 0;
725			break;
726		}
727		if (hio->hio_error != 0) {
728			reqlog(LOG_ERR, 0, hio->hio_error, hio,
729			    "Request failed: ");
730		}
731		pjdlog_debug(2, "disk: (%p) Moving request to the send queue.",
732		    hio);
733		QUEUE_INSERT(send, hio);
734	}
735	/* NOTREACHED */
736	return (NULL);
737}
738
739/*
740 * Thread sends requests back to primary node.
741 */
742static void *
743send_thread(void *arg)
744{
745	struct hast_resource *res = arg;
746	struct nv *nvout;
747	struct hio *hio;
748	void *data;
749	size_t length;
750
751	for (;;) {
752		pjdlog_debug(2, "send: Taking request.");
753		QUEUE_TAKE(send, hio);
754		reqlog(LOG_DEBUG, 2, -1, hio, "send: (%p) Got request: ", hio);
755		nvout = nv_alloc();
756		/* Copy sequence number. */
757		nv_add_uint64(nvout, nv_get_uint64(hio->hio_nv, "seq"), "seq");
758		switch (hio->hio_cmd) {
759		case HIO_READ:
760			if (hio->hio_error == 0) {
761				data = hio->hio_data;
762				length = hio->hio_length;
763				break;
764			}
765			/*
766			 * We send no data in case of an error.
767			 */
768			/* FALLTHROUGH */
769		case HIO_DELETE:
770		case HIO_FLUSH:
771		case HIO_WRITE:
772			data = NULL;
773			length = 0;
774			break;
775		default:
776			abort();
777			break;
778		}
779		if (hio->hio_error != 0)
780			nv_add_int16(nvout, hio->hio_error, "error");
781		if (hast_proto_send(res, res->hr_remoteout, nvout, data,
782		    length) < 0) {
783			secondary_exit(EX_TEMPFAIL, "Unable to send reply.");
784		}
785		nv_free(nvout);
786		pjdlog_debug(2, "send: (%p) Moving request to the free queue.",
787		    hio);
788		nv_free(hio->hio_nv);
789		hio->hio_error = 0;
790		QUEUE_INSERT(free, hio);
791	}
792	/* NOTREACHED */
793	return (NULL);
794}
795