Deleted Added
full compact
primary.c (213580) primary.c (214274)
1/*-
2 * Copyright (c) 2009 The FreeBSD Foundation
3 * Copyright (c) 2010 Pawel Jakub Dawidek <pjd@FreeBSD.org>
4 * All rights reserved.
5 *
6 * This software was developed by Pawel Jakub Dawidek under sponsorship from
7 * the FreeBSD Foundation.
8 *
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
11 * are met:
12 * 1. Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 * notice, this list of conditions and the following disclaimer in the
16 * documentation and/or other materials provided with the distribution.
17 *
18 * THIS SOFTWARE IS PROVIDED BY THE AUTHORS AND CONTRIBUTORS ``AS IS'' AND
19 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE
22 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
27 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28 * SUCH DAMAGE.
29 */
30
31#include <sys/cdefs.h>
1/*-
2 * Copyright (c) 2009 The FreeBSD Foundation
3 * Copyright (c) 2010 Pawel Jakub Dawidek <pjd@FreeBSD.org>
4 * All rights reserved.
5 *
6 * This software was developed by Pawel Jakub Dawidek under sponsorship from
7 * the FreeBSD Foundation.
8 *
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
11 * are met:
12 * 1. Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 * notice, this list of conditions and the following disclaimer in the
16 * documentation and/or other materials provided with the distribution.
17 *
18 * THIS SOFTWARE IS PROVIDED BY THE AUTHORS AND CONTRIBUTORS ``AS IS'' AND
19 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE
22 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
27 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28 * SUCH DAMAGE.
29 */
30
31#include <sys/cdefs.h>
32__FBSDID("$FreeBSD: head/sbin/hastd/primary.c 213580 2010-10-08 15:05:39Z pjd $");
32__FBSDID("$FreeBSD: head/sbin/hastd/primary.c 214274 2010-10-24 15:41:23Z pjd $");
33
34#include <sys/types.h>
35#include <sys/time.h>
36#include <sys/bio.h>
37#include <sys/disk.h>
38#include <sys/refcount.h>
39#include <sys/stat.h>
40
41#include <geom/gate/g_gate.h>
42
43#include <assert.h>
44#include <err.h>
45#include <errno.h>
46#include <fcntl.h>
47#include <libgeom.h>
48#include <pthread.h>
49#include <signal.h>
50#include <stdint.h>
51#include <stdio.h>
52#include <string.h>
53#include <sysexits.h>
54#include <unistd.h>
55
56#include <activemap.h>
57#include <nv.h>
58#include <rangelock.h>
59
60#include "control.h"
61#include "event.h"
62#include "hast.h"
63#include "hast_proto.h"
64#include "hastd.h"
65#include "hooks.h"
66#include "metadata.h"
67#include "proto.h"
68#include "pjdlog.h"
69#include "subr.h"
70#include "synch.h"
71
72/* The is only one remote component for now. */
73#define ISREMOTE(no) ((no) == 1)
74
75struct hio {
76 /*
77 * Number of components we are still waiting for.
78 * When this field goes to 0, we can send the request back to the
79 * kernel. Each component has to decrease this counter by one
80 * even on failure.
81 */
82 unsigned int hio_countdown;
83 /*
84 * Each component has a place to store its own error.
85 * Once the request is handled by all components we can decide if the
86 * request overall is successful or not.
87 */
88 int *hio_errors;
89 /*
90 * Structure used to comunicate with GEOM Gate class.
91 */
92 struct g_gate_ctl_io hio_ggio;
93 TAILQ_ENTRY(hio) *hio_next;
94};
95#define hio_free_next hio_next[0]
96#define hio_done_next hio_next[0]
97
98/*
99 * Free list holds unused structures. When free list is empty, we have to wait
100 * until some in-progress requests are freed.
101 */
102static TAILQ_HEAD(, hio) hio_free_list;
103static pthread_mutex_t hio_free_list_lock;
104static pthread_cond_t hio_free_list_cond;
105/*
106 * There is one send list for every component. One requests is placed on all
107 * send lists - each component gets the same request, but each component is
108 * responsible for managing his own send list.
109 */
110static TAILQ_HEAD(, hio) *hio_send_list;
111static pthread_mutex_t *hio_send_list_lock;
112static pthread_cond_t *hio_send_list_cond;
113/*
114 * There is one recv list for every component, although local components don't
115 * use recv lists as local requests are done synchronously.
116 */
117static TAILQ_HEAD(, hio) *hio_recv_list;
118static pthread_mutex_t *hio_recv_list_lock;
119static pthread_cond_t *hio_recv_list_cond;
120/*
121 * Request is placed on done list by the slowest component (the one that
122 * decreased hio_countdown from 1 to 0).
123 */
124static TAILQ_HEAD(, hio) hio_done_list;
125static pthread_mutex_t hio_done_list_lock;
126static pthread_cond_t hio_done_list_cond;
127/*
128 * Structure below are for interaction with sync thread.
129 */
130static bool sync_inprogress;
131static pthread_mutex_t sync_lock;
132static pthread_cond_t sync_cond;
133/*
134 * The lock below allows to synchornize access to remote connections.
135 */
136static pthread_rwlock_t *hio_remote_lock;
137
138/*
139 * Lock to synchronize metadata updates. Also synchronize access to
140 * hr_primary_localcnt and hr_primary_remotecnt fields.
141 */
142static pthread_mutex_t metadata_lock;
143
144/*
145 * Maximum number of outstanding I/O requests.
146 */
147#define HAST_HIO_MAX 256
148/*
149 * Number of components. At this point there are only two components: local
150 * and remote, but in the future it might be possible to use multiple local
151 * and remote components.
152 */
153#define HAST_NCOMPONENTS 2
154/*
155 * Number of seconds to sleep between reconnect retries or keepalive packets.
156 */
157#define RETRY_SLEEP 10
158
159#define ISCONNECTED(res, no) \
160 ((res)->hr_remotein != NULL && (res)->hr_remoteout != NULL)
161
162#define QUEUE_INSERT1(hio, name, ncomp) do { \
163 bool _wakeup; \
164 \
165 mtx_lock(&hio_##name##_list_lock[(ncomp)]); \
166 _wakeup = TAILQ_EMPTY(&hio_##name##_list[(ncomp)]); \
167 TAILQ_INSERT_TAIL(&hio_##name##_list[(ncomp)], (hio), \
168 hio_next[(ncomp)]); \
169 mtx_unlock(&hio_##name##_list_lock[ncomp]); \
170 if (_wakeup) \
171 cv_signal(&hio_##name##_list_cond[(ncomp)]); \
172} while (0)
173#define QUEUE_INSERT2(hio, name) do { \
174 bool _wakeup; \
175 \
176 mtx_lock(&hio_##name##_list_lock); \
177 _wakeup = TAILQ_EMPTY(&hio_##name##_list); \
178 TAILQ_INSERT_TAIL(&hio_##name##_list, (hio), hio_##name##_next);\
179 mtx_unlock(&hio_##name##_list_lock); \
180 if (_wakeup) \
181 cv_signal(&hio_##name##_list_cond); \
182} while (0)
183#define QUEUE_TAKE1(hio, name, ncomp) do { \
184 mtx_lock(&hio_##name##_list_lock[(ncomp)]); \
185 while (((hio) = TAILQ_FIRST(&hio_##name##_list[(ncomp)])) == NULL) { \
186 cv_wait(&hio_##name##_list_cond[(ncomp)], \
187 &hio_##name##_list_lock[(ncomp)]); \
188 } \
189 TAILQ_REMOVE(&hio_##name##_list[(ncomp)], (hio), \
190 hio_next[(ncomp)]); \
191 mtx_unlock(&hio_##name##_list_lock[(ncomp)]); \
192} while (0)
193#define QUEUE_TAKE2(hio, name) do { \
194 mtx_lock(&hio_##name##_list_lock); \
195 while (((hio) = TAILQ_FIRST(&hio_##name##_list)) == NULL) { \
196 cv_wait(&hio_##name##_list_cond, \
197 &hio_##name##_list_lock); \
198 } \
199 TAILQ_REMOVE(&hio_##name##_list, (hio), hio_##name##_next); \
200 mtx_unlock(&hio_##name##_list_lock); \
201} while (0)
202
203#define SYNCREQ(hio) do { \
204 (hio)->hio_ggio.gctl_unit = -1; \
205 (hio)->hio_ggio.gctl_seq = 1; \
206} while (0)
207#define ISSYNCREQ(hio) ((hio)->hio_ggio.gctl_unit == -1)
208#define SYNCREQDONE(hio) do { (hio)->hio_ggio.gctl_unit = -2; } while (0)
209#define ISSYNCREQDONE(hio) ((hio)->hio_ggio.gctl_unit == -2)
210
211static struct hast_resource *gres;
212
213static pthread_mutex_t range_lock;
214static struct rangelocks *range_regular;
215static bool range_regular_wait;
216static pthread_cond_t range_regular_cond;
217static struct rangelocks *range_sync;
218static bool range_sync_wait;
219static pthread_cond_t range_sync_cond;
220
221static void *ggate_recv_thread(void *arg);
222static void *local_send_thread(void *arg);
223static void *remote_send_thread(void *arg);
224static void *remote_recv_thread(void *arg);
225static void *ggate_send_thread(void *arg);
226static void *sync_thread(void *arg);
227static void *guard_thread(void *arg);
228
229static void
230cleanup(struct hast_resource *res)
231{
232 int rerrno;
233
234 /* Remember errno. */
235 rerrno = errno;
236
237 /* Destroy ggate provider if we created one. */
238 if (res->hr_ggateunit >= 0) {
239 struct g_gate_ctl_destroy ggiod;
240
241 bzero(&ggiod, sizeof(ggiod));
242 ggiod.gctl_version = G_GATE_VERSION;
243 ggiod.gctl_unit = res->hr_ggateunit;
244 ggiod.gctl_force = 1;
245 if (ioctl(res->hr_ggatefd, G_GATE_CMD_DESTROY, &ggiod) < 0) {
246 pjdlog_errno(LOG_WARNING,
247 "Unable to destroy hast/%s device",
248 res->hr_provname);
249 }
250 res->hr_ggateunit = -1;
251 }
252
253 /* Restore errno. */
254 errno = rerrno;
255}
256
257static __dead2 void
258primary_exit(int exitcode, const char *fmt, ...)
259{
260 va_list ap;
261
262 assert(exitcode != EX_OK);
263 va_start(ap, fmt);
264 pjdlogv_errno(LOG_ERR, fmt, ap);
265 va_end(ap);
266 cleanup(gres);
267 exit(exitcode);
268}
269
270static __dead2 void
271primary_exitx(int exitcode, const char *fmt, ...)
272{
273 va_list ap;
274
275 va_start(ap, fmt);
276 pjdlogv(exitcode == EX_OK ? LOG_INFO : LOG_ERR, fmt, ap);
277 va_end(ap);
278 cleanup(gres);
279 exit(exitcode);
280}
281
282static int
283hast_activemap_flush(struct hast_resource *res)
284{
285 const unsigned char *buf;
286 size_t size;
287
288 buf = activemap_bitmap(res->hr_amp, &size);
289 assert(buf != NULL);
290 assert((size % res->hr_local_sectorsize) == 0);
291 if (pwrite(res->hr_localfd, buf, size, METADATA_SIZE) !=
292 (ssize_t)size) {
293 KEEP_ERRNO(pjdlog_errno(LOG_ERR,
294 "Unable to flush activemap to disk"));
295 return (-1);
296 }
297 return (0);
298}
299
300static bool
301real_remote(const struct hast_resource *res)
302{
303
304 return (strcmp(res->hr_remoteaddr, "none") != 0);
305}
306
307static void
308init_environment(struct hast_resource *res __unused)
309{
310 struct hio *hio;
311 unsigned int ii, ncomps;
312
313 /*
314 * In the future it might be per-resource value.
315 */
316 ncomps = HAST_NCOMPONENTS;
317
318 /*
319 * Allocate memory needed by lists.
320 */
321 hio_send_list = malloc(sizeof(hio_send_list[0]) * ncomps);
322 if (hio_send_list == NULL) {
323 primary_exitx(EX_TEMPFAIL,
324 "Unable to allocate %zu bytes of memory for send lists.",
325 sizeof(hio_send_list[0]) * ncomps);
326 }
327 hio_send_list_lock = malloc(sizeof(hio_send_list_lock[0]) * ncomps);
328 if (hio_send_list_lock == NULL) {
329 primary_exitx(EX_TEMPFAIL,
330 "Unable to allocate %zu bytes of memory for send list locks.",
331 sizeof(hio_send_list_lock[0]) * ncomps);
332 }
333 hio_send_list_cond = malloc(sizeof(hio_send_list_cond[0]) * ncomps);
334 if (hio_send_list_cond == NULL) {
335 primary_exitx(EX_TEMPFAIL,
336 "Unable to allocate %zu bytes of memory for send list condition variables.",
337 sizeof(hio_send_list_cond[0]) * ncomps);
338 }
339 hio_recv_list = malloc(sizeof(hio_recv_list[0]) * ncomps);
340 if (hio_recv_list == NULL) {
341 primary_exitx(EX_TEMPFAIL,
342 "Unable to allocate %zu bytes of memory for recv lists.",
343 sizeof(hio_recv_list[0]) * ncomps);
344 }
345 hio_recv_list_lock = malloc(sizeof(hio_recv_list_lock[0]) * ncomps);
346 if (hio_recv_list_lock == NULL) {
347 primary_exitx(EX_TEMPFAIL,
348 "Unable to allocate %zu bytes of memory for recv list locks.",
349 sizeof(hio_recv_list_lock[0]) * ncomps);
350 }
351 hio_recv_list_cond = malloc(sizeof(hio_recv_list_cond[0]) * ncomps);
352 if (hio_recv_list_cond == NULL) {
353 primary_exitx(EX_TEMPFAIL,
354 "Unable to allocate %zu bytes of memory for recv list condition variables.",
355 sizeof(hio_recv_list_cond[0]) * ncomps);
356 }
357 hio_remote_lock = malloc(sizeof(hio_remote_lock[0]) * ncomps);
358 if (hio_remote_lock == NULL) {
359 primary_exitx(EX_TEMPFAIL,
360 "Unable to allocate %zu bytes of memory for remote connections locks.",
361 sizeof(hio_remote_lock[0]) * ncomps);
362 }
363
364 /*
365 * Initialize lists, their locks and theirs condition variables.
366 */
367 TAILQ_INIT(&hio_free_list);
368 mtx_init(&hio_free_list_lock);
369 cv_init(&hio_free_list_cond);
370 for (ii = 0; ii < HAST_NCOMPONENTS; ii++) {
371 TAILQ_INIT(&hio_send_list[ii]);
372 mtx_init(&hio_send_list_lock[ii]);
373 cv_init(&hio_send_list_cond[ii]);
374 TAILQ_INIT(&hio_recv_list[ii]);
375 mtx_init(&hio_recv_list_lock[ii]);
376 cv_init(&hio_recv_list_cond[ii]);
377 rw_init(&hio_remote_lock[ii]);
378 }
379 TAILQ_INIT(&hio_done_list);
380 mtx_init(&hio_done_list_lock);
381 cv_init(&hio_done_list_cond);
382 mtx_init(&metadata_lock);
383
384 /*
385 * Allocate requests pool and initialize requests.
386 */
387 for (ii = 0; ii < HAST_HIO_MAX; ii++) {
388 hio = malloc(sizeof(*hio));
389 if (hio == NULL) {
390 primary_exitx(EX_TEMPFAIL,
391 "Unable to allocate %zu bytes of memory for hio request.",
392 sizeof(*hio));
393 }
394 hio->hio_countdown = 0;
395 hio->hio_errors = malloc(sizeof(hio->hio_errors[0]) * ncomps);
396 if (hio->hio_errors == NULL) {
397 primary_exitx(EX_TEMPFAIL,
398 "Unable allocate %zu bytes of memory for hio errors.",
399 sizeof(hio->hio_errors[0]) * ncomps);
400 }
401 hio->hio_next = malloc(sizeof(hio->hio_next[0]) * ncomps);
402 if (hio->hio_next == NULL) {
403 primary_exitx(EX_TEMPFAIL,
404 "Unable allocate %zu bytes of memory for hio_next field.",
405 sizeof(hio->hio_next[0]) * ncomps);
406 }
407 hio->hio_ggio.gctl_version = G_GATE_VERSION;
408 hio->hio_ggio.gctl_data = malloc(MAXPHYS);
409 if (hio->hio_ggio.gctl_data == NULL) {
410 primary_exitx(EX_TEMPFAIL,
411 "Unable to allocate %zu bytes of memory for gctl_data.",
412 MAXPHYS);
413 }
414 hio->hio_ggio.gctl_length = MAXPHYS;
415 hio->hio_ggio.gctl_error = 0;
416 TAILQ_INSERT_HEAD(&hio_free_list, hio, hio_free_next);
417 }
418}
419
420static void
421init_local(struct hast_resource *res)
422{
423 unsigned char *buf;
424 size_t mapsize;
425
426 if (metadata_read(res, true) < 0)
427 exit(EX_NOINPUT);
428 mtx_init(&res->hr_amp_lock);
429 if (activemap_init(&res->hr_amp, res->hr_datasize, res->hr_extentsize,
430 res->hr_local_sectorsize, res->hr_keepdirty) < 0) {
431 primary_exit(EX_TEMPFAIL, "Unable to create activemap");
432 }
433 mtx_init(&range_lock);
434 cv_init(&range_regular_cond);
435 if (rangelock_init(&range_regular) < 0)
436 primary_exit(EX_TEMPFAIL, "Unable to create regular range lock");
437 cv_init(&range_sync_cond);
438 if (rangelock_init(&range_sync) < 0)
439 primary_exit(EX_TEMPFAIL, "Unable to create sync range lock");
440 mapsize = activemap_ondisk_size(res->hr_amp);
441 buf = calloc(1, mapsize);
442 if (buf == NULL) {
443 primary_exitx(EX_TEMPFAIL,
444 "Unable to allocate buffer for activemap.");
445 }
446 if (pread(res->hr_localfd, buf, mapsize, METADATA_SIZE) !=
447 (ssize_t)mapsize) {
448 primary_exit(EX_NOINPUT, "Unable to read activemap");
449 }
450 activemap_copyin(res->hr_amp, buf, mapsize);
451 free(buf);
452 if (res->hr_resuid != 0)
453 return;
454 /*
455 * We're using provider for the first time, so we have to generate
456 * resource unique identifier and initialize local and remote counts.
457 */
458 arc4random_buf(&res->hr_resuid, sizeof(res->hr_resuid));
459 res->hr_primary_localcnt = 1;
460 res->hr_primary_remotecnt = 0;
461 if (metadata_write(res) < 0)
462 exit(EX_NOINPUT);
463}
464
465static bool
466init_remote(struct hast_resource *res, struct proto_conn **inp,
467 struct proto_conn **outp)
468{
469 struct proto_conn *in, *out;
470 struct nv *nvout, *nvin;
471 const unsigned char *token;
472 unsigned char *map;
473 const char *errmsg;
474 int32_t extentsize;
475 int64_t datasize;
476 uint32_t mapsize;
477 size_t size;
478
479 assert((inp == NULL && outp == NULL) || (inp != NULL && outp != NULL));
480 assert(real_remote(res));
481
482 in = out = NULL;
483 errmsg = NULL;
484
485 /* Prepare outgoing connection with remote node. */
486 if (proto_client(res->hr_remoteaddr, &out) < 0) {
487 primary_exit(EX_TEMPFAIL, "Unable to create connection to %s",
488 res->hr_remoteaddr);
489 }
490 /* Try to connect, but accept failure. */
491 if (proto_connect(out) < 0) {
492 pjdlog_errno(LOG_WARNING, "Unable to connect to %s",
493 res->hr_remoteaddr);
494 goto close;
495 }
496 /* Error in setting timeout is not critical, but why should it fail? */
497 if (proto_timeout(out, res->hr_timeout) < 0)
498 pjdlog_errno(LOG_WARNING, "Unable to set connection timeout");
499 /*
500 * First handshake step.
501 * Setup outgoing connection with remote node.
502 */
503 nvout = nv_alloc();
504 nv_add_string(nvout, res->hr_name, "resource");
505 if (nv_error(nvout) != 0) {
506 pjdlog_common(LOG_WARNING, 0, nv_error(nvout),
507 "Unable to allocate header for connection with %s",
508 res->hr_remoteaddr);
509 nv_free(nvout);
510 goto close;
511 }
512 if (hast_proto_send(res, out, nvout, NULL, 0) < 0) {
513 pjdlog_errno(LOG_WARNING,
514 "Unable to send handshake header to %s",
515 res->hr_remoteaddr);
516 nv_free(nvout);
517 goto close;
518 }
519 nv_free(nvout);
520 if (hast_proto_recv_hdr(out, &nvin) < 0) {
521 pjdlog_errno(LOG_WARNING,
522 "Unable to receive handshake header from %s",
523 res->hr_remoteaddr);
524 goto close;
525 }
526 errmsg = nv_get_string(nvin, "errmsg");
527 if (errmsg != NULL) {
528 pjdlog_warning("%s", errmsg);
529 nv_free(nvin);
530 goto close;
531 }
532 token = nv_get_uint8_array(nvin, &size, "token");
533 if (token == NULL) {
534 pjdlog_warning("Handshake header from %s has no 'token' field.",
535 res->hr_remoteaddr);
536 nv_free(nvin);
537 goto close;
538 }
539 if (size != sizeof(res->hr_token)) {
540 pjdlog_warning("Handshake header from %s contains 'token' of wrong size (got %zu, expected %zu).",
541 res->hr_remoteaddr, size, sizeof(res->hr_token));
542 nv_free(nvin);
543 goto close;
544 }
545 bcopy(token, res->hr_token, sizeof(res->hr_token));
546 nv_free(nvin);
547
548 /*
549 * Second handshake step.
550 * Setup incoming connection with remote node.
551 */
552 if (proto_client(res->hr_remoteaddr, &in) < 0) {
553 pjdlog_errno(LOG_WARNING, "Unable to create connection to %s",
554 res->hr_remoteaddr);
555 }
556 /* Try to connect, but accept failure. */
557 if (proto_connect(in) < 0) {
558 pjdlog_errno(LOG_WARNING, "Unable to connect to %s",
559 res->hr_remoteaddr);
560 goto close;
561 }
562 /* Error in setting timeout is not critical, but why should it fail? */
563 if (proto_timeout(in, res->hr_timeout) < 0)
564 pjdlog_errno(LOG_WARNING, "Unable to set connection timeout");
565 nvout = nv_alloc();
566 nv_add_string(nvout, res->hr_name, "resource");
567 nv_add_uint8_array(nvout, res->hr_token, sizeof(res->hr_token),
568 "token");
569 nv_add_uint64(nvout, res->hr_resuid, "resuid");
570 nv_add_uint64(nvout, res->hr_primary_localcnt, "localcnt");
571 nv_add_uint64(nvout, res->hr_primary_remotecnt, "remotecnt");
572 if (nv_error(nvout) != 0) {
573 pjdlog_common(LOG_WARNING, 0, nv_error(nvout),
574 "Unable to allocate header for connection with %s",
575 res->hr_remoteaddr);
576 nv_free(nvout);
577 goto close;
578 }
579 if (hast_proto_send(res, in, nvout, NULL, 0) < 0) {
580 pjdlog_errno(LOG_WARNING,
581 "Unable to send handshake header to %s",
582 res->hr_remoteaddr);
583 nv_free(nvout);
584 goto close;
585 }
586 nv_free(nvout);
587 if (hast_proto_recv_hdr(out, &nvin) < 0) {
588 pjdlog_errno(LOG_WARNING,
589 "Unable to receive handshake header from %s",
590 res->hr_remoteaddr);
591 goto close;
592 }
593 errmsg = nv_get_string(nvin, "errmsg");
594 if (errmsg != NULL) {
595 pjdlog_warning("%s", errmsg);
596 nv_free(nvin);
597 goto close;
598 }
599 datasize = nv_get_int64(nvin, "datasize");
600 if (datasize != res->hr_datasize) {
601 pjdlog_warning("Data size differs between nodes (local=%jd, remote=%jd).",
602 (intmax_t)res->hr_datasize, (intmax_t)datasize);
603 nv_free(nvin);
604 goto close;
605 }
606 extentsize = nv_get_int32(nvin, "extentsize");
607 if (extentsize != res->hr_extentsize) {
608 pjdlog_warning("Extent size differs between nodes (local=%zd, remote=%zd).",
609 (ssize_t)res->hr_extentsize, (ssize_t)extentsize);
610 nv_free(nvin);
611 goto close;
612 }
613 res->hr_secondary_localcnt = nv_get_uint64(nvin, "localcnt");
614 res->hr_secondary_remotecnt = nv_get_uint64(nvin, "remotecnt");
615 res->hr_syncsrc = nv_get_uint8(nvin, "syncsrc");
616 map = NULL;
617 mapsize = nv_get_uint32(nvin, "mapsize");
618 if (mapsize > 0) {
619 map = malloc(mapsize);
620 if (map == NULL) {
621 pjdlog_error("Unable to allocate memory for remote activemap (mapsize=%ju).",
622 (uintmax_t)mapsize);
623 nv_free(nvin);
624 goto close;
625 }
626 /*
627 * Remote node have some dirty extents on its own, lets
628 * download its activemap.
629 */
630 if (hast_proto_recv_data(res, out, nvin, map,
631 mapsize) < 0) {
632 pjdlog_errno(LOG_ERR,
633 "Unable to receive remote activemap");
634 nv_free(nvin);
635 free(map);
636 goto close;
637 }
638 /*
639 * Merge local and remote bitmaps.
640 */
641 activemap_merge(res->hr_amp, map, mapsize);
642 free(map);
643 /*
644 * Now that we merged bitmaps from both nodes, flush it to the
645 * disk before we start to synchronize.
646 */
647 (void)hast_activemap_flush(res);
648 }
33
34#include <sys/types.h>
35#include <sys/time.h>
36#include <sys/bio.h>
37#include <sys/disk.h>
38#include <sys/refcount.h>
39#include <sys/stat.h>
40
41#include <geom/gate/g_gate.h>
42
43#include <assert.h>
44#include <err.h>
45#include <errno.h>
46#include <fcntl.h>
47#include <libgeom.h>
48#include <pthread.h>
49#include <signal.h>
50#include <stdint.h>
51#include <stdio.h>
52#include <string.h>
53#include <sysexits.h>
54#include <unistd.h>
55
56#include <activemap.h>
57#include <nv.h>
58#include <rangelock.h>
59
60#include "control.h"
61#include "event.h"
62#include "hast.h"
63#include "hast_proto.h"
64#include "hastd.h"
65#include "hooks.h"
66#include "metadata.h"
67#include "proto.h"
68#include "pjdlog.h"
69#include "subr.h"
70#include "synch.h"
71
72/* The is only one remote component for now. */
73#define ISREMOTE(no) ((no) == 1)
74
75struct hio {
76 /*
77 * Number of components we are still waiting for.
78 * When this field goes to 0, we can send the request back to the
79 * kernel. Each component has to decrease this counter by one
80 * even on failure.
81 */
82 unsigned int hio_countdown;
83 /*
84 * Each component has a place to store its own error.
85 * Once the request is handled by all components we can decide if the
86 * request overall is successful or not.
87 */
88 int *hio_errors;
89 /*
90 * Structure used to comunicate with GEOM Gate class.
91 */
92 struct g_gate_ctl_io hio_ggio;
93 TAILQ_ENTRY(hio) *hio_next;
94};
95#define hio_free_next hio_next[0]
96#define hio_done_next hio_next[0]
97
98/*
99 * Free list holds unused structures. When free list is empty, we have to wait
100 * until some in-progress requests are freed.
101 */
102static TAILQ_HEAD(, hio) hio_free_list;
103static pthread_mutex_t hio_free_list_lock;
104static pthread_cond_t hio_free_list_cond;
105/*
106 * There is one send list for every component. One requests is placed on all
107 * send lists - each component gets the same request, but each component is
108 * responsible for managing his own send list.
109 */
110static TAILQ_HEAD(, hio) *hio_send_list;
111static pthread_mutex_t *hio_send_list_lock;
112static pthread_cond_t *hio_send_list_cond;
113/*
114 * There is one recv list for every component, although local components don't
115 * use recv lists as local requests are done synchronously.
116 */
117static TAILQ_HEAD(, hio) *hio_recv_list;
118static pthread_mutex_t *hio_recv_list_lock;
119static pthread_cond_t *hio_recv_list_cond;
120/*
121 * Request is placed on done list by the slowest component (the one that
122 * decreased hio_countdown from 1 to 0).
123 */
124static TAILQ_HEAD(, hio) hio_done_list;
125static pthread_mutex_t hio_done_list_lock;
126static pthread_cond_t hio_done_list_cond;
127/*
128 * Structure below are for interaction with sync thread.
129 */
130static bool sync_inprogress;
131static pthread_mutex_t sync_lock;
132static pthread_cond_t sync_cond;
133/*
134 * The lock below allows to synchornize access to remote connections.
135 */
136static pthread_rwlock_t *hio_remote_lock;
137
138/*
139 * Lock to synchronize metadata updates. Also synchronize access to
140 * hr_primary_localcnt and hr_primary_remotecnt fields.
141 */
142static pthread_mutex_t metadata_lock;
143
144/*
145 * Maximum number of outstanding I/O requests.
146 */
147#define HAST_HIO_MAX 256
148/*
149 * Number of components. At this point there are only two components: local
150 * and remote, but in the future it might be possible to use multiple local
151 * and remote components.
152 */
153#define HAST_NCOMPONENTS 2
154/*
155 * Number of seconds to sleep between reconnect retries or keepalive packets.
156 */
157#define RETRY_SLEEP 10
158
159#define ISCONNECTED(res, no) \
160 ((res)->hr_remotein != NULL && (res)->hr_remoteout != NULL)
161
162#define QUEUE_INSERT1(hio, name, ncomp) do { \
163 bool _wakeup; \
164 \
165 mtx_lock(&hio_##name##_list_lock[(ncomp)]); \
166 _wakeup = TAILQ_EMPTY(&hio_##name##_list[(ncomp)]); \
167 TAILQ_INSERT_TAIL(&hio_##name##_list[(ncomp)], (hio), \
168 hio_next[(ncomp)]); \
169 mtx_unlock(&hio_##name##_list_lock[ncomp]); \
170 if (_wakeup) \
171 cv_signal(&hio_##name##_list_cond[(ncomp)]); \
172} while (0)
173#define QUEUE_INSERT2(hio, name) do { \
174 bool _wakeup; \
175 \
176 mtx_lock(&hio_##name##_list_lock); \
177 _wakeup = TAILQ_EMPTY(&hio_##name##_list); \
178 TAILQ_INSERT_TAIL(&hio_##name##_list, (hio), hio_##name##_next);\
179 mtx_unlock(&hio_##name##_list_lock); \
180 if (_wakeup) \
181 cv_signal(&hio_##name##_list_cond); \
182} while (0)
183#define QUEUE_TAKE1(hio, name, ncomp) do { \
184 mtx_lock(&hio_##name##_list_lock[(ncomp)]); \
185 while (((hio) = TAILQ_FIRST(&hio_##name##_list[(ncomp)])) == NULL) { \
186 cv_wait(&hio_##name##_list_cond[(ncomp)], \
187 &hio_##name##_list_lock[(ncomp)]); \
188 } \
189 TAILQ_REMOVE(&hio_##name##_list[(ncomp)], (hio), \
190 hio_next[(ncomp)]); \
191 mtx_unlock(&hio_##name##_list_lock[(ncomp)]); \
192} while (0)
193#define QUEUE_TAKE2(hio, name) do { \
194 mtx_lock(&hio_##name##_list_lock); \
195 while (((hio) = TAILQ_FIRST(&hio_##name##_list)) == NULL) { \
196 cv_wait(&hio_##name##_list_cond, \
197 &hio_##name##_list_lock); \
198 } \
199 TAILQ_REMOVE(&hio_##name##_list, (hio), hio_##name##_next); \
200 mtx_unlock(&hio_##name##_list_lock); \
201} while (0)
202
203#define SYNCREQ(hio) do { \
204 (hio)->hio_ggio.gctl_unit = -1; \
205 (hio)->hio_ggio.gctl_seq = 1; \
206} while (0)
207#define ISSYNCREQ(hio) ((hio)->hio_ggio.gctl_unit == -1)
208#define SYNCREQDONE(hio) do { (hio)->hio_ggio.gctl_unit = -2; } while (0)
209#define ISSYNCREQDONE(hio) ((hio)->hio_ggio.gctl_unit == -2)
210
211static struct hast_resource *gres;
212
213static pthread_mutex_t range_lock;
214static struct rangelocks *range_regular;
215static bool range_regular_wait;
216static pthread_cond_t range_regular_cond;
217static struct rangelocks *range_sync;
218static bool range_sync_wait;
219static pthread_cond_t range_sync_cond;
220
221static void *ggate_recv_thread(void *arg);
222static void *local_send_thread(void *arg);
223static void *remote_send_thread(void *arg);
224static void *remote_recv_thread(void *arg);
225static void *ggate_send_thread(void *arg);
226static void *sync_thread(void *arg);
227static void *guard_thread(void *arg);
228
229static void
230cleanup(struct hast_resource *res)
231{
232 int rerrno;
233
234 /* Remember errno. */
235 rerrno = errno;
236
237 /* Destroy ggate provider if we created one. */
238 if (res->hr_ggateunit >= 0) {
239 struct g_gate_ctl_destroy ggiod;
240
241 bzero(&ggiod, sizeof(ggiod));
242 ggiod.gctl_version = G_GATE_VERSION;
243 ggiod.gctl_unit = res->hr_ggateunit;
244 ggiod.gctl_force = 1;
245 if (ioctl(res->hr_ggatefd, G_GATE_CMD_DESTROY, &ggiod) < 0) {
246 pjdlog_errno(LOG_WARNING,
247 "Unable to destroy hast/%s device",
248 res->hr_provname);
249 }
250 res->hr_ggateunit = -1;
251 }
252
253 /* Restore errno. */
254 errno = rerrno;
255}
256
257static __dead2 void
258primary_exit(int exitcode, const char *fmt, ...)
259{
260 va_list ap;
261
262 assert(exitcode != EX_OK);
263 va_start(ap, fmt);
264 pjdlogv_errno(LOG_ERR, fmt, ap);
265 va_end(ap);
266 cleanup(gres);
267 exit(exitcode);
268}
269
270static __dead2 void
271primary_exitx(int exitcode, const char *fmt, ...)
272{
273 va_list ap;
274
275 va_start(ap, fmt);
276 pjdlogv(exitcode == EX_OK ? LOG_INFO : LOG_ERR, fmt, ap);
277 va_end(ap);
278 cleanup(gres);
279 exit(exitcode);
280}
281
282static int
283hast_activemap_flush(struct hast_resource *res)
284{
285 const unsigned char *buf;
286 size_t size;
287
288 buf = activemap_bitmap(res->hr_amp, &size);
289 assert(buf != NULL);
290 assert((size % res->hr_local_sectorsize) == 0);
291 if (pwrite(res->hr_localfd, buf, size, METADATA_SIZE) !=
292 (ssize_t)size) {
293 KEEP_ERRNO(pjdlog_errno(LOG_ERR,
294 "Unable to flush activemap to disk"));
295 return (-1);
296 }
297 return (0);
298}
299
300static bool
301real_remote(const struct hast_resource *res)
302{
303
304 return (strcmp(res->hr_remoteaddr, "none") != 0);
305}
306
307static void
308init_environment(struct hast_resource *res __unused)
309{
310 struct hio *hio;
311 unsigned int ii, ncomps;
312
313 /*
314 * In the future it might be per-resource value.
315 */
316 ncomps = HAST_NCOMPONENTS;
317
318 /*
319 * Allocate memory needed by lists.
320 */
321 hio_send_list = malloc(sizeof(hio_send_list[0]) * ncomps);
322 if (hio_send_list == NULL) {
323 primary_exitx(EX_TEMPFAIL,
324 "Unable to allocate %zu bytes of memory for send lists.",
325 sizeof(hio_send_list[0]) * ncomps);
326 }
327 hio_send_list_lock = malloc(sizeof(hio_send_list_lock[0]) * ncomps);
328 if (hio_send_list_lock == NULL) {
329 primary_exitx(EX_TEMPFAIL,
330 "Unable to allocate %zu bytes of memory for send list locks.",
331 sizeof(hio_send_list_lock[0]) * ncomps);
332 }
333 hio_send_list_cond = malloc(sizeof(hio_send_list_cond[0]) * ncomps);
334 if (hio_send_list_cond == NULL) {
335 primary_exitx(EX_TEMPFAIL,
336 "Unable to allocate %zu bytes of memory for send list condition variables.",
337 sizeof(hio_send_list_cond[0]) * ncomps);
338 }
339 hio_recv_list = malloc(sizeof(hio_recv_list[0]) * ncomps);
340 if (hio_recv_list == NULL) {
341 primary_exitx(EX_TEMPFAIL,
342 "Unable to allocate %zu bytes of memory for recv lists.",
343 sizeof(hio_recv_list[0]) * ncomps);
344 }
345 hio_recv_list_lock = malloc(sizeof(hio_recv_list_lock[0]) * ncomps);
346 if (hio_recv_list_lock == NULL) {
347 primary_exitx(EX_TEMPFAIL,
348 "Unable to allocate %zu bytes of memory for recv list locks.",
349 sizeof(hio_recv_list_lock[0]) * ncomps);
350 }
351 hio_recv_list_cond = malloc(sizeof(hio_recv_list_cond[0]) * ncomps);
352 if (hio_recv_list_cond == NULL) {
353 primary_exitx(EX_TEMPFAIL,
354 "Unable to allocate %zu bytes of memory for recv list condition variables.",
355 sizeof(hio_recv_list_cond[0]) * ncomps);
356 }
357 hio_remote_lock = malloc(sizeof(hio_remote_lock[0]) * ncomps);
358 if (hio_remote_lock == NULL) {
359 primary_exitx(EX_TEMPFAIL,
360 "Unable to allocate %zu bytes of memory for remote connections locks.",
361 sizeof(hio_remote_lock[0]) * ncomps);
362 }
363
364 /*
365 * Initialize lists, their locks and theirs condition variables.
366 */
367 TAILQ_INIT(&hio_free_list);
368 mtx_init(&hio_free_list_lock);
369 cv_init(&hio_free_list_cond);
370 for (ii = 0; ii < HAST_NCOMPONENTS; ii++) {
371 TAILQ_INIT(&hio_send_list[ii]);
372 mtx_init(&hio_send_list_lock[ii]);
373 cv_init(&hio_send_list_cond[ii]);
374 TAILQ_INIT(&hio_recv_list[ii]);
375 mtx_init(&hio_recv_list_lock[ii]);
376 cv_init(&hio_recv_list_cond[ii]);
377 rw_init(&hio_remote_lock[ii]);
378 }
379 TAILQ_INIT(&hio_done_list);
380 mtx_init(&hio_done_list_lock);
381 cv_init(&hio_done_list_cond);
382 mtx_init(&metadata_lock);
383
384 /*
385 * Allocate requests pool and initialize requests.
386 */
387 for (ii = 0; ii < HAST_HIO_MAX; ii++) {
388 hio = malloc(sizeof(*hio));
389 if (hio == NULL) {
390 primary_exitx(EX_TEMPFAIL,
391 "Unable to allocate %zu bytes of memory for hio request.",
392 sizeof(*hio));
393 }
394 hio->hio_countdown = 0;
395 hio->hio_errors = malloc(sizeof(hio->hio_errors[0]) * ncomps);
396 if (hio->hio_errors == NULL) {
397 primary_exitx(EX_TEMPFAIL,
398 "Unable allocate %zu bytes of memory for hio errors.",
399 sizeof(hio->hio_errors[0]) * ncomps);
400 }
401 hio->hio_next = malloc(sizeof(hio->hio_next[0]) * ncomps);
402 if (hio->hio_next == NULL) {
403 primary_exitx(EX_TEMPFAIL,
404 "Unable allocate %zu bytes of memory for hio_next field.",
405 sizeof(hio->hio_next[0]) * ncomps);
406 }
407 hio->hio_ggio.gctl_version = G_GATE_VERSION;
408 hio->hio_ggio.gctl_data = malloc(MAXPHYS);
409 if (hio->hio_ggio.gctl_data == NULL) {
410 primary_exitx(EX_TEMPFAIL,
411 "Unable to allocate %zu bytes of memory for gctl_data.",
412 MAXPHYS);
413 }
414 hio->hio_ggio.gctl_length = MAXPHYS;
415 hio->hio_ggio.gctl_error = 0;
416 TAILQ_INSERT_HEAD(&hio_free_list, hio, hio_free_next);
417 }
418}
419
420static void
421init_local(struct hast_resource *res)
422{
423 unsigned char *buf;
424 size_t mapsize;
425
426 if (metadata_read(res, true) < 0)
427 exit(EX_NOINPUT);
428 mtx_init(&res->hr_amp_lock);
429 if (activemap_init(&res->hr_amp, res->hr_datasize, res->hr_extentsize,
430 res->hr_local_sectorsize, res->hr_keepdirty) < 0) {
431 primary_exit(EX_TEMPFAIL, "Unable to create activemap");
432 }
433 mtx_init(&range_lock);
434 cv_init(&range_regular_cond);
435 if (rangelock_init(&range_regular) < 0)
436 primary_exit(EX_TEMPFAIL, "Unable to create regular range lock");
437 cv_init(&range_sync_cond);
438 if (rangelock_init(&range_sync) < 0)
439 primary_exit(EX_TEMPFAIL, "Unable to create sync range lock");
440 mapsize = activemap_ondisk_size(res->hr_amp);
441 buf = calloc(1, mapsize);
442 if (buf == NULL) {
443 primary_exitx(EX_TEMPFAIL,
444 "Unable to allocate buffer for activemap.");
445 }
446 if (pread(res->hr_localfd, buf, mapsize, METADATA_SIZE) !=
447 (ssize_t)mapsize) {
448 primary_exit(EX_NOINPUT, "Unable to read activemap");
449 }
450 activemap_copyin(res->hr_amp, buf, mapsize);
451 free(buf);
452 if (res->hr_resuid != 0)
453 return;
454 /*
455 * We're using provider for the first time, so we have to generate
456 * resource unique identifier and initialize local and remote counts.
457 */
458 arc4random_buf(&res->hr_resuid, sizeof(res->hr_resuid));
459 res->hr_primary_localcnt = 1;
460 res->hr_primary_remotecnt = 0;
461 if (metadata_write(res) < 0)
462 exit(EX_NOINPUT);
463}
464
465static bool
466init_remote(struct hast_resource *res, struct proto_conn **inp,
467 struct proto_conn **outp)
468{
469 struct proto_conn *in, *out;
470 struct nv *nvout, *nvin;
471 const unsigned char *token;
472 unsigned char *map;
473 const char *errmsg;
474 int32_t extentsize;
475 int64_t datasize;
476 uint32_t mapsize;
477 size_t size;
478
479 assert((inp == NULL && outp == NULL) || (inp != NULL && outp != NULL));
480 assert(real_remote(res));
481
482 in = out = NULL;
483 errmsg = NULL;
484
485 /* Prepare outgoing connection with remote node. */
486 if (proto_client(res->hr_remoteaddr, &out) < 0) {
487 primary_exit(EX_TEMPFAIL, "Unable to create connection to %s",
488 res->hr_remoteaddr);
489 }
490 /* Try to connect, but accept failure. */
491 if (proto_connect(out) < 0) {
492 pjdlog_errno(LOG_WARNING, "Unable to connect to %s",
493 res->hr_remoteaddr);
494 goto close;
495 }
496 /* Error in setting timeout is not critical, but why should it fail? */
497 if (proto_timeout(out, res->hr_timeout) < 0)
498 pjdlog_errno(LOG_WARNING, "Unable to set connection timeout");
499 /*
500 * First handshake step.
501 * Setup outgoing connection with remote node.
502 */
503 nvout = nv_alloc();
504 nv_add_string(nvout, res->hr_name, "resource");
505 if (nv_error(nvout) != 0) {
506 pjdlog_common(LOG_WARNING, 0, nv_error(nvout),
507 "Unable to allocate header for connection with %s",
508 res->hr_remoteaddr);
509 nv_free(nvout);
510 goto close;
511 }
512 if (hast_proto_send(res, out, nvout, NULL, 0) < 0) {
513 pjdlog_errno(LOG_WARNING,
514 "Unable to send handshake header to %s",
515 res->hr_remoteaddr);
516 nv_free(nvout);
517 goto close;
518 }
519 nv_free(nvout);
520 if (hast_proto_recv_hdr(out, &nvin) < 0) {
521 pjdlog_errno(LOG_WARNING,
522 "Unable to receive handshake header from %s",
523 res->hr_remoteaddr);
524 goto close;
525 }
526 errmsg = nv_get_string(nvin, "errmsg");
527 if (errmsg != NULL) {
528 pjdlog_warning("%s", errmsg);
529 nv_free(nvin);
530 goto close;
531 }
532 token = nv_get_uint8_array(nvin, &size, "token");
533 if (token == NULL) {
534 pjdlog_warning("Handshake header from %s has no 'token' field.",
535 res->hr_remoteaddr);
536 nv_free(nvin);
537 goto close;
538 }
539 if (size != sizeof(res->hr_token)) {
540 pjdlog_warning("Handshake header from %s contains 'token' of wrong size (got %zu, expected %zu).",
541 res->hr_remoteaddr, size, sizeof(res->hr_token));
542 nv_free(nvin);
543 goto close;
544 }
545 bcopy(token, res->hr_token, sizeof(res->hr_token));
546 nv_free(nvin);
547
548 /*
549 * Second handshake step.
550 * Setup incoming connection with remote node.
551 */
552 if (proto_client(res->hr_remoteaddr, &in) < 0) {
553 pjdlog_errno(LOG_WARNING, "Unable to create connection to %s",
554 res->hr_remoteaddr);
555 }
556 /* Try to connect, but accept failure. */
557 if (proto_connect(in) < 0) {
558 pjdlog_errno(LOG_WARNING, "Unable to connect to %s",
559 res->hr_remoteaddr);
560 goto close;
561 }
562 /* Error in setting timeout is not critical, but why should it fail? */
563 if (proto_timeout(in, res->hr_timeout) < 0)
564 pjdlog_errno(LOG_WARNING, "Unable to set connection timeout");
565 nvout = nv_alloc();
566 nv_add_string(nvout, res->hr_name, "resource");
567 nv_add_uint8_array(nvout, res->hr_token, sizeof(res->hr_token),
568 "token");
569 nv_add_uint64(nvout, res->hr_resuid, "resuid");
570 nv_add_uint64(nvout, res->hr_primary_localcnt, "localcnt");
571 nv_add_uint64(nvout, res->hr_primary_remotecnt, "remotecnt");
572 if (nv_error(nvout) != 0) {
573 pjdlog_common(LOG_WARNING, 0, nv_error(nvout),
574 "Unable to allocate header for connection with %s",
575 res->hr_remoteaddr);
576 nv_free(nvout);
577 goto close;
578 }
579 if (hast_proto_send(res, in, nvout, NULL, 0) < 0) {
580 pjdlog_errno(LOG_WARNING,
581 "Unable to send handshake header to %s",
582 res->hr_remoteaddr);
583 nv_free(nvout);
584 goto close;
585 }
586 nv_free(nvout);
587 if (hast_proto_recv_hdr(out, &nvin) < 0) {
588 pjdlog_errno(LOG_WARNING,
589 "Unable to receive handshake header from %s",
590 res->hr_remoteaddr);
591 goto close;
592 }
593 errmsg = nv_get_string(nvin, "errmsg");
594 if (errmsg != NULL) {
595 pjdlog_warning("%s", errmsg);
596 nv_free(nvin);
597 goto close;
598 }
599 datasize = nv_get_int64(nvin, "datasize");
600 if (datasize != res->hr_datasize) {
601 pjdlog_warning("Data size differs between nodes (local=%jd, remote=%jd).",
602 (intmax_t)res->hr_datasize, (intmax_t)datasize);
603 nv_free(nvin);
604 goto close;
605 }
606 extentsize = nv_get_int32(nvin, "extentsize");
607 if (extentsize != res->hr_extentsize) {
608 pjdlog_warning("Extent size differs between nodes (local=%zd, remote=%zd).",
609 (ssize_t)res->hr_extentsize, (ssize_t)extentsize);
610 nv_free(nvin);
611 goto close;
612 }
613 res->hr_secondary_localcnt = nv_get_uint64(nvin, "localcnt");
614 res->hr_secondary_remotecnt = nv_get_uint64(nvin, "remotecnt");
615 res->hr_syncsrc = nv_get_uint8(nvin, "syncsrc");
616 map = NULL;
617 mapsize = nv_get_uint32(nvin, "mapsize");
618 if (mapsize > 0) {
619 map = malloc(mapsize);
620 if (map == NULL) {
621 pjdlog_error("Unable to allocate memory for remote activemap (mapsize=%ju).",
622 (uintmax_t)mapsize);
623 nv_free(nvin);
624 goto close;
625 }
626 /*
627 * Remote node have some dirty extents on its own, lets
628 * download its activemap.
629 */
630 if (hast_proto_recv_data(res, out, nvin, map,
631 mapsize) < 0) {
632 pjdlog_errno(LOG_ERR,
633 "Unable to receive remote activemap");
634 nv_free(nvin);
635 free(map);
636 goto close;
637 }
638 /*
639 * Merge local and remote bitmaps.
640 */
641 activemap_merge(res->hr_amp, map, mapsize);
642 free(map);
643 /*
644 * Now that we merged bitmaps from both nodes, flush it to the
645 * disk before we start to synchronize.
646 */
647 (void)hast_activemap_flush(res);
648 }
649 nv_free(nvin);
649 pjdlog_info("Connected to %s.", res->hr_remoteaddr);
650 if (inp != NULL && outp != NULL) {
651 *inp = in;
652 *outp = out;
653 } else {
654 res->hr_remotein = in;
655 res->hr_remoteout = out;
656 }
657 event_send(res, EVENT_CONNECT);
658 return (true);
659close:
660 if (errmsg != NULL && strcmp(errmsg, "Split-brain condition!") == 0)
661 event_send(res, EVENT_SPLITBRAIN);
662 proto_close(out);
663 if (in != NULL)
664 proto_close(in);
665 return (false);
666}
667
668static void
669sync_start(void)
670{
671
672 mtx_lock(&sync_lock);
673 sync_inprogress = true;
674 mtx_unlock(&sync_lock);
675 cv_signal(&sync_cond);
676}
677
678static void
679sync_stop(void)
680{
681
682 mtx_lock(&sync_lock);
683 if (sync_inprogress)
684 sync_inprogress = false;
685 mtx_unlock(&sync_lock);
686}
687
688static void
689init_ggate(struct hast_resource *res)
690{
691 struct g_gate_ctl_create ggiocreate;
692 struct g_gate_ctl_cancel ggiocancel;
693
694 /*
695 * We communicate with ggate via /dev/ggctl. Open it.
696 */
697 res->hr_ggatefd = open("/dev/" G_GATE_CTL_NAME, O_RDWR);
698 if (res->hr_ggatefd < 0)
699 primary_exit(EX_OSFILE, "Unable to open /dev/" G_GATE_CTL_NAME);
700 /*
701 * Create provider before trying to connect, as connection failure
702 * is not critical, but may take some time.
703 */
704 bzero(&ggiocreate, sizeof(ggiocreate));
705 ggiocreate.gctl_version = G_GATE_VERSION;
706 ggiocreate.gctl_mediasize = res->hr_datasize;
707 ggiocreate.gctl_sectorsize = res->hr_local_sectorsize;
708 ggiocreate.gctl_flags = 0;
709 ggiocreate.gctl_maxcount = G_GATE_MAX_QUEUE_SIZE;
710 ggiocreate.gctl_timeout = 0;
711 ggiocreate.gctl_unit = G_GATE_NAME_GIVEN;
712 snprintf(ggiocreate.gctl_name, sizeof(ggiocreate.gctl_name), "hast/%s",
713 res->hr_provname);
714 if (ioctl(res->hr_ggatefd, G_GATE_CMD_CREATE, &ggiocreate) == 0) {
715 pjdlog_info("Device hast/%s created.", res->hr_provname);
716 res->hr_ggateunit = ggiocreate.gctl_unit;
717 return;
718 }
719 if (errno != EEXIST) {
720 primary_exit(EX_OSERR, "Unable to create hast/%s device",
721 res->hr_provname);
722 }
723 pjdlog_debug(1,
724 "Device hast/%s already exists, we will try to take it over.",
725 res->hr_provname);
726 /*
727 * If we received EEXIST, we assume that the process who created the
728 * provider died and didn't clean up. In that case we will start from
729 * where he left of.
730 */
731 bzero(&ggiocancel, sizeof(ggiocancel));
732 ggiocancel.gctl_version = G_GATE_VERSION;
733 ggiocancel.gctl_unit = G_GATE_NAME_GIVEN;
734 snprintf(ggiocancel.gctl_name, sizeof(ggiocancel.gctl_name), "hast/%s",
735 res->hr_provname);
736 if (ioctl(res->hr_ggatefd, G_GATE_CMD_CANCEL, &ggiocancel) == 0) {
737 pjdlog_info("Device hast/%s recovered.", res->hr_provname);
738 res->hr_ggateunit = ggiocancel.gctl_unit;
739 return;
740 }
741 primary_exit(EX_OSERR, "Unable to take over hast/%s device",
742 res->hr_provname);
743}
744
745void
746hastd_primary(struct hast_resource *res)
747{
748 pthread_t td;
749 pid_t pid;
750 int error;
751
752 /*
753 * Create communication channel between parent and child.
754 */
755 if (proto_client("socketpair://", &res->hr_ctrl) < 0) {
756 KEEP_ERRNO((void)pidfile_remove(pfh));
757 pjdlog_exit(EX_OSERR,
758 "Unable to create control sockets between parent and child");
759 }
760 /*
761 * Create communication channel between child and parent.
762 */
763 if (proto_client("socketpair://", &res->hr_event) < 0) {
764 KEEP_ERRNO((void)pidfile_remove(pfh));
765 pjdlog_exit(EX_OSERR,
766 "Unable to create event sockets between child and parent");
767 }
768
769 pid = fork();
770 if (pid < 0) {
771 KEEP_ERRNO((void)pidfile_remove(pfh));
772 pjdlog_exit(EX_TEMPFAIL, "Unable to fork");
773 }
774
775 if (pid > 0) {
776 /* This is parent. */
777 /* Declare that we are receiver. */
778 proto_recv(res->hr_event, NULL, 0);
779 res->hr_workerpid = pid;
780 return;
781 }
782
783 gres = res;
784
785 (void)pidfile_close(pfh);
786 hook_fini();
787
788 setproctitle("%s (primary)", res->hr_name);
789
790 /* Declare that we are sender. */
791 proto_send(res->hr_event, NULL, 0);
792
793 init_local(res);
794 init_ggate(res);
795 init_environment(res);
796 /*
797 * Create the guard thread first, so we can handle signals from the
798 * very begining.
799 */
800 error = pthread_create(&td, NULL, guard_thread, res);
801 assert(error == 0);
802 /*
803 * Create the control thread before sending any event to the parent,
804 * as we can deadlock when parent sends control request to worker,
805 * but worker has no control thread started yet, so parent waits.
806 * In the meantime worker sends an event to the parent, but parent
807 * is unable to handle the event, because it waits for control
808 * request response.
809 */
810 error = pthread_create(&td, NULL, ctrl_thread, res);
811 assert(error == 0);
812 if (real_remote(res) && init_remote(res, NULL, NULL))
813 sync_start();
814 error = pthread_create(&td, NULL, ggate_recv_thread, res);
815 assert(error == 0);
816 error = pthread_create(&td, NULL, local_send_thread, res);
817 assert(error == 0);
818 error = pthread_create(&td, NULL, remote_send_thread, res);
819 assert(error == 0);
820 error = pthread_create(&td, NULL, remote_recv_thread, res);
821 assert(error == 0);
822 error = pthread_create(&td, NULL, ggate_send_thread, res);
823 assert(error == 0);
824 (void)sync_thread(res);
825}
826
827static void
828reqlog(int loglevel, int debuglevel, struct g_gate_ctl_io *ggio, const char *fmt, ...)
829{
830 char msg[1024];
831 va_list ap;
832 int len;
833
834 va_start(ap, fmt);
835 len = vsnprintf(msg, sizeof(msg), fmt, ap);
836 va_end(ap);
837 if ((size_t)len < sizeof(msg)) {
838 switch (ggio->gctl_cmd) {
839 case BIO_READ:
840 (void)snprintf(msg + len, sizeof(msg) - len,
841 "READ(%ju, %ju).", (uintmax_t)ggio->gctl_offset,
842 (uintmax_t)ggio->gctl_length);
843 break;
844 case BIO_DELETE:
845 (void)snprintf(msg + len, sizeof(msg) - len,
846 "DELETE(%ju, %ju).", (uintmax_t)ggio->gctl_offset,
847 (uintmax_t)ggio->gctl_length);
848 break;
849 case BIO_FLUSH:
850 (void)snprintf(msg + len, sizeof(msg) - len, "FLUSH.");
851 break;
852 case BIO_WRITE:
853 (void)snprintf(msg + len, sizeof(msg) - len,
854 "WRITE(%ju, %ju).", (uintmax_t)ggio->gctl_offset,
855 (uintmax_t)ggio->gctl_length);
856 break;
857 default:
858 (void)snprintf(msg + len, sizeof(msg) - len,
859 "UNKNOWN(%u).", (unsigned int)ggio->gctl_cmd);
860 break;
861 }
862 }
863 pjdlog_common(loglevel, debuglevel, -1, "%s", msg);
864}
865
866static void
867remote_close(struct hast_resource *res, int ncomp)
868{
869
870 rw_wlock(&hio_remote_lock[ncomp]);
871 /*
872 * A race is possible between dropping rlock and acquiring wlock -
873 * another thread can close connection in-between.
874 */
875 if (!ISCONNECTED(res, ncomp)) {
876 assert(res->hr_remotein == NULL);
877 assert(res->hr_remoteout == NULL);
878 rw_unlock(&hio_remote_lock[ncomp]);
879 return;
880 }
881
882 assert(res->hr_remotein != NULL);
883 assert(res->hr_remoteout != NULL);
884
885 pjdlog_debug(2, "Closing incoming connection to %s.",
886 res->hr_remoteaddr);
887 proto_close(res->hr_remotein);
888 res->hr_remotein = NULL;
889 pjdlog_debug(2, "Closing outgoing connection to %s.",
890 res->hr_remoteaddr);
891 proto_close(res->hr_remoteout);
892 res->hr_remoteout = NULL;
893
894 rw_unlock(&hio_remote_lock[ncomp]);
895
896 pjdlog_warning("Disconnected from %s.", res->hr_remoteaddr);
897
898 /*
899 * Stop synchronization if in-progress.
900 */
901 sync_stop();
902
903 event_send(res, EVENT_DISCONNECT);
904}
905
906/*
907 * Thread receives ggate I/O requests from the kernel and passes them to
908 * appropriate threads:
909 * WRITE - always goes to both local_send and remote_send threads
910 * READ (when the block is up-to-date on local component) -
911 * only local_send thread
912 * READ (when the block isn't up-to-date on local component) -
913 * only remote_send thread
914 * DELETE - always goes to both local_send and remote_send threads
915 * FLUSH - always goes to both local_send and remote_send threads
916 */
917static void *
918ggate_recv_thread(void *arg)
919{
920 struct hast_resource *res = arg;
921 struct g_gate_ctl_io *ggio;
922 struct hio *hio;
923 unsigned int ii, ncomp, ncomps;
924 int error;
925
926 ncomps = HAST_NCOMPONENTS;
927
928 for (;;) {
929 pjdlog_debug(2, "ggate_recv: Taking free request.");
930 QUEUE_TAKE2(hio, free);
931 pjdlog_debug(2, "ggate_recv: (%p) Got free request.", hio);
932 ggio = &hio->hio_ggio;
933 ggio->gctl_unit = res->hr_ggateunit;
934 ggio->gctl_length = MAXPHYS;
935 ggio->gctl_error = 0;
936 pjdlog_debug(2,
937 "ggate_recv: (%p) Waiting for request from the kernel.",
938 hio);
939 if (ioctl(res->hr_ggatefd, G_GATE_CMD_START, ggio) < 0) {
940 if (sigexit_received)
941 pthread_exit(NULL);
942 primary_exit(EX_OSERR, "G_GATE_CMD_START failed");
943 }
944 error = ggio->gctl_error;
945 switch (error) {
946 case 0:
947 break;
948 case ECANCELED:
949 /* Exit gracefully. */
950 if (!sigexit_received) {
951 pjdlog_debug(2,
952 "ggate_recv: (%p) Received cancel from the kernel.",
953 hio);
954 pjdlog_info("Received cancel from the kernel, exiting.");
955 }
956 pthread_exit(NULL);
957 case ENOMEM:
958 /*
959 * Buffer too small? Impossible, we allocate MAXPHYS
960 * bytes - request can't be bigger than that.
961 */
962 /* FALLTHROUGH */
963 case ENXIO:
964 default:
965 primary_exitx(EX_OSERR, "G_GATE_CMD_START failed: %s.",
966 strerror(error));
967 }
968 for (ii = 0; ii < ncomps; ii++)
969 hio->hio_errors[ii] = EINVAL;
970 reqlog(LOG_DEBUG, 2, ggio,
971 "ggate_recv: (%p) Request received from the kernel: ",
972 hio);
973 /*
974 * Inform all components about new write request.
975 * For read request prefer local component unless the given
976 * range is out-of-date, then use remote component.
977 */
978 switch (ggio->gctl_cmd) {
979 case BIO_READ:
980 pjdlog_debug(2,
981 "ggate_recv: (%p) Moving request to the send queue.",
982 hio);
983 refcount_init(&hio->hio_countdown, 1);
984 mtx_lock(&metadata_lock);
985 if (res->hr_syncsrc == HAST_SYNCSRC_UNDEF ||
986 res->hr_syncsrc == HAST_SYNCSRC_PRIMARY) {
987 /*
988 * This range is up-to-date on local component,
989 * so handle request locally.
990 */
991 /* Local component is 0 for now. */
992 ncomp = 0;
993 } else /* if (res->hr_syncsrc ==
994 HAST_SYNCSRC_SECONDARY) */ {
995 assert(res->hr_syncsrc ==
996 HAST_SYNCSRC_SECONDARY);
997 /*
998 * This range is out-of-date on local component,
999 * so send request to the remote node.
1000 */
1001 /* Remote component is 1 for now. */
1002 ncomp = 1;
1003 }
1004 mtx_unlock(&metadata_lock);
1005 QUEUE_INSERT1(hio, send, ncomp);
1006 break;
1007 case BIO_WRITE:
1008 for (;;) {
1009 mtx_lock(&range_lock);
1010 if (rangelock_islocked(range_sync,
1011 ggio->gctl_offset, ggio->gctl_length)) {
1012 pjdlog_debug(2,
1013 "regular: Range offset=%jd length=%zu locked.",
1014 (intmax_t)ggio->gctl_offset,
1015 (size_t)ggio->gctl_length);
1016 range_regular_wait = true;
1017 cv_wait(&range_regular_cond, &range_lock);
1018 range_regular_wait = false;
1019 mtx_unlock(&range_lock);
1020 continue;
1021 }
1022 if (rangelock_add(range_regular,
1023 ggio->gctl_offset, ggio->gctl_length) < 0) {
1024 mtx_unlock(&range_lock);
1025 pjdlog_debug(2,
1026 "regular: Range offset=%jd length=%zu is already locked, waiting.",
1027 (intmax_t)ggio->gctl_offset,
1028 (size_t)ggio->gctl_length);
1029 sleep(1);
1030 continue;
1031 }
1032 mtx_unlock(&range_lock);
1033 break;
1034 }
1035 mtx_lock(&res->hr_amp_lock);
1036 if (activemap_write_start(res->hr_amp,
1037 ggio->gctl_offset, ggio->gctl_length)) {
1038 (void)hast_activemap_flush(res);
1039 }
1040 mtx_unlock(&res->hr_amp_lock);
1041 /* FALLTHROUGH */
1042 case BIO_DELETE:
1043 case BIO_FLUSH:
1044 pjdlog_debug(2,
1045 "ggate_recv: (%p) Moving request to the send queues.",
1046 hio);
1047 refcount_init(&hio->hio_countdown, ncomps);
1048 for (ii = 0; ii < ncomps; ii++)
1049 QUEUE_INSERT1(hio, send, ii);
1050 break;
1051 }
1052 }
1053 /* NOTREACHED */
1054 return (NULL);
1055}
1056
1057/*
1058 * Thread reads from or writes to local component.
1059 * If local read fails, it redirects it to remote_send thread.
1060 */
1061static void *
1062local_send_thread(void *arg)
1063{
1064 struct hast_resource *res = arg;
1065 struct g_gate_ctl_io *ggio;
1066 struct hio *hio;
1067 unsigned int ncomp, rncomp;
1068 ssize_t ret;
1069
1070 /* Local component is 0 for now. */
1071 ncomp = 0;
1072 /* Remote component is 1 for now. */
1073 rncomp = 1;
1074
1075 for (;;) {
1076 pjdlog_debug(2, "local_send: Taking request.");
1077 QUEUE_TAKE1(hio, send, ncomp);
1078 pjdlog_debug(2, "local_send: (%p) Got request.", hio);
1079 ggio = &hio->hio_ggio;
1080 switch (ggio->gctl_cmd) {
1081 case BIO_READ:
1082 ret = pread(res->hr_localfd, ggio->gctl_data,
1083 ggio->gctl_length,
1084 ggio->gctl_offset + res->hr_localoff);
1085 if (ret == ggio->gctl_length)
1086 hio->hio_errors[ncomp] = 0;
1087 else {
1088 /*
1089 * If READ failed, try to read from remote node.
1090 */
1091 QUEUE_INSERT1(hio, send, rncomp);
1092 continue;
1093 }
1094 break;
1095 case BIO_WRITE:
1096 ret = pwrite(res->hr_localfd, ggio->gctl_data,
1097 ggio->gctl_length,
1098 ggio->gctl_offset + res->hr_localoff);
1099 if (ret < 0)
1100 hio->hio_errors[ncomp] = errno;
1101 else if (ret != ggio->gctl_length)
1102 hio->hio_errors[ncomp] = EIO;
1103 else
1104 hio->hio_errors[ncomp] = 0;
1105 break;
1106 case BIO_DELETE:
1107 ret = g_delete(res->hr_localfd,
1108 ggio->gctl_offset + res->hr_localoff,
1109 ggio->gctl_length);
1110 if (ret < 0)
1111 hio->hio_errors[ncomp] = errno;
1112 else
1113 hio->hio_errors[ncomp] = 0;
1114 break;
1115 case BIO_FLUSH:
1116 ret = g_flush(res->hr_localfd);
1117 if (ret < 0)
1118 hio->hio_errors[ncomp] = errno;
1119 else
1120 hio->hio_errors[ncomp] = 0;
1121 break;
1122 }
1123 if (refcount_release(&hio->hio_countdown)) {
1124 if (ISSYNCREQ(hio)) {
1125 mtx_lock(&sync_lock);
1126 SYNCREQDONE(hio);
1127 mtx_unlock(&sync_lock);
1128 cv_signal(&sync_cond);
1129 } else {
1130 pjdlog_debug(2,
1131 "local_send: (%p) Moving request to the done queue.",
1132 hio);
1133 QUEUE_INSERT2(hio, done);
1134 }
1135 }
1136 }
1137 /* NOTREACHED */
1138 return (NULL);
1139}
1140
1141/*
1142 * Thread sends request to secondary node.
1143 */
1144static void *
1145remote_send_thread(void *arg)
1146{
1147 struct hast_resource *res = arg;
1148 struct g_gate_ctl_io *ggio;
1149 struct hio *hio;
1150 struct nv *nv;
1151 unsigned int ncomp;
1152 bool wakeup;
1153 uint64_t offset, length;
1154 uint8_t cmd;
1155 void *data;
1156
1157 /* Remote component is 1 for now. */
1158 ncomp = 1;
1159
1160 for (;;) {
1161 pjdlog_debug(2, "remote_send: Taking request.");
1162 QUEUE_TAKE1(hio, send, ncomp);
1163 pjdlog_debug(2, "remote_send: (%p) Got request.", hio);
1164 ggio = &hio->hio_ggio;
1165 switch (ggio->gctl_cmd) {
1166 case BIO_READ:
1167 cmd = HIO_READ;
1168 data = NULL;
1169 offset = ggio->gctl_offset;
1170 length = ggio->gctl_length;
1171 break;
1172 case BIO_WRITE:
1173 cmd = HIO_WRITE;
1174 data = ggio->gctl_data;
1175 offset = ggio->gctl_offset;
1176 length = ggio->gctl_length;
1177 break;
1178 case BIO_DELETE:
1179 cmd = HIO_DELETE;
1180 data = NULL;
1181 offset = ggio->gctl_offset;
1182 length = ggio->gctl_length;
1183 break;
1184 case BIO_FLUSH:
1185 cmd = HIO_FLUSH;
1186 data = NULL;
1187 offset = 0;
1188 length = 0;
1189 break;
1190 default:
1191 assert(!"invalid condition");
1192 abort();
1193 }
1194 nv = nv_alloc();
1195 nv_add_uint8(nv, cmd, "cmd");
1196 nv_add_uint64(nv, (uint64_t)ggio->gctl_seq, "seq");
1197 nv_add_uint64(nv, offset, "offset");
1198 nv_add_uint64(nv, length, "length");
1199 if (nv_error(nv) != 0) {
1200 hio->hio_errors[ncomp] = nv_error(nv);
1201 pjdlog_debug(2,
1202 "remote_send: (%p) Unable to prepare header to send.",
1203 hio);
1204 reqlog(LOG_ERR, 0, ggio,
1205 "Unable to prepare header to send (%s): ",
1206 strerror(nv_error(nv)));
1207 /* Move failed request immediately to the done queue. */
1208 goto done_queue;
1209 }
1210 pjdlog_debug(2,
1211 "remote_send: (%p) Moving request to the recv queue.",
1212 hio);
1213 /*
1214 * Protect connection from disappearing.
1215 */
1216 rw_rlock(&hio_remote_lock[ncomp]);
1217 if (!ISCONNECTED(res, ncomp)) {
1218 rw_unlock(&hio_remote_lock[ncomp]);
1219 hio->hio_errors[ncomp] = ENOTCONN;
1220 goto done_queue;
1221 }
1222 /*
1223 * Move the request to recv queue before sending it, because
1224 * in different order we can get reply before we move request
1225 * to recv queue.
1226 */
1227 mtx_lock(&hio_recv_list_lock[ncomp]);
1228 wakeup = TAILQ_EMPTY(&hio_recv_list[ncomp]);
1229 TAILQ_INSERT_TAIL(&hio_recv_list[ncomp], hio, hio_next[ncomp]);
1230 mtx_unlock(&hio_recv_list_lock[ncomp]);
1231 if (hast_proto_send(res, res->hr_remoteout, nv, data,
1232 data != NULL ? length : 0) < 0) {
1233 hio->hio_errors[ncomp] = errno;
1234 rw_unlock(&hio_remote_lock[ncomp]);
1235 pjdlog_debug(2,
1236 "remote_send: (%p) Unable to send request.", hio);
1237 reqlog(LOG_ERR, 0, ggio,
1238 "Unable to send request (%s): ",
1239 strerror(hio->hio_errors[ncomp]));
1240 remote_close(res, ncomp);
1241 /*
1242 * Take request back from the receive queue and move
1243 * it immediately to the done queue.
1244 */
1245 mtx_lock(&hio_recv_list_lock[ncomp]);
1246 TAILQ_REMOVE(&hio_recv_list[ncomp], hio, hio_next[ncomp]);
1247 mtx_unlock(&hio_recv_list_lock[ncomp]);
1248 goto done_queue;
1249 }
1250 rw_unlock(&hio_remote_lock[ncomp]);
1251 nv_free(nv);
1252 if (wakeup)
1253 cv_signal(&hio_recv_list_cond[ncomp]);
1254 continue;
1255done_queue:
1256 nv_free(nv);
1257 if (ISSYNCREQ(hio)) {
1258 if (!refcount_release(&hio->hio_countdown))
1259 continue;
1260 mtx_lock(&sync_lock);
1261 SYNCREQDONE(hio);
1262 mtx_unlock(&sync_lock);
1263 cv_signal(&sync_cond);
1264 continue;
1265 }
1266 if (ggio->gctl_cmd == BIO_WRITE) {
1267 mtx_lock(&res->hr_amp_lock);
1268 if (activemap_need_sync(res->hr_amp, ggio->gctl_offset,
1269 ggio->gctl_length)) {
1270 (void)hast_activemap_flush(res);
1271 }
1272 mtx_unlock(&res->hr_amp_lock);
1273 }
1274 if (!refcount_release(&hio->hio_countdown))
1275 continue;
1276 pjdlog_debug(2,
1277 "remote_send: (%p) Moving request to the done queue.",
1278 hio);
1279 QUEUE_INSERT2(hio, done);
1280 }
1281 /* NOTREACHED */
1282 return (NULL);
1283}
1284
1285/*
1286 * Thread receives answer from secondary node and passes it to ggate_send
1287 * thread.
1288 */
1289static void *
1290remote_recv_thread(void *arg)
1291{
1292 struct hast_resource *res = arg;
1293 struct g_gate_ctl_io *ggio;
1294 struct hio *hio;
1295 struct nv *nv;
1296 unsigned int ncomp;
1297 uint64_t seq;
1298 int error;
1299
1300 /* Remote component is 1 for now. */
1301 ncomp = 1;
1302
1303 for (;;) {
1304 /* Wait until there is anything to receive. */
1305 mtx_lock(&hio_recv_list_lock[ncomp]);
1306 while (TAILQ_EMPTY(&hio_recv_list[ncomp])) {
1307 pjdlog_debug(2, "remote_recv: No requests, waiting.");
1308 cv_wait(&hio_recv_list_cond[ncomp],
1309 &hio_recv_list_lock[ncomp]);
1310 }
1311 mtx_unlock(&hio_recv_list_lock[ncomp]);
1312 rw_rlock(&hio_remote_lock[ncomp]);
1313 if (!ISCONNECTED(res, ncomp)) {
1314 rw_unlock(&hio_remote_lock[ncomp]);
1315 /*
1316 * Connection is dead, so move all pending requests to
1317 * the done queue (one-by-one).
1318 */
1319 mtx_lock(&hio_recv_list_lock[ncomp]);
1320 hio = TAILQ_FIRST(&hio_recv_list[ncomp]);
1321 assert(hio != NULL);
1322 TAILQ_REMOVE(&hio_recv_list[ncomp], hio,
1323 hio_next[ncomp]);
1324 mtx_unlock(&hio_recv_list_lock[ncomp]);
1325 goto done_queue;
1326 }
1327 if (hast_proto_recv_hdr(res->hr_remotein, &nv) < 0) {
1328 pjdlog_errno(LOG_ERR,
1329 "Unable to receive reply header");
1330 rw_unlock(&hio_remote_lock[ncomp]);
1331 remote_close(res, ncomp);
1332 continue;
1333 }
1334 rw_unlock(&hio_remote_lock[ncomp]);
1335 seq = nv_get_uint64(nv, "seq");
1336 if (seq == 0) {
1337 pjdlog_error("Header contains no 'seq' field.");
1338 nv_free(nv);
1339 continue;
1340 }
1341 mtx_lock(&hio_recv_list_lock[ncomp]);
1342 TAILQ_FOREACH(hio, &hio_recv_list[ncomp], hio_next[ncomp]) {
1343 if (hio->hio_ggio.gctl_seq == seq) {
1344 TAILQ_REMOVE(&hio_recv_list[ncomp], hio,
1345 hio_next[ncomp]);
1346 break;
1347 }
1348 }
1349 mtx_unlock(&hio_recv_list_lock[ncomp]);
1350 if (hio == NULL) {
1351 pjdlog_error("Found no request matching received 'seq' field (%ju).",
1352 (uintmax_t)seq);
1353 nv_free(nv);
1354 continue;
1355 }
1356 error = nv_get_int16(nv, "error");
1357 if (error != 0) {
1358 /* Request failed on remote side. */
1359 hio->hio_errors[ncomp] = 0;
1360 nv_free(nv);
1361 goto done_queue;
1362 }
1363 ggio = &hio->hio_ggio;
1364 switch (ggio->gctl_cmd) {
1365 case BIO_READ:
1366 rw_rlock(&hio_remote_lock[ncomp]);
1367 if (!ISCONNECTED(res, ncomp)) {
1368 rw_unlock(&hio_remote_lock[ncomp]);
1369 nv_free(nv);
1370 goto done_queue;
1371 }
1372 if (hast_proto_recv_data(res, res->hr_remotein, nv,
1373 ggio->gctl_data, ggio->gctl_length) < 0) {
1374 hio->hio_errors[ncomp] = errno;
1375 pjdlog_errno(LOG_ERR,
1376 "Unable to receive reply data");
1377 rw_unlock(&hio_remote_lock[ncomp]);
1378 nv_free(nv);
1379 remote_close(res, ncomp);
1380 goto done_queue;
1381 }
1382 rw_unlock(&hio_remote_lock[ncomp]);
1383 break;
1384 case BIO_WRITE:
1385 case BIO_DELETE:
1386 case BIO_FLUSH:
1387 break;
1388 default:
1389 assert(!"invalid condition");
1390 abort();
1391 }
1392 hio->hio_errors[ncomp] = 0;
1393 nv_free(nv);
1394done_queue:
1395 if (refcount_release(&hio->hio_countdown)) {
1396 if (ISSYNCREQ(hio)) {
1397 mtx_lock(&sync_lock);
1398 SYNCREQDONE(hio);
1399 mtx_unlock(&sync_lock);
1400 cv_signal(&sync_cond);
1401 } else {
1402 pjdlog_debug(2,
1403 "remote_recv: (%p) Moving request to the done queue.",
1404 hio);
1405 QUEUE_INSERT2(hio, done);
1406 }
1407 }
1408 }
1409 /* NOTREACHED */
1410 return (NULL);
1411}
1412
1413/*
1414 * Thread sends answer to the kernel.
1415 */
1416static void *
1417ggate_send_thread(void *arg)
1418{
1419 struct hast_resource *res = arg;
1420 struct g_gate_ctl_io *ggio;
1421 struct hio *hio;
1422 unsigned int ii, ncomp, ncomps;
1423
1424 ncomps = HAST_NCOMPONENTS;
1425
1426 for (;;) {
1427 pjdlog_debug(2, "ggate_send: Taking request.");
1428 QUEUE_TAKE2(hio, done);
1429 pjdlog_debug(2, "ggate_send: (%p) Got request.", hio);
1430 ggio = &hio->hio_ggio;
1431 for (ii = 0; ii < ncomps; ii++) {
1432 if (hio->hio_errors[ii] == 0) {
1433 /*
1434 * One successful request is enough to declare
1435 * success.
1436 */
1437 ggio->gctl_error = 0;
1438 break;
1439 }
1440 }
1441 if (ii == ncomps) {
1442 /*
1443 * None of the requests were successful.
1444 * Use first error.
1445 */
1446 ggio->gctl_error = hio->hio_errors[0];
1447 }
1448 if (ggio->gctl_error == 0 && ggio->gctl_cmd == BIO_WRITE) {
1449 mtx_lock(&res->hr_amp_lock);
1450 activemap_write_complete(res->hr_amp,
1451 ggio->gctl_offset, ggio->gctl_length);
1452 mtx_unlock(&res->hr_amp_lock);
1453 }
1454 if (ggio->gctl_cmd == BIO_WRITE) {
1455 /*
1456 * Unlock range we locked.
1457 */
1458 mtx_lock(&range_lock);
1459 rangelock_del(range_regular, ggio->gctl_offset,
1460 ggio->gctl_length);
1461 if (range_sync_wait)
1462 cv_signal(&range_sync_cond);
1463 mtx_unlock(&range_lock);
1464 /*
1465 * Bump local count if this is first write after
1466 * connection failure with remote node.
1467 */
1468 ncomp = 1;
1469 rw_rlock(&hio_remote_lock[ncomp]);
1470 if (!ISCONNECTED(res, ncomp)) {
1471 mtx_lock(&metadata_lock);
1472 if (res->hr_primary_localcnt ==
1473 res->hr_secondary_remotecnt) {
1474 res->hr_primary_localcnt++;
1475 pjdlog_debug(1,
1476 "Increasing localcnt to %ju.",
1477 (uintmax_t)res->hr_primary_localcnt);
1478 (void)metadata_write(res);
1479 }
1480 mtx_unlock(&metadata_lock);
1481 }
1482 rw_unlock(&hio_remote_lock[ncomp]);
1483 }
1484 if (ioctl(res->hr_ggatefd, G_GATE_CMD_DONE, ggio) < 0)
1485 primary_exit(EX_OSERR, "G_GATE_CMD_DONE failed");
1486 pjdlog_debug(2,
1487 "ggate_send: (%p) Moving request to the free queue.", hio);
1488 QUEUE_INSERT2(hio, free);
1489 }
1490 /* NOTREACHED */
1491 return (NULL);
1492}
1493
1494/*
1495 * Thread synchronize local and remote components.
1496 */
1497static void *
1498sync_thread(void *arg __unused)
1499{
1500 struct hast_resource *res = arg;
1501 struct hio *hio;
1502 struct g_gate_ctl_io *ggio;
1503 unsigned int ii, ncomp, ncomps;
1504 off_t offset, length, synced;
1505 bool dorewind;
1506 int syncext;
1507
1508 ncomps = HAST_NCOMPONENTS;
1509 dorewind = true;
1510 synced = 0;
1511 offset = -1;
1512
1513 for (;;) {
1514 mtx_lock(&sync_lock);
1515 if (offset >= 0 && !sync_inprogress) {
1516 pjdlog_info("Synchronization interrupted. "
1517 "%jd bytes synchronized so far.",
1518 (intmax_t)synced);
1519 event_send(res, EVENT_SYNCINTR);
1520 }
1521 while (!sync_inprogress) {
1522 dorewind = true;
1523 synced = 0;
1524 cv_wait(&sync_cond, &sync_lock);
1525 }
1526 mtx_unlock(&sync_lock);
1527 /*
1528 * Obtain offset at which we should synchronize.
1529 * Rewind synchronization if needed.
1530 */
1531 mtx_lock(&res->hr_amp_lock);
1532 if (dorewind)
1533 activemap_sync_rewind(res->hr_amp);
1534 offset = activemap_sync_offset(res->hr_amp, &length, &syncext);
1535 if (syncext != -1) {
1536 /*
1537 * We synchronized entire syncext extent, we can mark
1538 * it as clean now.
1539 */
1540 if (activemap_extent_complete(res->hr_amp, syncext))
1541 (void)hast_activemap_flush(res);
1542 }
1543 mtx_unlock(&res->hr_amp_lock);
1544 if (dorewind) {
1545 dorewind = false;
1546 if (offset < 0)
1547 pjdlog_info("Nodes are in sync.");
1548 else {
1549 pjdlog_info("Synchronization started. %ju bytes to go.",
1550 (uintmax_t)(res->hr_extentsize *
1551 activemap_ndirty(res->hr_amp)));
1552 event_send(res, EVENT_SYNCSTART);
1553 }
1554 }
1555 if (offset < 0) {
1556 sync_stop();
1557 pjdlog_debug(1, "Nothing to synchronize.");
1558 /*
1559 * Synchronization complete, make both localcnt and
1560 * remotecnt equal.
1561 */
1562 ncomp = 1;
1563 rw_rlock(&hio_remote_lock[ncomp]);
1564 if (ISCONNECTED(res, ncomp)) {
1565 if (synced > 0) {
1566 pjdlog_info("Synchronization complete. "
1567 "%jd bytes synchronized.",
1568 (intmax_t)synced);
1569 event_send(res, EVENT_SYNCDONE);
1570 }
1571 mtx_lock(&metadata_lock);
1572 res->hr_syncsrc = HAST_SYNCSRC_UNDEF;
1573 res->hr_primary_localcnt =
1574 res->hr_secondary_localcnt;
1575 res->hr_primary_remotecnt =
1576 res->hr_secondary_remotecnt;
1577 pjdlog_debug(1,
1578 "Setting localcnt to %ju and remotecnt to %ju.",
1579 (uintmax_t)res->hr_primary_localcnt,
1580 (uintmax_t)res->hr_secondary_localcnt);
1581 (void)metadata_write(res);
1582 mtx_unlock(&metadata_lock);
1583 }
1584 rw_unlock(&hio_remote_lock[ncomp]);
1585 continue;
1586 }
1587 pjdlog_debug(2, "sync: Taking free request.");
1588 QUEUE_TAKE2(hio, free);
1589 pjdlog_debug(2, "sync: (%p) Got free request.", hio);
1590 /*
1591 * Lock the range we are going to synchronize. We don't want
1592 * race where someone writes between our read and write.
1593 */
1594 for (;;) {
1595 mtx_lock(&range_lock);
1596 if (rangelock_islocked(range_regular, offset, length)) {
1597 pjdlog_debug(2,
1598 "sync: Range offset=%jd length=%jd locked.",
1599 (intmax_t)offset, (intmax_t)length);
1600 range_sync_wait = true;
1601 cv_wait(&range_sync_cond, &range_lock);
1602 range_sync_wait = false;
1603 mtx_unlock(&range_lock);
1604 continue;
1605 }
1606 if (rangelock_add(range_sync, offset, length) < 0) {
1607 mtx_unlock(&range_lock);
1608 pjdlog_debug(2,
1609 "sync: Range offset=%jd length=%jd is already locked, waiting.",
1610 (intmax_t)offset, (intmax_t)length);
1611 sleep(1);
1612 continue;
1613 }
1614 mtx_unlock(&range_lock);
1615 break;
1616 }
1617 /*
1618 * First read the data from synchronization source.
1619 */
1620 SYNCREQ(hio);
1621 ggio = &hio->hio_ggio;
1622 ggio->gctl_cmd = BIO_READ;
1623 ggio->gctl_offset = offset;
1624 ggio->gctl_length = length;
1625 ggio->gctl_error = 0;
1626 for (ii = 0; ii < ncomps; ii++)
1627 hio->hio_errors[ii] = EINVAL;
1628 reqlog(LOG_DEBUG, 2, ggio, "sync: (%p) Sending sync request: ",
1629 hio);
1630 pjdlog_debug(2, "sync: (%p) Moving request to the send queue.",
1631 hio);
1632 mtx_lock(&metadata_lock);
1633 if (res->hr_syncsrc == HAST_SYNCSRC_PRIMARY) {
1634 /*
1635 * This range is up-to-date on local component,
1636 * so handle request locally.
1637 */
1638 /* Local component is 0 for now. */
1639 ncomp = 0;
1640 } else /* if (res->hr_syncsrc == HAST_SYNCSRC_SECONDARY) */ {
1641 assert(res->hr_syncsrc == HAST_SYNCSRC_SECONDARY);
1642 /*
1643 * This range is out-of-date on local component,
1644 * so send request to the remote node.
1645 */
1646 /* Remote component is 1 for now. */
1647 ncomp = 1;
1648 }
1649 mtx_unlock(&metadata_lock);
1650 refcount_init(&hio->hio_countdown, 1);
1651 QUEUE_INSERT1(hio, send, ncomp);
1652
1653 /*
1654 * Let's wait for READ to finish.
1655 */
1656 mtx_lock(&sync_lock);
1657 while (!ISSYNCREQDONE(hio))
1658 cv_wait(&sync_cond, &sync_lock);
1659 mtx_unlock(&sync_lock);
1660
1661 if (hio->hio_errors[ncomp] != 0) {
1662 pjdlog_error("Unable to read synchronization data: %s.",
1663 strerror(hio->hio_errors[ncomp]));
1664 goto free_queue;
1665 }
1666
1667 /*
1668 * We read the data from synchronization source, now write it
1669 * to synchronization target.
1670 */
1671 SYNCREQ(hio);
1672 ggio->gctl_cmd = BIO_WRITE;
1673 for (ii = 0; ii < ncomps; ii++)
1674 hio->hio_errors[ii] = EINVAL;
1675 reqlog(LOG_DEBUG, 2, ggio, "sync: (%p) Sending sync request: ",
1676 hio);
1677 pjdlog_debug(2, "sync: (%p) Moving request to the send queue.",
1678 hio);
1679 mtx_lock(&metadata_lock);
1680 if (res->hr_syncsrc == HAST_SYNCSRC_PRIMARY) {
1681 /*
1682 * This range is up-to-date on local component,
1683 * so we update remote component.
1684 */
1685 /* Remote component is 1 for now. */
1686 ncomp = 1;
1687 } else /* if (res->hr_syncsrc == HAST_SYNCSRC_SECONDARY) */ {
1688 assert(res->hr_syncsrc == HAST_SYNCSRC_SECONDARY);
1689 /*
1690 * This range is out-of-date on local component,
1691 * so we update it.
1692 */
1693 /* Local component is 0 for now. */
1694 ncomp = 0;
1695 }
1696 mtx_unlock(&metadata_lock);
1697
1698 pjdlog_debug(2, "sync: (%p) Moving request to the send queues.",
1699 hio);
1700 refcount_init(&hio->hio_countdown, 1);
1701 QUEUE_INSERT1(hio, send, ncomp);
1702
1703 /*
1704 * Let's wait for WRITE to finish.
1705 */
1706 mtx_lock(&sync_lock);
1707 while (!ISSYNCREQDONE(hio))
1708 cv_wait(&sync_cond, &sync_lock);
1709 mtx_unlock(&sync_lock);
1710
1711 if (hio->hio_errors[ncomp] != 0) {
1712 pjdlog_error("Unable to write synchronization data: %s.",
1713 strerror(hio->hio_errors[ncomp]));
1714 goto free_queue;
1715 }
1716
1717 synced += length;
1718free_queue:
1719 mtx_lock(&range_lock);
1720 rangelock_del(range_sync, offset, length);
1721 if (range_regular_wait)
1722 cv_signal(&range_regular_cond);
1723 mtx_unlock(&range_lock);
1724 pjdlog_debug(2, "sync: (%p) Moving request to the free queue.",
1725 hio);
1726 QUEUE_INSERT2(hio, free);
1727 }
1728 /* NOTREACHED */
1729 return (NULL);
1730}
1731
1732static void
1733config_reload(void)
1734{
1735 struct hastd_config *newcfg;
1736 struct hast_resource *res;
1737 unsigned int ii, ncomps;
1738 int modified;
1739
1740 pjdlog_info("Reloading configuration...");
1741
1742 ncomps = HAST_NCOMPONENTS;
1743
1744 newcfg = yy_config_parse(cfgpath, false);
1745 if (newcfg == NULL)
1746 goto failed;
1747
1748 TAILQ_FOREACH(res, &newcfg->hc_resources, hr_next) {
1749 if (strcmp(res->hr_name, gres->hr_name) == 0)
1750 break;
1751 }
1752 /*
1753 * If resource was removed from the configuration file, resource
1754 * name, provider name or path to local component was modified we
1755 * shouldn't be here. This means that someone modified configuration
1756 * file and send SIGHUP to us instead of main hastd process.
1757 * Log advice and ignore the signal.
1758 */
1759 if (res == NULL || strcmp(gres->hr_name, res->hr_name) != 0 ||
1760 strcmp(gres->hr_provname, res->hr_provname) != 0 ||
1761 strcmp(gres->hr_localpath, res->hr_localpath) != 0) {
1762 pjdlog_warning("To reload configuration send SIGHUP to the main hastd process (pid %u).",
1763 (unsigned int)getppid());
1764 goto failed;
1765 }
1766
1767#define MODIFIED_REMOTEADDR 0x1
1768#define MODIFIED_REPLICATION 0x2
1769#define MODIFIED_TIMEOUT 0x4
1770#define MODIFIED_EXEC 0x8
1771 modified = 0;
1772 if (strcmp(gres->hr_remoteaddr, res->hr_remoteaddr) != 0) {
1773 /*
1774 * Don't copy res->hr_remoteaddr to gres just yet.
1775 * We want remote_close() to log disconnect from the old
1776 * addresses, not from the new ones.
1777 */
1778 modified |= MODIFIED_REMOTEADDR;
1779 }
1780 if (gres->hr_replication != res->hr_replication) {
1781 gres->hr_replication = res->hr_replication;
1782 modified |= MODIFIED_REPLICATION;
1783 }
1784 if (gres->hr_timeout != res->hr_timeout) {
1785 gres->hr_timeout = res->hr_timeout;
1786 modified |= MODIFIED_TIMEOUT;
1787 }
1788 if (strcmp(gres->hr_exec, res->hr_exec) != 0) {
1789 strlcpy(gres->hr_exec, res->hr_exec, sizeof(gres->hr_exec));
1790 modified |= MODIFIED_EXEC;
1791 }
1792 /*
1793 * If only timeout was modified we only need to change it without
1794 * reconnecting.
1795 */
1796 if (modified == MODIFIED_TIMEOUT) {
1797 for (ii = 0; ii < ncomps; ii++) {
1798 if (!ISREMOTE(ii))
1799 continue;
1800 rw_rlock(&hio_remote_lock[ii]);
1801 if (!ISCONNECTED(gres, ii)) {
1802 rw_unlock(&hio_remote_lock[ii]);
1803 continue;
1804 }
1805 rw_unlock(&hio_remote_lock[ii]);
1806 if (proto_timeout(gres->hr_remotein,
1807 gres->hr_timeout) < 0) {
1808 pjdlog_errno(LOG_WARNING,
1809 "Unable to set connection timeout");
1810 }
1811 if (proto_timeout(gres->hr_remoteout,
1812 gres->hr_timeout) < 0) {
1813 pjdlog_errno(LOG_WARNING,
1814 "Unable to set connection timeout");
1815 }
1816 }
1817 } else if ((modified &
1818 (MODIFIED_REMOTEADDR | MODIFIED_REPLICATION)) != 0) {
1819 for (ii = 0; ii < ncomps; ii++) {
1820 if (!ISREMOTE(ii))
1821 continue;
1822 remote_close(gres, ii);
1823 }
1824 if (modified & MODIFIED_REMOTEADDR) {
1825 strlcpy(gres->hr_remoteaddr, res->hr_remoteaddr,
1826 sizeof(gres->hr_remoteaddr));
1827 }
1828 }
1829#undef MODIFIED_REMOTEADDR
1830#undef MODIFIED_REPLICATION
1831#undef MODIFIED_TIMEOUT
1832#undef MODIFIED_EXEC
1833
1834 pjdlog_info("Configuration reloaded successfully.");
1835 return;
1836failed:
1837 if (newcfg != NULL) {
1838 if (newcfg->hc_controlconn != NULL)
1839 proto_close(newcfg->hc_controlconn);
1840 if (newcfg->hc_listenconn != NULL)
1841 proto_close(newcfg->hc_listenconn);
1842 yy_config_free(newcfg);
1843 }
1844 pjdlog_warning("Configuration not reloaded.");
1845}
1846
1847static void
1848keepalive_send(struct hast_resource *res, unsigned int ncomp)
1849{
1850 struct nv *nv;
1851
1852 nv = nv_alloc();
1853 nv_add_uint8(nv, HIO_KEEPALIVE, "cmd");
1854 if (nv_error(nv) != 0) {
1855 nv_free(nv);
1856 pjdlog_debug(1,
1857 "keepalive_send: Unable to prepare header to send.");
1858 return;
1859 }
1860 if (hast_proto_send(res, res->hr_remoteout, nv, NULL, 0) < 0) {
1861 pjdlog_common(LOG_DEBUG, 1, errno,
1862 "keepalive_send: Unable to send request");
1863 nv_free(nv);
1864 rw_unlock(&hio_remote_lock[ncomp]);
1865 remote_close(res, ncomp);
1866 rw_rlock(&hio_remote_lock[ncomp]);
1867 return;
1868 }
1869 nv_free(nv);
1870 pjdlog_debug(2, "keepalive_send: Request sent.");
1871}
1872
1873static void
1874guard_one(struct hast_resource *res, unsigned int ncomp)
1875{
1876 struct proto_conn *in, *out;
1877
1878 if (!ISREMOTE(ncomp))
1879 return;
1880
1881 rw_rlock(&hio_remote_lock[ncomp]);
1882
1883 if (!real_remote(res)) {
1884 rw_unlock(&hio_remote_lock[ncomp]);
1885 return;
1886 }
1887
1888 if (ISCONNECTED(res, ncomp)) {
1889 assert(res->hr_remotein != NULL);
1890 assert(res->hr_remoteout != NULL);
1891 keepalive_send(res, ncomp);
1892 }
1893
1894 if (ISCONNECTED(res, ncomp)) {
1895 assert(res->hr_remotein != NULL);
1896 assert(res->hr_remoteout != NULL);
1897 rw_unlock(&hio_remote_lock[ncomp]);
1898 pjdlog_debug(2, "remote_guard: Connection to %s is ok.",
1899 res->hr_remoteaddr);
1900 return;
1901 }
1902
1903 assert(res->hr_remotein == NULL);
1904 assert(res->hr_remoteout == NULL);
1905 /*
1906 * Upgrade the lock. It doesn't have to be atomic as no other thread
1907 * can change connection status from disconnected to connected.
1908 */
1909 rw_unlock(&hio_remote_lock[ncomp]);
1910 pjdlog_debug(2, "remote_guard: Reconnecting to %s.",
1911 res->hr_remoteaddr);
1912 in = out = NULL;
1913 if (init_remote(res, &in, &out)) {
1914 rw_wlock(&hio_remote_lock[ncomp]);
1915 assert(res->hr_remotein == NULL);
1916 assert(res->hr_remoteout == NULL);
1917 assert(in != NULL && out != NULL);
1918 res->hr_remotein = in;
1919 res->hr_remoteout = out;
1920 rw_unlock(&hio_remote_lock[ncomp]);
1921 pjdlog_info("Successfully reconnected to %s.",
1922 res->hr_remoteaddr);
1923 sync_start();
1924 } else {
1925 /* Both connections should be NULL. */
1926 assert(res->hr_remotein == NULL);
1927 assert(res->hr_remoteout == NULL);
1928 assert(in == NULL && out == NULL);
1929 pjdlog_debug(2, "remote_guard: Reconnect to %s failed.",
1930 res->hr_remoteaddr);
1931 }
1932}
1933
1934/*
1935 * Thread guards remote connections and reconnects when needed, handles
1936 * signals, etc.
1937 */
1938static void *
1939guard_thread(void *arg)
1940{
1941 struct hast_resource *res = arg;
1942 unsigned int ii, ncomps;
1943 struct timespec timeout;
1944 time_t lastcheck, now;
1945 sigset_t mask;
1946 int signo;
1947
1948 ncomps = HAST_NCOMPONENTS;
1949 lastcheck = time(NULL);
1950
1951 PJDLOG_VERIFY(sigemptyset(&mask) == 0);
1952 PJDLOG_VERIFY(sigaddset(&mask, SIGHUP) == 0);
1953 PJDLOG_VERIFY(sigaddset(&mask, SIGINT) == 0);
1954 PJDLOG_VERIFY(sigaddset(&mask, SIGTERM) == 0);
1955
1956 timeout.tv_nsec = 0;
1957 signo = -1;
1958
1959 for (;;) {
1960 switch (signo) {
1961 case SIGHUP:
1962 config_reload();
1963 break;
1964 case SIGINT:
1965 case SIGTERM:
1966 sigexit_received = true;
1967 primary_exitx(EX_OK,
1968 "Termination signal received, exiting.");
1969 break;
1970 default:
1971 break;
1972 }
1973
1974 pjdlog_debug(2, "remote_guard: Checking connections.");
1975 now = time(NULL);
1976 if (lastcheck + RETRY_SLEEP <= now) {
1977 for (ii = 0; ii < ncomps; ii++)
1978 guard_one(res, ii);
1979 lastcheck = now;
1980 }
1981 timeout.tv_sec = RETRY_SLEEP;
1982 signo = sigtimedwait(&mask, NULL, &timeout);
1983 }
1984 /* NOTREACHED */
1985 return (NULL);
1986}
650 pjdlog_info("Connected to %s.", res->hr_remoteaddr);
651 if (inp != NULL && outp != NULL) {
652 *inp = in;
653 *outp = out;
654 } else {
655 res->hr_remotein = in;
656 res->hr_remoteout = out;
657 }
658 event_send(res, EVENT_CONNECT);
659 return (true);
660close:
661 if (errmsg != NULL && strcmp(errmsg, "Split-brain condition!") == 0)
662 event_send(res, EVENT_SPLITBRAIN);
663 proto_close(out);
664 if (in != NULL)
665 proto_close(in);
666 return (false);
667}
668
669static void
670sync_start(void)
671{
672
673 mtx_lock(&sync_lock);
674 sync_inprogress = true;
675 mtx_unlock(&sync_lock);
676 cv_signal(&sync_cond);
677}
678
679static void
680sync_stop(void)
681{
682
683 mtx_lock(&sync_lock);
684 if (sync_inprogress)
685 sync_inprogress = false;
686 mtx_unlock(&sync_lock);
687}
688
689static void
690init_ggate(struct hast_resource *res)
691{
692 struct g_gate_ctl_create ggiocreate;
693 struct g_gate_ctl_cancel ggiocancel;
694
695 /*
696 * We communicate with ggate via /dev/ggctl. Open it.
697 */
698 res->hr_ggatefd = open("/dev/" G_GATE_CTL_NAME, O_RDWR);
699 if (res->hr_ggatefd < 0)
700 primary_exit(EX_OSFILE, "Unable to open /dev/" G_GATE_CTL_NAME);
701 /*
702 * Create provider before trying to connect, as connection failure
703 * is not critical, but may take some time.
704 */
705 bzero(&ggiocreate, sizeof(ggiocreate));
706 ggiocreate.gctl_version = G_GATE_VERSION;
707 ggiocreate.gctl_mediasize = res->hr_datasize;
708 ggiocreate.gctl_sectorsize = res->hr_local_sectorsize;
709 ggiocreate.gctl_flags = 0;
710 ggiocreate.gctl_maxcount = G_GATE_MAX_QUEUE_SIZE;
711 ggiocreate.gctl_timeout = 0;
712 ggiocreate.gctl_unit = G_GATE_NAME_GIVEN;
713 snprintf(ggiocreate.gctl_name, sizeof(ggiocreate.gctl_name), "hast/%s",
714 res->hr_provname);
715 if (ioctl(res->hr_ggatefd, G_GATE_CMD_CREATE, &ggiocreate) == 0) {
716 pjdlog_info("Device hast/%s created.", res->hr_provname);
717 res->hr_ggateunit = ggiocreate.gctl_unit;
718 return;
719 }
720 if (errno != EEXIST) {
721 primary_exit(EX_OSERR, "Unable to create hast/%s device",
722 res->hr_provname);
723 }
724 pjdlog_debug(1,
725 "Device hast/%s already exists, we will try to take it over.",
726 res->hr_provname);
727 /*
728 * If we received EEXIST, we assume that the process who created the
729 * provider died and didn't clean up. In that case we will start from
730 * where he left of.
731 */
732 bzero(&ggiocancel, sizeof(ggiocancel));
733 ggiocancel.gctl_version = G_GATE_VERSION;
734 ggiocancel.gctl_unit = G_GATE_NAME_GIVEN;
735 snprintf(ggiocancel.gctl_name, sizeof(ggiocancel.gctl_name), "hast/%s",
736 res->hr_provname);
737 if (ioctl(res->hr_ggatefd, G_GATE_CMD_CANCEL, &ggiocancel) == 0) {
738 pjdlog_info("Device hast/%s recovered.", res->hr_provname);
739 res->hr_ggateunit = ggiocancel.gctl_unit;
740 return;
741 }
742 primary_exit(EX_OSERR, "Unable to take over hast/%s device",
743 res->hr_provname);
744}
745
746void
747hastd_primary(struct hast_resource *res)
748{
749 pthread_t td;
750 pid_t pid;
751 int error;
752
753 /*
754 * Create communication channel between parent and child.
755 */
756 if (proto_client("socketpair://", &res->hr_ctrl) < 0) {
757 KEEP_ERRNO((void)pidfile_remove(pfh));
758 pjdlog_exit(EX_OSERR,
759 "Unable to create control sockets between parent and child");
760 }
761 /*
762 * Create communication channel between child and parent.
763 */
764 if (proto_client("socketpair://", &res->hr_event) < 0) {
765 KEEP_ERRNO((void)pidfile_remove(pfh));
766 pjdlog_exit(EX_OSERR,
767 "Unable to create event sockets between child and parent");
768 }
769
770 pid = fork();
771 if (pid < 0) {
772 KEEP_ERRNO((void)pidfile_remove(pfh));
773 pjdlog_exit(EX_TEMPFAIL, "Unable to fork");
774 }
775
776 if (pid > 0) {
777 /* This is parent. */
778 /* Declare that we are receiver. */
779 proto_recv(res->hr_event, NULL, 0);
780 res->hr_workerpid = pid;
781 return;
782 }
783
784 gres = res;
785
786 (void)pidfile_close(pfh);
787 hook_fini();
788
789 setproctitle("%s (primary)", res->hr_name);
790
791 /* Declare that we are sender. */
792 proto_send(res->hr_event, NULL, 0);
793
794 init_local(res);
795 init_ggate(res);
796 init_environment(res);
797 /*
798 * Create the guard thread first, so we can handle signals from the
799 * very begining.
800 */
801 error = pthread_create(&td, NULL, guard_thread, res);
802 assert(error == 0);
803 /*
804 * Create the control thread before sending any event to the parent,
805 * as we can deadlock when parent sends control request to worker,
806 * but worker has no control thread started yet, so parent waits.
807 * In the meantime worker sends an event to the parent, but parent
808 * is unable to handle the event, because it waits for control
809 * request response.
810 */
811 error = pthread_create(&td, NULL, ctrl_thread, res);
812 assert(error == 0);
813 if (real_remote(res) && init_remote(res, NULL, NULL))
814 sync_start();
815 error = pthread_create(&td, NULL, ggate_recv_thread, res);
816 assert(error == 0);
817 error = pthread_create(&td, NULL, local_send_thread, res);
818 assert(error == 0);
819 error = pthread_create(&td, NULL, remote_send_thread, res);
820 assert(error == 0);
821 error = pthread_create(&td, NULL, remote_recv_thread, res);
822 assert(error == 0);
823 error = pthread_create(&td, NULL, ggate_send_thread, res);
824 assert(error == 0);
825 (void)sync_thread(res);
826}
827
828static void
829reqlog(int loglevel, int debuglevel, struct g_gate_ctl_io *ggio, const char *fmt, ...)
830{
831 char msg[1024];
832 va_list ap;
833 int len;
834
835 va_start(ap, fmt);
836 len = vsnprintf(msg, sizeof(msg), fmt, ap);
837 va_end(ap);
838 if ((size_t)len < sizeof(msg)) {
839 switch (ggio->gctl_cmd) {
840 case BIO_READ:
841 (void)snprintf(msg + len, sizeof(msg) - len,
842 "READ(%ju, %ju).", (uintmax_t)ggio->gctl_offset,
843 (uintmax_t)ggio->gctl_length);
844 break;
845 case BIO_DELETE:
846 (void)snprintf(msg + len, sizeof(msg) - len,
847 "DELETE(%ju, %ju).", (uintmax_t)ggio->gctl_offset,
848 (uintmax_t)ggio->gctl_length);
849 break;
850 case BIO_FLUSH:
851 (void)snprintf(msg + len, sizeof(msg) - len, "FLUSH.");
852 break;
853 case BIO_WRITE:
854 (void)snprintf(msg + len, sizeof(msg) - len,
855 "WRITE(%ju, %ju).", (uintmax_t)ggio->gctl_offset,
856 (uintmax_t)ggio->gctl_length);
857 break;
858 default:
859 (void)snprintf(msg + len, sizeof(msg) - len,
860 "UNKNOWN(%u).", (unsigned int)ggio->gctl_cmd);
861 break;
862 }
863 }
864 pjdlog_common(loglevel, debuglevel, -1, "%s", msg);
865}
866
867static void
868remote_close(struct hast_resource *res, int ncomp)
869{
870
871 rw_wlock(&hio_remote_lock[ncomp]);
872 /*
873 * A race is possible between dropping rlock and acquiring wlock -
874 * another thread can close connection in-between.
875 */
876 if (!ISCONNECTED(res, ncomp)) {
877 assert(res->hr_remotein == NULL);
878 assert(res->hr_remoteout == NULL);
879 rw_unlock(&hio_remote_lock[ncomp]);
880 return;
881 }
882
883 assert(res->hr_remotein != NULL);
884 assert(res->hr_remoteout != NULL);
885
886 pjdlog_debug(2, "Closing incoming connection to %s.",
887 res->hr_remoteaddr);
888 proto_close(res->hr_remotein);
889 res->hr_remotein = NULL;
890 pjdlog_debug(2, "Closing outgoing connection to %s.",
891 res->hr_remoteaddr);
892 proto_close(res->hr_remoteout);
893 res->hr_remoteout = NULL;
894
895 rw_unlock(&hio_remote_lock[ncomp]);
896
897 pjdlog_warning("Disconnected from %s.", res->hr_remoteaddr);
898
899 /*
900 * Stop synchronization if in-progress.
901 */
902 sync_stop();
903
904 event_send(res, EVENT_DISCONNECT);
905}
906
907/*
908 * Thread receives ggate I/O requests from the kernel and passes them to
909 * appropriate threads:
910 * WRITE - always goes to both local_send and remote_send threads
911 * READ (when the block is up-to-date on local component) -
912 * only local_send thread
913 * READ (when the block isn't up-to-date on local component) -
914 * only remote_send thread
915 * DELETE - always goes to both local_send and remote_send threads
916 * FLUSH - always goes to both local_send and remote_send threads
917 */
918static void *
919ggate_recv_thread(void *arg)
920{
921 struct hast_resource *res = arg;
922 struct g_gate_ctl_io *ggio;
923 struct hio *hio;
924 unsigned int ii, ncomp, ncomps;
925 int error;
926
927 ncomps = HAST_NCOMPONENTS;
928
929 for (;;) {
930 pjdlog_debug(2, "ggate_recv: Taking free request.");
931 QUEUE_TAKE2(hio, free);
932 pjdlog_debug(2, "ggate_recv: (%p) Got free request.", hio);
933 ggio = &hio->hio_ggio;
934 ggio->gctl_unit = res->hr_ggateunit;
935 ggio->gctl_length = MAXPHYS;
936 ggio->gctl_error = 0;
937 pjdlog_debug(2,
938 "ggate_recv: (%p) Waiting for request from the kernel.",
939 hio);
940 if (ioctl(res->hr_ggatefd, G_GATE_CMD_START, ggio) < 0) {
941 if (sigexit_received)
942 pthread_exit(NULL);
943 primary_exit(EX_OSERR, "G_GATE_CMD_START failed");
944 }
945 error = ggio->gctl_error;
946 switch (error) {
947 case 0:
948 break;
949 case ECANCELED:
950 /* Exit gracefully. */
951 if (!sigexit_received) {
952 pjdlog_debug(2,
953 "ggate_recv: (%p) Received cancel from the kernel.",
954 hio);
955 pjdlog_info("Received cancel from the kernel, exiting.");
956 }
957 pthread_exit(NULL);
958 case ENOMEM:
959 /*
960 * Buffer too small? Impossible, we allocate MAXPHYS
961 * bytes - request can't be bigger than that.
962 */
963 /* FALLTHROUGH */
964 case ENXIO:
965 default:
966 primary_exitx(EX_OSERR, "G_GATE_CMD_START failed: %s.",
967 strerror(error));
968 }
969 for (ii = 0; ii < ncomps; ii++)
970 hio->hio_errors[ii] = EINVAL;
971 reqlog(LOG_DEBUG, 2, ggio,
972 "ggate_recv: (%p) Request received from the kernel: ",
973 hio);
974 /*
975 * Inform all components about new write request.
976 * For read request prefer local component unless the given
977 * range is out-of-date, then use remote component.
978 */
979 switch (ggio->gctl_cmd) {
980 case BIO_READ:
981 pjdlog_debug(2,
982 "ggate_recv: (%p) Moving request to the send queue.",
983 hio);
984 refcount_init(&hio->hio_countdown, 1);
985 mtx_lock(&metadata_lock);
986 if (res->hr_syncsrc == HAST_SYNCSRC_UNDEF ||
987 res->hr_syncsrc == HAST_SYNCSRC_PRIMARY) {
988 /*
989 * This range is up-to-date on local component,
990 * so handle request locally.
991 */
992 /* Local component is 0 for now. */
993 ncomp = 0;
994 } else /* if (res->hr_syncsrc ==
995 HAST_SYNCSRC_SECONDARY) */ {
996 assert(res->hr_syncsrc ==
997 HAST_SYNCSRC_SECONDARY);
998 /*
999 * This range is out-of-date on local component,
1000 * so send request to the remote node.
1001 */
1002 /* Remote component is 1 for now. */
1003 ncomp = 1;
1004 }
1005 mtx_unlock(&metadata_lock);
1006 QUEUE_INSERT1(hio, send, ncomp);
1007 break;
1008 case BIO_WRITE:
1009 for (;;) {
1010 mtx_lock(&range_lock);
1011 if (rangelock_islocked(range_sync,
1012 ggio->gctl_offset, ggio->gctl_length)) {
1013 pjdlog_debug(2,
1014 "regular: Range offset=%jd length=%zu locked.",
1015 (intmax_t)ggio->gctl_offset,
1016 (size_t)ggio->gctl_length);
1017 range_regular_wait = true;
1018 cv_wait(&range_regular_cond, &range_lock);
1019 range_regular_wait = false;
1020 mtx_unlock(&range_lock);
1021 continue;
1022 }
1023 if (rangelock_add(range_regular,
1024 ggio->gctl_offset, ggio->gctl_length) < 0) {
1025 mtx_unlock(&range_lock);
1026 pjdlog_debug(2,
1027 "regular: Range offset=%jd length=%zu is already locked, waiting.",
1028 (intmax_t)ggio->gctl_offset,
1029 (size_t)ggio->gctl_length);
1030 sleep(1);
1031 continue;
1032 }
1033 mtx_unlock(&range_lock);
1034 break;
1035 }
1036 mtx_lock(&res->hr_amp_lock);
1037 if (activemap_write_start(res->hr_amp,
1038 ggio->gctl_offset, ggio->gctl_length)) {
1039 (void)hast_activemap_flush(res);
1040 }
1041 mtx_unlock(&res->hr_amp_lock);
1042 /* FALLTHROUGH */
1043 case BIO_DELETE:
1044 case BIO_FLUSH:
1045 pjdlog_debug(2,
1046 "ggate_recv: (%p) Moving request to the send queues.",
1047 hio);
1048 refcount_init(&hio->hio_countdown, ncomps);
1049 for (ii = 0; ii < ncomps; ii++)
1050 QUEUE_INSERT1(hio, send, ii);
1051 break;
1052 }
1053 }
1054 /* NOTREACHED */
1055 return (NULL);
1056}
1057
1058/*
1059 * Thread reads from or writes to local component.
1060 * If local read fails, it redirects it to remote_send thread.
1061 */
1062static void *
1063local_send_thread(void *arg)
1064{
1065 struct hast_resource *res = arg;
1066 struct g_gate_ctl_io *ggio;
1067 struct hio *hio;
1068 unsigned int ncomp, rncomp;
1069 ssize_t ret;
1070
1071 /* Local component is 0 for now. */
1072 ncomp = 0;
1073 /* Remote component is 1 for now. */
1074 rncomp = 1;
1075
1076 for (;;) {
1077 pjdlog_debug(2, "local_send: Taking request.");
1078 QUEUE_TAKE1(hio, send, ncomp);
1079 pjdlog_debug(2, "local_send: (%p) Got request.", hio);
1080 ggio = &hio->hio_ggio;
1081 switch (ggio->gctl_cmd) {
1082 case BIO_READ:
1083 ret = pread(res->hr_localfd, ggio->gctl_data,
1084 ggio->gctl_length,
1085 ggio->gctl_offset + res->hr_localoff);
1086 if (ret == ggio->gctl_length)
1087 hio->hio_errors[ncomp] = 0;
1088 else {
1089 /*
1090 * If READ failed, try to read from remote node.
1091 */
1092 QUEUE_INSERT1(hio, send, rncomp);
1093 continue;
1094 }
1095 break;
1096 case BIO_WRITE:
1097 ret = pwrite(res->hr_localfd, ggio->gctl_data,
1098 ggio->gctl_length,
1099 ggio->gctl_offset + res->hr_localoff);
1100 if (ret < 0)
1101 hio->hio_errors[ncomp] = errno;
1102 else if (ret != ggio->gctl_length)
1103 hio->hio_errors[ncomp] = EIO;
1104 else
1105 hio->hio_errors[ncomp] = 0;
1106 break;
1107 case BIO_DELETE:
1108 ret = g_delete(res->hr_localfd,
1109 ggio->gctl_offset + res->hr_localoff,
1110 ggio->gctl_length);
1111 if (ret < 0)
1112 hio->hio_errors[ncomp] = errno;
1113 else
1114 hio->hio_errors[ncomp] = 0;
1115 break;
1116 case BIO_FLUSH:
1117 ret = g_flush(res->hr_localfd);
1118 if (ret < 0)
1119 hio->hio_errors[ncomp] = errno;
1120 else
1121 hio->hio_errors[ncomp] = 0;
1122 break;
1123 }
1124 if (refcount_release(&hio->hio_countdown)) {
1125 if (ISSYNCREQ(hio)) {
1126 mtx_lock(&sync_lock);
1127 SYNCREQDONE(hio);
1128 mtx_unlock(&sync_lock);
1129 cv_signal(&sync_cond);
1130 } else {
1131 pjdlog_debug(2,
1132 "local_send: (%p) Moving request to the done queue.",
1133 hio);
1134 QUEUE_INSERT2(hio, done);
1135 }
1136 }
1137 }
1138 /* NOTREACHED */
1139 return (NULL);
1140}
1141
1142/*
1143 * Thread sends request to secondary node.
1144 */
1145static void *
1146remote_send_thread(void *arg)
1147{
1148 struct hast_resource *res = arg;
1149 struct g_gate_ctl_io *ggio;
1150 struct hio *hio;
1151 struct nv *nv;
1152 unsigned int ncomp;
1153 bool wakeup;
1154 uint64_t offset, length;
1155 uint8_t cmd;
1156 void *data;
1157
1158 /* Remote component is 1 for now. */
1159 ncomp = 1;
1160
1161 for (;;) {
1162 pjdlog_debug(2, "remote_send: Taking request.");
1163 QUEUE_TAKE1(hio, send, ncomp);
1164 pjdlog_debug(2, "remote_send: (%p) Got request.", hio);
1165 ggio = &hio->hio_ggio;
1166 switch (ggio->gctl_cmd) {
1167 case BIO_READ:
1168 cmd = HIO_READ;
1169 data = NULL;
1170 offset = ggio->gctl_offset;
1171 length = ggio->gctl_length;
1172 break;
1173 case BIO_WRITE:
1174 cmd = HIO_WRITE;
1175 data = ggio->gctl_data;
1176 offset = ggio->gctl_offset;
1177 length = ggio->gctl_length;
1178 break;
1179 case BIO_DELETE:
1180 cmd = HIO_DELETE;
1181 data = NULL;
1182 offset = ggio->gctl_offset;
1183 length = ggio->gctl_length;
1184 break;
1185 case BIO_FLUSH:
1186 cmd = HIO_FLUSH;
1187 data = NULL;
1188 offset = 0;
1189 length = 0;
1190 break;
1191 default:
1192 assert(!"invalid condition");
1193 abort();
1194 }
1195 nv = nv_alloc();
1196 nv_add_uint8(nv, cmd, "cmd");
1197 nv_add_uint64(nv, (uint64_t)ggio->gctl_seq, "seq");
1198 nv_add_uint64(nv, offset, "offset");
1199 nv_add_uint64(nv, length, "length");
1200 if (nv_error(nv) != 0) {
1201 hio->hio_errors[ncomp] = nv_error(nv);
1202 pjdlog_debug(2,
1203 "remote_send: (%p) Unable to prepare header to send.",
1204 hio);
1205 reqlog(LOG_ERR, 0, ggio,
1206 "Unable to prepare header to send (%s): ",
1207 strerror(nv_error(nv)));
1208 /* Move failed request immediately to the done queue. */
1209 goto done_queue;
1210 }
1211 pjdlog_debug(2,
1212 "remote_send: (%p) Moving request to the recv queue.",
1213 hio);
1214 /*
1215 * Protect connection from disappearing.
1216 */
1217 rw_rlock(&hio_remote_lock[ncomp]);
1218 if (!ISCONNECTED(res, ncomp)) {
1219 rw_unlock(&hio_remote_lock[ncomp]);
1220 hio->hio_errors[ncomp] = ENOTCONN;
1221 goto done_queue;
1222 }
1223 /*
1224 * Move the request to recv queue before sending it, because
1225 * in different order we can get reply before we move request
1226 * to recv queue.
1227 */
1228 mtx_lock(&hio_recv_list_lock[ncomp]);
1229 wakeup = TAILQ_EMPTY(&hio_recv_list[ncomp]);
1230 TAILQ_INSERT_TAIL(&hio_recv_list[ncomp], hio, hio_next[ncomp]);
1231 mtx_unlock(&hio_recv_list_lock[ncomp]);
1232 if (hast_proto_send(res, res->hr_remoteout, nv, data,
1233 data != NULL ? length : 0) < 0) {
1234 hio->hio_errors[ncomp] = errno;
1235 rw_unlock(&hio_remote_lock[ncomp]);
1236 pjdlog_debug(2,
1237 "remote_send: (%p) Unable to send request.", hio);
1238 reqlog(LOG_ERR, 0, ggio,
1239 "Unable to send request (%s): ",
1240 strerror(hio->hio_errors[ncomp]));
1241 remote_close(res, ncomp);
1242 /*
1243 * Take request back from the receive queue and move
1244 * it immediately to the done queue.
1245 */
1246 mtx_lock(&hio_recv_list_lock[ncomp]);
1247 TAILQ_REMOVE(&hio_recv_list[ncomp], hio, hio_next[ncomp]);
1248 mtx_unlock(&hio_recv_list_lock[ncomp]);
1249 goto done_queue;
1250 }
1251 rw_unlock(&hio_remote_lock[ncomp]);
1252 nv_free(nv);
1253 if (wakeup)
1254 cv_signal(&hio_recv_list_cond[ncomp]);
1255 continue;
1256done_queue:
1257 nv_free(nv);
1258 if (ISSYNCREQ(hio)) {
1259 if (!refcount_release(&hio->hio_countdown))
1260 continue;
1261 mtx_lock(&sync_lock);
1262 SYNCREQDONE(hio);
1263 mtx_unlock(&sync_lock);
1264 cv_signal(&sync_cond);
1265 continue;
1266 }
1267 if (ggio->gctl_cmd == BIO_WRITE) {
1268 mtx_lock(&res->hr_amp_lock);
1269 if (activemap_need_sync(res->hr_amp, ggio->gctl_offset,
1270 ggio->gctl_length)) {
1271 (void)hast_activemap_flush(res);
1272 }
1273 mtx_unlock(&res->hr_amp_lock);
1274 }
1275 if (!refcount_release(&hio->hio_countdown))
1276 continue;
1277 pjdlog_debug(2,
1278 "remote_send: (%p) Moving request to the done queue.",
1279 hio);
1280 QUEUE_INSERT2(hio, done);
1281 }
1282 /* NOTREACHED */
1283 return (NULL);
1284}
1285
1286/*
1287 * Thread receives answer from secondary node and passes it to ggate_send
1288 * thread.
1289 */
1290static void *
1291remote_recv_thread(void *arg)
1292{
1293 struct hast_resource *res = arg;
1294 struct g_gate_ctl_io *ggio;
1295 struct hio *hio;
1296 struct nv *nv;
1297 unsigned int ncomp;
1298 uint64_t seq;
1299 int error;
1300
1301 /* Remote component is 1 for now. */
1302 ncomp = 1;
1303
1304 for (;;) {
1305 /* Wait until there is anything to receive. */
1306 mtx_lock(&hio_recv_list_lock[ncomp]);
1307 while (TAILQ_EMPTY(&hio_recv_list[ncomp])) {
1308 pjdlog_debug(2, "remote_recv: No requests, waiting.");
1309 cv_wait(&hio_recv_list_cond[ncomp],
1310 &hio_recv_list_lock[ncomp]);
1311 }
1312 mtx_unlock(&hio_recv_list_lock[ncomp]);
1313 rw_rlock(&hio_remote_lock[ncomp]);
1314 if (!ISCONNECTED(res, ncomp)) {
1315 rw_unlock(&hio_remote_lock[ncomp]);
1316 /*
1317 * Connection is dead, so move all pending requests to
1318 * the done queue (one-by-one).
1319 */
1320 mtx_lock(&hio_recv_list_lock[ncomp]);
1321 hio = TAILQ_FIRST(&hio_recv_list[ncomp]);
1322 assert(hio != NULL);
1323 TAILQ_REMOVE(&hio_recv_list[ncomp], hio,
1324 hio_next[ncomp]);
1325 mtx_unlock(&hio_recv_list_lock[ncomp]);
1326 goto done_queue;
1327 }
1328 if (hast_proto_recv_hdr(res->hr_remotein, &nv) < 0) {
1329 pjdlog_errno(LOG_ERR,
1330 "Unable to receive reply header");
1331 rw_unlock(&hio_remote_lock[ncomp]);
1332 remote_close(res, ncomp);
1333 continue;
1334 }
1335 rw_unlock(&hio_remote_lock[ncomp]);
1336 seq = nv_get_uint64(nv, "seq");
1337 if (seq == 0) {
1338 pjdlog_error("Header contains no 'seq' field.");
1339 nv_free(nv);
1340 continue;
1341 }
1342 mtx_lock(&hio_recv_list_lock[ncomp]);
1343 TAILQ_FOREACH(hio, &hio_recv_list[ncomp], hio_next[ncomp]) {
1344 if (hio->hio_ggio.gctl_seq == seq) {
1345 TAILQ_REMOVE(&hio_recv_list[ncomp], hio,
1346 hio_next[ncomp]);
1347 break;
1348 }
1349 }
1350 mtx_unlock(&hio_recv_list_lock[ncomp]);
1351 if (hio == NULL) {
1352 pjdlog_error("Found no request matching received 'seq' field (%ju).",
1353 (uintmax_t)seq);
1354 nv_free(nv);
1355 continue;
1356 }
1357 error = nv_get_int16(nv, "error");
1358 if (error != 0) {
1359 /* Request failed on remote side. */
1360 hio->hio_errors[ncomp] = 0;
1361 nv_free(nv);
1362 goto done_queue;
1363 }
1364 ggio = &hio->hio_ggio;
1365 switch (ggio->gctl_cmd) {
1366 case BIO_READ:
1367 rw_rlock(&hio_remote_lock[ncomp]);
1368 if (!ISCONNECTED(res, ncomp)) {
1369 rw_unlock(&hio_remote_lock[ncomp]);
1370 nv_free(nv);
1371 goto done_queue;
1372 }
1373 if (hast_proto_recv_data(res, res->hr_remotein, nv,
1374 ggio->gctl_data, ggio->gctl_length) < 0) {
1375 hio->hio_errors[ncomp] = errno;
1376 pjdlog_errno(LOG_ERR,
1377 "Unable to receive reply data");
1378 rw_unlock(&hio_remote_lock[ncomp]);
1379 nv_free(nv);
1380 remote_close(res, ncomp);
1381 goto done_queue;
1382 }
1383 rw_unlock(&hio_remote_lock[ncomp]);
1384 break;
1385 case BIO_WRITE:
1386 case BIO_DELETE:
1387 case BIO_FLUSH:
1388 break;
1389 default:
1390 assert(!"invalid condition");
1391 abort();
1392 }
1393 hio->hio_errors[ncomp] = 0;
1394 nv_free(nv);
1395done_queue:
1396 if (refcount_release(&hio->hio_countdown)) {
1397 if (ISSYNCREQ(hio)) {
1398 mtx_lock(&sync_lock);
1399 SYNCREQDONE(hio);
1400 mtx_unlock(&sync_lock);
1401 cv_signal(&sync_cond);
1402 } else {
1403 pjdlog_debug(2,
1404 "remote_recv: (%p) Moving request to the done queue.",
1405 hio);
1406 QUEUE_INSERT2(hio, done);
1407 }
1408 }
1409 }
1410 /* NOTREACHED */
1411 return (NULL);
1412}
1413
1414/*
1415 * Thread sends answer to the kernel.
1416 */
1417static void *
1418ggate_send_thread(void *arg)
1419{
1420 struct hast_resource *res = arg;
1421 struct g_gate_ctl_io *ggio;
1422 struct hio *hio;
1423 unsigned int ii, ncomp, ncomps;
1424
1425 ncomps = HAST_NCOMPONENTS;
1426
1427 for (;;) {
1428 pjdlog_debug(2, "ggate_send: Taking request.");
1429 QUEUE_TAKE2(hio, done);
1430 pjdlog_debug(2, "ggate_send: (%p) Got request.", hio);
1431 ggio = &hio->hio_ggio;
1432 for (ii = 0; ii < ncomps; ii++) {
1433 if (hio->hio_errors[ii] == 0) {
1434 /*
1435 * One successful request is enough to declare
1436 * success.
1437 */
1438 ggio->gctl_error = 0;
1439 break;
1440 }
1441 }
1442 if (ii == ncomps) {
1443 /*
1444 * None of the requests were successful.
1445 * Use first error.
1446 */
1447 ggio->gctl_error = hio->hio_errors[0];
1448 }
1449 if (ggio->gctl_error == 0 && ggio->gctl_cmd == BIO_WRITE) {
1450 mtx_lock(&res->hr_amp_lock);
1451 activemap_write_complete(res->hr_amp,
1452 ggio->gctl_offset, ggio->gctl_length);
1453 mtx_unlock(&res->hr_amp_lock);
1454 }
1455 if (ggio->gctl_cmd == BIO_WRITE) {
1456 /*
1457 * Unlock range we locked.
1458 */
1459 mtx_lock(&range_lock);
1460 rangelock_del(range_regular, ggio->gctl_offset,
1461 ggio->gctl_length);
1462 if (range_sync_wait)
1463 cv_signal(&range_sync_cond);
1464 mtx_unlock(&range_lock);
1465 /*
1466 * Bump local count if this is first write after
1467 * connection failure with remote node.
1468 */
1469 ncomp = 1;
1470 rw_rlock(&hio_remote_lock[ncomp]);
1471 if (!ISCONNECTED(res, ncomp)) {
1472 mtx_lock(&metadata_lock);
1473 if (res->hr_primary_localcnt ==
1474 res->hr_secondary_remotecnt) {
1475 res->hr_primary_localcnt++;
1476 pjdlog_debug(1,
1477 "Increasing localcnt to %ju.",
1478 (uintmax_t)res->hr_primary_localcnt);
1479 (void)metadata_write(res);
1480 }
1481 mtx_unlock(&metadata_lock);
1482 }
1483 rw_unlock(&hio_remote_lock[ncomp]);
1484 }
1485 if (ioctl(res->hr_ggatefd, G_GATE_CMD_DONE, ggio) < 0)
1486 primary_exit(EX_OSERR, "G_GATE_CMD_DONE failed");
1487 pjdlog_debug(2,
1488 "ggate_send: (%p) Moving request to the free queue.", hio);
1489 QUEUE_INSERT2(hio, free);
1490 }
1491 /* NOTREACHED */
1492 return (NULL);
1493}
1494
1495/*
1496 * Thread synchronize local and remote components.
1497 */
1498static void *
1499sync_thread(void *arg __unused)
1500{
1501 struct hast_resource *res = arg;
1502 struct hio *hio;
1503 struct g_gate_ctl_io *ggio;
1504 unsigned int ii, ncomp, ncomps;
1505 off_t offset, length, synced;
1506 bool dorewind;
1507 int syncext;
1508
1509 ncomps = HAST_NCOMPONENTS;
1510 dorewind = true;
1511 synced = 0;
1512 offset = -1;
1513
1514 for (;;) {
1515 mtx_lock(&sync_lock);
1516 if (offset >= 0 && !sync_inprogress) {
1517 pjdlog_info("Synchronization interrupted. "
1518 "%jd bytes synchronized so far.",
1519 (intmax_t)synced);
1520 event_send(res, EVENT_SYNCINTR);
1521 }
1522 while (!sync_inprogress) {
1523 dorewind = true;
1524 synced = 0;
1525 cv_wait(&sync_cond, &sync_lock);
1526 }
1527 mtx_unlock(&sync_lock);
1528 /*
1529 * Obtain offset at which we should synchronize.
1530 * Rewind synchronization if needed.
1531 */
1532 mtx_lock(&res->hr_amp_lock);
1533 if (dorewind)
1534 activemap_sync_rewind(res->hr_amp);
1535 offset = activemap_sync_offset(res->hr_amp, &length, &syncext);
1536 if (syncext != -1) {
1537 /*
1538 * We synchronized entire syncext extent, we can mark
1539 * it as clean now.
1540 */
1541 if (activemap_extent_complete(res->hr_amp, syncext))
1542 (void)hast_activemap_flush(res);
1543 }
1544 mtx_unlock(&res->hr_amp_lock);
1545 if (dorewind) {
1546 dorewind = false;
1547 if (offset < 0)
1548 pjdlog_info("Nodes are in sync.");
1549 else {
1550 pjdlog_info("Synchronization started. %ju bytes to go.",
1551 (uintmax_t)(res->hr_extentsize *
1552 activemap_ndirty(res->hr_amp)));
1553 event_send(res, EVENT_SYNCSTART);
1554 }
1555 }
1556 if (offset < 0) {
1557 sync_stop();
1558 pjdlog_debug(1, "Nothing to synchronize.");
1559 /*
1560 * Synchronization complete, make both localcnt and
1561 * remotecnt equal.
1562 */
1563 ncomp = 1;
1564 rw_rlock(&hio_remote_lock[ncomp]);
1565 if (ISCONNECTED(res, ncomp)) {
1566 if (synced > 0) {
1567 pjdlog_info("Synchronization complete. "
1568 "%jd bytes synchronized.",
1569 (intmax_t)synced);
1570 event_send(res, EVENT_SYNCDONE);
1571 }
1572 mtx_lock(&metadata_lock);
1573 res->hr_syncsrc = HAST_SYNCSRC_UNDEF;
1574 res->hr_primary_localcnt =
1575 res->hr_secondary_localcnt;
1576 res->hr_primary_remotecnt =
1577 res->hr_secondary_remotecnt;
1578 pjdlog_debug(1,
1579 "Setting localcnt to %ju and remotecnt to %ju.",
1580 (uintmax_t)res->hr_primary_localcnt,
1581 (uintmax_t)res->hr_secondary_localcnt);
1582 (void)metadata_write(res);
1583 mtx_unlock(&metadata_lock);
1584 }
1585 rw_unlock(&hio_remote_lock[ncomp]);
1586 continue;
1587 }
1588 pjdlog_debug(2, "sync: Taking free request.");
1589 QUEUE_TAKE2(hio, free);
1590 pjdlog_debug(2, "sync: (%p) Got free request.", hio);
1591 /*
1592 * Lock the range we are going to synchronize. We don't want
1593 * race where someone writes between our read and write.
1594 */
1595 for (;;) {
1596 mtx_lock(&range_lock);
1597 if (rangelock_islocked(range_regular, offset, length)) {
1598 pjdlog_debug(2,
1599 "sync: Range offset=%jd length=%jd locked.",
1600 (intmax_t)offset, (intmax_t)length);
1601 range_sync_wait = true;
1602 cv_wait(&range_sync_cond, &range_lock);
1603 range_sync_wait = false;
1604 mtx_unlock(&range_lock);
1605 continue;
1606 }
1607 if (rangelock_add(range_sync, offset, length) < 0) {
1608 mtx_unlock(&range_lock);
1609 pjdlog_debug(2,
1610 "sync: Range offset=%jd length=%jd is already locked, waiting.",
1611 (intmax_t)offset, (intmax_t)length);
1612 sleep(1);
1613 continue;
1614 }
1615 mtx_unlock(&range_lock);
1616 break;
1617 }
1618 /*
1619 * First read the data from synchronization source.
1620 */
1621 SYNCREQ(hio);
1622 ggio = &hio->hio_ggio;
1623 ggio->gctl_cmd = BIO_READ;
1624 ggio->gctl_offset = offset;
1625 ggio->gctl_length = length;
1626 ggio->gctl_error = 0;
1627 for (ii = 0; ii < ncomps; ii++)
1628 hio->hio_errors[ii] = EINVAL;
1629 reqlog(LOG_DEBUG, 2, ggio, "sync: (%p) Sending sync request: ",
1630 hio);
1631 pjdlog_debug(2, "sync: (%p) Moving request to the send queue.",
1632 hio);
1633 mtx_lock(&metadata_lock);
1634 if (res->hr_syncsrc == HAST_SYNCSRC_PRIMARY) {
1635 /*
1636 * This range is up-to-date on local component,
1637 * so handle request locally.
1638 */
1639 /* Local component is 0 for now. */
1640 ncomp = 0;
1641 } else /* if (res->hr_syncsrc == HAST_SYNCSRC_SECONDARY) */ {
1642 assert(res->hr_syncsrc == HAST_SYNCSRC_SECONDARY);
1643 /*
1644 * This range is out-of-date on local component,
1645 * so send request to the remote node.
1646 */
1647 /* Remote component is 1 for now. */
1648 ncomp = 1;
1649 }
1650 mtx_unlock(&metadata_lock);
1651 refcount_init(&hio->hio_countdown, 1);
1652 QUEUE_INSERT1(hio, send, ncomp);
1653
1654 /*
1655 * Let's wait for READ to finish.
1656 */
1657 mtx_lock(&sync_lock);
1658 while (!ISSYNCREQDONE(hio))
1659 cv_wait(&sync_cond, &sync_lock);
1660 mtx_unlock(&sync_lock);
1661
1662 if (hio->hio_errors[ncomp] != 0) {
1663 pjdlog_error("Unable to read synchronization data: %s.",
1664 strerror(hio->hio_errors[ncomp]));
1665 goto free_queue;
1666 }
1667
1668 /*
1669 * We read the data from synchronization source, now write it
1670 * to synchronization target.
1671 */
1672 SYNCREQ(hio);
1673 ggio->gctl_cmd = BIO_WRITE;
1674 for (ii = 0; ii < ncomps; ii++)
1675 hio->hio_errors[ii] = EINVAL;
1676 reqlog(LOG_DEBUG, 2, ggio, "sync: (%p) Sending sync request: ",
1677 hio);
1678 pjdlog_debug(2, "sync: (%p) Moving request to the send queue.",
1679 hio);
1680 mtx_lock(&metadata_lock);
1681 if (res->hr_syncsrc == HAST_SYNCSRC_PRIMARY) {
1682 /*
1683 * This range is up-to-date on local component,
1684 * so we update remote component.
1685 */
1686 /* Remote component is 1 for now. */
1687 ncomp = 1;
1688 } else /* if (res->hr_syncsrc == HAST_SYNCSRC_SECONDARY) */ {
1689 assert(res->hr_syncsrc == HAST_SYNCSRC_SECONDARY);
1690 /*
1691 * This range is out-of-date on local component,
1692 * so we update it.
1693 */
1694 /* Local component is 0 for now. */
1695 ncomp = 0;
1696 }
1697 mtx_unlock(&metadata_lock);
1698
1699 pjdlog_debug(2, "sync: (%p) Moving request to the send queues.",
1700 hio);
1701 refcount_init(&hio->hio_countdown, 1);
1702 QUEUE_INSERT1(hio, send, ncomp);
1703
1704 /*
1705 * Let's wait for WRITE to finish.
1706 */
1707 mtx_lock(&sync_lock);
1708 while (!ISSYNCREQDONE(hio))
1709 cv_wait(&sync_cond, &sync_lock);
1710 mtx_unlock(&sync_lock);
1711
1712 if (hio->hio_errors[ncomp] != 0) {
1713 pjdlog_error("Unable to write synchronization data: %s.",
1714 strerror(hio->hio_errors[ncomp]));
1715 goto free_queue;
1716 }
1717
1718 synced += length;
1719free_queue:
1720 mtx_lock(&range_lock);
1721 rangelock_del(range_sync, offset, length);
1722 if (range_regular_wait)
1723 cv_signal(&range_regular_cond);
1724 mtx_unlock(&range_lock);
1725 pjdlog_debug(2, "sync: (%p) Moving request to the free queue.",
1726 hio);
1727 QUEUE_INSERT2(hio, free);
1728 }
1729 /* NOTREACHED */
1730 return (NULL);
1731}
1732
1733static void
1734config_reload(void)
1735{
1736 struct hastd_config *newcfg;
1737 struct hast_resource *res;
1738 unsigned int ii, ncomps;
1739 int modified;
1740
1741 pjdlog_info("Reloading configuration...");
1742
1743 ncomps = HAST_NCOMPONENTS;
1744
1745 newcfg = yy_config_parse(cfgpath, false);
1746 if (newcfg == NULL)
1747 goto failed;
1748
1749 TAILQ_FOREACH(res, &newcfg->hc_resources, hr_next) {
1750 if (strcmp(res->hr_name, gres->hr_name) == 0)
1751 break;
1752 }
1753 /*
1754 * If resource was removed from the configuration file, resource
1755 * name, provider name or path to local component was modified we
1756 * shouldn't be here. This means that someone modified configuration
1757 * file and send SIGHUP to us instead of main hastd process.
1758 * Log advice and ignore the signal.
1759 */
1760 if (res == NULL || strcmp(gres->hr_name, res->hr_name) != 0 ||
1761 strcmp(gres->hr_provname, res->hr_provname) != 0 ||
1762 strcmp(gres->hr_localpath, res->hr_localpath) != 0) {
1763 pjdlog_warning("To reload configuration send SIGHUP to the main hastd process (pid %u).",
1764 (unsigned int)getppid());
1765 goto failed;
1766 }
1767
1768#define MODIFIED_REMOTEADDR 0x1
1769#define MODIFIED_REPLICATION 0x2
1770#define MODIFIED_TIMEOUT 0x4
1771#define MODIFIED_EXEC 0x8
1772 modified = 0;
1773 if (strcmp(gres->hr_remoteaddr, res->hr_remoteaddr) != 0) {
1774 /*
1775 * Don't copy res->hr_remoteaddr to gres just yet.
1776 * We want remote_close() to log disconnect from the old
1777 * addresses, not from the new ones.
1778 */
1779 modified |= MODIFIED_REMOTEADDR;
1780 }
1781 if (gres->hr_replication != res->hr_replication) {
1782 gres->hr_replication = res->hr_replication;
1783 modified |= MODIFIED_REPLICATION;
1784 }
1785 if (gres->hr_timeout != res->hr_timeout) {
1786 gres->hr_timeout = res->hr_timeout;
1787 modified |= MODIFIED_TIMEOUT;
1788 }
1789 if (strcmp(gres->hr_exec, res->hr_exec) != 0) {
1790 strlcpy(gres->hr_exec, res->hr_exec, sizeof(gres->hr_exec));
1791 modified |= MODIFIED_EXEC;
1792 }
1793 /*
1794 * If only timeout was modified we only need to change it without
1795 * reconnecting.
1796 */
1797 if (modified == MODIFIED_TIMEOUT) {
1798 for (ii = 0; ii < ncomps; ii++) {
1799 if (!ISREMOTE(ii))
1800 continue;
1801 rw_rlock(&hio_remote_lock[ii]);
1802 if (!ISCONNECTED(gres, ii)) {
1803 rw_unlock(&hio_remote_lock[ii]);
1804 continue;
1805 }
1806 rw_unlock(&hio_remote_lock[ii]);
1807 if (proto_timeout(gres->hr_remotein,
1808 gres->hr_timeout) < 0) {
1809 pjdlog_errno(LOG_WARNING,
1810 "Unable to set connection timeout");
1811 }
1812 if (proto_timeout(gres->hr_remoteout,
1813 gres->hr_timeout) < 0) {
1814 pjdlog_errno(LOG_WARNING,
1815 "Unable to set connection timeout");
1816 }
1817 }
1818 } else if ((modified &
1819 (MODIFIED_REMOTEADDR | MODIFIED_REPLICATION)) != 0) {
1820 for (ii = 0; ii < ncomps; ii++) {
1821 if (!ISREMOTE(ii))
1822 continue;
1823 remote_close(gres, ii);
1824 }
1825 if (modified & MODIFIED_REMOTEADDR) {
1826 strlcpy(gres->hr_remoteaddr, res->hr_remoteaddr,
1827 sizeof(gres->hr_remoteaddr));
1828 }
1829 }
1830#undef MODIFIED_REMOTEADDR
1831#undef MODIFIED_REPLICATION
1832#undef MODIFIED_TIMEOUT
1833#undef MODIFIED_EXEC
1834
1835 pjdlog_info("Configuration reloaded successfully.");
1836 return;
1837failed:
1838 if (newcfg != NULL) {
1839 if (newcfg->hc_controlconn != NULL)
1840 proto_close(newcfg->hc_controlconn);
1841 if (newcfg->hc_listenconn != NULL)
1842 proto_close(newcfg->hc_listenconn);
1843 yy_config_free(newcfg);
1844 }
1845 pjdlog_warning("Configuration not reloaded.");
1846}
1847
1848static void
1849keepalive_send(struct hast_resource *res, unsigned int ncomp)
1850{
1851 struct nv *nv;
1852
1853 nv = nv_alloc();
1854 nv_add_uint8(nv, HIO_KEEPALIVE, "cmd");
1855 if (nv_error(nv) != 0) {
1856 nv_free(nv);
1857 pjdlog_debug(1,
1858 "keepalive_send: Unable to prepare header to send.");
1859 return;
1860 }
1861 if (hast_proto_send(res, res->hr_remoteout, nv, NULL, 0) < 0) {
1862 pjdlog_common(LOG_DEBUG, 1, errno,
1863 "keepalive_send: Unable to send request");
1864 nv_free(nv);
1865 rw_unlock(&hio_remote_lock[ncomp]);
1866 remote_close(res, ncomp);
1867 rw_rlock(&hio_remote_lock[ncomp]);
1868 return;
1869 }
1870 nv_free(nv);
1871 pjdlog_debug(2, "keepalive_send: Request sent.");
1872}
1873
1874static void
1875guard_one(struct hast_resource *res, unsigned int ncomp)
1876{
1877 struct proto_conn *in, *out;
1878
1879 if (!ISREMOTE(ncomp))
1880 return;
1881
1882 rw_rlock(&hio_remote_lock[ncomp]);
1883
1884 if (!real_remote(res)) {
1885 rw_unlock(&hio_remote_lock[ncomp]);
1886 return;
1887 }
1888
1889 if (ISCONNECTED(res, ncomp)) {
1890 assert(res->hr_remotein != NULL);
1891 assert(res->hr_remoteout != NULL);
1892 keepalive_send(res, ncomp);
1893 }
1894
1895 if (ISCONNECTED(res, ncomp)) {
1896 assert(res->hr_remotein != NULL);
1897 assert(res->hr_remoteout != NULL);
1898 rw_unlock(&hio_remote_lock[ncomp]);
1899 pjdlog_debug(2, "remote_guard: Connection to %s is ok.",
1900 res->hr_remoteaddr);
1901 return;
1902 }
1903
1904 assert(res->hr_remotein == NULL);
1905 assert(res->hr_remoteout == NULL);
1906 /*
1907 * Upgrade the lock. It doesn't have to be atomic as no other thread
1908 * can change connection status from disconnected to connected.
1909 */
1910 rw_unlock(&hio_remote_lock[ncomp]);
1911 pjdlog_debug(2, "remote_guard: Reconnecting to %s.",
1912 res->hr_remoteaddr);
1913 in = out = NULL;
1914 if (init_remote(res, &in, &out)) {
1915 rw_wlock(&hio_remote_lock[ncomp]);
1916 assert(res->hr_remotein == NULL);
1917 assert(res->hr_remoteout == NULL);
1918 assert(in != NULL && out != NULL);
1919 res->hr_remotein = in;
1920 res->hr_remoteout = out;
1921 rw_unlock(&hio_remote_lock[ncomp]);
1922 pjdlog_info("Successfully reconnected to %s.",
1923 res->hr_remoteaddr);
1924 sync_start();
1925 } else {
1926 /* Both connections should be NULL. */
1927 assert(res->hr_remotein == NULL);
1928 assert(res->hr_remoteout == NULL);
1929 assert(in == NULL && out == NULL);
1930 pjdlog_debug(2, "remote_guard: Reconnect to %s failed.",
1931 res->hr_remoteaddr);
1932 }
1933}
1934
1935/*
1936 * Thread guards remote connections and reconnects when needed, handles
1937 * signals, etc.
1938 */
1939static void *
1940guard_thread(void *arg)
1941{
1942 struct hast_resource *res = arg;
1943 unsigned int ii, ncomps;
1944 struct timespec timeout;
1945 time_t lastcheck, now;
1946 sigset_t mask;
1947 int signo;
1948
1949 ncomps = HAST_NCOMPONENTS;
1950 lastcheck = time(NULL);
1951
1952 PJDLOG_VERIFY(sigemptyset(&mask) == 0);
1953 PJDLOG_VERIFY(sigaddset(&mask, SIGHUP) == 0);
1954 PJDLOG_VERIFY(sigaddset(&mask, SIGINT) == 0);
1955 PJDLOG_VERIFY(sigaddset(&mask, SIGTERM) == 0);
1956
1957 timeout.tv_nsec = 0;
1958 signo = -1;
1959
1960 for (;;) {
1961 switch (signo) {
1962 case SIGHUP:
1963 config_reload();
1964 break;
1965 case SIGINT:
1966 case SIGTERM:
1967 sigexit_received = true;
1968 primary_exitx(EX_OK,
1969 "Termination signal received, exiting.");
1970 break;
1971 default:
1972 break;
1973 }
1974
1975 pjdlog_debug(2, "remote_guard: Checking connections.");
1976 now = time(NULL);
1977 if (lastcheck + RETRY_SLEEP <= now) {
1978 for (ii = 0; ii < ncomps; ii++)
1979 guard_one(res, ii);
1980 lastcheck = now;
1981 }
1982 timeout.tv_sec = RETRY_SLEEP;
1983 signo = sigtimedwait(&mask, NULL, &timeout);
1984 }
1985 /* NOTREACHED */
1986 return (NULL);
1987}