secondary.c revision 219864
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 219864 2011-03-22 10:39:34Z pjd $");
33204076Spjd
34204076Spjd#include <sys/param.h>
35204076Spjd#include <sys/time.h>
36204076Spjd#include <sys/bio.h>
37204076Spjd#include <sys/disk.h>
38204076Spjd#include <sys/stat.h>
39204076Spjd
40204076Spjd#include <err.h>
41204076Spjd#include <errno.h>
42204076Spjd#include <fcntl.h>
43204076Spjd#include <libgeom.h>
44204076Spjd#include <pthread.h>
45213009Spjd#include <signal.h>
46204076Spjd#include <stdint.h>
47204076Spjd#include <stdio.h>
48204076Spjd#include <string.h>
49204076Spjd#include <sysexits.h>
50204076Spjd#include <unistd.h>
51204076Spjd
52204076Spjd#include <activemap.h>
53204076Spjd#include <nv.h>
54204076Spjd#include <pjdlog.h>
55204076Spjd
56204076Spjd#include "control.h"
57212038Spjd#include "event.h"
58204076Spjd#include "hast.h"
59204076Spjd#include "hast_proto.h"
60204076Spjd#include "hastd.h"
61211977Spjd#include "hooks.h"
62204076Spjd#include "metadata.h"
63204076Spjd#include "proto.h"
64204076Spjd#include "subr.h"
65204076Spjd#include "synch.h"
66204076Spjd
67204076Spjdstruct hio {
68219864Spjd	uint64_t	 hio_seq;
69219864Spjd	int		 hio_error;
70204076Spjd	struct nv	*hio_nv;
71204076Spjd	void		*hio_data;
72204076Spjd	uint8_t		 hio_cmd;
73204076Spjd	uint64_t	 hio_offset;
74204076Spjd	uint64_t	 hio_length;
75204076Spjd	TAILQ_ENTRY(hio) hio_next;
76204076Spjd};
77204076Spjd
78211984Spjdstatic struct hast_resource *gres;
79211984Spjd
80204076Spjd/*
81204076Spjd * Free list holds unused structures. When free list is empty, we have to wait
82204076Spjd * until some in-progress requests are freed.
83204076Spjd */
84204076Spjdstatic TAILQ_HEAD(, hio) hio_free_list;
85204076Spjdstatic pthread_mutex_t hio_free_list_lock;
86204076Spjdstatic pthread_cond_t hio_free_list_cond;
87204076Spjd/*
88204076Spjd * Disk thread (the one that do I/O requests) takes requests from this list.
89204076Spjd */
90204076Spjdstatic TAILQ_HEAD(, hio) hio_disk_list;
91204076Spjdstatic pthread_mutex_t hio_disk_list_lock;
92204076Spjdstatic pthread_cond_t hio_disk_list_cond;
93204076Spjd/*
94204076Spjd * There is one recv list for every component, although local components don't
95204076Spjd * use recv lists as local requests are done synchronously.
96204076Spjd */
97204076Spjdstatic TAILQ_HEAD(, hio) hio_send_list;
98204076Spjdstatic pthread_mutex_t hio_send_list_lock;
99204076Spjdstatic pthread_cond_t hio_send_list_cond;
100204076Spjd
101204076Spjd/*
102204076Spjd * Maximum number of outstanding I/O requests.
103204076Spjd */
104204076Spjd#define	HAST_HIO_MAX	256
105204076Spjd
106204076Spjdstatic void *recv_thread(void *arg);
107204076Spjdstatic void *disk_thread(void *arg);
108204076Spjdstatic void *send_thread(void *arg);
109204076Spjd
110211877Spjd#define	QUEUE_INSERT(name, hio)	do {					\
111211877Spjd	bool _wakeup;							\
112211877Spjd									\
113211877Spjd	mtx_lock(&hio_##name##_list_lock);				\
114211877Spjd	_wakeup = TAILQ_EMPTY(&hio_##name##_list);			\
115211877Spjd	TAILQ_INSERT_TAIL(&hio_##name##_list, (hio), hio_next);		\
116211877Spjd	mtx_unlock(&hio_##name##_list_lock);				\
117211877Spjd	if (_wakeup)							\
118211877Spjd		cv_signal(&hio_##name##_list_cond);			\
119211877Spjd} while (0)
120211877Spjd#define	QUEUE_TAKE(name, hio)	do {					\
121211877Spjd	mtx_lock(&hio_##name##_list_lock);				\
122211877Spjd	while (((hio) = TAILQ_FIRST(&hio_##name##_list)) == NULL) {	\
123211877Spjd		cv_wait(&hio_##name##_list_cond,			\
124211877Spjd		    &hio_##name##_list_lock);				\
125211877Spjd	}								\
126211877Spjd	TAILQ_REMOVE(&hio_##name##_list, (hio), hio_next);		\
127211877Spjd	mtx_unlock(&hio_##name##_list_lock);				\
128211877Spjd} while (0)
129211877Spjd
130204076Spjdstatic void
131204076Spjdinit_environment(void)
132204076Spjd{
133204076Spjd	struct hio *hio;
134204076Spjd	unsigned int ii;
135204076Spjd
136204076Spjd	/*
137204076Spjd	 * Initialize lists, their locks and theirs condition variables.
138204076Spjd	 */
139204076Spjd	TAILQ_INIT(&hio_free_list);
140204076Spjd	mtx_init(&hio_free_list_lock);
141204076Spjd	cv_init(&hio_free_list_cond);
142204076Spjd	TAILQ_INIT(&hio_disk_list);
143204076Spjd	mtx_init(&hio_disk_list_lock);
144204076Spjd	cv_init(&hio_disk_list_cond);
145204076Spjd	TAILQ_INIT(&hio_send_list);
146204076Spjd	mtx_init(&hio_send_list_lock);
147204076Spjd	cv_init(&hio_send_list_cond);
148204076Spjd
149204076Spjd	/*
150204076Spjd	 * Allocate requests pool and initialize requests.
151204076Spjd	 */
152204076Spjd	for (ii = 0; ii < HAST_HIO_MAX; ii++) {
153204076Spjd		hio = malloc(sizeof(*hio));
154204076Spjd		if (hio == NULL) {
155210879Spjd			pjdlog_exitx(EX_TEMPFAIL,
156210879Spjd			    "Unable to allocate memory (%zu bytes) for hio request.",
157210879Spjd			    sizeof(*hio));
158204076Spjd		}
159204076Spjd		hio->hio_error = 0;
160204076Spjd		hio->hio_data = malloc(MAXPHYS);
161204076Spjd		if (hio->hio_data == NULL) {
162210879Spjd			pjdlog_exitx(EX_TEMPFAIL,
163210879Spjd			    "Unable to allocate memory (%zu bytes) for gctl_data.",
164210879Spjd			    (size_t)MAXPHYS);
165204076Spjd		}
166204076Spjd		TAILQ_INSERT_HEAD(&hio_free_list, hio, hio_next);
167204076Spjd	}
168204076Spjd}
169204076Spjd
170204076Spjdstatic void
171204076Spjdinit_local(struct hast_resource *res)
172204076Spjd{
173204076Spjd
174204076Spjd	if (metadata_read(res, true) < 0)
175204076Spjd		exit(EX_NOINPUT);
176204076Spjd}
177204076Spjd
178204076Spjdstatic void
179204076Spjdinit_remote(struct hast_resource *res, struct nv *nvin)
180204076Spjd{
181204076Spjd	uint64_t resuid;
182204076Spjd	struct nv *nvout;
183204076Spjd	unsigned char *map;
184204076Spjd	size_t mapsize;
185204076Spjd
186204076Spjd	map = NULL;
187204076Spjd	mapsize = 0;
188204076Spjd	nvout = nv_alloc();
189204076Spjd	nv_add_int64(nvout, (int64_t)res->hr_datasize, "datasize");
190204076Spjd	nv_add_int32(nvout, (int32_t)res->hr_extentsize, "extentsize");
191204076Spjd	resuid = nv_get_uint64(nvin, "resuid");
192204076Spjd	res->hr_primary_localcnt = nv_get_uint64(nvin, "localcnt");
193204076Spjd	res->hr_primary_remotecnt = nv_get_uint64(nvin, "remotecnt");
194204076Spjd	nv_add_uint64(nvout, res->hr_secondary_localcnt, "localcnt");
195204076Spjd	nv_add_uint64(nvout, res->hr_secondary_remotecnt, "remotecnt");
196204076Spjd	mapsize = activemap_calc_ondisk_size(res->hr_local_mediasize -
197204076Spjd	    METADATA_SIZE, res->hr_extentsize, res->hr_local_sectorsize);
198204076Spjd	map = malloc(mapsize);
199204076Spjd	if (map == NULL) {
200204076Spjd		pjdlog_exitx(EX_TEMPFAIL,
201204076Spjd		    "Unable to allocate memory (%zu bytes) for activemap.",
202204076Spjd		    mapsize);
203204076Spjd	}
204204076Spjd	nv_add_uint32(nvout, (uint32_t)mapsize, "mapsize");
205204076Spjd	/*
206204076Spjd	 * When we work as primary and secondary is missing we will increase
207204076Spjd	 * localcnt in our metadata. When secondary is connected and synced
208204076Spjd	 * we make localcnt be equal to remotecnt, which means nodes are more
209204076Spjd	 * or less in sync.
210204076Spjd	 * Split-brain condition is when both nodes are not able to communicate
211204076Spjd	 * and are both configured as primary nodes. In turn, they can both
212204076Spjd	 * make incompatible changes to the data and we have to detect that.
213204076Spjd	 * Under split-brain condition we will increase our localcnt on first
214204076Spjd	 * write and remote node will increase its localcnt on first write.
215204076Spjd	 * When we connect we can see that primary's localcnt is greater than
216204076Spjd	 * our remotecnt (primary was modified while we weren't watching) and
217204076Spjd	 * our localcnt is greater than primary's remotecnt (we were modified
218204076Spjd	 * while primary wasn't watching).
219204076Spjd	 * There are many possible combinations which are all gathered below.
220204076Spjd	 * Don't pay too much attention to exact numbers, the more important
221204076Spjd	 * is to compare them. We compare secondary's local with primary's
222204076Spjd	 * remote and secondary's remote with primary's local.
223204076Spjd	 * Note that every case where primary's localcnt is smaller than
224204076Spjd	 * secondary's remotecnt and where secondary's localcnt is smaller than
225204076Spjd	 * primary's remotecnt should be impossible in practise. We will perform
226204076Spjd	 * full synchronization then. Those cases are marked with an asterisk.
227204076Spjd	 * Regular synchronization means that only extents marked as dirty are
228204076Spjd	 * synchronized (regular synchronization).
229204076Spjd	 *
230204076Spjd	 * SECONDARY METADATA PRIMARY METADATA
231204076Spjd	 * local=3 remote=3   local=2 remote=2*  ?! Full sync from secondary.
232204076Spjd	 * local=3 remote=3   local=2 remote=3*  ?! Full sync from primary.
233204076Spjd	 * local=3 remote=3   local=2 remote=4*  ?! Full sync from primary.
234204076Spjd	 * local=3 remote=3   local=3 remote=2   Primary is out-of-date,
235204076Spjd	 *                                       regular sync from secondary.
236204076Spjd	 * local=3 remote=3   local=3 remote=3   Regular sync just in case.
237204076Spjd	 * local=3 remote=3   local=3 remote=4*  ?! Full sync from primary.
238204076Spjd	 * local=3 remote=3   local=4 remote=2   Split-brain condition.
239204076Spjd	 * local=3 remote=3   local=4 remote=3   Secondary out-of-date,
240204076Spjd	 *                                       regular sync from primary.
241204076Spjd	 * local=3 remote=3   local=4 remote=4*  ?! Full sync from primary.
242204076Spjd	 */
243204076Spjd	if (res->hr_resuid == 0) {
244204076Spjd		/*
245214284Spjd		 * Provider is used for the first time. If primary node done no
246214284Spjd		 * writes yet as well (we will find "virgin" argument) then
247214284Spjd		 * there is no need to synchronize anything. If primary node
248214284Spjd		 * done any writes already we have to synchronize everything.
249204076Spjd		 */
250218138Spjd		PJDLOG_ASSERT(res->hr_secondary_localcnt == 0);
251204076Spjd		res->hr_resuid = resuid;
252204076Spjd		if (metadata_write(res) < 0)
253204076Spjd			exit(EX_NOINPUT);
254214284Spjd		if (nv_exists(nvin, "virgin")) {
255214284Spjd			free(map);
256214284Spjd			map = NULL;
257214284Spjd			mapsize = 0;
258214284Spjd		} else {
259214284Spjd			memset(map, 0xff, mapsize);
260214284Spjd		}
261204076Spjd		nv_add_uint8(nvout, HAST_SYNCSRC_PRIMARY, "syncsrc");
262219830Spjd	} else if (res->hr_resuid != resuid) {
263219830Spjd		char errmsg[256];
264219830Spjd
265219830Spjd		(void)snprintf(errmsg, sizeof(errmsg),
266219830Spjd		    "Resource unique ID mismatch (primary=%ju, secondary=%ju).",
267219830Spjd		    (uintmax_t)resuid, (uintmax_t)res->hr_resuid);
268219830Spjd		pjdlog_error("%s", errmsg);
269219830Spjd		nv_add_string(nvout, errmsg, "errmsg");
270219830Spjd		if (hast_proto_send(res, res->hr_remotein, nvout, NULL, 0) < 0) {
271219830Spjd			pjdlog_exit(EX_TEMPFAIL, "Unable to send response to %s",
272219830Spjd			    res->hr_remoteaddr);
273219830Spjd		}
274219831Spjd		nv_free(nvout);
275219830Spjd		exit(EX_CONFIG);
276204076Spjd	} else if (
277204076Spjd	    /* Is primary is out-of-date? */
278204076Spjd	    (res->hr_secondary_localcnt > res->hr_primary_remotecnt &&
279204076Spjd	     res->hr_secondary_remotecnt == res->hr_primary_localcnt) ||
280219843Spjd	    /* Nodes are more or less in sync? */
281204076Spjd	    (res->hr_secondary_localcnt == res->hr_primary_remotecnt &&
282204076Spjd	     res->hr_secondary_remotecnt == res->hr_primary_localcnt) ||
283204076Spjd	    /* Is secondary is out-of-date? */
284204076Spjd	    (res->hr_secondary_localcnt == res->hr_primary_remotecnt &&
285204076Spjd	     res->hr_secondary_remotecnt < res->hr_primary_localcnt)) {
286204076Spjd		/*
287204076Spjd		 * Nodes are more or less in sync or one of the nodes is
288204076Spjd		 * out-of-date.
289204076Spjd		 * It doesn't matter at this point which one, we just have to
290204076Spjd		 * send out local bitmap to the remote node.
291204076Spjd		 */
292204076Spjd		if (pread(res->hr_localfd, map, mapsize, METADATA_SIZE) !=
293204076Spjd		    (ssize_t)mapsize) {
294204076Spjd			pjdlog_exit(LOG_ERR, "Unable to read activemap");
295204076Spjd		}
296204076Spjd		if (res->hr_secondary_localcnt > res->hr_primary_remotecnt &&
297204076Spjd		     res->hr_secondary_remotecnt == res->hr_primary_localcnt) {
298204076Spjd			/* Primary is out-of-date, sync from secondary. */
299204076Spjd			nv_add_uint8(nvout, HAST_SYNCSRC_SECONDARY, "syncsrc");
300204076Spjd		} else {
301204076Spjd			/*
302204076Spjd			 * Secondary is out-of-date or counts match.
303204076Spjd			 * Sync from primary.
304204076Spjd			 */
305204076Spjd			nv_add_uint8(nvout, HAST_SYNCSRC_PRIMARY, "syncsrc");
306204076Spjd		}
307204076Spjd	} else if (res->hr_secondary_localcnt > res->hr_primary_remotecnt &&
308204076Spjd	     res->hr_primary_localcnt > res->hr_secondary_remotecnt) {
309204076Spjd		/*
310204076Spjd		 * Not good, we have split-brain condition.
311204076Spjd		 */
312204076Spjd		pjdlog_error("Split-brain detected, exiting.");
313204076Spjd		nv_add_string(nvout, "Split-brain condition!", "errmsg");
314204076Spjd		free(map);
315204076Spjd		map = NULL;
316204076Spjd		mapsize = 0;
317204076Spjd	} else /* if (res->hr_secondary_localcnt < res->hr_primary_remotecnt ||
318204076Spjd	    res->hr_primary_localcnt < res->hr_secondary_remotecnt) */ {
319204076Spjd		/*
320204076Spjd		 * This should never happen in practise, but we will perform
321204076Spjd		 * full synchronization.
322204076Spjd		 */
323218138Spjd		PJDLOG_ASSERT(res->hr_secondary_localcnt < res->hr_primary_remotecnt ||
324204076Spjd		    res->hr_primary_localcnt < res->hr_secondary_remotecnt);
325204076Spjd		mapsize = activemap_calc_ondisk_size(res->hr_local_mediasize -
326204076Spjd		    METADATA_SIZE, res->hr_extentsize,
327204076Spjd		    res->hr_local_sectorsize);
328204076Spjd		memset(map, 0xff, mapsize);
329204076Spjd		if (res->hr_secondary_localcnt > res->hr_primary_remotecnt) {
330204076Spjd			/* In this one of five cases sync from secondary. */
331204076Spjd			nv_add_uint8(nvout, HAST_SYNCSRC_SECONDARY, "syncsrc");
332204076Spjd		} else {
333204076Spjd			/* For the rest four cases sync from primary. */
334204076Spjd			nv_add_uint8(nvout, HAST_SYNCSRC_PRIMARY, "syncsrc");
335204076Spjd		}
336204076Spjd		pjdlog_warning("This should never happen, asking for full synchronization (primary(local=%ju, remote=%ju), secondary(local=%ju, remote=%ju)).",
337204076Spjd		    (uintmax_t)res->hr_primary_localcnt,
338204076Spjd		    (uintmax_t)res->hr_primary_remotecnt,
339204076Spjd		    (uintmax_t)res->hr_secondary_localcnt,
340204076Spjd		    (uintmax_t)res->hr_secondary_remotecnt);
341204076Spjd	}
342204076Spjd	if (hast_proto_send(res, res->hr_remotein, nvout, map, mapsize) < 0) {
343214276Spjd		pjdlog_exit(EX_TEMPFAIL, "Unable to send activemap to %s",
344204076Spjd		    res->hr_remoteaddr);
345204076Spjd	}
346214275Spjd	if (map != NULL)
347214275Spjd		free(map);
348209182Spjd	nv_free(nvout);
349204076Spjd	if (res->hr_secondary_localcnt > res->hr_primary_remotecnt &&
350204076Spjd	     res->hr_primary_localcnt > res->hr_secondary_remotecnt) {
351204076Spjd		/* Exit on split-brain. */
352212038Spjd		event_send(res, EVENT_SPLITBRAIN);
353204076Spjd		exit(EX_CONFIG);
354204076Spjd	}
355204076Spjd}
356204076Spjd
357204076Spjdvoid
358204076Spjdhastd_secondary(struct hast_resource *res, struct nv *nvin)
359204076Spjd{
360213009Spjd	sigset_t mask;
361204076Spjd	pthread_t td;
362204076Spjd	pid_t pid;
363219482Strociny	int error, mode, debuglevel;
364204076Spjd
365204076Spjd	/*
366204076Spjd	 * Create communication channel between parent and child.
367204076Spjd	 */
368219818Spjd	if (proto_client(NULL, "socketpair://", &res->hr_ctrl) < 0) {
369204076Spjd		KEEP_ERRNO((void)pidfile_remove(pfh));
370204076Spjd		pjdlog_exit(EX_OSERR,
371204076Spjd		    "Unable to create control sockets between parent and child");
372204076Spjd	}
373212038Spjd	/*
374212038Spjd	 * Create communication channel between child and parent.
375212038Spjd	 */
376219818Spjd	if (proto_client(NULL, "socketpair://", &res->hr_event) < 0) {
377212038Spjd		KEEP_ERRNO((void)pidfile_remove(pfh));
378212038Spjd		pjdlog_exit(EX_OSERR,
379212038Spjd		    "Unable to create event sockets between child and parent");
380212038Spjd	}
381218218Spjd	/*
382218218Spjd	 * Create communication channel for sending connection requests from
383218218Spjd	 * parent to child.
384218218Spjd	 */
385219818Spjd	if (proto_client(NULL, "socketpair://", &res->hr_conn) < 0) {
386218218Spjd		/* TODO: There's no need for this to be fatal error. */
387218218Spjd		KEEP_ERRNO((void)pidfile_remove(pfh));
388218218Spjd		pjdlog_exit(EX_OSERR,
389218218Spjd		    "Unable to create connection sockets between parent and child");
390218218Spjd	}
391204076Spjd
392204076Spjd	pid = fork();
393204076Spjd	if (pid < 0) {
394204076Spjd		KEEP_ERRNO((void)pidfile_remove(pfh));
395204076Spjd		pjdlog_exit(EX_OSERR, "Unable to fork");
396204076Spjd	}
397204076Spjd
398204076Spjd	if (pid > 0) {
399204076Spjd		/* This is parent. */
400204076Spjd		proto_close(res->hr_remotein);
401204076Spjd		res->hr_remotein = NULL;
402204076Spjd		proto_close(res->hr_remoteout);
403204076Spjd		res->hr_remoteout = NULL;
404212038Spjd		/* Declare that we are receiver. */
405212038Spjd		proto_recv(res->hr_event, NULL, 0);
406218043Spjd		/* Declare that we are sender. */
407218043Spjd		proto_send(res->hr_ctrl, NULL, 0);
408218218Spjd		proto_send(res->hr_conn, NULL, 0);
409204076Spjd		res->hr_workerpid = pid;
410204076Spjd		return;
411204076Spjd	}
412211977Spjd
413211984Spjd	gres = res;
414218043Spjd	mode = pjdlog_mode_get();
415219482Strociny	debuglevel = pjdlog_debug_get();
416211984Spjd
417218043Spjd	/* Declare that we are sender. */
418218043Spjd	proto_send(res->hr_event, NULL, 0);
419218043Spjd	/* Declare that we are receiver. */
420218043Spjd	proto_recv(res->hr_ctrl, NULL, 0);
421218218Spjd	proto_recv(res->hr_conn, NULL, 0);
422218043Spjd	descriptors_cleanup(res);
423204076Spjd
424218045Spjd	descriptors_assert(res, mode);
425218045Spjd
426218043Spjd	pjdlog_init(mode);
427219482Strociny	pjdlog_debug_set(debuglevel);
428218043Spjd	pjdlog_prefix_set("[%s] (%s) ", res->hr_name, role2str(res->hr_role));
429204076Spjd	setproctitle("%s (secondary)", res->hr_name);
430204076Spjd
431213009Spjd	PJDLOG_VERIFY(sigemptyset(&mask) == 0);
432213009Spjd	PJDLOG_VERIFY(sigprocmask(SIG_SETMASK, &mask, NULL) == 0);
433210880Spjd
434207371Spjd	/* Error in setting timeout is not critical, but why should it fail? */
435219721Strociny	if (proto_timeout(res->hr_remotein, 2 * HAST_KEEPALIVE) < 0)
436207371Spjd		pjdlog_errno(LOG_WARNING, "Unable to set connection timeout");
437207371Spjd	if (proto_timeout(res->hr_remoteout, res->hr_timeout) < 0)
438207371Spjd		pjdlog_errno(LOG_WARNING, "Unable to set connection timeout");
439207371Spjd
440204076Spjd	init_local(res);
441213007Spjd	init_environment();
442213007Spjd
443219847Spjd	if (drop_privs(true) != 0)
444218049Spjd		exit(EX_CONFIG);
445218214Spjd	pjdlog_info("Privileges successfully dropped.");
446218049Spjd
447213007Spjd	/*
448213007Spjd	 * Create the control thread before sending any event to the parent,
449213007Spjd	 * as we can deadlock when parent sends control request to worker,
450213007Spjd	 * but worker has no control thread started yet, so parent waits.
451213007Spjd	 * In the meantime worker sends an event to the parent, but parent
452213007Spjd	 * is unable to handle the event, because it waits for control
453213007Spjd	 * request response.
454213007Spjd	 */
455213007Spjd	error = pthread_create(&td, NULL, ctrl_thread, res);
456218138Spjd	PJDLOG_ASSERT(error == 0);
457213007Spjd
458204076Spjd	init_remote(res, nvin);
459212038Spjd	event_send(res, EVENT_CONNECT);
460204076Spjd
461204076Spjd	error = pthread_create(&td, NULL, recv_thread, res);
462218138Spjd	PJDLOG_ASSERT(error == 0);
463204076Spjd	error = pthread_create(&td, NULL, disk_thread, res);
464218138Spjd	PJDLOG_ASSERT(error == 0);
465213007Spjd	(void)send_thread(res);
466204076Spjd}
467204076Spjd
468204076Spjdstatic void
469204076Spjdreqlog(int loglevel, int debuglevel, int error, struct hio *hio, const char *fmt, ...)
470204076Spjd{
471204076Spjd	char msg[1024];
472204076Spjd	va_list ap;
473204076Spjd	int len;
474204076Spjd
475204076Spjd	va_start(ap, fmt);
476204076Spjd	len = vsnprintf(msg, sizeof(msg), fmt, ap);
477204076Spjd	va_end(ap);
478204076Spjd	if ((size_t)len < sizeof(msg)) {
479204076Spjd		switch (hio->hio_cmd) {
480204076Spjd		case HIO_READ:
481204076Spjd			(void)snprintf(msg + len, sizeof(msg) - len,
482204076Spjd			    "READ(%ju, %ju).", (uintmax_t)hio->hio_offset,
483204076Spjd			    (uintmax_t)hio->hio_length);
484204076Spjd			break;
485204076Spjd		case HIO_DELETE:
486204076Spjd			(void)snprintf(msg + len, sizeof(msg) - len,
487204076Spjd			    "DELETE(%ju, %ju).", (uintmax_t)hio->hio_offset,
488204076Spjd			    (uintmax_t)hio->hio_length);
489204076Spjd			break;
490204076Spjd		case HIO_FLUSH:
491204076Spjd			(void)snprintf(msg + len, sizeof(msg) - len, "FLUSH.");
492204076Spjd			break;
493204076Spjd		case HIO_WRITE:
494204076Spjd			(void)snprintf(msg + len, sizeof(msg) - len,
495204076Spjd			    "WRITE(%ju, %ju).", (uintmax_t)hio->hio_offset,
496204076Spjd			    (uintmax_t)hio->hio_length);
497204076Spjd			break;
498211882Spjd		case HIO_KEEPALIVE:
499211882Spjd			(void)snprintf(msg + len, sizeof(msg) - len, "KEEPALIVE.");
500211882Spjd			break;
501204076Spjd		default:
502204076Spjd			(void)snprintf(msg + len, sizeof(msg) - len,
503204076Spjd			    "UNKNOWN(%u).", (unsigned int)hio->hio_cmd);
504204076Spjd			break;
505204076Spjd		}
506204076Spjd	}
507204076Spjd	pjdlog_common(loglevel, debuglevel, error, "%s", msg);
508204076Spjd}
509204076Spjd
510204076Spjdstatic int
511204076Spjdrequnpack(struct hast_resource *res, struct hio *hio)
512204076Spjd{
513204076Spjd
514204076Spjd	hio->hio_cmd = nv_get_uint8(hio->hio_nv, "cmd");
515204076Spjd	if (hio->hio_cmd == 0) {
516204076Spjd		pjdlog_error("Header contains no 'cmd' field.");
517204076Spjd		hio->hio_error = EINVAL;
518204076Spjd		goto end;
519204076Spjd	}
520204076Spjd	switch (hio->hio_cmd) {
521211882Spjd	case HIO_KEEPALIVE:
522211882Spjd		break;
523204076Spjd	case HIO_READ:
524204076Spjd	case HIO_WRITE:
525204076Spjd	case HIO_DELETE:
526204076Spjd		hio->hio_offset = nv_get_uint64(hio->hio_nv, "offset");
527204076Spjd		if (nv_error(hio->hio_nv) != 0) {
528204076Spjd			pjdlog_error("Header is missing 'offset' field.");
529204076Spjd			hio->hio_error = EINVAL;
530204076Spjd			goto end;
531204076Spjd		}
532204076Spjd		hio->hio_length = nv_get_uint64(hio->hio_nv, "length");
533204076Spjd		if (nv_error(hio->hio_nv) != 0) {
534204076Spjd			pjdlog_error("Header is missing 'length' field.");
535204076Spjd			hio->hio_error = EINVAL;
536204076Spjd			goto end;
537204076Spjd		}
538204076Spjd		if (hio->hio_length == 0) {
539204076Spjd			pjdlog_error("Data length is zero.");
540204076Spjd			hio->hio_error = EINVAL;
541204076Spjd			goto end;
542204076Spjd		}
543204076Spjd		if (hio->hio_length > MAXPHYS) {
544204076Spjd			pjdlog_error("Data length is too large (%ju > %ju).",
545204076Spjd			    (uintmax_t)hio->hio_length, (uintmax_t)MAXPHYS);
546204076Spjd			hio->hio_error = EINVAL;
547204076Spjd			goto end;
548204076Spjd		}
549204076Spjd		if ((hio->hio_offset % res->hr_local_sectorsize) != 0) {
550204076Spjd			pjdlog_error("Offset %ju is not multiple of sector size.",
551204076Spjd			    (uintmax_t)hio->hio_offset);
552204076Spjd			hio->hio_error = EINVAL;
553204076Spjd			goto end;
554204076Spjd		}
555204076Spjd		if ((hio->hio_length % res->hr_local_sectorsize) != 0) {
556204076Spjd			pjdlog_error("Length %ju is not multiple of sector size.",
557204076Spjd			    (uintmax_t)hio->hio_length);
558204076Spjd			hio->hio_error = EINVAL;
559204076Spjd			goto end;
560204076Spjd		}
561204076Spjd		if (hio->hio_offset + hio->hio_length >
562204076Spjd		    (uint64_t)res->hr_datasize) {
563204076Spjd			pjdlog_error("Data offset is too large (%ju > %ju).",
564204076Spjd			    (uintmax_t)(hio->hio_offset + hio->hio_length),
565204076Spjd			    (uintmax_t)res->hr_datasize);
566204076Spjd			hio->hio_error = EINVAL;
567204076Spjd			goto end;
568204076Spjd		}
569204076Spjd		break;
570204076Spjd	default:
571204076Spjd		pjdlog_error("Header contains invalid 'cmd' (%hhu).",
572204076Spjd		    hio->hio_cmd);
573204076Spjd		hio->hio_error = EINVAL;
574204076Spjd		goto end;
575204076Spjd	}
576204076Spjd	hio->hio_error = 0;
577204076Spjdend:
578204076Spjd	return (hio->hio_error);
579204076Spjd}
580204076Spjd
581212899Spjdstatic __dead2 void
582211984Spjdsecondary_exit(int exitcode, const char *fmt, ...)
583211984Spjd{
584211984Spjd	va_list ap;
585211984Spjd
586218138Spjd	PJDLOG_ASSERT(exitcode != EX_OK);
587211984Spjd	va_start(ap, fmt);
588211984Spjd	pjdlogv_errno(LOG_ERR, fmt, ap);
589211984Spjd	va_end(ap);
590212038Spjd	event_send(gres, EVENT_DISCONNECT);
591211984Spjd	exit(exitcode);
592211984Spjd}
593211984Spjd
594204076Spjd/*
595204076Spjd * Thread receives requests from the primary node.
596204076Spjd */
597204076Spjdstatic void *
598204076Spjdrecv_thread(void *arg)
599204076Spjd{
600204076Spjd	struct hast_resource *res = arg;
601204076Spjd	struct hio *hio;
602204076Spjd
603204076Spjd	for (;;) {
604204076Spjd		pjdlog_debug(2, "recv: Taking free request.");
605211877Spjd		QUEUE_TAKE(free, hio);
606204076Spjd		pjdlog_debug(2, "recv: (%p) Got request.", hio);
607204076Spjd		if (hast_proto_recv_hdr(res->hr_remotein, &hio->hio_nv) < 0) {
608211984Spjd			secondary_exit(EX_TEMPFAIL,
609204076Spjd			    "Unable to receive request header");
610204076Spjd		}
611211877Spjd		if (requnpack(res, hio) != 0) {
612211877Spjd			pjdlog_debug(2,
613211877Spjd			    "recv: (%p) Moving request to the send queue.",
614211877Spjd			    hio);
615211877Spjd			QUEUE_INSERT(send, hio);
616211877Spjd			continue;
617211877Spjd		}
618204076Spjd		reqlog(LOG_DEBUG, 2, -1, hio,
619204076Spjd		    "recv: (%p) Got request header: ", hio);
620211882Spjd		if (hio->hio_cmd == HIO_KEEPALIVE) {
621211882Spjd			pjdlog_debug(2,
622211882Spjd			    "recv: (%p) Moving request to the free queue.",
623211882Spjd			    hio);
624211882Spjd			nv_free(hio->hio_nv);
625211882Spjd			QUEUE_INSERT(free, hio);
626211882Spjd			continue;
627211882Spjd		} else if (hio->hio_cmd == HIO_WRITE) {
628204076Spjd			if (hast_proto_recv_data(res, res->hr_remotein,
629204076Spjd			    hio->hio_nv, hio->hio_data, MAXPHYS) < 0) {
630211984Spjd				secondary_exit(EX_TEMPFAIL,
631212051Spjd				    "Unable to receive request data");
632204076Spjd			}
633204076Spjd		}
634204076Spjd		pjdlog_debug(2, "recv: (%p) Moving request to the disk queue.",
635204076Spjd		    hio);
636211877Spjd		QUEUE_INSERT(disk, hio);
637204076Spjd	}
638204076Spjd	/* NOTREACHED */
639204076Spjd	return (NULL);
640204076Spjd}
641204076Spjd
642204076Spjd/*
643204076Spjd * Thread reads from or writes to local component and also handles DELETE and
644204076Spjd * FLUSH requests.
645204076Spjd */
646204076Spjdstatic void *
647204076Spjddisk_thread(void *arg)
648204076Spjd{
649204076Spjd	struct hast_resource *res = arg;
650204076Spjd	struct hio *hio;
651204076Spjd	ssize_t ret;
652211877Spjd	bool clear_activemap;
653204076Spjd
654204076Spjd	clear_activemap = true;
655204076Spjd
656204076Spjd	for (;;) {
657204076Spjd		pjdlog_debug(2, "disk: Taking request.");
658211877Spjd		QUEUE_TAKE(disk, hio);
659204076Spjd		while (clear_activemap) {
660204076Spjd			unsigned char *map;
661204076Spjd			size_t mapsize;
662204076Spjd
663204076Spjd			/*
664204076Spjd			 * When first request is received, it means that primary
665204076Spjd			 * already received our activemap, merged it and stored
666204076Spjd			 * locally. We can now safely clear our activemap.
667204076Spjd			 */
668204076Spjd			mapsize =
669204076Spjd			    activemap_calc_ondisk_size(res->hr_local_mediasize -
670204076Spjd			    METADATA_SIZE, res->hr_extentsize,
671204076Spjd			    res->hr_local_sectorsize);
672204076Spjd			map = calloc(1, mapsize);
673204076Spjd			if (map == NULL) {
674204076Spjd				pjdlog_warning("Unable to allocate memory to clear local activemap.");
675204076Spjd				break;
676204076Spjd			}
677204076Spjd			if (pwrite(res->hr_localfd, map, mapsize,
678204076Spjd			    METADATA_SIZE) != (ssize_t)mapsize) {
679204076Spjd				pjdlog_errno(LOG_WARNING,
680204076Spjd				    "Unable to store cleared activemap");
681204076Spjd				free(map);
682204076Spjd				break;
683204076Spjd			}
684204076Spjd			free(map);
685204076Spjd			clear_activemap = false;
686204076Spjd			pjdlog_debug(1, "Local activemap cleared.");
687204076Spjd		}
688204076Spjd		reqlog(LOG_DEBUG, 2, -1, hio, "disk: (%p) Got request: ", hio);
689204076Spjd		/* Handle the actual request. */
690204076Spjd		switch (hio->hio_cmd) {
691204076Spjd		case HIO_READ:
692204076Spjd			ret = pread(res->hr_localfd, hio->hio_data,
693204076Spjd			    hio->hio_length,
694204076Spjd			    hio->hio_offset + res->hr_localoff);
695204076Spjd			if (ret < 0)
696204076Spjd				hio->hio_error = errno;
697204076Spjd			else if (ret != (int64_t)hio->hio_length)
698204076Spjd				hio->hio_error = EIO;
699204076Spjd			else
700204076Spjd				hio->hio_error = 0;
701204076Spjd			break;
702204076Spjd		case HIO_WRITE:
703204076Spjd			ret = pwrite(res->hr_localfd, hio->hio_data,
704204076Spjd			    hio->hio_length,
705204076Spjd			    hio->hio_offset + res->hr_localoff);
706204076Spjd			if (ret < 0)
707204076Spjd				hio->hio_error = errno;
708204076Spjd			else if (ret != (int64_t)hio->hio_length)
709204076Spjd				hio->hio_error = EIO;
710204076Spjd			else
711204076Spjd				hio->hio_error = 0;
712204076Spjd			break;
713204076Spjd		case HIO_DELETE:
714204076Spjd			ret = g_delete(res->hr_localfd,
715204076Spjd			    hio->hio_offset + res->hr_localoff,
716204076Spjd			    hio->hio_length);
717204076Spjd			if (ret < 0)
718204076Spjd				hio->hio_error = errno;
719204076Spjd			else
720204076Spjd				hio->hio_error = 0;
721204076Spjd			break;
722204076Spjd		case HIO_FLUSH:
723204076Spjd			ret = g_flush(res->hr_localfd);
724204076Spjd			if (ret < 0)
725204076Spjd				hio->hio_error = errno;
726204076Spjd			else
727204076Spjd				hio->hio_error = 0;
728204076Spjd			break;
729204076Spjd		}
730204076Spjd		if (hio->hio_error != 0) {
731204076Spjd			reqlog(LOG_ERR, 0, hio->hio_error, hio,
732204076Spjd			    "Request failed: ");
733204076Spjd		}
734204076Spjd		pjdlog_debug(2, "disk: (%p) Moving request to the send queue.",
735204076Spjd		    hio);
736211877Spjd		QUEUE_INSERT(send, hio);
737204076Spjd	}
738204076Spjd	/* NOTREACHED */
739204076Spjd	return (NULL);
740204076Spjd}
741204076Spjd
742204076Spjd/*
743204076Spjd * Thread sends requests back to primary node.
744204076Spjd */
745204076Spjdstatic void *
746204076Spjdsend_thread(void *arg)
747204076Spjd{
748204076Spjd	struct hast_resource *res = arg;
749204076Spjd	struct nv *nvout;
750204076Spjd	struct hio *hio;
751204076Spjd	void *data;
752204076Spjd	size_t length;
753204076Spjd
754204076Spjd	for (;;) {
755204076Spjd		pjdlog_debug(2, "send: Taking request.");
756211877Spjd		QUEUE_TAKE(send, hio);
757204076Spjd		reqlog(LOG_DEBUG, 2, -1, hio, "send: (%p) Got request: ", hio);
758204076Spjd		nvout = nv_alloc();
759204076Spjd		/* Copy sequence number. */
760204076Spjd		nv_add_uint64(nvout, nv_get_uint64(hio->hio_nv, "seq"), "seq");
761204076Spjd		switch (hio->hio_cmd) {
762204076Spjd		case HIO_READ:
763204076Spjd			if (hio->hio_error == 0) {
764204076Spjd				data = hio->hio_data;
765204076Spjd				length = hio->hio_length;
766204076Spjd				break;
767204076Spjd			}
768204076Spjd			/*
769204076Spjd			 * We send no data in case of an error.
770204076Spjd			 */
771204076Spjd			/* FALLTHROUGH */
772204076Spjd		case HIO_DELETE:
773204076Spjd		case HIO_FLUSH:
774204076Spjd		case HIO_WRITE:
775204076Spjd			data = NULL;
776204076Spjd			length = 0;
777204076Spjd			break;
778204076Spjd		default:
779204076Spjd			abort();
780204076Spjd			break;
781204076Spjd		}
782204076Spjd		if (hio->hio_error != 0)
783204076Spjd			nv_add_int16(nvout, hio->hio_error, "error");
784204076Spjd		if (hast_proto_send(res, res->hr_remoteout, nvout, data,
785204076Spjd		    length) < 0) {
786211984Spjd			secondary_exit(EX_TEMPFAIL, "Unable to send reply.");
787204076Spjd		}
788204076Spjd		nv_free(nvout);
789209185Spjd		pjdlog_debug(2, "send: (%p) Moving request to the free queue.",
790204076Spjd		    hio);
791204076Spjd		nv_free(hio->hio_nv);
792204076Spjd		hio->hio_error = 0;
793211877Spjd		QUEUE_INSERT(free, hio);
794204076Spjd	}
795204076Spjd	/* NOTREACHED */
796204076Spjd	return (NULL);
797204076Spjd}
798