secondary.c revision 218043
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 218043 2011-01-28 21:52:37Z 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 <assert.h>
41204076Spjd#include <err.h>
42204076Spjd#include <errno.h>
43204076Spjd#include <fcntl.h>
44204076Spjd#include <libgeom.h>
45204076Spjd#include <pthread.h>
46213009Spjd#include <signal.h>
47204076Spjd#include <stdint.h>
48204076Spjd#include <stdio.h>
49204076Spjd#include <string.h>
50204076Spjd#include <sysexits.h>
51204076Spjd#include <unistd.h>
52204076Spjd
53204076Spjd#include <activemap.h>
54204076Spjd#include <nv.h>
55204076Spjd#include <pjdlog.h>
56204076Spjd
57204076Spjd#include "control.h"
58212038Spjd#include "event.h"
59204076Spjd#include "hast.h"
60204076Spjd#include "hast_proto.h"
61204076Spjd#include "hastd.h"
62211977Spjd#include "hooks.h"
63204076Spjd#include "metadata.h"
64204076Spjd#include "proto.h"
65204076Spjd#include "subr.h"
66204076Spjd#include "synch.h"
67204076Spjd
68204076Spjdstruct hio {
69204076Spjd	uint64_t 	 hio_seq;
70204076Spjd	int	 	 hio_error;
71204076Spjd	struct nv	*hio_nv;
72204076Spjd	void		*hio_data;
73204076Spjd	uint8_t		 hio_cmd;
74204076Spjd	uint64_t	 hio_offset;
75204076Spjd	uint64_t	 hio_length;
76204076Spjd	TAILQ_ENTRY(hio) hio_next;
77204076Spjd};
78204076Spjd
79211984Spjdstatic struct hast_resource *gres;
80211984Spjd
81204076Spjd/*
82204076Spjd * Free list holds unused structures. When free list is empty, we have to wait
83204076Spjd * until some in-progress requests are freed.
84204076Spjd */
85204076Spjdstatic TAILQ_HEAD(, hio) hio_free_list;
86204076Spjdstatic pthread_mutex_t hio_free_list_lock;
87204076Spjdstatic pthread_cond_t hio_free_list_cond;
88204076Spjd/*
89204076Spjd * Disk thread (the one that do I/O requests) takes requests from this list.
90204076Spjd */
91204076Spjdstatic TAILQ_HEAD(, hio) hio_disk_list;
92204076Spjdstatic pthread_mutex_t hio_disk_list_lock;
93204076Spjdstatic pthread_cond_t hio_disk_list_cond;
94204076Spjd/*
95204076Spjd * There is one recv list for every component, although local components don't
96204076Spjd * use recv lists as local requests are done synchronously.
97204076Spjd */
98204076Spjdstatic TAILQ_HEAD(, hio) hio_send_list;
99204076Spjdstatic pthread_mutex_t hio_send_list_lock;
100204076Spjdstatic pthread_cond_t hio_send_list_cond;
101204076Spjd
102204076Spjd/*
103204076Spjd * Maximum number of outstanding I/O requests.
104204076Spjd */
105204076Spjd#define	HAST_HIO_MAX	256
106204076Spjd
107204076Spjdstatic void *recv_thread(void *arg);
108204076Spjdstatic void *disk_thread(void *arg);
109204076Spjdstatic void *send_thread(void *arg);
110204076Spjd
111211877Spjd#define	QUEUE_INSERT(name, hio)	do {					\
112211877Spjd	bool _wakeup;							\
113211877Spjd									\
114211877Spjd	mtx_lock(&hio_##name##_list_lock);				\
115211877Spjd	_wakeup = TAILQ_EMPTY(&hio_##name##_list);			\
116211877Spjd	TAILQ_INSERT_TAIL(&hio_##name##_list, (hio), hio_next);		\
117211877Spjd	mtx_unlock(&hio_##name##_list_lock);				\
118211877Spjd	if (_wakeup)							\
119211877Spjd		cv_signal(&hio_##name##_list_cond);			\
120211877Spjd} while (0)
121211877Spjd#define	QUEUE_TAKE(name, hio)	do {					\
122211877Spjd	mtx_lock(&hio_##name##_list_lock);				\
123211877Spjd	while (((hio) = TAILQ_FIRST(&hio_##name##_list)) == NULL) {	\
124211877Spjd		cv_wait(&hio_##name##_list_cond,			\
125211877Spjd		    &hio_##name##_list_lock);				\
126211877Spjd	}								\
127211877Spjd	TAILQ_REMOVE(&hio_##name##_list, (hio), hio_next);		\
128211877Spjd	mtx_unlock(&hio_##name##_list_lock);				\
129211877Spjd} while (0)
130211877Spjd
131204076Spjdstatic void
132204076Spjdinit_environment(void)
133204076Spjd{
134204076Spjd	struct hio *hio;
135204076Spjd	unsigned int ii;
136204076Spjd
137204076Spjd	/*
138204076Spjd	 * Initialize lists, their locks and theirs condition variables.
139204076Spjd	 */
140204076Spjd	TAILQ_INIT(&hio_free_list);
141204076Spjd	mtx_init(&hio_free_list_lock);
142204076Spjd	cv_init(&hio_free_list_cond);
143204076Spjd	TAILQ_INIT(&hio_disk_list);
144204076Spjd	mtx_init(&hio_disk_list_lock);
145204076Spjd	cv_init(&hio_disk_list_cond);
146204076Spjd	TAILQ_INIT(&hio_send_list);
147204076Spjd	mtx_init(&hio_send_list_lock);
148204076Spjd	cv_init(&hio_send_list_cond);
149204076Spjd
150204076Spjd	/*
151204076Spjd	 * Allocate requests pool and initialize requests.
152204076Spjd	 */
153204076Spjd	for (ii = 0; ii < HAST_HIO_MAX; ii++) {
154204076Spjd		hio = malloc(sizeof(*hio));
155204076Spjd		if (hio == NULL) {
156210879Spjd			pjdlog_exitx(EX_TEMPFAIL,
157210879Spjd			    "Unable to allocate memory (%zu bytes) for hio request.",
158210879Spjd			    sizeof(*hio));
159204076Spjd		}
160204076Spjd		hio->hio_error = 0;
161204076Spjd		hio->hio_data = malloc(MAXPHYS);
162204076Spjd		if (hio->hio_data == NULL) {
163210879Spjd			pjdlog_exitx(EX_TEMPFAIL,
164210879Spjd			    "Unable to allocate memory (%zu bytes) for gctl_data.",
165210879Spjd			    (size_t)MAXPHYS);
166204076Spjd		}
167204076Spjd		TAILQ_INSERT_HEAD(&hio_free_list, hio, hio_next);
168204076Spjd	}
169204076Spjd}
170204076Spjd
171204076Spjdstatic void
172204076Spjdinit_local(struct hast_resource *res)
173204076Spjd{
174204076Spjd
175204076Spjd	if (metadata_read(res, true) < 0)
176204076Spjd		exit(EX_NOINPUT);
177204076Spjd}
178204076Spjd
179204076Spjdstatic void
180204076Spjdinit_remote(struct hast_resource *res, struct nv *nvin)
181204076Spjd{
182204076Spjd	uint64_t resuid;
183204076Spjd	struct nv *nvout;
184204076Spjd	unsigned char *map;
185204076Spjd	size_t mapsize;
186204076Spjd
187204076Spjd	map = NULL;
188204076Spjd	mapsize = 0;
189204076Spjd	nvout = nv_alloc();
190204076Spjd	nv_add_int64(nvout, (int64_t)res->hr_datasize, "datasize");
191204076Spjd	nv_add_int32(nvout, (int32_t)res->hr_extentsize, "extentsize");
192204076Spjd	resuid = nv_get_uint64(nvin, "resuid");
193204076Spjd	res->hr_primary_localcnt = nv_get_uint64(nvin, "localcnt");
194204076Spjd	res->hr_primary_remotecnt = nv_get_uint64(nvin, "remotecnt");
195204076Spjd	nv_add_uint64(nvout, res->hr_secondary_localcnt, "localcnt");
196204076Spjd	nv_add_uint64(nvout, res->hr_secondary_remotecnt, "remotecnt");
197204076Spjd	mapsize = activemap_calc_ondisk_size(res->hr_local_mediasize -
198204076Spjd	    METADATA_SIZE, res->hr_extentsize, res->hr_local_sectorsize);
199204076Spjd	map = malloc(mapsize);
200204076Spjd	if (map == NULL) {
201204076Spjd		pjdlog_exitx(EX_TEMPFAIL,
202204076Spjd		    "Unable to allocate memory (%zu bytes) for activemap.",
203204076Spjd		    mapsize);
204204076Spjd	}
205204076Spjd	nv_add_uint32(nvout, (uint32_t)mapsize, "mapsize");
206204076Spjd	/*
207204076Spjd	 * When we work as primary and secondary is missing we will increase
208204076Spjd	 * localcnt in our metadata. When secondary is connected and synced
209204076Spjd	 * we make localcnt be equal to remotecnt, which means nodes are more
210204076Spjd	 * or less in sync.
211204076Spjd	 * Split-brain condition is when both nodes are not able to communicate
212204076Spjd	 * and are both configured as primary nodes. In turn, they can both
213204076Spjd	 * make incompatible changes to the data and we have to detect that.
214204076Spjd	 * Under split-brain condition we will increase our localcnt on first
215204076Spjd	 * write and remote node will increase its localcnt on first write.
216204076Spjd	 * When we connect we can see that primary's localcnt is greater than
217204076Spjd	 * our remotecnt (primary was modified while we weren't watching) and
218204076Spjd	 * our localcnt is greater than primary's remotecnt (we were modified
219204076Spjd	 * while primary wasn't watching).
220204076Spjd	 * There are many possible combinations which are all gathered below.
221204076Spjd	 * Don't pay too much attention to exact numbers, the more important
222204076Spjd	 * is to compare them. We compare secondary's local with primary's
223204076Spjd	 * remote and secondary's remote with primary's local.
224204076Spjd	 * Note that every case where primary's localcnt is smaller than
225204076Spjd	 * secondary's remotecnt and where secondary's localcnt is smaller than
226204076Spjd	 * primary's remotecnt should be impossible in practise. We will perform
227204076Spjd	 * full synchronization then. Those cases are marked with an asterisk.
228204076Spjd	 * Regular synchronization means that only extents marked as dirty are
229204076Spjd	 * synchronized (regular synchronization).
230204076Spjd	 *
231204076Spjd	 * SECONDARY METADATA PRIMARY METADATA
232204076Spjd	 * local=3 remote=3   local=2 remote=2*  ?! Full sync from secondary.
233204076Spjd	 * local=3 remote=3   local=2 remote=3*  ?! Full sync from primary.
234204076Spjd	 * local=3 remote=3   local=2 remote=4*  ?! Full sync from primary.
235204076Spjd	 * local=3 remote=3   local=3 remote=2   Primary is out-of-date,
236204076Spjd	 *                                       regular sync from secondary.
237204076Spjd	 * local=3 remote=3   local=3 remote=3   Regular sync just in case.
238204076Spjd	 * local=3 remote=3   local=3 remote=4*  ?! Full sync from primary.
239204076Spjd	 * local=3 remote=3   local=4 remote=2   Split-brain condition.
240204076Spjd	 * local=3 remote=3   local=4 remote=3   Secondary out-of-date,
241204076Spjd	 *                                       regular sync from primary.
242204076Spjd	 * local=3 remote=3   local=4 remote=4*  ?! Full sync from primary.
243204076Spjd	 */
244204076Spjd	if (res->hr_resuid == 0) {
245204076Spjd		/*
246214284Spjd		 * Provider is used for the first time. If primary node done no
247214284Spjd		 * writes yet as well (we will find "virgin" argument) then
248214284Spjd		 * there is no need to synchronize anything. If primary node
249214284Spjd		 * done any writes already we have to synchronize everything.
250204076Spjd		 */
251204076Spjd		assert(res->hr_secondary_localcnt == 0);
252204076Spjd		res->hr_resuid = resuid;
253204076Spjd		if (metadata_write(res) < 0)
254204076Spjd			exit(EX_NOINPUT);
255214284Spjd		if (nv_exists(nvin, "virgin")) {
256214284Spjd			free(map);
257214284Spjd			map = NULL;
258214284Spjd			mapsize = 0;
259214284Spjd		} else {
260214284Spjd			memset(map, 0xff, mapsize);
261214284Spjd		}
262204076Spjd		nv_add_uint8(nvout, HAST_SYNCSRC_PRIMARY, "syncsrc");
263204076Spjd	} else if (
264204076Spjd	    /* Is primary is out-of-date? */
265204076Spjd	    (res->hr_secondary_localcnt > res->hr_primary_remotecnt &&
266204076Spjd	     res->hr_secondary_remotecnt == res->hr_primary_localcnt) ||
267204076Spjd	    /* Node are more or less in sync? */
268204076Spjd	    (res->hr_secondary_localcnt == res->hr_primary_remotecnt &&
269204076Spjd	     res->hr_secondary_remotecnt == res->hr_primary_localcnt) ||
270204076Spjd	    /* Is secondary is out-of-date? */
271204076Spjd	    (res->hr_secondary_localcnt == res->hr_primary_remotecnt &&
272204076Spjd	     res->hr_secondary_remotecnt < res->hr_primary_localcnt)) {
273204076Spjd		/*
274204076Spjd		 * Nodes are more or less in sync or one of the nodes is
275204076Spjd		 * out-of-date.
276204076Spjd		 * It doesn't matter at this point which one, we just have to
277204076Spjd		 * send out local bitmap to the remote node.
278204076Spjd		 */
279204076Spjd		if (pread(res->hr_localfd, map, mapsize, METADATA_SIZE) !=
280204076Spjd		    (ssize_t)mapsize) {
281204076Spjd			pjdlog_exit(LOG_ERR, "Unable to read activemap");
282204076Spjd		}
283204076Spjd		if (res->hr_secondary_localcnt > res->hr_primary_remotecnt &&
284204076Spjd		     res->hr_secondary_remotecnt == res->hr_primary_localcnt) {
285204076Spjd			/* Primary is out-of-date, sync from secondary. */
286204076Spjd			nv_add_uint8(nvout, HAST_SYNCSRC_SECONDARY, "syncsrc");
287204076Spjd		} else {
288204076Spjd			/*
289204076Spjd			 * Secondary is out-of-date or counts match.
290204076Spjd			 * Sync from primary.
291204076Spjd			 */
292204076Spjd			nv_add_uint8(nvout, HAST_SYNCSRC_PRIMARY, "syncsrc");
293204076Spjd		}
294204076Spjd	} else if (res->hr_secondary_localcnt > res->hr_primary_remotecnt &&
295204076Spjd	     res->hr_primary_localcnt > res->hr_secondary_remotecnt) {
296204076Spjd		/*
297204076Spjd		 * Not good, we have split-brain condition.
298204076Spjd		 */
299204076Spjd		pjdlog_error("Split-brain detected, exiting.");
300204076Spjd		nv_add_string(nvout, "Split-brain condition!", "errmsg");
301204076Spjd		free(map);
302204076Spjd		map = NULL;
303204076Spjd		mapsize = 0;
304204076Spjd	} else /* if (res->hr_secondary_localcnt < res->hr_primary_remotecnt ||
305204076Spjd	    res->hr_primary_localcnt < res->hr_secondary_remotecnt) */ {
306204076Spjd		/*
307204076Spjd		 * This should never happen in practise, but we will perform
308204076Spjd		 * full synchronization.
309204076Spjd		 */
310204076Spjd		assert(res->hr_secondary_localcnt < res->hr_primary_remotecnt ||
311204076Spjd		    res->hr_primary_localcnt < res->hr_secondary_remotecnt);
312204076Spjd		mapsize = activemap_calc_ondisk_size(res->hr_local_mediasize -
313204076Spjd		    METADATA_SIZE, res->hr_extentsize,
314204076Spjd		    res->hr_local_sectorsize);
315204076Spjd		memset(map, 0xff, mapsize);
316204076Spjd		if (res->hr_secondary_localcnt > res->hr_primary_remotecnt) {
317204076Spjd			/* In this one of five cases sync from secondary. */
318204076Spjd			nv_add_uint8(nvout, HAST_SYNCSRC_SECONDARY, "syncsrc");
319204076Spjd		} else {
320204076Spjd			/* For the rest four cases sync from primary. */
321204076Spjd			nv_add_uint8(nvout, HAST_SYNCSRC_PRIMARY, "syncsrc");
322204076Spjd		}
323204076Spjd		pjdlog_warning("This should never happen, asking for full synchronization (primary(local=%ju, remote=%ju), secondary(local=%ju, remote=%ju)).",
324204076Spjd		    (uintmax_t)res->hr_primary_localcnt,
325204076Spjd		    (uintmax_t)res->hr_primary_remotecnt,
326204076Spjd		    (uintmax_t)res->hr_secondary_localcnt,
327204076Spjd		    (uintmax_t)res->hr_secondary_remotecnt);
328204076Spjd	}
329204076Spjd	if (hast_proto_send(res, res->hr_remotein, nvout, map, mapsize) < 0) {
330214276Spjd		pjdlog_exit(EX_TEMPFAIL, "Unable to send activemap to %s",
331204076Spjd		    res->hr_remoteaddr);
332204076Spjd	}
333214275Spjd	if (map != NULL)
334214275Spjd		free(map);
335209182Spjd	nv_free(nvout);
336204076Spjd	if (res->hr_secondary_localcnt > res->hr_primary_remotecnt &&
337204076Spjd	     res->hr_primary_localcnt > res->hr_secondary_remotecnt) {
338204076Spjd		/* Exit on split-brain. */
339212038Spjd		event_send(res, EVENT_SPLITBRAIN);
340204076Spjd		exit(EX_CONFIG);
341204076Spjd	}
342204076Spjd}
343204076Spjd
344204076Spjdvoid
345204076Spjdhastd_secondary(struct hast_resource *res, struct nv *nvin)
346204076Spjd{
347213009Spjd	sigset_t mask;
348204076Spjd	pthread_t td;
349204076Spjd	pid_t pid;
350218043Spjd	int error, mode;
351204076Spjd
352204076Spjd	/*
353204076Spjd	 * Create communication channel between parent and child.
354204076Spjd	 */
355204076Spjd	if (proto_client("socketpair://", &res->hr_ctrl) < 0) {
356204076Spjd		KEEP_ERRNO((void)pidfile_remove(pfh));
357204076Spjd		pjdlog_exit(EX_OSERR,
358204076Spjd		    "Unable to create control sockets between parent and child");
359204076Spjd	}
360212038Spjd	/*
361212038Spjd	 * Create communication channel between child and parent.
362212038Spjd	 */
363212038Spjd	if (proto_client("socketpair://", &res->hr_event) < 0) {
364212038Spjd		KEEP_ERRNO((void)pidfile_remove(pfh));
365212038Spjd		pjdlog_exit(EX_OSERR,
366212038Spjd		    "Unable to create event sockets between child and parent");
367212038Spjd	}
368204076Spjd
369204076Spjd	pid = fork();
370204076Spjd	if (pid < 0) {
371204076Spjd		KEEP_ERRNO((void)pidfile_remove(pfh));
372204076Spjd		pjdlog_exit(EX_OSERR, "Unable to fork");
373204076Spjd	}
374204076Spjd
375204076Spjd	if (pid > 0) {
376204076Spjd		/* This is parent. */
377204076Spjd		proto_close(res->hr_remotein);
378204076Spjd		res->hr_remotein = NULL;
379204076Spjd		proto_close(res->hr_remoteout);
380204076Spjd		res->hr_remoteout = NULL;
381212038Spjd		/* Declare that we are receiver. */
382212038Spjd		proto_recv(res->hr_event, NULL, 0);
383218043Spjd		/* Declare that we are sender. */
384218043Spjd		proto_send(res->hr_ctrl, NULL, 0);
385204076Spjd		res->hr_workerpid = pid;
386204076Spjd		return;
387204076Spjd	}
388211977Spjd
389211984Spjd	gres = res;
390218043Spjd	mode = pjdlog_mode_get();
391211984Spjd
392218043Spjd	/* Declare that we are sender. */
393218043Spjd	proto_send(res->hr_event, NULL, 0);
394218043Spjd	/* Declare that we are receiver. */
395218043Spjd	proto_recv(res->hr_ctrl, NULL, 0);
396218043Spjd	descriptors_cleanup(res);
397204076Spjd
398218043Spjd	pjdlog_init(mode);
399218043Spjd	pjdlog_prefix_set("[%s] (%s) ", res->hr_name, role2str(res->hr_role));
400204076Spjd	setproctitle("%s (secondary)", res->hr_name);
401204076Spjd
402213009Spjd	PJDLOG_VERIFY(sigemptyset(&mask) == 0);
403213009Spjd	PJDLOG_VERIFY(sigprocmask(SIG_SETMASK, &mask, NULL) == 0);
404210880Spjd
405207371Spjd	/* Error in setting timeout is not critical, but why should it fail? */
406207371Spjd	if (proto_timeout(res->hr_remotein, 0) < 0)
407207371Spjd		pjdlog_errno(LOG_WARNING, "Unable to set connection timeout");
408207371Spjd	if (proto_timeout(res->hr_remoteout, res->hr_timeout) < 0)
409207371Spjd		pjdlog_errno(LOG_WARNING, "Unable to set connection timeout");
410207371Spjd
411204076Spjd	init_local(res);
412213007Spjd	init_environment();
413213007Spjd
414213007Spjd	/*
415213007Spjd	 * Create the control thread before sending any event to the parent,
416213007Spjd	 * as we can deadlock when parent sends control request to worker,
417213007Spjd	 * but worker has no control thread started yet, so parent waits.
418213007Spjd	 * In the meantime worker sends an event to the parent, but parent
419213007Spjd	 * is unable to handle the event, because it waits for control
420213007Spjd	 * request response.
421213007Spjd	 */
422213007Spjd	error = pthread_create(&td, NULL, ctrl_thread, res);
423213007Spjd	assert(error == 0);
424213007Spjd
425204076Spjd	init_remote(res, nvin);
426212038Spjd	event_send(res, EVENT_CONNECT);
427204076Spjd
428204076Spjd	error = pthread_create(&td, NULL, recv_thread, res);
429204076Spjd	assert(error == 0);
430204076Spjd	error = pthread_create(&td, NULL, disk_thread, res);
431204076Spjd	assert(error == 0);
432213007Spjd	(void)send_thread(res);
433204076Spjd}
434204076Spjd
435204076Spjdstatic void
436204076Spjdreqlog(int loglevel, int debuglevel, int error, struct hio *hio, const char *fmt, ...)
437204076Spjd{
438204076Spjd	char msg[1024];
439204076Spjd	va_list ap;
440204076Spjd	int len;
441204076Spjd
442204076Spjd	va_start(ap, fmt);
443204076Spjd	len = vsnprintf(msg, sizeof(msg), fmt, ap);
444204076Spjd	va_end(ap);
445204076Spjd	if ((size_t)len < sizeof(msg)) {
446204076Spjd		switch (hio->hio_cmd) {
447204076Spjd		case HIO_READ:
448204076Spjd			(void)snprintf(msg + len, sizeof(msg) - len,
449204076Spjd			    "READ(%ju, %ju).", (uintmax_t)hio->hio_offset,
450204076Spjd			    (uintmax_t)hio->hio_length);
451204076Spjd			break;
452204076Spjd		case HIO_DELETE:
453204076Spjd			(void)snprintf(msg + len, sizeof(msg) - len,
454204076Spjd			    "DELETE(%ju, %ju).", (uintmax_t)hio->hio_offset,
455204076Spjd			    (uintmax_t)hio->hio_length);
456204076Spjd			break;
457204076Spjd		case HIO_FLUSH:
458204076Spjd			(void)snprintf(msg + len, sizeof(msg) - len, "FLUSH.");
459204076Spjd			break;
460204076Spjd		case HIO_WRITE:
461204076Spjd			(void)snprintf(msg + len, sizeof(msg) - len,
462204076Spjd			    "WRITE(%ju, %ju).", (uintmax_t)hio->hio_offset,
463204076Spjd			    (uintmax_t)hio->hio_length);
464204076Spjd			break;
465211882Spjd		case HIO_KEEPALIVE:
466211882Spjd			(void)snprintf(msg + len, sizeof(msg) - len, "KEEPALIVE.");
467211882Spjd			break;
468204076Spjd		default:
469204076Spjd			(void)snprintf(msg + len, sizeof(msg) - len,
470204076Spjd			    "UNKNOWN(%u).", (unsigned int)hio->hio_cmd);
471204076Spjd			break;
472204076Spjd		}
473204076Spjd	}
474204076Spjd	pjdlog_common(loglevel, debuglevel, error, "%s", msg);
475204076Spjd}
476204076Spjd
477204076Spjdstatic int
478204076Spjdrequnpack(struct hast_resource *res, struct hio *hio)
479204076Spjd{
480204076Spjd
481204076Spjd	hio->hio_cmd = nv_get_uint8(hio->hio_nv, "cmd");
482204076Spjd	if (hio->hio_cmd == 0) {
483204076Spjd		pjdlog_error("Header contains no 'cmd' field.");
484204076Spjd		hio->hio_error = EINVAL;
485204076Spjd		goto end;
486204076Spjd	}
487204076Spjd	switch (hio->hio_cmd) {
488211882Spjd	case HIO_KEEPALIVE:
489211882Spjd		break;
490204076Spjd	case HIO_READ:
491204076Spjd	case HIO_WRITE:
492204076Spjd	case HIO_DELETE:
493204076Spjd		hio->hio_offset = nv_get_uint64(hio->hio_nv, "offset");
494204076Spjd		if (nv_error(hio->hio_nv) != 0) {
495204076Spjd			pjdlog_error("Header is missing 'offset' field.");
496204076Spjd			hio->hio_error = EINVAL;
497204076Spjd			goto end;
498204076Spjd		}
499204076Spjd		hio->hio_length = nv_get_uint64(hio->hio_nv, "length");
500204076Spjd		if (nv_error(hio->hio_nv) != 0) {
501204076Spjd			pjdlog_error("Header is missing 'length' field.");
502204076Spjd			hio->hio_error = EINVAL;
503204076Spjd			goto end;
504204076Spjd		}
505204076Spjd		if (hio->hio_length == 0) {
506204076Spjd			pjdlog_error("Data length is zero.");
507204076Spjd			hio->hio_error = EINVAL;
508204076Spjd			goto end;
509204076Spjd		}
510204076Spjd		if (hio->hio_length > MAXPHYS) {
511204076Spjd			pjdlog_error("Data length is too large (%ju > %ju).",
512204076Spjd			    (uintmax_t)hio->hio_length, (uintmax_t)MAXPHYS);
513204076Spjd			hio->hio_error = EINVAL;
514204076Spjd			goto end;
515204076Spjd		}
516204076Spjd		if ((hio->hio_offset % res->hr_local_sectorsize) != 0) {
517204076Spjd			pjdlog_error("Offset %ju is not multiple of sector size.",
518204076Spjd			    (uintmax_t)hio->hio_offset);
519204076Spjd			hio->hio_error = EINVAL;
520204076Spjd			goto end;
521204076Spjd		}
522204076Spjd		if ((hio->hio_length % res->hr_local_sectorsize) != 0) {
523204076Spjd			pjdlog_error("Length %ju is not multiple of sector size.",
524204076Spjd			    (uintmax_t)hio->hio_length);
525204076Spjd			hio->hio_error = EINVAL;
526204076Spjd			goto end;
527204076Spjd		}
528204076Spjd		if (hio->hio_offset + hio->hio_length >
529204076Spjd		    (uint64_t)res->hr_datasize) {
530204076Spjd			pjdlog_error("Data offset is too large (%ju > %ju).",
531204076Spjd			    (uintmax_t)(hio->hio_offset + hio->hio_length),
532204076Spjd			    (uintmax_t)res->hr_datasize);
533204076Spjd			hio->hio_error = EINVAL;
534204076Spjd			goto end;
535204076Spjd		}
536204076Spjd		break;
537204076Spjd	default:
538204076Spjd		pjdlog_error("Header contains invalid 'cmd' (%hhu).",
539204076Spjd		    hio->hio_cmd);
540204076Spjd		hio->hio_error = EINVAL;
541204076Spjd		goto end;
542204076Spjd	}
543204076Spjd	hio->hio_error = 0;
544204076Spjdend:
545204076Spjd	return (hio->hio_error);
546204076Spjd}
547204076Spjd
548212899Spjdstatic __dead2 void
549211984Spjdsecondary_exit(int exitcode, const char *fmt, ...)
550211984Spjd{
551211984Spjd	va_list ap;
552211984Spjd
553211984Spjd	assert(exitcode != EX_OK);
554211984Spjd	va_start(ap, fmt);
555211984Spjd	pjdlogv_errno(LOG_ERR, fmt, ap);
556211984Spjd	va_end(ap);
557212038Spjd	event_send(gres, EVENT_DISCONNECT);
558211984Spjd	exit(exitcode);
559211984Spjd}
560211984Spjd
561204076Spjd/*
562204076Spjd * Thread receives requests from the primary node.
563204076Spjd */
564204076Spjdstatic void *
565204076Spjdrecv_thread(void *arg)
566204076Spjd{
567204076Spjd	struct hast_resource *res = arg;
568204076Spjd	struct hio *hio;
569204076Spjd
570204076Spjd	for (;;) {
571204076Spjd		pjdlog_debug(2, "recv: Taking free request.");
572211877Spjd		QUEUE_TAKE(free, hio);
573204076Spjd		pjdlog_debug(2, "recv: (%p) Got request.", hio);
574204076Spjd		if (hast_proto_recv_hdr(res->hr_remotein, &hio->hio_nv) < 0) {
575211984Spjd			secondary_exit(EX_TEMPFAIL,
576204076Spjd			    "Unable to receive request header");
577204076Spjd		}
578211877Spjd		if (requnpack(res, hio) != 0) {
579211877Spjd			pjdlog_debug(2,
580211877Spjd			    "recv: (%p) Moving request to the send queue.",
581211877Spjd			    hio);
582211877Spjd			QUEUE_INSERT(send, hio);
583211877Spjd			continue;
584211877Spjd		}
585204076Spjd		reqlog(LOG_DEBUG, 2, -1, hio,
586204076Spjd		    "recv: (%p) Got request header: ", hio);
587211882Spjd		if (hio->hio_cmd == HIO_KEEPALIVE) {
588211882Spjd			pjdlog_debug(2,
589211882Spjd			    "recv: (%p) Moving request to the free queue.",
590211882Spjd			    hio);
591211882Spjd			nv_free(hio->hio_nv);
592211882Spjd			QUEUE_INSERT(free, hio);
593211882Spjd			continue;
594211882Spjd		} else if (hio->hio_cmd == HIO_WRITE) {
595204076Spjd			if (hast_proto_recv_data(res, res->hr_remotein,
596204076Spjd			    hio->hio_nv, hio->hio_data, MAXPHYS) < 0) {
597211984Spjd				secondary_exit(EX_TEMPFAIL,
598212051Spjd				    "Unable to receive request data");
599204076Spjd			}
600204076Spjd		}
601204076Spjd		pjdlog_debug(2, "recv: (%p) Moving request to the disk queue.",
602204076Spjd		    hio);
603211877Spjd		QUEUE_INSERT(disk, hio);
604204076Spjd	}
605204076Spjd	/* NOTREACHED */
606204076Spjd	return (NULL);
607204076Spjd}
608204076Spjd
609204076Spjd/*
610204076Spjd * Thread reads from or writes to local component and also handles DELETE and
611204076Spjd * FLUSH requests.
612204076Spjd */
613204076Spjdstatic void *
614204076Spjddisk_thread(void *arg)
615204076Spjd{
616204076Spjd	struct hast_resource *res = arg;
617204076Spjd	struct hio *hio;
618204076Spjd	ssize_t ret;
619211877Spjd	bool clear_activemap;
620204076Spjd
621204076Spjd	clear_activemap = true;
622204076Spjd
623204076Spjd	for (;;) {
624204076Spjd		pjdlog_debug(2, "disk: Taking request.");
625211877Spjd		QUEUE_TAKE(disk, hio);
626204076Spjd		while (clear_activemap) {
627204076Spjd			unsigned char *map;
628204076Spjd			size_t mapsize;
629204076Spjd
630204076Spjd			/*
631204076Spjd			 * When first request is received, it means that primary
632204076Spjd			 * already received our activemap, merged it and stored
633204076Spjd			 * locally. We can now safely clear our activemap.
634204076Spjd			 */
635204076Spjd			mapsize =
636204076Spjd			    activemap_calc_ondisk_size(res->hr_local_mediasize -
637204076Spjd			    METADATA_SIZE, res->hr_extentsize,
638204076Spjd			    res->hr_local_sectorsize);
639204076Spjd			map = calloc(1, mapsize);
640204076Spjd			if (map == NULL) {
641204076Spjd				pjdlog_warning("Unable to allocate memory to clear local activemap.");
642204076Spjd				break;
643204076Spjd			}
644204076Spjd			if (pwrite(res->hr_localfd, map, mapsize,
645204076Spjd			    METADATA_SIZE) != (ssize_t)mapsize) {
646204076Spjd				pjdlog_errno(LOG_WARNING,
647204076Spjd				    "Unable to store cleared activemap");
648204076Spjd				free(map);
649204076Spjd				break;
650204076Spjd			}
651204076Spjd			free(map);
652204076Spjd			clear_activemap = false;
653204076Spjd			pjdlog_debug(1, "Local activemap cleared.");
654204076Spjd		}
655204076Spjd		reqlog(LOG_DEBUG, 2, -1, hio, "disk: (%p) Got request: ", hio);
656204076Spjd		/* Handle the actual request. */
657204076Spjd		switch (hio->hio_cmd) {
658204076Spjd		case HIO_READ:
659204076Spjd			ret = pread(res->hr_localfd, hio->hio_data,
660204076Spjd			    hio->hio_length,
661204076Spjd			    hio->hio_offset + res->hr_localoff);
662204076Spjd			if (ret < 0)
663204076Spjd				hio->hio_error = errno;
664204076Spjd			else if (ret != (int64_t)hio->hio_length)
665204076Spjd				hio->hio_error = EIO;
666204076Spjd			else
667204076Spjd				hio->hio_error = 0;
668204076Spjd			break;
669204076Spjd		case HIO_WRITE:
670204076Spjd			ret = pwrite(res->hr_localfd, hio->hio_data,
671204076Spjd			    hio->hio_length,
672204076Spjd			    hio->hio_offset + res->hr_localoff);
673204076Spjd			if (ret < 0)
674204076Spjd				hio->hio_error = errno;
675204076Spjd			else if (ret != (int64_t)hio->hio_length)
676204076Spjd				hio->hio_error = EIO;
677204076Spjd			else
678204076Spjd				hio->hio_error = 0;
679204076Spjd			break;
680204076Spjd		case HIO_DELETE:
681204076Spjd			ret = g_delete(res->hr_localfd,
682204076Spjd			    hio->hio_offset + res->hr_localoff,
683204076Spjd			    hio->hio_length);
684204076Spjd			if (ret < 0)
685204076Spjd				hio->hio_error = errno;
686204076Spjd			else
687204076Spjd				hio->hio_error = 0;
688204076Spjd			break;
689204076Spjd		case HIO_FLUSH:
690204076Spjd			ret = g_flush(res->hr_localfd);
691204076Spjd			if (ret < 0)
692204076Spjd				hio->hio_error = errno;
693204076Spjd			else
694204076Spjd				hio->hio_error = 0;
695204076Spjd			break;
696204076Spjd		}
697204076Spjd		if (hio->hio_error != 0) {
698204076Spjd			reqlog(LOG_ERR, 0, hio->hio_error, hio,
699204076Spjd			    "Request failed: ");
700204076Spjd		}
701204076Spjd		pjdlog_debug(2, "disk: (%p) Moving request to the send queue.",
702204076Spjd		    hio);
703211877Spjd		QUEUE_INSERT(send, hio);
704204076Spjd	}
705204076Spjd	/* NOTREACHED */
706204076Spjd	return (NULL);
707204076Spjd}
708204076Spjd
709204076Spjd/*
710204076Spjd * Thread sends requests back to primary node.
711204076Spjd */
712204076Spjdstatic void *
713204076Spjdsend_thread(void *arg)
714204076Spjd{
715204076Spjd	struct hast_resource *res = arg;
716204076Spjd	struct nv *nvout;
717204076Spjd	struct hio *hio;
718204076Spjd	void *data;
719204076Spjd	size_t length;
720204076Spjd
721204076Spjd	for (;;) {
722204076Spjd		pjdlog_debug(2, "send: Taking request.");
723211877Spjd		QUEUE_TAKE(send, hio);
724204076Spjd		reqlog(LOG_DEBUG, 2, -1, hio, "send: (%p) Got request: ", hio);
725204076Spjd		nvout = nv_alloc();
726204076Spjd		/* Copy sequence number. */
727204076Spjd		nv_add_uint64(nvout, nv_get_uint64(hio->hio_nv, "seq"), "seq");
728204076Spjd		switch (hio->hio_cmd) {
729204076Spjd		case HIO_READ:
730204076Spjd			if (hio->hio_error == 0) {
731204076Spjd				data = hio->hio_data;
732204076Spjd				length = hio->hio_length;
733204076Spjd				break;
734204076Spjd			}
735204076Spjd			/*
736204076Spjd			 * We send no data in case of an error.
737204076Spjd			 */
738204076Spjd			/* FALLTHROUGH */
739204076Spjd		case HIO_DELETE:
740204076Spjd		case HIO_FLUSH:
741204076Spjd		case HIO_WRITE:
742204076Spjd			data = NULL;
743204076Spjd			length = 0;
744204076Spjd			break;
745204076Spjd		default:
746204076Spjd			abort();
747204076Spjd			break;
748204076Spjd		}
749204076Spjd		if (hio->hio_error != 0)
750204076Spjd			nv_add_int16(nvout, hio->hio_error, "error");
751204076Spjd		if (hast_proto_send(res, res->hr_remoteout, nvout, data,
752204076Spjd		    length) < 0) {
753211984Spjd			secondary_exit(EX_TEMPFAIL, "Unable to send reply.");
754204076Spjd		}
755204076Spjd		nv_free(nvout);
756209185Spjd		pjdlog_debug(2, "send: (%p) Moving request to the free queue.",
757204076Spjd		    hio);
758204076Spjd		nv_free(hio->hio_nv);
759204076Spjd		hio->hio_error = 0;
760211877Spjd		QUEUE_INSERT(free, hio);
761204076Spjd	}
762204076Spjd	/* NOTREACHED */
763204076Spjd	return (NULL);
764204076Spjd}
765