secondary.c revision 210879
1/*-
2 * Copyright (c) 2009-2010 The FreeBSD Foundation
3 * All rights reserved.
4 *
5 * This software was developed by Pawel Jakub Dawidek under sponsorship from
6 * the FreeBSD Foundation.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 * 1. Redistributions of source code must retain the above copyright
12 *    notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 *    notice, this list of conditions and the following disclaimer in the
15 *    documentation and/or other materials provided with the distribution.
16 *
17 * THIS SOFTWARE IS PROVIDED BY THE AUTHORS AND CONTRIBUTORS ``AS IS'' AND
18 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE
21 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27 * SUCH DAMAGE.
28 */
29
30#include <sys/cdefs.h>
31__FBSDID("$FreeBSD: head/sbin/hastd/secondary.c 210879 2010-08-05 18:56:24Z pjd $");
32
33#include <sys/param.h>
34#include <sys/time.h>
35#include <sys/bio.h>
36#include <sys/disk.h>
37#include <sys/stat.h>
38
39#include <assert.h>
40#include <err.h>
41#include <errno.h>
42#include <fcntl.h>
43#include <libgeom.h>
44#include <pthread.h>
45#include <stdint.h>
46#include <stdio.h>
47#include <string.h>
48#include <sysexits.h>
49#include <unistd.h>
50
51#include <activemap.h>
52#include <nv.h>
53#include <pjdlog.h>
54
55#include "control.h"
56#include "hast.h"
57#include "hast_proto.h"
58#include "hastd.h"
59#include "metadata.h"
60#include "proto.h"
61#include "subr.h"
62#include "synch.h"
63
64struct hio {
65	uint64_t 	 hio_seq;
66	int	 	 hio_error;
67	struct nv	*hio_nv;
68	void		*hio_data;
69	uint8_t		 hio_cmd;
70	uint64_t	 hio_offset;
71	uint64_t	 hio_length;
72	TAILQ_ENTRY(hio) hio_next;
73};
74
75/*
76 * Free list holds unused structures. When free list is empty, we have to wait
77 * until some in-progress requests are freed.
78 */
79static TAILQ_HEAD(, hio) hio_free_list;
80static pthread_mutex_t hio_free_list_lock;
81static pthread_cond_t hio_free_list_cond;
82/*
83 * Disk thread (the one that do I/O requests) takes requests from this list.
84 */
85static TAILQ_HEAD(, hio) hio_disk_list;
86static pthread_mutex_t hio_disk_list_lock;
87static pthread_cond_t hio_disk_list_cond;
88/*
89 * There is one recv list for every component, although local components don't
90 * use recv lists as local requests are done synchronously.
91 */
92static TAILQ_HEAD(, hio) hio_send_list;
93static pthread_mutex_t hio_send_list_lock;
94static pthread_cond_t hio_send_list_cond;
95
96/*
97 * Maximum number of outstanding I/O requests.
98 */
99#define	HAST_HIO_MAX	256
100
101static void *recv_thread(void *arg);
102static void *disk_thread(void *arg);
103static void *send_thread(void *arg);
104
105static void
106init_environment(void)
107{
108	struct hio *hio;
109	unsigned int ii;
110
111	/*
112	 * Initialize lists, their locks and theirs condition variables.
113	 */
114	TAILQ_INIT(&hio_free_list);
115	mtx_init(&hio_free_list_lock);
116	cv_init(&hio_free_list_cond);
117	TAILQ_INIT(&hio_disk_list);
118	mtx_init(&hio_disk_list_lock);
119	cv_init(&hio_disk_list_cond);
120	TAILQ_INIT(&hio_send_list);
121	mtx_init(&hio_send_list_lock);
122	cv_init(&hio_send_list_cond);
123
124	/*
125	 * Allocate requests pool and initialize requests.
126	 */
127	for (ii = 0; ii < HAST_HIO_MAX; ii++) {
128		hio = malloc(sizeof(*hio));
129		if (hio == NULL) {
130			pjdlog_exitx(EX_TEMPFAIL,
131			    "Unable to allocate memory (%zu bytes) for hio request.",
132			    sizeof(*hio));
133		}
134		hio->hio_error = 0;
135		hio->hio_data = malloc(MAXPHYS);
136		if (hio->hio_data == NULL) {
137			pjdlog_exitx(EX_TEMPFAIL,
138			    "Unable to allocate memory (%zu bytes) for gctl_data.",
139			    (size_t)MAXPHYS);
140		}
141		TAILQ_INSERT_HEAD(&hio_free_list, hio, hio_next);
142	}
143}
144
145static void
146init_local(struct hast_resource *res)
147{
148
149	if (metadata_read(res, true) < 0)
150		exit(EX_NOINPUT);
151}
152
153static void
154init_remote(struct hast_resource *res, struct nv *nvin)
155{
156	uint64_t resuid;
157	struct nv *nvout;
158	unsigned char *map;
159	size_t mapsize;
160
161	map = NULL;
162	mapsize = 0;
163	nvout = nv_alloc();
164	nv_add_int64(nvout, (int64_t)res->hr_datasize, "datasize");
165	nv_add_int32(nvout, (int32_t)res->hr_extentsize, "extentsize");
166	resuid = nv_get_uint64(nvin, "resuid");
167	res->hr_primary_localcnt = nv_get_uint64(nvin, "localcnt");
168	res->hr_primary_remotecnt = nv_get_uint64(nvin, "remotecnt");
169	nv_add_uint64(nvout, res->hr_secondary_localcnt, "localcnt");
170	nv_add_uint64(nvout, res->hr_secondary_remotecnt, "remotecnt");
171	mapsize = activemap_calc_ondisk_size(res->hr_local_mediasize -
172	    METADATA_SIZE, res->hr_extentsize, res->hr_local_sectorsize);
173	map = malloc(mapsize);
174	if (map == NULL) {
175		pjdlog_exitx(EX_TEMPFAIL,
176		    "Unable to allocate memory (%zu bytes) for activemap.",
177		    mapsize);
178	}
179	nv_add_uint32(nvout, (uint32_t)mapsize, "mapsize");
180	/*
181	 * When we work as primary and secondary is missing we will increase
182	 * localcnt in our metadata. When secondary is connected and synced
183	 * we make localcnt be equal to remotecnt, which means nodes are more
184	 * or less in sync.
185	 * Split-brain condition is when both nodes are not able to communicate
186	 * and are both configured as primary nodes. In turn, they can both
187	 * make incompatible changes to the data and we have to detect that.
188	 * Under split-brain condition we will increase our localcnt on first
189	 * write and remote node will increase its localcnt on first write.
190	 * When we connect we can see that primary's localcnt is greater than
191	 * our remotecnt (primary was modified while we weren't watching) and
192	 * our localcnt is greater than primary's remotecnt (we were modified
193	 * while primary wasn't watching).
194	 * There are many possible combinations which are all gathered below.
195	 * Don't pay too much attention to exact numbers, the more important
196	 * is to compare them. We compare secondary's local with primary's
197	 * remote and secondary's remote with primary's local.
198	 * Note that every case where primary's localcnt is smaller than
199	 * secondary's remotecnt and where secondary's localcnt is smaller than
200	 * primary's remotecnt should be impossible in practise. We will perform
201	 * full synchronization then. Those cases are marked with an asterisk.
202	 * Regular synchronization means that only extents marked as dirty are
203	 * synchronized (regular synchronization).
204	 *
205	 * SECONDARY METADATA PRIMARY METADATA
206	 * local=3 remote=3   local=2 remote=2*  ?! Full sync from secondary.
207	 * local=3 remote=3   local=2 remote=3*  ?! Full sync from primary.
208	 * local=3 remote=3   local=2 remote=4*  ?! Full sync from primary.
209	 * local=3 remote=3   local=3 remote=2   Primary is out-of-date,
210	 *                                       regular sync from secondary.
211	 * local=3 remote=3   local=3 remote=3   Regular sync just in case.
212	 * local=3 remote=3   local=3 remote=4*  ?! Full sync from primary.
213	 * local=3 remote=3   local=4 remote=2   Split-brain condition.
214	 * local=3 remote=3   local=4 remote=3   Secondary out-of-date,
215	 *                                       regular sync from primary.
216	 * local=3 remote=3   local=4 remote=4*  ?! Full sync from primary.
217	 */
218	if (res->hr_resuid == 0) {
219		/*
220		 * Provider is used for the first time. Initialize everything.
221		 */
222		assert(res->hr_secondary_localcnt == 0);
223		res->hr_resuid = resuid;
224		if (metadata_write(res) < 0)
225			exit(EX_NOINPUT);
226		memset(map, 0xff, mapsize);
227		nv_add_uint8(nvout, HAST_SYNCSRC_PRIMARY, "syncsrc");
228	} else if (
229	    /* Is primary is out-of-date? */
230	    (res->hr_secondary_localcnt > res->hr_primary_remotecnt &&
231	     res->hr_secondary_remotecnt == res->hr_primary_localcnt) ||
232	    /* Node are more or less in sync? */
233	    (res->hr_secondary_localcnt == res->hr_primary_remotecnt &&
234	     res->hr_secondary_remotecnt == res->hr_primary_localcnt) ||
235	    /* Is secondary is out-of-date? */
236	    (res->hr_secondary_localcnt == res->hr_primary_remotecnt &&
237	     res->hr_secondary_remotecnt < res->hr_primary_localcnt)) {
238		/*
239		 * Nodes are more or less in sync or one of the nodes is
240		 * out-of-date.
241		 * It doesn't matter at this point which one, we just have to
242		 * send out local bitmap to the remote node.
243		 */
244		if (pread(res->hr_localfd, map, mapsize, METADATA_SIZE) !=
245		    (ssize_t)mapsize) {
246			pjdlog_exit(LOG_ERR, "Unable to read activemap");
247		}
248		if (res->hr_secondary_localcnt > res->hr_primary_remotecnt &&
249		     res->hr_secondary_remotecnt == res->hr_primary_localcnt) {
250			/* Primary is out-of-date, sync from secondary. */
251			nv_add_uint8(nvout, HAST_SYNCSRC_SECONDARY, "syncsrc");
252		} else {
253			/*
254			 * Secondary is out-of-date or counts match.
255			 * Sync from primary.
256			 */
257			nv_add_uint8(nvout, HAST_SYNCSRC_PRIMARY, "syncsrc");
258		}
259	} else if (res->hr_secondary_localcnt > res->hr_primary_remotecnt &&
260	     res->hr_primary_localcnt > res->hr_secondary_remotecnt) {
261		/*
262		 * Not good, we have split-brain condition.
263		 */
264		pjdlog_error("Split-brain detected, exiting.");
265		nv_add_string(nvout, "Split-brain condition!", "errmsg");
266		free(map);
267		map = NULL;
268		mapsize = 0;
269	} else /* if (res->hr_secondary_localcnt < res->hr_primary_remotecnt ||
270	    res->hr_primary_localcnt < res->hr_secondary_remotecnt) */ {
271		/*
272		 * This should never happen in practise, but we will perform
273		 * full synchronization.
274		 */
275		assert(res->hr_secondary_localcnt < res->hr_primary_remotecnt ||
276		    res->hr_primary_localcnt < res->hr_secondary_remotecnt);
277		mapsize = activemap_calc_ondisk_size(res->hr_local_mediasize -
278		    METADATA_SIZE, res->hr_extentsize,
279		    res->hr_local_sectorsize);
280		memset(map, 0xff, mapsize);
281		if (res->hr_secondary_localcnt > res->hr_primary_remotecnt) {
282			/* In this one of five cases sync from secondary. */
283			nv_add_uint8(nvout, HAST_SYNCSRC_SECONDARY, "syncsrc");
284		} else {
285			/* For the rest four cases sync from primary. */
286			nv_add_uint8(nvout, HAST_SYNCSRC_PRIMARY, "syncsrc");
287		}
288		pjdlog_warning("This should never happen, asking for full synchronization (primary(local=%ju, remote=%ju), secondary(local=%ju, remote=%ju)).",
289		    (uintmax_t)res->hr_primary_localcnt,
290		    (uintmax_t)res->hr_primary_remotecnt,
291		    (uintmax_t)res->hr_secondary_localcnt,
292		    (uintmax_t)res->hr_secondary_remotecnt);
293	}
294	if (hast_proto_send(res, res->hr_remotein, nvout, map, mapsize) < 0) {
295		pjdlog_errno(LOG_WARNING, "Unable to send activemap to %s",
296		    res->hr_remoteaddr);
297		nv_free(nvout);
298		exit(EX_TEMPFAIL);
299	}
300	nv_free(nvout);
301	if (res->hr_secondary_localcnt > res->hr_primary_remotecnt &&
302	     res->hr_primary_localcnt > res->hr_secondary_remotecnt) {
303		/* Exit on split-brain. */
304		exit(EX_CONFIG);
305	}
306}
307
308void
309hastd_secondary(struct hast_resource *res, struct nv *nvin)
310{
311	pthread_t td;
312	pid_t pid;
313	int error;
314
315	/*
316	 * Create communication channel between parent and child.
317	 */
318	if (proto_client("socketpair://", &res->hr_ctrl) < 0) {
319		KEEP_ERRNO((void)pidfile_remove(pfh));
320		pjdlog_exit(EX_OSERR,
321		    "Unable to create control sockets between parent and child");
322	}
323
324	pid = fork();
325	if (pid < 0) {
326		KEEP_ERRNO((void)pidfile_remove(pfh));
327		pjdlog_exit(EX_OSERR, "Unable to fork");
328	}
329
330	if (pid > 0) {
331		/* This is parent. */
332		proto_close(res->hr_remotein);
333		res->hr_remotein = NULL;
334		proto_close(res->hr_remoteout);
335		res->hr_remoteout = NULL;
336		res->hr_workerpid = pid;
337		return;
338	}
339	(void)pidfile_close(pfh);
340
341	setproctitle("%s (secondary)", res->hr_name);
342
343	/* Error in setting timeout is not critical, but why should it fail? */
344	if (proto_timeout(res->hr_remotein, 0) < 0)
345		pjdlog_errno(LOG_WARNING, "Unable to set connection timeout");
346	if (proto_timeout(res->hr_remoteout, res->hr_timeout) < 0)
347		pjdlog_errno(LOG_WARNING, "Unable to set connection timeout");
348
349	init_local(res);
350	init_remote(res, nvin);
351	init_environment();
352
353	error = pthread_create(&td, NULL, recv_thread, res);
354	assert(error == 0);
355	error = pthread_create(&td, NULL, disk_thread, res);
356	assert(error == 0);
357	error = pthread_create(&td, NULL, send_thread, res);
358	assert(error == 0);
359	(void)ctrl_thread(res);
360}
361
362static void
363reqlog(int loglevel, int debuglevel, int error, struct hio *hio, const char *fmt, ...)
364{
365	char msg[1024];
366	va_list ap;
367	int len;
368
369	va_start(ap, fmt);
370	len = vsnprintf(msg, sizeof(msg), fmt, ap);
371	va_end(ap);
372	if ((size_t)len < sizeof(msg)) {
373		switch (hio->hio_cmd) {
374		case HIO_READ:
375			(void)snprintf(msg + len, sizeof(msg) - len,
376			    "READ(%ju, %ju).", (uintmax_t)hio->hio_offset,
377			    (uintmax_t)hio->hio_length);
378			break;
379		case HIO_DELETE:
380			(void)snprintf(msg + len, sizeof(msg) - len,
381			    "DELETE(%ju, %ju).", (uintmax_t)hio->hio_offset,
382			    (uintmax_t)hio->hio_length);
383			break;
384		case HIO_FLUSH:
385			(void)snprintf(msg + len, sizeof(msg) - len, "FLUSH.");
386			break;
387		case HIO_WRITE:
388			(void)snprintf(msg + len, sizeof(msg) - len,
389			    "WRITE(%ju, %ju).", (uintmax_t)hio->hio_offset,
390			    (uintmax_t)hio->hio_length);
391			break;
392		default:
393			(void)snprintf(msg + len, sizeof(msg) - len,
394			    "UNKNOWN(%u).", (unsigned int)hio->hio_cmd);
395			break;
396		}
397	}
398	pjdlog_common(loglevel, debuglevel, error, "%s", msg);
399}
400
401static int
402requnpack(struct hast_resource *res, struct hio *hio)
403{
404
405	hio->hio_cmd = nv_get_uint8(hio->hio_nv, "cmd");
406	if (hio->hio_cmd == 0) {
407		pjdlog_error("Header contains no 'cmd' field.");
408		hio->hio_error = EINVAL;
409		goto end;
410	}
411	switch (hio->hio_cmd) {
412	case HIO_READ:
413	case HIO_WRITE:
414	case HIO_DELETE:
415		hio->hio_offset = nv_get_uint64(hio->hio_nv, "offset");
416		if (nv_error(hio->hio_nv) != 0) {
417			pjdlog_error("Header is missing 'offset' field.");
418			hio->hio_error = EINVAL;
419			goto end;
420		}
421		hio->hio_length = nv_get_uint64(hio->hio_nv, "length");
422		if (nv_error(hio->hio_nv) != 0) {
423			pjdlog_error("Header is missing 'length' field.");
424			hio->hio_error = EINVAL;
425			goto end;
426		}
427		if (hio->hio_length == 0) {
428			pjdlog_error("Data length is zero.");
429			hio->hio_error = EINVAL;
430			goto end;
431		}
432		if (hio->hio_length > MAXPHYS) {
433			pjdlog_error("Data length is too large (%ju > %ju).",
434			    (uintmax_t)hio->hio_length, (uintmax_t)MAXPHYS);
435			hio->hio_error = EINVAL;
436			goto end;
437		}
438		if ((hio->hio_offset % res->hr_local_sectorsize) != 0) {
439			pjdlog_error("Offset %ju is not multiple of sector size.",
440			    (uintmax_t)hio->hio_offset);
441			hio->hio_error = EINVAL;
442			goto end;
443		}
444		if ((hio->hio_length % res->hr_local_sectorsize) != 0) {
445			pjdlog_error("Length %ju is not multiple of sector size.",
446			    (uintmax_t)hio->hio_length);
447			hio->hio_error = EINVAL;
448			goto end;
449		}
450		if (hio->hio_offset + hio->hio_length >
451		    (uint64_t)res->hr_datasize) {
452			pjdlog_error("Data offset is too large (%ju > %ju).",
453			    (uintmax_t)(hio->hio_offset + hio->hio_length),
454			    (uintmax_t)res->hr_datasize);
455			hio->hio_error = EINVAL;
456			goto end;
457		}
458		break;
459	default:
460		pjdlog_error("Header contains invalid 'cmd' (%hhu).",
461		    hio->hio_cmd);
462		hio->hio_error = EINVAL;
463		goto end;
464	}
465	hio->hio_error = 0;
466end:
467	return (hio->hio_error);
468}
469
470/*
471 * Thread receives requests from the primary node.
472 */
473static void *
474recv_thread(void *arg)
475{
476	struct hast_resource *res = arg;
477	struct hio *hio;
478	bool wakeup;
479
480	for (;;) {
481		pjdlog_debug(2, "recv: Taking free request.");
482		mtx_lock(&hio_free_list_lock);
483		while ((hio = TAILQ_FIRST(&hio_free_list)) == NULL) {
484			pjdlog_debug(2, "recv: No free requests, waiting.");
485			cv_wait(&hio_free_list_cond, &hio_free_list_lock);
486		}
487		TAILQ_REMOVE(&hio_free_list, hio, hio_next);
488		mtx_unlock(&hio_free_list_lock);
489		pjdlog_debug(2, "recv: (%p) Got request.", hio);
490		if (hast_proto_recv_hdr(res->hr_remotein, &hio->hio_nv) < 0) {
491			pjdlog_exit(EX_TEMPFAIL,
492			    "Unable to receive request header");
493		}
494		if (requnpack(res, hio) != 0)
495			goto send_queue;
496		reqlog(LOG_DEBUG, 2, -1, hio,
497		    "recv: (%p) Got request header: ", hio);
498		if (hio->hio_cmd == HIO_WRITE) {
499			if (hast_proto_recv_data(res, res->hr_remotein,
500			    hio->hio_nv, hio->hio_data, MAXPHYS) < 0) {
501				pjdlog_exit(EX_TEMPFAIL,
502				    "Unable to receive reply data");
503			}
504		}
505		pjdlog_debug(2, "recv: (%p) Moving request to the disk queue.",
506		    hio);
507		mtx_lock(&hio_disk_list_lock);
508		wakeup = TAILQ_EMPTY(&hio_disk_list);
509		TAILQ_INSERT_TAIL(&hio_disk_list, hio, hio_next);
510		mtx_unlock(&hio_disk_list_lock);
511		if (wakeup)
512			cv_signal(&hio_disk_list_cond);
513		continue;
514send_queue:
515		pjdlog_debug(2, "recv: (%p) Moving request to the send queue.",
516		    hio);
517		mtx_lock(&hio_send_list_lock);
518		wakeup = TAILQ_EMPTY(&hio_send_list);
519		TAILQ_INSERT_TAIL(&hio_send_list, hio, hio_next);
520		mtx_unlock(&hio_send_list_lock);
521		if (wakeup)
522			cv_signal(&hio_send_list_cond);
523	}
524	/* NOTREACHED */
525	return (NULL);
526}
527
528/*
529 * Thread reads from or writes to local component and also handles DELETE and
530 * FLUSH requests.
531 */
532static void *
533disk_thread(void *arg)
534{
535	struct hast_resource *res = arg;
536	struct hio *hio;
537	ssize_t ret;
538	bool clear_activemap, wakeup;
539
540	clear_activemap = true;
541
542	for (;;) {
543		pjdlog_debug(2, "disk: Taking request.");
544		mtx_lock(&hio_disk_list_lock);
545		while ((hio = TAILQ_FIRST(&hio_disk_list)) == NULL) {
546			pjdlog_debug(2, "disk: No requests, waiting.");
547			cv_wait(&hio_disk_list_cond, &hio_disk_list_lock);
548		}
549		TAILQ_REMOVE(&hio_disk_list, hio, hio_next);
550		mtx_unlock(&hio_disk_list_lock);
551		while (clear_activemap) {
552			unsigned char *map;
553			size_t mapsize;
554
555			/*
556			 * When first request is received, it means that primary
557			 * already received our activemap, merged it and stored
558			 * locally. We can now safely clear our activemap.
559			 */
560			mapsize =
561			    activemap_calc_ondisk_size(res->hr_local_mediasize -
562			    METADATA_SIZE, res->hr_extentsize,
563			    res->hr_local_sectorsize);
564			map = calloc(1, mapsize);
565			if (map == NULL) {
566				pjdlog_warning("Unable to allocate memory to clear local activemap.");
567				break;
568			}
569			if (pwrite(res->hr_localfd, map, mapsize,
570			    METADATA_SIZE) != (ssize_t)mapsize) {
571				pjdlog_errno(LOG_WARNING,
572				    "Unable to store cleared activemap");
573				free(map);
574				break;
575			}
576			free(map);
577			clear_activemap = false;
578			pjdlog_debug(1, "Local activemap cleared.");
579		}
580		reqlog(LOG_DEBUG, 2, -1, hio, "disk: (%p) Got request: ", hio);
581		/* Handle the actual request. */
582		switch (hio->hio_cmd) {
583		case HIO_READ:
584			ret = pread(res->hr_localfd, hio->hio_data,
585			    hio->hio_length,
586			    hio->hio_offset + res->hr_localoff);
587			if (ret < 0)
588				hio->hio_error = errno;
589			else if (ret != (int64_t)hio->hio_length)
590				hio->hio_error = EIO;
591			else
592				hio->hio_error = 0;
593			break;
594		case HIO_WRITE:
595			ret = pwrite(res->hr_localfd, hio->hio_data,
596			    hio->hio_length,
597			    hio->hio_offset + res->hr_localoff);
598			if (ret < 0)
599				hio->hio_error = errno;
600			else if (ret != (int64_t)hio->hio_length)
601				hio->hio_error = EIO;
602			else
603				hio->hio_error = 0;
604			break;
605		case HIO_DELETE:
606			ret = g_delete(res->hr_localfd,
607			    hio->hio_offset + res->hr_localoff,
608			    hio->hio_length);
609			if (ret < 0)
610				hio->hio_error = errno;
611			else
612				hio->hio_error = 0;
613			break;
614		case HIO_FLUSH:
615			ret = g_flush(res->hr_localfd);
616			if (ret < 0)
617				hio->hio_error = errno;
618			else
619				hio->hio_error = 0;
620			break;
621		}
622		if (hio->hio_error != 0) {
623			reqlog(LOG_ERR, 0, hio->hio_error, hio,
624			    "Request failed: ");
625		}
626		pjdlog_debug(2, "disk: (%p) Moving request to the send queue.",
627		    hio);
628		mtx_lock(&hio_send_list_lock);
629		wakeup = TAILQ_EMPTY(&hio_send_list);
630		TAILQ_INSERT_TAIL(&hio_send_list, hio, hio_next);
631		mtx_unlock(&hio_send_list_lock);
632		if (wakeup)
633			cv_signal(&hio_send_list_cond);
634	}
635	/* NOTREACHED */
636	return (NULL);
637}
638
639/*
640 * Thread sends requests back to primary node.
641 */
642static void *
643send_thread(void *arg)
644{
645	struct hast_resource *res = arg;
646	struct nv *nvout;
647	struct hio *hio;
648	void *data;
649	size_t length;
650	bool wakeup;
651
652	for (;;) {
653		pjdlog_debug(2, "send: Taking request.");
654		mtx_lock(&hio_send_list_lock);
655		while ((hio = TAILQ_FIRST(&hio_send_list)) == NULL) {
656			pjdlog_debug(2, "send: No requests, waiting.");
657			cv_wait(&hio_send_list_cond, &hio_send_list_lock);
658		}
659		TAILQ_REMOVE(&hio_send_list, hio, hio_next);
660		mtx_unlock(&hio_send_list_lock);
661		reqlog(LOG_DEBUG, 2, -1, hio, "send: (%p) Got request: ", hio);
662		nvout = nv_alloc();
663		/* Copy sequence number. */
664		nv_add_uint64(nvout, nv_get_uint64(hio->hio_nv, "seq"), "seq");
665		switch (hio->hio_cmd) {
666		case HIO_READ:
667			if (hio->hio_error == 0) {
668				data = hio->hio_data;
669				length = hio->hio_length;
670				break;
671			}
672			/*
673			 * We send no data in case of an error.
674			 */
675			/* FALLTHROUGH */
676		case HIO_DELETE:
677		case HIO_FLUSH:
678		case HIO_WRITE:
679			data = NULL;
680			length = 0;
681			break;
682		default:
683			abort();
684			break;
685		}
686		if (hio->hio_error != 0)
687			nv_add_int16(nvout, hio->hio_error, "error");
688		if (hast_proto_send(res, res->hr_remoteout, nvout, data,
689		    length) < 0) {
690			pjdlog_exit(EX_TEMPFAIL, "Unable to send reply.");
691		}
692		nv_free(nvout);
693		pjdlog_debug(2, "send: (%p) Moving request to the free queue.",
694		    hio);
695		nv_free(hio->hio_nv);
696		hio->hio_error = 0;
697		mtx_lock(&hio_free_list_lock);
698		wakeup = TAILQ_EMPTY(&hio_free_list);
699		TAILQ_INSERT_TAIL(&hio_free_list, hio, hio_next);
700		mtx_unlock(&hio_free_list_lock);
701		if (wakeup)
702			cv_signal(&hio_free_list_cond);
703	}
704	/* NOTREACHED */
705	return (NULL);
706}
707