secondary.c revision 219482
1117397Skan/*-
2117397Skan * Copyright (c) 2009-2010 The FreeBSD Foundation
3169691Skan * Copyright (c) 2010 Pawel Jakub Dawidek <pjd@FreeBSD.org>
4169691Skan * All rights reserved.
5117397Skan *
6117397Skan * This software was developed by Pawel Jakub Dawidek under sponsorship from
7117397Skan * the FreeBSD Foundation.
8117397Skan *
9117397Skan * Redistribution and use in source and binary forms, with or without
10117397Skan * modification, are permitted provided that the following conditions
11117397Skan * are met:
12117397Skan * 1. Redistributions of source code must retain the above copyright
13117397Skan *    notice, this list of conditions and the following disclaimer.
14117397Skan * 2. Redistributions in binary form must reproduce the above copyright
15117397Skan *    notice, this list of conditions and the following disclaimer in the
16117397Skan *    documentation and/or other materials provided with the distribution.
17117397Skan *
18117397Skan * THIS SOFTWARE IS PROVIDED BY THE AUTHORS AND CONTRIBUTORS ``AS IS'' AND
19169691Skan * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20117397Skan * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21117397Skan * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE
22117397Skan * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23117397Skan * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24117397Skan * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25117397Skan * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26117397Skan * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
27117397Skan * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28117397Skan * SUCH DAMAGE.
29117397Skan */
30117397Skan
31117397Skan#include <sys/cdefs.h>
32117397Skan__FBSDID("$FreeBSD: head/sbin/hastd/secondary.c 219482 2011-03-11 12:12:35Z trociny $");
33117397Skan
34117397Skan#include <sys/param.h>
35117397Skan#include <sys/time.h>
36117397Skan#include <sys/bio.h>
37117397Skan#include <sys/disk.h>
38117397Skan#include <sys/stat.h>
39117397Skan
40117397Skan#include <err.h>
41117397Skan#include <errno.h>
42117397Skan#include <fcntl.h>
43117397Skan#include <libgeom.h>
44117397Skan#include <pthread.h>
45117397Skan#include <signal.h>
46117397Skan#include <stdint.h>
47117397Skan#include <stdio.h>
48117397Skan#include <string.h>
49117397Skan#include <sysexits.h>
50117397Skan#include <unistd.h>
51117397Skan
52117397Skan#include <activemap.h>
53117397Skan#include <nv.h>
54117397Skan#include <pjdlog.h>
55117397Skan
56117397Skan#include "control.h"
57117397Skan#include "event.h"
58117397Skan#include "hast.h"
59117397Skan#include "hast_proto.h"
60117397Skan#include "hastd.h"
61117397Skan#include "hooks.h"
62132720Skan#include "metadata.h"
63132720Skan#include "proto.h"
64117397Skan#include "subr.h"
65169691Skan#include "synch.h"
66169691Skan
67117397Skanstruct hio {
68117397Skan	uint64_t 	 hio_seq;
69169691Skan	int	 	 hio_error;
70132720Skan	struct nv	*hio_nv;
71117397Skan	void		*hio_data;
72117397Skan	uint8_t		 hio_cmd;
73132720Skan	uint64_t	 hio_offset;
74132720Skan	uint64_t	 hio_length;
75169691Skan	TAILQ_ENTRY(hio) hio_next;
76169691Skan};
77169691Skan
78169691Skanstatic struct hast_resource *gres;
79169691Skan
80169691Skan/*
81117397Skan * Free list holds unused structures. When free list is empty, we have to wait
82132720Skan * until some in-progress requests are freed.
83117397Skan */
84169691Skanstatic TAILQ_HEAD(, hio) hio_free_list;
85169691Skanstatic pthread_mutex_t hio_free_list_lock;
86117397Skanstatic pthread_cond_t hio_free_list_cond;
87117397Skan/*
88117397Skan * Disk thread (the one that do I/O requests) takes requests from this list.
89132720Skan */
90169691Skanstatic TAILQ_HEAD(, hio) hio_disk_list;
91117397Skanstatic pthread_mutex_t hio_disk_list_lock;
92132720Skanstatic pthread_cond_t hio_disk_list_cond;
93117397Skan/*
94169691Skan * There is one recv list for every component, although local components don't
95169691Skan * use recv lists as local requests are done synchronously.
96117397Skan */
97117397Skanstatic TAILQ_HEAD(, hio) hio_send_list;
98169691Skanstatic pthread_mutex_t hio_send_list_lock;
99132720Skanstatic pthread_cond_t hio_send_list_cond;
100132720Skan
101117397Skan/*
102132720Skan * Maximum number of outstanding I/O requests.
103117397Skan */
104117397Skan#define	HAST_HIO_MAX	256
105169691Skan
106169691Skanstatic void *recv_thread(void *arg);
107117397Skanstatic void *disk_thread(void *arg);
108117397Skanstatic void *send_thread(void *arg);
109117397Skan
110169691Skan#define	QUEUE_INSERT(name, hio)	do {					\
111117397Skan	bool _wakeup;							\
112117397Skan									\
113117397Skan	mtx_lock(&hio_##name##_list_lock);				\
114117397Skan	_wakeup = TAILQ_EMPTY(&hio_##name##_list);			\
115117397Skan	TAILQ_INSERT_TAIL(&hio_##name##_list, (hio), hio_next);		\
116117397Skan	mtx_unlock(&hio_##name##_list_lock);				\
117132720Skan	if (_wakeup)							\
118117397Skan		cv_signal(&hio_##name##_list_cond);			\
119169691Skan} while (0)
120169691Skan#define	QUEUE_TAKE(name, hio)	do {					\
121117397Skan	mtx_lock(&hio_##name##_list_lock);				\
122117397Skan	while (((hio) = TAILQ_FIRST(&hio_##name##_list)) == NULL) {	\
123117397Skan		cv_wait(&hio_##name##_list_cond,			\
124132720Skan		    &hio_##name##_list_lock);				\
125132720Skan	}								\
126132720Skan	TAILQ_REMOVE(&hio_##name##_list, (hio), hio_next);		\
127132720Skan	mtx_unlock(&hio_##name##_list_lock);				\
128132720Skan} while (0)
129169691Skan
130169691Skanstatic void
131169691Skaninit_environment(void)
132132720Skan{
133132720Skan	struct hio *hio;
134132720Skan	unsigned int ii;
135132720Skan
136132720Skan	/*
137117397Skan	 * Initialize lists, their locks and theirs condition variables.
138117397Skan	 */
139132720Skan	TAILQ_INIT(&hio_free_list);
140117397Skan	mtx_init(&hio_free_list_lock);
141117397Skan	cv_init(&hio_free_list_cond);
142169691Skan	TAILQ_INIT(&hio_disk_list);
143117397Skan	mtx_init(&hio_disk_list_lock);
144117397Skan	cv_init(&hio_disk_list_cond);
145117397Skan	TAILQ_INIT(&hio_send_list);
146169691Skan	mtx_init(&hio_send_list_lock);
147117397Skan	cv_init(&hio_send_list_cond);
148117397Skan
149117397Skan	/*
150117397Skan	 * Allocate requests pool and initialize requests.
151117397Skan	 */
152117397Skan	for (ii = 0; ii < HAST_HIO_MAX; ii++) {
153132720Skan		hio = malloc(sizeof(*hio));
154117397Skan		if (hio == NULL) {
155132720Skan			pjdlog_exitx(EX_TEMPFAIL,
156117397Skan			    "Unable to allocate memory (%zu bytes) for hio request.",
157169691Skan			    sizeof(*hio));
158132720Skan		}
159132720Skan		hio->hio_error = 0;
160117397Skan		hio->hio_data = malloc(MAXPHYS);
161117397Skan		if (hio->hio_data == NULL) {
162117397Skan			pjdlog_exitx(EX_TEMPFAIL,
163132720Skan			    "Unable to allocate memory (%zu bytes) for gctl_data.",
164132720Skan			    (size_t)MAXPHYS);
165117397Skan		}
166117397Skan		TAILQ_INSERT_HEAD(&hio_free_list, hio, hio_next);
167117397Skan	}
168117397Skan}
169117397Skan
170117397Skanstatic void
171132720Skaninit_local(struct hast_resource *res)
172117397Skan{
173117397Skan
174169691Skan	if (metadata_read(res, true) < 0)
175117397Skan		exit(EX_NOINPUT);
176117397Skan}
177117397Skan
178117397Skanstatic void
179117397Skaninit_remote(struct hast_resource *res, struct nv *nvin)
180169691Skan{
181169691Skan	uint64_t resuid;
182169691Skan	struct nv *nvout;
183169691Skan	unsigned char *map;
184169691Skan	size_t mapsize;
185169691Skan
186169691Skan	map = NULL;
187117397Skan	mapsize = 0;
188132720Skan	nvout = nv_alloc();
189117397Skan	nv_add_int64(nvout, (int64_t)res->hr_datasize, "datasize");
190117397Skan	nv_add_int32(nvout, (int32_t)res->hr_extentsize, "extentsize");
191169691Skan	resuid = nv_get_uint64(nvin, "resuid");
192117397Skan	res->hr_primary_localcnt = nv_get_uint64(nvin, "localcnt");
193117397Skan	res->hr_primary_remotecnt = nv_get_uint64(nvin, "remotecnt");
194117397Skan	nv_add_uint64(nvout, res->hr_secondary_localcnt, "localcnt");
195117397Skan	nv_add_uint64(nvout, res->hr_secondary_remotecnt, "remotecnt");
196132720Skan	mapsize = activemap_calc_ondisk_size(res->hr_local_mediasize -
197132720Skan	    METADATA_SIZE, res->hr_extentsize, res->hr_local_sectorsize);
198117397Skan	map = malloc(mapsize);
199117397Skan	if (map == NULL) {
200169691Skan		pjdlog_exitx(EX_TEMPFAIL,
201169691Skan		    "Unable to allocate memory (%zu bytes) for activemap.",
202169691Skan		    mapsize);
203169691Skan	}
204169691Skan	nv_add_uint32(nvout, (uint32_t)mapsize, "mapsize");
205169691Skan	/*
206169691Skan	 * When we work as primary and secondary is missing we will increase
207117397Skan	 * localcnt in our metadata. When secondary is connected and synced
208132720Skan	 * we make localcnt be equal to remotecnt, which means nodes are more
209117397Skan	 * or less in sync.
210117397Skan	 * Split-brain condition is when both nodes are not able to communicate
211169691Skan	 * and are both configured as primary nodes. In turn, they can both
212117397Skan	 * make incompatible changes to the data and we have to detect that.
213117397Skan	 * Under split-brain condition we will increase our localcnt on first
214132720Skan	 * write and remote node will increase its localcnt on first write.
215132720Skan	 * When we connect we can see that primary's localcnt is greater than
216132720Skan	 * our remotecnt (primary was modified while we weren't watching) and
217132720Skan	 * our localcnt is greater than primary's remotecnt (we were modified
218169691Skan	 * while primary wasn't watching).
219169691Skan	 * There are many possible combinations which are all gathered below.
220132720Skan	 * Don't pay too much attention to exact numbers, the more important
221132720Skan	 * is to compare them. We compare secondary's local with primary's
222132720Skan	 * remote and secondary's remote with primary's local.
223132720Skan	 * Note that every case where primary's localcnt is smaller than
224132720Skan	 * secondary's remotecnt and where secondary's localcnt is smaller than
225132720Skan	 * primary's remotecnt should be impossible in practise. We will perform
226132720Skan	 * full synchronization then. Those cases are marked with an asterisk.
227132720Skan	 * Regular synchronization means that only extents marked as dirty are
228132720Skan	 * synchronized (regular synchronization).
229132720Skan	 *
230132720Skan	 * SECONDARY METADATA PRIMARY METADATA
231132720Skan	 * local=3 remote=3   local=2 remote=2*  ?! Full sync from secondary.
232132720Skan	 * local=3 remote=3   local=2 remote=3*  ?! Full sync from primary.
233132720Skan	 * local=3 remote=3   local=2 remote=4*  ?! Full sync from primary.
234132720Skan	 * local=3 remote=3   local=3 remote=2   Primary is out-of-date,
235132720Skan	 *                                       regular sync from secondary.
236117397Skan	 * local=3 remote=3   local=3 remote=3   Regular sync just in case.
237132720Skan	 * local=3 remote=3   local=3 remote=4*  ?! Full sync from primary.
238117397Skan	 * local=3 remote=3   local=4 remote=2   Split-brain condition.
239169691Skan	 * local=3 remote=3   local=4 remote=3   Secondary out-of-date,
240169691Skan	 *                                       regular sync from primary.
241169691Skan	 * local=3 remote=3   local=4 remote=4*  ?! Full sync from primary.
242169691Skan	 */
243169691Skan	if (res->hr_resuid == 0) {
244169691Skan		/*
245169691Skan		 * Provider is used for the first time. If primary node done no
246169691Skan		 * writes yet as well (we will find "virgin" argument) then
247169691Skan		 * there is no need to synchronize anything. If primary node
248169691Skan		 * done any writes already we have to synchronize everything.
249169691Skan		 */
250169691Skan		PJDLOG_ASSERT(res->hr_secondary_localcnt == 0);
251169691Skan		res->hr_resuid = resuid;
252169691Skan		if (metadata_write(res) < 0)
253169691Skan			exit(EX_NOINPUT);
254169691Skan		if (nv_exists(nvin, "virgin")) {
255169691Skan			free(map);
256169691Skan			map = NULL;
257169691Skan			mapsize = 0;
258169691Skan		} else {
259169691Skan			memset(map, 0xff, mapsize);
260169691Skan		}
261169691Skan		nv_add_uint8(nvout, HAST_SYNCSRC_PRIMARY, "syncsrc");
262169691Skan	} else if (
263169691Skan	    /* Is primary is out-of-date? */
264169691Skan	    (res->hr_secondary_localcnt > res->hr_primary_remotecnt &&
265169691Skan	     res->hr_secondary_remotecnt == res->hr_primary_localcnt) ||
266169691Skan	    /* Node are more or less in sync? */
267169691Skan	    (res->hr_secondary_localcnt == res->hr_primary_remotecnt &&
268169691Skan	     res->hr_secondary_remotecnt == res->hr_primary_localcnt) ||
269117397Skan	    /* Is secondary is out-of-date? */
270169691Skan	    (res->hr_secondary_localcnt == res->hr_primary_remotecnt &&
271117397Skan	     res->hr_secondary_remotecnt < res->hr_primary_localcnt)) {
272117397Skan		/*
273117397Skan		 * Nodes are more or less in sync or one of the nodes is
274132720Skan		 * out-of-date.
275132720Skan		 * It doesn't matter at this point which one, we just have to
276117397Skan		 * send out local bitmap to the remote node.
277117397Skan		 */
278132720Skan		if (pread(res->hr_localfd, map, mapsize, METADATA_SIZE) !=
279132720Skan		    (ssize_t)mapsize) {
280132720Skan			pjdlog_exit(LOG_ERR, "Unable to read activemap");
281132720Skan		}
282132720Skan		if (res->hr_secondary_localcnt > res->hr_primary_remotecnt &&
283132720Skan		     res->hr_secondary_remotecnt == res->hr_primary_localcnt) {
284132720Skan			/* Primary is out-of-date, sync from secondary. */
285132720Skan			nv_add_uint8(nvout, HAST_SYNCSRC_SECONDARY, "syncsrc");
286132720Skan		} else {
287169691Skan			/*
288132720Skan			 * Secondary is out-of-date or counts match.
289132720Skan			 * Sync from primary.
290132720Skan			 */
291132720Skan			nv_add_uint8(nvout, HAST_SYNCSRC_PRIMARY, "syncsrc");
292132720Skan		}
293132720Skan	} else if (res->hr_secondary_localcnt > res->hr_primary_remotecnt &&
294132720Skan	     res->hr_primary_localcnt > res->hr_secondary_remotecnt) {
295132720Skan		/*
296132720Skan		 * Not good, we have split-brain condition.
297132720Skan		 */
298132720Skan		pjdlog_error("Split-brain detected, exiting.");
299169691Skan		nv_add_string(nvout, "Split-brain condition!", "errmsg");
300169691Skan		free(map);
301169691Skan		map = NULL;
302117397Skan		mapsize = 0;
303117397Skan	} else /* if (res->hr_secondary_localcnt < res->hr_primary_remotecnt ||
304132720Skan	    res->hr_primary_localcnt < res->hr_secondary_remotecnt) */ {
305117397Skan		/*
306117397Skan		 * This should never happen in practise, but we will perform
307117397Skan		 * full synchronization.
308169691Skan		 */
309117397Skan		PJDLOG_ASSERT(res->hr_secondary_localcnt < res->hr_primary_remotecnt ||
310117397Skan		    res->hr_primary_localcnt < res->hr_secondary_remotecnt);
311117397Skan		mapsize = activemap_calc_ondisk_size(res->hr_local_mediasize -
312117397Skan		    METADATA_SIZE, res->hr_extentsize,
313117397Skan		    res->hr_local_sectorsize);
314169691Skan		memset(map, 0xff, mapsize);
315169691Skan		if (res->hr_secondary_localcnt > res->hr_primary_remotecnt) {
316169691Skan			/* In this one of five cases sync from secondary. */
317169691Skan			nv_add_uint8(nvout, HAST_SYNCSRC_SECONDARY, "syncsrc");
318169691Skan		} else {
319169691Skan			/* For the rest four cases sync from primary. */
320169691Skan			nv_add_uint8(nvout, HAST_SYNCSRC_PRIMARY, "syncsrc");
321117397Skan		}
322132720Skan		pjdlog_warning("This should never happen, asking for full synchronization (primary(local=%ju, remote=%ju), secondary(local=%ju, remote=%ju)).",
323117397Skan		    (uintmax_t)res->hr_primary_localcnt,
324117397Skan		    (uintmax_t)res->hr_primary_remotecnt,
325117397Skan		    (uintmax_t)res->hr_secondary_localcnt,
326169691Skan		    (uintmax_t)res->hr_secondary_remotecnt);
327117397Skan	}
328117397Skan	if (hast_proto_send(res, res->hr_remotein, nvout, map, mapsize) < 0) {
329117397Skan		pjdlog_exit(EX_TEMPFAIL, "Unable to send activemap to %s",
330117397Skan		    res->hr_remoteaddr);
331169691Skan	}
332169691Skan	if (map != NULL)
333117397Skan		free(map);
334117397Skan	nv_free(nvout);
335132720Skan	if (res->hr_secondary_localcnt > res->hr_primary_remotecnt &&
336169691Skan	     res->hr_primary_localcnt > res->hr_secondary_remotecnt) {
337169691Skan		/* Exit on split-brain. */
338169691Skan		event_send(res, EVENT_SPLITBRAIN);
339169691Skan		exit(EX_CONFIG);
340169691Skan	}
341132720Skan}
342117397Skan
343132720Skanvoid
344117397Skanhastd_secondary(struct hast_resource *res, struct nv *nvin)
345117397Skan{
346132720Skan	sigset_t mask;
347169691Skan	pthread_t td;
348132720Skan	pid_t pid;
349117397Skan	int error, mode, debuglevel;
350132720Skan
351132720Skan	/*
352132720Skan	 * Create communication channel between parent and child.
353132720Skan	 */
354132720Skan	if (proto_client("socketpair://", &res->hr_ctrl) < 0) {
355132720Skan		KEEP_ERRNO((void)pidfile_remove(pfh));
356132720Skan		pjdlog_exit(EX_OSERR,
357132720Skan		    "Unable to create control sockets between parent and child");
358132720Skan	}
359132720Skan	/*
360132720Skan	 * Create communication channel between child and parent.
361132720Skan	 */
362132720Skan	if (proto_client("socketpair://", &res->hr_event) < 0) {
363132720Skan		KEEP_ERRNO((void)pidfile_remove(pfh));
364169691Skan		pjdlog_exit(EX_OSERR,
365132720Skan		    "Unable to create event sockets between child and parent");
366132720Skan	}
367132720Skan	/*
368132720Skan	 * Create communication channel for sending connection requests from
369132720Skan	 * parent to child.
370132720Skan	 */
371132720Skan	if (proto_client("socketpair://", &res->hr_conn) < 0) {
372132720Skan		/* TODO: There's no need for this to be fatal error. */
373132720Skan		KEEP_ERRNO((void)pidfile_remove(pfh));
374132720Skan		pjdlog_exit(EX_OSERR,
375132720Skan		    "Unable to create connection sockets between parent and child");
376169691Skan	}
377169691Skan
378169691Skan	pid = fork();
379132720Skan	if (pid < 0) {
380117397Skan		KEEP_ERRNO((void)pidfile_remove(pfh));
381117397Skan		pjdlog_exit(EX_OSERR, "Unable to fork");
382169691Skan	}
383169691Skan
384132720Skan	if (pid > 0) {
385132720Skan		/* This is parent. */
386		proto_close(res->hr_remotein);
387		res->hr_remotein = NULL;
388		proto_close(res->hr_remoteout);
389		res->hr_remoteout = NULL;
390		/* Declare that we are receiver. */
391		proto_recv(res->hr_event, NULL, 0);
392		/* Declare that we are sender. */
393		proto_send(res->hr_ctrl, NULL, 0);
394		proto_send(res->hr_conn, NULL, 0);
395		res->hr_workerpid = pid;
396		return;
397	}
398
399	gres = res;
400	mode = pjdlog_mode_get();
401	debuglevel = pjdlog_debug_get();
402
403	/* Declare that we are sender. */
404	proto_send(res->hr_event, NULL, 0);
405	/* Declare that we are receiver. */
406	proto_recv(res->hr_ctrl, NULL, 0);
407	proto_recv(res->hr_conn, NULL, 0);
408	descriptors_cleanup(res);
409
410	descriptors_assert(res, mode);
411
412	pjdlog_init(mode);
413	pjdlog_debug_set(debuglevel);
414	pjdlog_prefix_set("[%s] (%s) ", res->hr_name, role2str(res->hr_role));
415	setproctitle("%s (secondary)", res->hr_name);
416
417	PJDLOG_VERIFY(sigemptyset(&mask) == 0);
418	PJDLOG_VERIFY(sigprocmask(SIG_SETMASK, &mask, NULL) == 0);
419
420	/* Error in setting timeout is not critical, but why should it fail? */
421	if (proto_timeout(res->hr_remotein, 0) < 0)
422		pjdlog_errno(LOG_WARNING, "Unable to set connection timeout");
423	if (proto_timeout(res->hr_remoteout, res->hr_timeout) < 0)
424		pjdlog_errno(LOG_WARNING, "Unable to set connection timeout");
425
426	init_local(res);
427	init_environment();
428
429	if (drop_privs() != 0)
430		exit(EX_CONFIG);
431	pjdlog_info("Privileges successfully dropped.");
432
433	/*
434	 * Create the control thread before sending any event to the parent,
435	 * as we can deadlock when parent sends control request to worker,
436	 * but worker has no control thread started yet, so parent waits.
437	 * In the meantime worker sends an event to the parent, but parent
438	 * is unable to handle the event, because it waits for control
439	 * request response.
440	 */
441	error = pthread_create(&td, NULL, ctrl_thread, res);
442	PJDLOG_ASSERT(error == 0);
443
444	init_remote(res, nvin);
445	event_send(res, EVENT_CONNECT);
446
447	error = pthread_create(&td, NULL, recv_thread, res);
448	PJDLOG_ASSERT(error == 0);
449	error = pthread_create(&td, NULL, disk_thread, res);
450	PJDLOG_ASSERT(error == 0);
451	(void)send_thread(res);
452}
453
454static void
455reqlog(int loglevel, int debuglevel, int error, struct hio *hio, const char *fmt, ...)
456{
457	char msg[1024];
458	va_list ap;
459	int len;
460
461	va_start(ap, fmt);
462	len = vsnprintf(msg, sizeof(msg), fmt, ap);
463	va_end(ap);
464	if ((size_t)len < sizeof(msg)) {
465		switch (hio->hio_cmd) {
466		case HIO_READ:
467			(void)snprintf(msg + len, sizeof(msg) - len,
468			    "READ(%ju, %ju).", (uintmax_t)hio->hio_offset,
469			    (uintmax_t)hio->hio_length);
470			break;
471		case HIO_DELETE:
472			(void)snprintf(msg + len, sizeof(msg) - len,
473			    "DELETE(%ju, %ju).", (uintmax_t)hio->hio_offset,
474			    (uintmax_t)hio->hio_length);
475			break;
476		case HIO_FLUSH:
477			(void)snprintf(msg + len, sizeof(msg) - len, "FLUSH.");
478			break;
479		case HIO_WRITE:
480			(void)snprintf(msg + len, sizeof(msg) - len,
481			    "WRITE(%ju, %ju).", (uintmax_t)hio->hio_offset,
482			    (uintmax_t)hio->hio_length);
483			break;
484		case HIO_KEEPALIVE:
485			(void)snprintf(msg + len, sizeof(msg) - len, "KEEPALIVE.");
486			break;
487		default:
488			(void)snprintf(msg + len, sizeof(msg) - len,
489			    "UNKNOWN(%u).", (unsigned int)hio->hio_cmd);
490			break;
491		}
492	}
493	pjdlog_common(loglevel, debuglevel, error, "%s", msg);
494}
495
496static int
497requnpack(struct hast_resource *res, struct hio *hio)
498{
499
500	hio->hio_cmd = nv_get_uint8(hio->hio_nv, "cmd");
501	if (hio->hio_cmd == 0) {
502		pjdlog_error("Header contains no 'cmd' field.");
503		hio->hio_error = EINVAL;
504		goto end;
505	}
506	switch (hio->hio_cmd) {
507	case HIO_KEEPALIVE:
508		break;
509	case HIO_READ:
510	case HIO_WRITE:
511	case HIO_DELETE:
512		hio->hio_offset = nv_get_uint64(hio->hio_nv, "offset");
513		if (nv_error(hio->hio_nv) != 0) {
514			pjdlog_error("Header is missing 'offset' field.");
515			hio->hio_error = EINVAL;
516			goto end;
517		}
518		hio->hio_length = nv_get_uint64(hio->hio_nv, "length");
519		if (nv_error(hio->hio_nv) != 0) {
520			pjdlog_error("Header is missing 'length' field.");
521			hio->hio_error = EINVAL;
522			goto end;
523		}
524		if (hio->hio_length == 0) {
525			pjdlog_error("Data length is zero.");
526			hio->hio_error = EINVAL;
527			goto end;
528		}
529		if (hio->hio_length > MAXPHYS) {
530			pjdlog_error("Data length is too large (%ju > %ju).",
531			    (uintmax_t)hio->hio_length, (uintmax_t)MAXPHYS);
532			hio->hio_error = EINVAL;
533			goto end;
534		}
535		if ((hio->hio_offset % res->hr_local_sectorsize) != 0) {
536			pjdlog_error("Offset %ju is not multiple of sector size.",
537			    (uintmax_t)hio->hio_offset);
538			hio->hio_error = EINVAL;
539			goto end;
540		}
541		if ((hio->hio_length % res->hr_local_sectorsize) != 0) {
542			pjdlog_error("Length %ju is not multiple of sector size.",
543			    (uintmax_t)hio->hio_length);
544			hio->hio_error = EINVAL;
545			goto end;
546		}
547		if (hio->hio_offset + hio->hio_length >
548		    (uint64_t)res->hr_datasize) {
549			pjdlog_error("Data offset is too large (%ju > %ju).",
550			    (uintmax_t)(hio->hio_offset + hio->hio_length),
551			    (uintmax_t)res->hr_datasize);
552			hio->hio_error = EINVAL;
553			goto end;
554		}
555		break;
556	default:
557		pjdlog_error("Header contains invalid 'cmd' (%hhu).",
558		    hio->hio_cmd);
559		hio->hio_error = EINVAL;
560		goto end;
561	}
562	hio->hio_error = 0;
563end:
564	return (hio->hio_error);
565}
566
567static __dead2 void
568secondary_exit(int exitcode, const char *fmt, ...)
569{
570	va_list ap;
571
572	PJDLOG_ASSERT(exitcode != EX_OK);
573	va_start(ap, fmt);
574	pjdlogv_errno(LOG_ERR, fmt, ap);
575	va_end(ap);
576	event_send(gres, EVENT_DISCONNECT);
577	exit(exitcode);
578}
579
580/*
581 * Thread receives requests from the primary node.
582 */
583static void *
584recv_thread(void *arg)
585{
586	struct hast_resource *res = arg;
587	struct hio *hio;
588
589	for (;;) {
590		pjdlog_debug(2, "recv: Taking free request.");
591		QUEUE_TAKE(free, hio);
592		pjdlog_debug(2, "recv: (%p) Got request.", hio);
593		if (hast_proto_recv_hdr(res->hr_remotein, &hio->hio_nv) < 0) {
594			secondary_exit(EX_TEMPFAIL,
595			    "Unable to receive request header");
596		}
597		if (requnpack(res, hio) != 0) {
598			pjdlog_debug(2,
599			    "recv: (%p) Moving request to the send queue.",
600			    hio);
601			QUEUE_INSERT(send, hio);
602			continue;
603		}
604		reqlog(LOG_DEBUG, 2, -1, hio,
605		    "recv: (%p) Got request header: ", hio);
606		if (hio->hio_cmd == HIO_KEEPALIVE) {
607			pjdlog_debug(2,
608			    "recv: (%p) Moving request to the free queue.",
609			    hio);
610			nv_free(hio->hio_nv);
611			QUEUE_INSERT(free, hio);
612			continue;
613		} else if (hio->hio_cmd == HIO_WRITE) {
614			if (hast_proto_recv_data(res, res->hr_remotein,
615			    hio->hio_nv, hio->hio_data, MAXPHYS) < 0) {
616				secondary_exit(EX_TEMPFAIL,
617				    "Unable to receive request data");
618			}
619		}
620		pjdlog_debug(2, "recv: (%p) Moving request to the disk queue.",
621		    hio);
622		QUEUE_INSERT(disk, hio);
623	}
624	/* NOTREACHED */
625	return (NULL);
626}
627
628/*
629 * Thread reads from or writes to local component and also handles DELETE and
630 * FLUSH requests.
631 */
632static void *
633disk_thread(void *arg)
634{
635	struct hast_resource *res = arg;
636	struct hio *hio;
637	ssize_t ret;
638	bool clear_activemap;
639
640	clear_activemap = true;
641
642	for (;;) {
643		pjdlog_debug(2, "disk: Taking request.");
644		QUEUE_TAKE(disk, hio);
645		while (clear_activemap) {
646			unsigned char *map;
647			size_t mapsize;
648
649			/*
650			 * When first request is received, it means that primary
651			 * already received our activemap, merged it and stored
652			 * locally. We can now safely clear our activemap.
653			 */
654			mapsize =
655			    activemap_calc_ondisk_size(res->hr_local_mediasize -
656			    METADATA_SIZE, res->hr_extentsize,
657			    res->hr_local_sectorsize);
658			map = calloc(1, mapsize);
659			if (map == NULL) {
660				pjdlog_warning("Unable to allocate memory to clear local activemap.");
661				break;
662			}
663			if (pwrite(res->hr_localfd, map, mapsize,
664			    METADATA_SIZE) != (ssize_t)mapsize) {
665				pjdlog_errno(LOG_WARNING,
666				    "Unable to store cleared activemap");
667				free(map);
668				break;
669			}
670			free(map);
671			clear_activemap = false;
672			pjdlog_debug(1, "Local activemap cleared.");
673		}
674		reqlog(LOG_DEBUG, 2, -1, hio, "disk: (%p) Got request: ", hio);
675		/* Handle the actual request. */
676		switch (hio->hio_cmd) {
677		case HIO_READ:
678			ret = pread(res->hr_localfd, hio->hio_data,
679			    hio->hio_length,
680			    hio->hio_offset + res->hr_localoff);
681			if (ret < 0)
682				hio->hio_error = errno;
683			else if (ret != (int64_t)hio->hio_length)
684				hio->hio_error = EIO;
685			else
686				hio->hio_error = 0;
687			break;
688		case HIO_WRITE:
689			ret = pwrite(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_DELETE:
700			ret = g_delete(res->hr_localfd,
701			    hio->hio_offset + res->hr_localoff,
702			    hio->hio_length);
703			if (ret < 0)
704				hio->hio_error = errno;
705			else
706				hio->hio_error = 0;
707			break;
708		case HIO_FLUSH:
709			ret = g_flush(res->hr_localfd);
710			if (ret < 0)
711				hio->hio_error = errno;
712			else
713				hio->hio_error = 0;
714			break;
715		}
716		if (hio->hio_error != 0) {
717			reqlog(LOG_ERR, 0, hio->hio_error, hio,
718			    "Request failed: ");
719		}
720		pjdlog_debug(2, "disk: (%p) Moving request to the send queue.",
721		    hio);
722		QUEUE_INSERT(send, hio);
723	}
724	/* NOTREACHED */
725	return (NULL);
726}
727
728/*
729 * Thread sends requests back to primary node.
730 */
731static void *
732send_thread(void *arg)
733{
734	struct hast_resource *res = arg;
735	struct nv *nvout;
736	struct hio *hio;
737	void *data;
738	size_t length;
739
740	for (;;) {
741		pjdlog_debug(2, "send: Taking request.");
742		QUEUE_TAKE(send, hio);
743		reqlog(LOG_DEBUG, 2, -1, hio, "send: (%p) Got request: ", hio);
744		nvout = nv_alloc();
745		/* Copy sequence number. */
746		nv_add_uint64(nvout, nv_get_uint64(hio->hio_nv, "seq"), "seq");
747		switch (hio->hio_cmd) {
748		case HIO_READ:
749			if (hio->hio_error == 0) {
750				data = hio->hio_data;
751				length = hio->hio_length;
752				break;
753			}
754			/*
755			 * We send no data in case of an error.
756			 */
757			/* FALLTHROUGH */
758		case HIO_DELETE:
759		case HIO_FLUSH:
760		case HIO_WRITE:
761			data = NULL;
762			length = 0;
763			break;
764		default:
765			abort();
766			break;
767		}
768		if (hio->hio_error != 0)
769			nv_add_int16(nvout, hio->hio_error, "error");
770		if (hast_proto_send(res, res->hr_remoteout, nvout, data,
771		    length) < 0) {
772			secondary_exit(EX_TEMPFAIL, "Unable to send reply.");
773		}
774		nv_free(nvout);
775		pjdlog_debug(2, "send: (%p) Moving request to the free queue.",
776		    hio);
777		nv_free(hio->hio_nv);
778		hio->hio_error = 0;
779		QUEUE_INSERT(free, hio);
780	}
781	/* NOTREACHED */
782	return (NULL);
783}
784