2 * Copyright (c) 2011-2012 The DragonFly Project. All rights reserved.
4 * This code is derived from software contributed to The DragonFly Project
5 * by Matthew Dillon <dillon@dragonflybsd.org>
6 * by Venkatesh Srinivas <vsrinivas@dragonflybsd.org>
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
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
16 * the documentation and/or other materials provided with the
18 * 3. Neither the name of The DragonFly Project nor the names of its
19 * contributors may be used to endorse or promote products derived
20 * from this software without specific, prior written permission.
22 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
23 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
24 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
25 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
26 * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
27 * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
28 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
29 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
30 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
31 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
32 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
38 static int hammer2_state_msgrx(hammer2_iocom_t *iocom, hammer2_msg_t *msg);
39 static void hammer2_state_cleanuptx(hammer2_iocom_t *iocom, hammer2_msg_t *msg);
42 * ROUTER TREE - Represents available routes for message routing, indexed
43 * by their spanid. The router structure is embedded in
44 * either an iocom, h2span_link, or h2span_relay (see msg_lnk.c).
47 hammer2_router_cmp(hammer2_router_t *router1, hammer2_router_t *router2)
49 if (router1->spanid < router2->spanid)
51 if (router1->spanid > router2->spanid)
56 RB_GENERATE(hammer2_router_tree, hammer2_router, rbnode, hammer2_router_cmp);
58 static pthread_mutex_t router_mtx;
59 static struct hammer2_router_tree router_ltree = RB_INITIALIZER(router_ltree);
60 static struct hammer2_router_tree router_rtree = RB_INITIALIZER(router_rtree);
63 * STATE TREE - Represents open transactions which are indexed by their
64 * {spanid,msgid} relative to the governing iocom. spanid
65 * will usually be 0 since a non-zero spanid would have been
69 hammer2_state_cmp(hammer2_state_t *state1, hammer2_state_t *state2)
71 if (state1->spanid < state2->spanid)
73 if (state1->spanid > state2->spanid)
75 if (state1->msgid < state2->msgid)
77 if (state1->msgid > state2->msgid)
82 RB_GENERATE(hammer2_state_tree, hammer2_state, rbnode, hammer2_state_cmp);
85 * Initialize a low-level ioq
88 hammer2_ioq_init(hammer2_iocom_t *iocom __unused, hammer2_ioq_t *ioq)
90 bzero(ioq, sizeof(*ioq));
91 ioq->state = HAMMER2_MSGQ_STATE_HEADER1;
92 TAILQ_INIT(&ioq->msgq);
98 * caller holds iocom->mtx.
101 hammer2_ioq_done(hammer2_iocom_t *iocom __unused, hammer2_ioq_t *ioq)
105 while ((msg = TAILQ_FIRST(&ioq->msgq)) != NULL) {
106 assert(0); /* shouldn't happen */
107 TAILQ_REMOVE(&ioq->msgq, msg, qentry);
108 hammer2_msg_free(msg);
110 if ((msg = ioq->msg) != NULL) {
112 hammer2_msg_free(msg);
117 * Initialize a low-level communications channel.
119 * NOTE: The signal_func() is called at least once from the loop and can be
120 * re-armed via hammer2_iocom_restate().
123 hammer2_iocom_init(hammer2_iocom_t *iocom, int sock_fd, int alt_fd,
124 void (*signal_func)(hammer2_router_t *),
125 void (*rcvmsg_func)(hammer2_msg_t *),
126 void (*altmsg_func)(hammer2_iocom_t *))
128 bzero(iocom, sizeof(*iocom));
130 iocom->router = hammer2_router_alloc();
131 iocom->router->signal_callback = signal_func;
132 iocom->router->rcvmsg_callback = rcvmsg_func;
133 iocom->router->altmsg_callback = altmsg_func;
134 /* we do not call hammer2_router_connect() for iocom routers */
136 pthread_mutex_init(&iocom->mtx, NULL);
137 RB_INIT(&iocom->router->staterd_tree);
138 RB_INIT(&iocom->router->statewr_tree);
139 TAILQ_INIT(&iocom->freeq);
140 TAILQ_INIT(&iocom->freeq_aux);
141 TAILQ_INIT(&iocom->addrq);
142 TAILQ_INIT(&iocom->router->txmsgq);
143 iocom->router->iocom = iocom;
144 iocom->sock_fd = sock_fd;
145 iocom->alt_fd = alt_fd;
146 iocom->flags = HAMMER2_IOCOMF_RREQ;
148 iocom->flags |= HAMMER2_IOCOMF_SWORK;
149 hammer2_ioq_init(iocom, &iocom->ioq_rx);
150 hammer2_ioq_init(iocom, &iocom->ioq_tx);
151 if (pipe(iocom->wakeupfds) < 0)
153 fcntl(iocom->wakeupfds[0], F_SETFL, O_NONBLOCK);
154 fcntl(iocom->wakeupfds[1], F_SETFL, O_NONBLOCK);
157 * Negotiate session crypto synchronously. This will mark the
158 * connection as error'd if it fails.
160 hammer2_crypto_negotiate(iocom);
163 * Make sure our fds are set to non-blocking for the iocom core.
166 fcntl(sock_fd, F_SETFL, O_NONBLOCK);
168 /* if line buffered our single fgets() should be fine */
170 fcntl(alt_fd, F_SETFL, O_NONBLOCK);
175 * May only be called from a callback from iocom_core.
177 * Adjust state machine functions, set flags to guarantee that both
178 * the recevmsg_func and the sendmsg_func is called at least once.
181 hammer2_router_restate(hammer2_router_t *router,
182 void (*signal_func)(hammer2_router_t *),
183 void (*rcvmsg_func)(hammer2_msg_t *msg),
184 void (*altmsg_func)(hammer2_iocom_t *))
186 router->signal_callback = signal_func;
187 router->rcvmsg_callback = rcvmsg_func;
188 router->altmsg_callback = altmsg_func;
190 router->iocom->flags |= HAMMER2_IOCOMF_SWORK;
192 router->iocom->flags &= ~HAMMER2_IOCOMF_SWORK;
196 hammer2_router_signal(hammer2_router_t *router)
198 if (router->signal_callback)
199 router->iocom->flags |= HAMMER2_IOCOMF_SWORK;
203 * Cleanup a terminating iocom.
205 * Caller should not hold iocom->mtx. The iocom has already been disconnected
206 * from all possible references to it.
209 hammer2_iocom_done(hammer2_iocom_t *iocom)
213 if (iocom->sock_fd >= 0) {
214 close(iocom->sock_fd);
217 if (iocom->alt_fd >= 0) {
218 close(iocom->alt_fd);
221 hammer2_ioq_done(iocom, &iocom->ioq_rx);
222 hammer2_ioq_done(iocom, &iocom->ioq_tx);
223 if ((msg = TAILQ_FIRST(&iocom->freeq)) != NULL) {
224 TAILQ_REMOVE(&iocom->freeq, msg, qentry);
227 if ((msg = TAILQ_FIRST(&iocom->freeq_aux)) != NULL) {
228 TAILQ_REMOVE(&iocom->freeq_aux, msg, qentry);
230 msg->aux_data = NULL;
233 if (iocom->wakeupfds[0] >= 0) {
234 close(iocom->wakeupfds[0]);
235 iocom->wakeupfds[0] = -1;
237 if (iocom->wakeupfds[1] >= 0) {
238 close(iocom->wakeupfds[1]);
239 iocom->wakeupfds[1] = -1;
241 pthread_mutex_destroy(&iocom->mtx);
245 * Allocate a new one-way message.
248 hammer2_msg_alloc(hammer2_router_t *router, size_t aux_size, uint32_t cmd,
249 void (*func)(hammer2_msg_t *), void *data)
251 hammer2_state_t *state = NULL;
252 hammer2_iocom_t *iocom = router->iocom;
256 pthread_mutex_lock(&iocom->mtx);
258 aux_size = (aux_size + HAMMER2_MSG_ALIGNMASK) &
259 ~HAMMER2_MSG_ALIGNMASK;
260 if ((msg = TAILQ_FIRST(&iocom->freeq_aux)) != NULL)
261 TAILQ_REMOVE(&iocom->freeq_aux, msg, qentry);
263 if ((msg = TAILQ_FIRST(&iocom->freeq)) != NULL)
264 TAILQ_REMOVE(&iocom->freeq, msg, qentry);
266 if ((cmd & (HAMMER2_MSGF_CREATE | HAMMER2_MSGF_REPLY)) ==
267 HAMMER2_MSGF_CREATE) {
269 * Create state when CREATE is set without REPLY.
271 * NOTE: CREATE in txcmd handled by hammer2_msg_write()
272 * NOTE: DELETE in txcmd handled by hammer2_state_cleanuptx()
274 state = malloc(sizeof(*state));
275 bzero(state, sizeof(*state));
276 state->iocom = iocom;
277 state->flags = HAMMER2_STATE_DYNAMIC;
278 state->msgid = (uint64_t)(uintptr_t)state;
280 state->spanid = router->spanid;
281 state->txcmd = cmd & ~(HAMMER2_MSGF_CREATE |
282 HAMMER2_MSGF_DELETE);
283 state->rxcmd = HAMMER2_MSGF_REPLY;
285 state->any.any = data;
286 pthread_mutex_lock(&iocom->mtx);
287 RB_INSERT(hammer2_state_tree,
288 &iocom->router->statewr_tree,
290 pthread_mutex_unlock(&iocom->mtx);
291 state->flags |= HAMMER2_STATE_INSERTED;
293 pthread_mutex_unlock(&iocom->mtx);
295 msg = malloc(sizeof(*msg));
296 bzero(msg, sizeof(*msg));
297 msg->aux_data = NULL;
300 if (msg->aux_size != aux_size) {
303 msg->aux_data = NULL;
307 msg->aux_data = malloc(aux_size);
308 msg->aux_size = aux_size;
311 hbytes = (cmd & HAMMER2_MSGF_SIZE) * HAMMER2_MSG_ALIGN;
313 bzero(&msg->any.head, hbytes);
314 msg->hdr_size = hbytes;
315 msg->any.head.cmd = cmd;
316 msg->any.head.aux_descr = 0;
317 msg->any.head.aux_crc = 0;
318 msg->router = router;
322 msg->any.head.msgid = state->msgid;
328 * Free a message so it can be reused afresh.
330 * NOTE: aux_size can be 0 with a non-NULL aux_data.
334 hammer2_msg_free_locked(hammer2_msg_t *msg)
336 hammer2_iocom_t *iocom = msg->router->iocom;
340 TAILQ_INSERT_TAIL(&iocom->freeq_aux, msg, qentry);
342 TAILQ_INSERT_TAIL(&iocom->freeq, msg, qentry);
346 hammer2_msg_free(hammer2_msg_t *msg)
348 hammer2_iocom_t *iocom = msg->router->iocom;
350 pthread_mutex_lock(&iocom->mtx);
351 hammer2_msg_free_locked(msg);
352 pthread_mutex_unlock(&iocom->mtx);
356 * I/O core loop for an iocom.
358 * Thread localized, iocom->mtx not held.
361 hammer2_iocom_core(hammer2_iocom_t *iocom)
363 struct pollfd fds[3];
368 int wi; /* wakeup pipe */
370 int ai; /* alt bulk path socket */
372 while ((iocom->flags & HAMMER2_IOCOMF_EOF) == 0) {
373 if ((iocom->flags & (HAMMER2_IOCOMF_RWORK |
374 HAMMER2_IOCOMF_WWORK |
375 HAMMER2_IOCOMF_PWORK |
376 HAMMER2_IOCOMF_SWORK |
377 HAMMER2_IOCOMF_ARWORK |
378 HAMMER2_IOCOMF_AWWORK)) == 0) {
380 * Only poll if no immediate work is pending.
381 * Otherwise we are just wasting our time calling
392 * Always check the inter-thread pipe, e.g.
393 * for iocom->txmsgq work.
396 fds[wi].fd = iocom->wakeupfds[0];
397 fds[wi].events = POLLIN;
401 * Check the socket input/output direction as
404 if (iocom->flags & (HAMMER2_IOCOMF_RREQ |
405 HAMMER2_IOCOMF_WREQ)) {
407 fds[si].fd = iocom->sock_fd;
411 if (iocom->flags & HAMMER2_IOCOMF_RREQ)
412 fds[si].events |= POLLIN;
413 if (iocom->flags & HAMMER2_IOCOMF_WREQ)
414 fds[si].events |= POLLOUT;
418 * Check the alternative fd for work.
420 if (iocom->alt_fd >= 0) {
422 fds[ai].fd = iocom->alt_fd;
423 fds[ai].events = POLLIN;
426 poll(fds, count, timeout);
428 if (wi >= 0 && (fds[wi].revents & POLLIN))
429 iocom->flags |= HAMMER2_IOCOMF_PWORK;
430 if (si >= 0 && (fds[si].revents & POLLIN))
431 iocom->flags |= HAMMER2_IOCOMF_RWORK;
432 if (si >= 0 && (fds[si].revents & POLLOUT))
433 iocom->flags |= HAMMER2_IOCOMF_WWORK;
434 if (wi >= 0 && (fds[wi].revents & POLLOUT))
435 iocom->flags |= HAMMER2_IOCOMF_WWORK;
436 if (ai >= 0 && (fds[ai].revents & POLLIN))
437 iocom->flags |= HAMMER2_IOCOMF_ARWORK;
440 * Always check the pipe
442 iocom->flags |= HAMMER2_IOCOMF_PWORK;
445 if (iocom->flags & HAMMER2_IOCOMF_SWORK) {
446 iocom->flags &= ~HAMMER2_IOCOMF_SWORK;
447 iocom->router->signal_callback(iocom->router);
451 * Pending message queues from other threads wake us up
452 * with a write to the wakeupfds[] pipe. We have to clear
453 * the pipe with a dummy read.
455 if (iocom->flags & HAMMER2_IOCOMF_PWORK) {
456 iocom->flags &= ~HAMMER2_IOCOMF_PWORK;
457 read(iocom->wakeupfds[0], dummybuf, sizeof(dummybuf));
458 iocom->flags |= HAMMER2_IOCOMF_RWORK;
459 iocom->flags |= HAMMER2_IOCOMF_WWORK;
460 if (TAILQ_FIRST(&iocom->router->txmsgq))
461 hammer2_iocom_flush1(iocom);
465 * Message write sequencing
467 if (iocom->flags & HAMMER2_IOCOMF_WWORK)
468 hammer2_iocom_flush1(iocom);
471 * Message read sequencing. Run this after the write
472 * sequencing in case the write sequencing allowed another
473 * auto-DELETE to occur on the read side.
475 if (iocom->flags & HAMMER2_IOCOMF_RWORK) {
476 while ((iocom->flags & HAMMER2_IOCOMF_EOF) == 0 &&
477 (msg = hammer2_ioq_read(iocom)) != NULL) {
479 fprintf(stderr, "receive %s\n",
480 hammer2_msg_str(msg));
482 iocom->router->rcvmsg_callback(msg);
483 hammer2_state_cleanuprx(iocom, msg);
487 if (iocom->flags & HAMMER2_IOCOMF_ARWORK) {
488 iocom->flags &= ~HAMMER2_IOCOMF_ARWORK;
489 iocom->router->altmsg_callback(iocom);
495 * Make sure there's enough room in the FIFO to hold the
498 * Assume worst case encrypted form is 2x the size of the
499 * plaintext equivalent.
503 hammer2_ioq_makeroom(hammer2_ioq_t *ioq, size_t needed)
508 bytes = ioq->fifo_cdx - ioq->fifo_beg;
509 nmax = sizeof(ioq->buf) - ioq->fifo_end;
510 if (bytes + nmax / 2 < needed) {
512 bcopy(ioq->buf + ioq->fifo_beg,
516 ioq->fifo_cdx -= ioq->fifo_beg;
518 if (ioq->fifo_cdn < ioq->fifo_end) {
519 bcopy(ioq->buf + ioq->fifo_cdn,
520 ioq->buf + ioq->fifo_cdx,
521 ioq->fifo_end - ioq->fifo_cdn);
523 ioq->fifo_end -= ioq->fifo_cdn - ioq->fifo_cdx;
524 ioq->fifo_cdn = ioq->fifo_cdx;
525 nmax = sizeof(ioq->buf) - ioq->fifo_end;
531 * Read the next ready message from the ioq, issuing I/O if needed.
532 * Caller should retry on a read-event when NULL is returned.
534 * If an error occurs during reception a HAMMER2_LNK_ERROR msg will
535 * be returned for each open transaction, then the ioq and iocom
536 * will be errored out and a non-transactional HAMMER2_LNK_ERROR
537 * msg will be returned as the final message. The caller should not call
538 * us again after the final message is returned.
540 * Thread localized, iocom->mtx not held.
543 hammer2_ioq_read(hammer2_iocom_t *iocom)
545 hammer2_ioq_t *ioq = &iocom->ioq_rx;
547 hammer2_msg_hdr_t *head;
548 hammer2_state_t *state;
556 iocom->flags &= ~(HAMMER2_IOCOMF_RREQ | HAMMER2_IOCOMF_RWORK);
559 * If a message is already pending we can just remove and
560 * return it. Message state has already been processed.
561 * (currently not implemented)
563 if ((msg = TAILQ_FIRST(&ioq->msgq)) != NULL) {
564 TAILQ_REMOVE(&ioq->msgq, msg, qentry);
569 * If the stream is errored out we stop processing it.
575 * Message read in-progress (msg is NULL at the moment). We don't
576 * allocate a msg until we have its core header.
578 nmax = sizeof(ioq->buf) - ioq->fifo_end;
579 bytes = ioq->fifo_cdx - ioq->fifo_beg; /* already decrypted */
583 case HAMMER2_MSGQ_STATE_HEADER1:
585 * Load the primary header, fail on any non-trivial read
586 * error or on EOF. Since the primary header is the same
587 * size is the message alignment it will never straddle
588 * the end of the buffer.
590 nmax = hammer2_ioq_makeroom(ioq, sizeof(msg->any.head));
591 if (bytes < sizeof(msg->any.head)) {
592 n = read(iocom->sock_fd,
593 ioq->buf + ioq->fifo_end,
597 ioq->error = HAMMER2_IOQ_ERROR_EOF;
600 if (errno != EINTR &&
601 errno != EINPROGRESS &&
603 ioq->error = HAMMER2_IOQ_ERROR_SOCK;
609 ioq->fifo_end += (size_t)n;
614 * Decrypt data received so far. Data will be decrypted
615 * in-place but might create gaps in the FIFO. Partial
616 * blocks are not immediately decrypted.
618 * WARNING! The header might be in the wrong endian, we
619 * do not fix it up until we get the entire
622 if (iocom->flags & HAMMER2_IOCOMF_CRYPTED) {
623 hammer2_crypto_decrypt(iocom, ioq);
625 ioq->fifo_cdx = ioq->fifo_end;
626 ioq->fifo_cdn = ioq->fifo_end;
628 bytes = ioq->fifo_cdx - ioq->fifo_beg;
631 * Insufficient data accumulated (msg is NULL, caller will
635 if (bytes < sizeof(msg->any.head))
639 * Check and fixup the core header. Note that the icrc
640 * has to be calculated before any fixups, but the crc
641 * fields in the msg may have to be swapped like everything
644 head = (void *)(ioq->buf + ioq->fifo_beg);
645 if (head->magic != HAMMER2_MSGHDR_MAGIC &&
646 head->magic != HAMMER2_MSGHDR_MAGIC_REV) {
647 ioq->error = HAMMER2_IOQ_ERROR_SYNC;
652 * Calculate the full header size and aux data size
654 if (head->magic == HAMMER2_MSGHDR_MAGIC_REV) {
655 ioq->hbytes = (bswap32(head->cmd) & HAMMER2_MSGF_SIZE) *
657 ioq->abytes = bswap32(head->aux_bytes) *
660 ioq->hbytes = (head->cmd & HAMMER2_MSGF_SIZE) *
662 ioq->abytes = head->aux_bytes * HAMMER2_MSG_ALIGN;
664 if (ioq->hbytes < sizeof(msg->any.head) ||
665 ioq->hbytes > sizeof(msg->any) ||
666 ioq->abytes > HAMMER2_MSGAUX_MAX) {
667 ioq->error = HAMMER2_IOQ_ERROR_FIELD;
672 * Allocate the message, the next state will fill it in.
674 msg = hammer2_msg_alloc(iocom->router, ioq->abytes, 0,
679 * Fall through to the next state. Make sure that the
680 * extended header does not straddle the end of the buffer.
681 * We still want to issue larger reads into our buffer,
682 * book-keeping is easier if we don't bcopy() yet.
684 * Make sure there is enough room for bloated encrypt data.
686 nmax = hammer2_ioq_makeroom(ioq, ioq->hbytes);
687 ioq->state = HAMMER2_MSGQ_STATE_HEADER2;
689 case HAMMER2_MSGQ_STATE_HEADER2:
691 * Fill out the extended header.
694 if (bytes < ioq->hbytes) {
695 n = read(iocom->sock_fd,
696 ioq->buf + ioq->fifo_end,
700 ioq->error = HAMMER2_IOQ_ERROR_EOF;
703 if (errno != EINTR &&
704 errno != EINPROGRESS &&
706 ioq->error = HAMMER2_IOQ_ERROR_SOCK;
712 ioq->fifo_end += (size_t)n;
716 if (iocom->flags & HAMMER2_IOCOMF_CRYPTED) {
717 hammer2_crypto_decrypt(iocom, ioq);
719 ioq->fifo_cdx = ioq->fifo_end;
720 ioq->fifo_cdn = ioq->fifo_end;
722 bytes = ioq->fifo_cdx - ioq->fifo_beg;
725 * Insufficient data accumulated (set msg NULL so caller will
728 if (bytes < ioq->hbytes) {
734 * Calculate the extended header, decrypt data received
735 * so far. Handle endian-conversion for the entire extended
738 head = (void *)(ioq->buf + ioq->fifo_beg);
743 if (head->magic == HAMMER2_MSGHDR_MAGIC_REV)
744 xcrc32 = bswap32(head->hdr_crc);
746 xcrc32 = head->hdr_crc;
748 if (hammer2_icrc32(head, ioq->hbytes) != xcrc32) {
749 ioq->error = HAMMER2_IOQ_ERROR_XCRC;
750 fprintf(stderr, "BAD-XCRC(%08x,%08x) %s\n",
751 xcrc32, hammer2_icrc32(head, ioq->hbytes),
752 hammer2_msg_str(msg));
756 head->hdr_crc = xcrc32;
758 if (head->magic == HAMMER2_MSGHDR_MAGIC_REV) {
759 hammer2_bswap_head(head);
763 * Copy the extended header into the msg and adjust the
766 bcopy(head, &msg->any, ioq->hbytes);
769 * We are either done or we fall-through.
771 if (ioq->abytes == 0) {
772 ioq->fifo_beg += ioq->hbytes;
777 * Must adjust bytes (and the state) when falling through.
778 * nmax doesn't change.
780 ioq->fifo_beg += ioq->hbytes;
781 bytes -= ioq->hbytes;
782 ioq->state = HAMMER2_MSGQ_STATE_AUXDATA1;
784 case HAMMER2_MSGQ_STATE_AUXDATA1:
786 * Copy the partial or complete payload from remaining
787 * bytes in the FIFO in order to optimize the makeroom call
788 * in the AUXDATA2 state. We have to fall-through either
789 * way so we can check the crc.
791 * msg->aux_size tracks our aux data.
793 if (bytes >= ioq->abytes) {
794 bcopy(ioq->buf + ioq->fifo_beg, msg->aux_data,
796 msg->aux_size = ioq->abytes;
797 ioq->fifo_beg += ioq->abytes;
798 assert(ioq->fifo_beg <= ioq->fifo_cdx);
799 assert(ioq->fifo_cdx <= ioq->fifo_cdn);
800 bytes -= ioq->abytes;
802 bcopy(ioq->buf + ioq->fifo_beg, msg->aux_data,
804 msg->aux_size = bytes;
805 ioq->fifo_beg += bytes;
806 if (ioq->fifo_cdx < ioq->fifo_beg)
807 ioq->fifo_cdx = ioq->fifo_beg;
808 assert(ioq->fifo_beg <= ioq->fifo_cdx);
809 assert(ioq->fifo_cdx <= ioq->fifo_cdn);
814 ioq->state = HAMMER2_MSGQ_STATE_AUXDATA2;
816 case HAMMER2_MSGQ_STATE_AUXDATA2:
818 * Make sure there is enough room for more data.
821 nmax = hammer2_ioq_makeroom(ioq, ioq->abytes - msg->aux_size);
824 * Read and decrypt more of the payload.
826 if (msg->aux_size < ioq->abytes) {
828 n = read(iocom->sock_fd,
829 ioq->buf + ioq->fifo_end,
833 ioq->error = HAMMER2_IOQ_ERROR_EOF;
836 if (errno != EINTR &&
837 errno != EINPROGRESS &&
839 ioq->error = HAMMER2_IOQ_ERROR_SOCK;
845 ioq->fifo_end += (size_t)n;
849 if (iocom->flags & HAMMER2_IOCOMF_CRYPTED) {
850 hammer2_crypto_decrypt(iocom, ioq);
852 ioq->fifo_cdx = ioq->fifo_end;
853 ioq->fifo_cdn = ioq->fifo_end;
855 bytes = ioq->fifo_cdx - ioq->fifo_beg;
857 if (bytes > ioq->abytes - msg->aux_size)
858 bytes = ioq->abytes - msg->aux_size;
861 bcopy(ioq->buf + ioq->fifo_beg,
862 msg->aux_data + msg->aux_size,
864 msg->aux_size += bytes;
865 ioq->fifo_beg += bytes;
869 * Insufficient data accumulated (set msg NULL so caller will
872 if (msg->aux_size < ioq->abytes) {
876 assert(msg->aux_size == ioq->abytes);
879 * Check aux_crc, then we are done.
881 xcrc32 = hammer2_icrc32(msg->aux_data, msg->aux_size);
882 if (xcrc32 != msg->any.head.aux_crc) {
883 ioq->error = HAMMER2_IOQ_ERROR_ACRC;
887 case HAMMER2_MSGQ_STATE_ERROR:
889 * Continued calls to drain recorded transactions (returning
890 * a LNK_ERROR for each one), before we return the final
897 * We don't double-return errors, the caller should not
898 * have called us again after getting an error msg.
905 * Check the message sequence. The iv[] should prevent any
906 * possibility of a replay but we add this check anyway.
908 if (msg && ioq->error == 0) {
909 if ((msg->any.head.salt & 255) != (ioq->seq & 255)) {
910 ioq->error = HAMMER2_IOQ_ERROR_MSGSEQ;
917 * Process transactional state for the message.
919 if (msg && ioq->error == 0) {
920 error = hammer2_state_msgrx(iocom, msg);
922 if (error == HAMMER2_IOQ_ERROR_EALREADY) {
923 hammer2_msg_free(msg);
931 * Handle error, RREQ, or completion
933 * NOTE: nmax and bytes are invalid at this point, we don't bother
934 * to update them when breaking out.
939 * An unrecoverable error causes all active receive
940 * transactions to be terminated with a LNK_ERROR message.
942 * Once all active transactions are exhausted we set the
943 * iocom ERROR flag and return a non-transactional LNK_ERROR
944 * message, which should cause master processing loops to
947 assert(ioq->msg == msg);
949 hammer2_msg_free(msg);
954 * No more I/O read processing
956 ioq->state = HAMMER2_MSGQ_STATE_ERROR;
959 * Simulate a remote LNK_ERROR DELETE msg for any open
960 * transactions, ending with a final non-transactional
961 * LNK_ERROR (that the session can detect) when no
962 * transactions remain.
964 msg = hammer2_msg_alloc(iocom->router, 0, 0, NULL, NULL);
965 bzero(&msg->any.head, sizeof(msg->any.head));
966 msg->any.head.magic = HAMMER2_MSGHDR_MAGIC;
967 msg->any.head.cmd = HAMMER2_LNK_ERROR;
968 msg->any.head.error = ioq->error;
970 pthread_mutex_lock(&iocom->mtx);
971 hammer2_iocom_drain(iocom);
972 if ((state = RB_ROOT(&iocom->router->staterd_tree)) != NULL) {
974 * Active remote transactions are still present.
975 * Simulate the other end sending us a DELETE.
977 if (state->rxcmd & HAMMER2_MSGF_DELETE) {
978 hammer2_msg_free(msg);
981 /*state->txcmd |= HAMMER2_MSGF_DELETE;*/
983 msg->any.head.spanid = state->spanid;
984 msg->any.head.msgid = state->msgid;
985 msg->any.head.cmd |= HAMMER2_MSGF_ABORT |
988 } else if ((state = RB_ROOT(&iocom->router->statewr_tree)) !=
991 * Active local transactions are still present.
992 * Simulate the other end sending us a DELETE.
994 if (state->rxcmd & HAMMER2_MSGF_DELETE) {
995 hammer2_msg_free(msg);
999 msg->any.head.spanid = state->spanid;
1000 msg->any.head.msgid = state->msgid;
1001 msg->any.head.cmd |= HAMMER2_MSGF_ABORT |
1002 HAMMER2_MSGF_DELETE |
1004 if ((state->rxcmd & HAMMER2_MSGF_CREATE) == 0) {
1005 msg->any.head.cmd |=
1006 HAMMER2_MSGF_CREATE;
1011 * No active local or remote transactions remain.
1012 * Generate a final LNK_ERROR and flag EOF.
1015 iocom->flags |= HAMMER2_IOCOMF_EOF;
1016 fprintf(stderr, "EOF ON SOCKET %d\n", iocom->sock_fd);
1018 pthread_mutex_unlock(&iocom->mtx);
1021 * For the iocom error case we want to set RWORK to indicate
1022 * that more messages might be pending.
1024 * It is possible to return NULL when there is more work to
1025 * do because each message has to be DELETEd in both
1026 * directions before we continue on with the next (though
1027 * this could be optimized). The transmit direction will
1031 iocom->flags |= HAMMER2_IOCOMF_RWORK;
1032 } else if (msg == NULL) {
1034 * Insufficient data received to finish building the message,
1035 * set RREQ and return NULL.
1037 * Leave ioq->msg intact.
1038 * Leave the FIFO intact.
1040 iocom->flags |= HAMMER2_IOCOMF_RREQ;
1045 * The fifo has already been advanced past the message.
1046 * Trivially reset the FIFO indices if possible.
1048 * clear the FIFO if it is now empty and set RREQ to wait
1049 * for more from the socket. If the FIFO is not empty set
1050 * TWORK to bypass the poll so we loop immediately.
1052 if (ioq->fifo_beg == ioq->fifo_cdx &&
1053 ioq->fifo_cdn == ioq->fifo_end) {
1054 iocom->flags |= HAMMER2_IOCOMF_RREQ;
1060 iocom->flags |= HAMMER2_IOCOMF_RWORK;
1062 ioq->state = HAMMER2_MSGQ_STATE_HEADER1;
1069 * Calculate the header and data crc's and write a low-level message to
1070 * the connection. If aux_crc is non-zero the aux_data crc is already
1071 * assumed to have been set.
1073 * A non-NULL msg is added to the queue but not necessarily flushed.
1074 * Calling this function with msg == NULL will get a flush going.
1076 * Caller must hold iocom->mtx.
1079 hammer2_iocom_flush1(hammer2_iocom_t *iocom)
1081 hammer2_ioq_t *ioq = &iocom->ioq_tx;
1085 hammer2_msg_queue_t tmpq;
1087 iocom->flags &= ~(HAMMER2_IOCOMF_WREQ | HAMMER2_IOCOMF_WWORK);
1089 pthread_mutex_lock(&iocom->mtx);
1090 while ((msg = TAILQ_FIRST(&iocom->router->txmsgq)) != NULL) {
1091 TAILQ_REMOVE(&iocom->router->txmsgq, msg, qentry);
1092 TAILQ_INSERT_TAIL(&tmpq, msg, qentry);
1094 pthread_mutex_unlock(&iocom->mtx);
1096 while ((msg = TAILQ_FIRST(&tmpq)) != NULL) {
1098 * Process terminal connection errors.
1100 TAILQ_REMOVE(&tmpq, msg, qentry);
1102 TAILQ_INSERT_TAIL(&ioq->msgq, msg, qentry);
1108 * Finish populating the msg fields. The salt ensures that
1109 * the iv[] array is ridiculously randomized and we also
1110 * re-seed our PRNG every 32768 messages just to be sure.
1112 msg->any.head.magic = HAMMER2_MSGHDR_MAGIC;
1113 msg->any.head.salt = (random() << 8) | (ioq->seq & 255);
1115 if ((ioq->seq & 32767) == 0)
1119 * Calculate aux_crc if 0, then calculate hdr_crc.
1121 if (msg->aux_size && msg->any.head.aux_crc == 0) {
1122 assert((msg->aux_size & HAMMER2_MSG_ALIGNMASK) == 0);
1123 xcrc32 = hammer2_icrc32(msg->aux_data, msg->aux_size);
1124 msg->any.head.aux_crc = xcrc32;
1126 msg->any.head.aux_bytes = msg->aux_size / HAMMER2_MSG_ALIGN;
1127 assert((msg->aux_size & HAMMER2_MSG_ALIGNMASK) == 0);
1129 hbytes = (msg->any.head.cmd & HAMMER2_MSGF_SIZE) *
1131 msg->any.head.hdr_crc = 0;
1132 msg->any.head.hdr_crc = hammer2_icrc32(&msg->any.head, hbytes);
1135 * Enqueue the message (the flush codes handles stream
1138 TAILQ_INSERT_TAIL(&ioq->msgq, msg, qentry);
1141 hammer2_iocom_flush2(iocom);
1145 * Thread localized, iocom->mtx not held by caller.
1148 hammer2_iocom_flush2(hammer2_iocom_t *iocom)
1150 hammer2_ioq_t *ioq = &iocom->ioq_tx;
1153 struct iovec iov[HAMMER2_IOQ_MAXIOVEC];
1162 hammer2_iocom_drain(iocom);
1167 * Pump messages out the connection by building an iovec.
1169 * ioq->hbytes/ioq->abytes tracks how much of the first message
1170 * in the queue has been successfully written out, so we can
1178 TAILQ_FOREACH(msg, &ioq->msgq, qentry) {
1179 hbytes = (msg->any.head.cmd & HAMMER2_MSGF_SIZE) *
1181 abytes = msg->aux_size;
1182 assert(hoff <= hbytes && aoff <= abytes);
1184 if (hoff < hbytes) {
1185 iov[iovcnt].iov_base = (char *)&msg->any.head + hoff;
1186 iov[iovcnt].iov_len = hbytes - hoff;
1187 nact += hbytes - hoff;
1189 if (iovcnt == HAMMER2_IOQ_MAXIOVEC)
1192 if (aoff < abytes) {
1193 assert(msg->aux_data != NULL);
1194 iov[iovcnt].iov_base = (char *)msg->aux_data + aoff;
1195 iov[iovcnt].iov_len = abytes - aoff;
1196 nact += abytes - aoff;
1198 if (iovcnt == HAMMER2_IOQ_MAXIOVEC)
1208 * Encrypt and write the data. The crypto code will move the
1209 * data into the fifo and adjust the iov as necessary. If
1210 * encryption is disabled the iov is left alone.
1212 * May return a smaller iov (thus a smaller n), with aggregated
1213 * chunks. May reduce nmax to what fits in the FIFO.
1215 * This function sets nact to the number of original bytes now
1216 * encrypted, adding to the FIFO some number of bytes that might
1217 * be greater depending on the crypto mechanic. iov[] is adjusted
1218 * to point at the FIFO if necessary.
1220 * NOTE: The return value from the writev() is the post-encrypted
1221 * byte count, not the plaintext count.
1223 if (iocom->flags & HAMMER2_IOCOMF_CRYPTED) {
1225 * Make sure the FIFO has a reasonable amount of space
1226 * left (if not completely full).
1228 if (ioq->fifo_beg > sizeof(ioq->buf) / 2 &&
1229 sizeof(ioq->buf) - ioq->fifo_end >= HAMMER2_MSG_ALIGN * 2) {
1230 bcopy(ioq->buf + ioq->fifo_beg, ioq->buf,
1231 ioq->fifo_end - ioq->fifo_beg);
1232 ioq->fifo_cdx -= ioq->fifo_beg;
1233 ioq->fifo_cdn -= ioq->fifo_beg;
1234 ioq->fifo_end -= ioq->fifo_beg;
1238 iovcnt = hammer2_crypto_encrypt(iocom, ioq, iov, iovcnt, &nact);
1239 n = writev(iocom->sock_fd, iov, iovcnt);
1244 if (ioq->fifo_beg == ioq->fifo_end) {
1252 n = writev(iocom->sock_fd, iov, iovcnt);
1260 * Clean out the transmit queue based on what we successfully
1261 * sent (nact is the plaintext count). ioq->hbytes/abytes
1262 * represents the portion of the first message previously sent.
1264 while ((msg = TAILQ_FIRST(&ioq->msgq)) != NULL) {
1265 hbytes = (msg->any.head.cmd & HAMMER2_MSGF_SIZE) *
1267 abytes = msg->aux_size;
1269 if ((size_t)nact < hbytes - ioq->hbytes) {
1270 ioq->hbytes += nact;
1274 nact -= hbytes - ioq->hbytes;
1275 ioq->hbytes = hbytes;
1276 if ((size_t)nact < abytes - ioq->abytes) {
1277 ioq->abytes += nact;
1281 nact -= abytes - ioq->abytes;
1283 TAILQ_REMOVE(&ioq->msgq, msg, qentry);
1288 hammer2_state_cleanuptx(iocom, msg);
1293 * Process the return value from the write w/regards to blocking.
1296 if (errno != EINTR &&
1297 errno != EINPROGRESS &&
1302 ioq->error = HAMMER2_IOQ_ERROR_SOCK;
1303 hammer2_iocom_drain(iocom);
1306 * Wait for socket buffer space
1308 iocom->flags |= HAMMER2_IOCOMF_WREQ;
1311 iocom->flags |= HAMMER2_IOCOMF_WREQ;
1314 hammer2_iocom_drain(iocom);
1319 * Kill pending msgs on ioq_tx and adjust the flags such that no more
1320 * write events will occur. We don't kill read msgs because we want
1321 * the caller to pull off our contrived terminal error msg to detect
1322 * the connection failure.
1324 * Thread localized, iocom->mtx not held by caller.
1327 hammer2_iocom_drain(hammer2_iocom_t *iocom)
1329 hammer2_ioq_t *ioq = &iocom->ioq_tx;
1332 iocom->flags &= ~(HAMMER2_IOCOMF_WREQ | HAMMER2_IOCOMF_WWORK);
1336 while ((msg = TAILQ_FIRST(&ioq->msgq)) != NULL) {
1337 TAILQ_REMOVE(&ioq->msgq, msg, qentry);
1339 hammer2_state_cleanuptx(iocom, msg);
1344 * Write a message to an iocom, with additional state processing.
1347 hammer2_msg_write(hammer2_msg_t *msg)
1349 hammer2_iocom_t *iocom = msg->router->iocom;
1350 hammer2_state_t *state;
1354 * Handle state processing, create state if necessary.
1356 pthread_mutex_lock(&iocom->mtx);
1357 if ((state = msg->state) != NULL) {
1359 * Existing transaction (could be reply). It is also
1360 * possible for this to be the first reply (CREATE is set),
1361 * in which case we populate state->txcmd.
1363 * state->txcmd is adjusted to hold the final message cmd,
1364 * and we also be sure to set the CREATE bit here. We did
1365 * not set it in hammer2_msg_alloc() because that would have
1366 * not been serialized (state could have gotten ripped out
1367 * from under the message prior to it being transmitted).
1369 if ((msg->any.head.cmd & (HAMMER2_MSGF_CREATE |
1370 HAMMER2_MSGF_REPLY)) ==
1371 HAMMER2_MSGF_CREATE) {
1372 state->txcmd = msg->any.head.cmd & ~HAMMER2_MSGF_DELETE;
1374 msg->any.head.msgid = state->msgid;
1375 msg->any.head.spanid = state->spanid;
1376 assert(((state->txcmd ^ msg->any.head.cmd) &
1377 HAMMER2_MSGF_REPLY) == 0);
1378 if (msg->any.head.cmd & HAMMER2_MSGF_CREATE)
1379 state->txcmd = msg->any.head.cmd & ~HAMMER2_MSGF_DELETE;
1381 msg->any.head.msgid = 0;
1382 /* XXX set spanid by router */
1386 * Queue it for output, wake up the I/O pthread. Note that the
1387 * I/O thread is responsible for generating the CRCs and encryption.
1389 TAILQ_INSERT_TAIL(&iocom->router->txmsgq, msg, qentry);
1391 write(iocom->wakeupfds[1], &dummy, 1); /* XXX optimize me */
1392 pthread_mutex_unlock(&iocom->mtx);
1396 * This is a shortcut to formulate a reply to msg with a simple error code,
1397 * It can reply to and terminate a transaction, or it can reply to a one-way
1398 * messages. A HAMMER2_LNK_ERROR command code is utilized to encode
1399 * the error code (which can be 0). Not all transactions are terminated
1400 * with HAMMER2_LNK_ERROR status (the low level only cares about the
1401 * MSGF_DELETE flag), but most are.
1403 * Replies to one-way messages are a bit of an oxymoron but the feature
1404 * is used by the debug (DBG) protocol.
1406 * The reply contains no extended data.
1409 hammer2_msg_reply(hammer2_msg_t *msg, uint32_t error)
1411 hammer2_iocom_t *iocom = msg->router->iocom;
1412 hammer2_state_t *state = msg->state;
1413 hammer2_msg_t *nmsg;
1418 * Reply with a simple error code and terminate the transaction.
1420 cmd = HAMMER2_LNK_ERROR;
1423 * Check if our direction has even been initiated yet, set CREATE.
1425 * Check what direction this is (command or reply direction). Note
1426 * that txcmd might not have been initiated yet.
1428 * If our direction has already been closed we just return without
1432 if (state->txcmd & HAMMER2_MSGF_DELETE)
1434 if (state->txcmd & HAMMER2_MSGF_REPLY)
1435 cmd |= HAMMER2_MSGF_REPLY;
1436 cmd |= HAMMER2_MSGF_DELETE;
1438 if ((msg->any.head.cmd & HAMMER2_MSGF_REPLY) == 0)
1439 cmd |= HAMMER2_MSGF_REPLY;
1443 * Allocate the message and associate it with the existing state.
1444 * We cannot pass MSGF_CREATE to msg_alloc() because that may
1445 * allocate new state. We have our state already.
1447 nmsg = hammer2_msg_alloc(iocom->router, 0, cmd, NULL, NULL);
1449 if ((state->txcmd & HAMMER2_MSGF_CREATE) == 0)
1450 nmsg->any.head.cmd |= HAMMER2_MSGF_CREATE;
1452 nmsg->any.head.error = error;
1453 nmsg->state = state;
1454 hammer2_msg_write(nmsg);
1458 * Similar to hammer2_msg_reply() but leave the transaction open. That is,
1459 * we are generating a streaming reply or an intermediate acknowledgement
1460 * of some sort as part of the higher level protocol, with more to come
1464 hammer2_msg_result(hammer2_msg_t *msg, uint32_t error)
1466 hammer2_iocom_t *iocom = msg->router->iocom;
1467 hammer2_state_t *state = msg->state;
1468 hammer2_msg_t *nmsg;
1473 * Reply with a simple error code and terminate the transaction.
1475 cmd = HAMMER2_LNK_ERROR;
1478 * Check if our direction has even been initiated yet, set CREATE.
1480 * Check what direction this is (command or reply direction). Note
1481 * that txcmd might not have been initiated yet.
1483 * If our direction has already been closed we just return without
1487 if (state->txcmd & HAMMER2_MSGF_DELETE)
1489 if (state->txcmd & HAMMER2_MSGF_REPLY)
1490 cmd |= HAMMER2_MSGF_REPLY;
1491 /* continuing transaction, do not set MSGF_DELETE */
1493 if ((msg->any.head.cmd & HAMMER2_MSGF_REPLY) == 0)
1494 cmd |= HAMMER2_MSGF_REPLY;
1497 nmsg = hammer2_msg_alloc(iocom->router, 0, cmd, NULL, NULL);
1499 if ((state->txcmd & HAMMER2_MSGF_CREATE) == 0)
1500 nmsg->any.head.cmd |= HAMMER2_MSGF_CREATE;
1502 nmsg->any.head.error = error;
1503 nmsg->state = state;
1504 hammer2_msg_write(nmsg);
1508 * Terminate a transaction given a state structure by issuing a DELETE.
1511 hammer2_state_reply(hammer2_state_t *state, uint32_t error)
1513 hammer2_msg_t *nmsg;
1514 uint32_t cmd = HAMMER2_LNK_ERROR | HAMMER2_MSGF_DELETE;
1517 * Nothing to do if we already transmitted a delete
1519 if (state->txcmd & HAMMER2_MSGF_DELETE)
1523 * Set REPLY if the other end initiated the command. Otherwise
1524 * we are the command direction.
1526 if (state->txcmd & HAMMER2_MSGF_REPLY)
1527 cmd |= HAMMER2_MSGF_REPLY;
1529 nmsg = hammer2_msg_alloc(state->iocom->router, 0, cmd, NULL, NULL);
1531 if ((state->txcmd & HAMMER2_MSGF_CREATE) == 0)
1532 nmsg->any.head.cmd |= HAMMER2_MSGF_CREATE;
1534 nmsg->any.head.error = error;
1535 nmsg->state = state;
1536 hammer2_msg_write(nmsg);
1539 /************************************************************************
1540 * TRANSACTION STATE HANDLING *
1541 ************************************************************************
1546 * Process state tracking for a message after reception, prior to
1549 * Called with msglk held and the msg dequeued.
1551 * All messages are called with dummy state and return actual state.
1552 * (One-off messages often just return the same dummy state).
1554 * May request that caller discard the message by setting *discardp to 1.
1555 * The returned state is not used in this case and is allowed to be NULL.
1559 * These routines handle persistent and command/reply message state via the
1560 * CREATE and DELETE flags. The first message in a command or reply sequence
1561 * sets CREATE, the last message in a command or reply sequence sets DELETE.
1563 * There can be any number of intermediate messages belonging to the same
1564 * sequence sent inbetween the CREATE message and the DELETE message,
1565 * which set neither flag. This represents a streaming command or reply.
1567 * Any command message received with CREATE set expects a reply sequence to
1568 * be returned. Reply sequences work the same as command sequences except the
1569 * REPLY bit is also sent. Both the command side and reply side can
1570 * degenerate into a single message with both CREATE and DELETE set. Note
1571 * that one side can be streaming and the other side not, or neither, or both.
1573 * The msgid is unique for the initiator. That is, two sides sending a new
1574 * message can use the same msgid without colliding.
1578 * ABORT sequences work by setting the ABORT flag along with normal message
1579 * state. However, ABORTs can also be sent on half-closed messages, that is
1580 * even if the command or reply side has already sent a DELETE, as long as
1581 * the message has not been fully closed it can still send an ABORT+DELETE
1582 * to terminate the half-closed message state.
1584 * Since ABORT+DELETEs can race we silently discard ABORT's for message
1585 * state which has already been fully closed. REPLY+ABORT+DELETEs can
1586 * also race, and in this situation the other side might have already
1587 * initiated a new unrelated command with the same message id. Since
1588 * the abort has not set the CREATE flag the situation can be detected
1589 * and the message will also be discarded.
1591 * Non-blocking requests can be initiated with ABORT+CREATE[+DELETE].
1592 * The ABORT request is essentially integrated into the command instead
1593 * of being sent later on. In this situation the command implementation
1594 * detects that CREATE and ABORT are both set (vs ABORT alone) and can
1595 * special-case non-blocking operation for the command.
1597 * NOTE! Messages with ABORT set without CREATE or DELETE are considered
1598 * to be mid-stream aborts for command/reply sequences. ABORTs on
1599 * one-way messages are not supported.
1601 * NOTE! If a command sequence does not support aborts the ABORT flag is
1606 * One-off messages (no reply expected) are sent with neither CREATE or DELETE
1607 * set. One-off messages cannot be aborted and typically aren't processed
1608 * by these routines. The REPLY bit can be used to distinguish whether a
1609 * one-off message is a command or reply. For example, one-off replies
1610 * will typically just contain status updates.
1613 hammer2_state_msgrx(hammer2_iocom_t *iocom, hammer2_msg_t *msg)
1615 hammer2_state_t *state;
1616 hammer2_state_t dummy;
1620 * Lock RB tree and locate existing persistent state, if any.
1622 * If received msg is a command state is on staterd_tree.
1623 * If received msg is a reply state is on statewr_tree.
1626 dummy.msgid = msg->any.head.msgid;
1627 dummy.spanid = msg->any.head.spanid;
1628 pthread_mutex_lock(&iocom->mtx);
1629 if (msg->any.head.cmd & HAMMER2_MSGF_REPLY) {
1630 state = RB_FIND(hammer2_state_tree,
1631 &iocom->router->statewr_tree, &dummy);
1633 state = RB_FIND(hammer2_state_tree,
1634 &iocom->router->staterd_tree, &dummy);
1637 pthread_mutex_unlock(&iocom->mtx);
1640 * Short-cut one-off or mid-stream messages (state may be NULL).
1642 if ((msg->any.head.cmd & (HAMMER2_MSGF_CREATE | HAMMER2_MSGF_DELETE |
1643 HAMMER2_MSGF_ABORT)) == 0) {
1648 * Switch on CREATE, DELETE, REPLY, and also handle ABORT from
1649 * inside the case statements.
1651 switch(msg->any.head.cmd & (HAMMER2_MSGF_CREATE | HAMMER2_MSGF_DELETE |
1652 HAMMER2_MSGF_REPLY)) {
1653 case HAMMER2_MSGF_CREATE:
1654 case HAMMER2_MSGF_CREATE | HAMMER2_MSGF_DELETE:
1656 * New persistant command received.
1659 fprintf(stderr, "duplicate-trans %s\n",
1660 hammer2_msg_str(msg));
1661 error = HAMMER2_IOQ_ERROR_TRANS;
1665 state = malloc(sizeof(*state));
1666 bzero(state, sizeof(*state));
1667 state->iocom = iocom;
1668 state->flags = HAMMER2_STATE_DYNAMIC;
1670 state->txcmd = HAMMER2_MSGF_REPLY;
1671 state->rxcmd = msg->any.head.cmd & ~HAMMER2_MSGF_DELETE;
1672 state->flags |= HAMMER2_STATE_INSERTED;
1673 state->msgid = msg->any.head.msgid;
1674 state->spanid = msg->any.head.spanid;
1676 pthread_mutex_lock(&iocom->mtx);
1677 RB_INSERT(hammer2_state_tree,
1678 &iocom->router->staterd_tree, state);
1679 pthread_mutex_unlock(&iocom->mtx);
1682 fprintf(stderr, "create state %p id=%08x on iocom staterd %p\n",
1683 state, (uint32_t)state->msgid, iocom);
1686 case HAMMER2_MSGF_DELETE:
1688 * Persistent state is expected but might not exist if an
1689 * ABORT+DELETE races the close.
1691 if (state == NULL) {
1692 if (msg->any.head.cmd & HAMMER2_MSGF_ABORT) {
1693 error = HAMMER2_IOQ_ERROR_EALREADY;
1695 fprintf(stderr, "missing-state %s\n",
1696 hammer2_msg_str(msg));
1697 error = HAMMER2_IOQ_ERROR_TRANS;
1704 * Handle another ABORT+DELETE case if the msgid has already
1707 if ((state->rxcmd & HAMMER2_MSGF_CREATE) == 0) {
1708 if (msg->any.head.cmd & HAMMER2_MSGF_ABORT) {
1709 error = HAMMER2_IOQ_ERROR_EALREADY;
1711 fprintf(stderr, "reused-state %s\n",
1712 hammer2_msg_str(msg));
1713 error = HAMMER2_IOQ_ERROR_TRANS;
1722 * Check for mid-stream ABORT command received, otherwise
1725 if (msg->any.head.cmd & HAMMER2_MSGF_ABORT) {
1726 if (state == NULL ||
1727 (state->rxcmd & HAMMER2_MSGF_CREATE) == 0) {
1728 error = HAMMER2_IOQ_ERROR_EALREADY;
1734 case HAMMER2_MSGF_REPLY | HAMMER2_MSGF_CREATE:
1735 case HAMMER2_MSGF_REPLY | HAMMER2_MSGF_CREATE | HAMMER2_MSGF_DELETE:
1737 * When receiving a reply with CREATE set the original
1738 * persistent state message should already exist.
1740 if (state == NULL) {
1741 fprintf(stderr, "no-state(r) %s\n",
1742 hammer2_msg_str(msg));
1743 error = HAMMER2_IOQ_ERROR_TRANS;
1747 assert(((state->rxcmd ^ msg->any.head.cmd) &
1748 HAMMER2_MSGF_REPLY) == 0);
1749 state->rxcmd = msg->any.head.cmd & ~HAMMER2_MSGF_DELETE;
1752 case HAMMER2_MSGF_REPLY | HAMMER2_MSGF_DELETE:
1754 * Received REPLY+ABORT+DELETE in case where msgid has
1755 * already been fully closed, ignore the message.
1757 if (state == NULL) {
1758 if (msg->any.head.cmd & HAMMER2_MSGF_ABORT) {
1759 error = HAMMER2_IOQ_ERROR_EALREADY;
1761 fprintf(stderr, "no-state(r,d) %s\n",
1762 hammer2_msg_str(msg));
1763 error = HAMMER2_IOQ_ERROR_TRANS;
1770 * Received REPLY+ABORT+DELETE in case where msgid has
1771 * already been reused for an unrelated message,
1772 * ignore the message.
1774 if ((state->rxcmd & HAMMER2_MSGF_CREATE) == 0) {
1775 if (msg->any.head.cmd & HAMMER2_MSGF_ABORT) {
1776 error = HAMMER2_IOQ_ERROR_EALREADY;
1778 fprintf(stderr, "reused-state(r,d) %s\n",
1779 hammer2_msg_str(msg));
1780 error = HAMMER2_IOQ_ERROR_TRANS;
1787 case HAMMER2_MSGF_REPLY:
1789 * Check for mid-stream ABORT reply received to sent command.
1791 if (msg->any.head.cmd & HAMMER2_MSGF_ABORT) {
1792 if (state == NULL ||
1793 (state->rxcmd & HAMMER2_MSGF_CREATE) == 0) {
1794 error = HAMMER2_IOQ_ERROR_EALREADY;
1805 hammer2_state_cleanuprx(hammer2_iocom_t *iocom, hammer2_msg_t *msg)
1807 hammer2_state_t *state;
1809 if ((state = msg->state) == NULL) {
1811 * Free a non-transactional message, there is no state
1814 hammer2_msg_free(msg);
1815 } else if (msg->any.head.cmd & HAMMER2_MSGF_DELETE) {
1817 * Message terminating transaction, destroy the related
1818 * state, the original message, and this message (if it
1819 * isn't the original message due to a CREATE|DELETE).
1821 pthread_mutex_lock(&iocom->mtx);
1822 state->rxcmd |= HAMMER2_MSGF_DELETE;
1823 if (state->txcmd & HAMMER2_MSGF_DELETE) {
1824 if (state->msg == msg)
1826 assert(state->flags & HAMMER2_STATE_INSERTED);
1827 if (state->rxcmd & HAMMER2_MSGF_REPLY) {
1828 assert(msg->any.head.cmd & HAMMER2_MSGF_REPLY);
1829 RB_REMOVE(hammer2_state_tree,
1830 &iocom->router->statewr_tree, state);
1832 assert((msg->any.head.cmd & HAMMER2_MSGF_REPLY) == 0);
1833 RB_REMOVE(hammer2_state_tree,
1834 &iocom->router->staterd_tree, state);
1836 state->flags &= ~HAMMER2_STATE_INSERTED;
1837 hammer2_state_free(state);
1841 pthread_mutex_unlock(&iocom->mtx);
1842 hammer2_msg_free(msg);
1843 } else if (state->msg != msg) {
1845 * Message not terminating transaction, leave state intact
1846 * and free message if it isn't the CREATE message.
1848 hammer2_msg_free(msg);
1853 hammer2_state_cleanuptx(hammer2_iocom_t *iocom, hammer2_msg_t *msg)
1855 hammer2_state_t *state;
1857 if ((state = msg->state) == NULL) {
1858 hammer2_msg_free(msg);
1859 } else if (msg->any.head.cmd & HAMMER2_MSGF_DELETE) {
1860 pthread_mutex_lock(&iocom->mtx);
1861 state->txcmd |= HAMMER2_MSGF_DELETE;
1862 if (state->rxcmd & HAMMER2_MSGF_DELETE) {
1863 if (state->msg == msg)
1865 assert(state->flags & HAMMER2_STATE_INSERTED);
1866 if (state->txcmd & HAMMER2_MSGF_REPLY) {
1867 assert(msg->any.head.cmd & HAMMER2_MSGF_REPLY);
1868 RB_REMOVE(hammer2_state_tree,
1869 &iocom->router->staterd_tree, state);
1871 assert((msg->any.head.cmd & HAMMER2_MSGF_REPLY) == 0);
1872 RB_REMOVE(hammer2_state_tree,
1873 &iocom->router->statewr_tree, state);
1875 state->flags &= ~HAMMER2_STATE_INSERTED;
1876 hammer2_state_free(state);
1880 pthread_mutex_unlock(&iocom->mtx);
1881 hammer2_msg_free(msg);
1882 } else if (state->msg != msg) {
1883 hammer2_msg_free(msg);
1888 * Called with iocom locked
1891 hammer2_state_free(hammer2_state_t *state)
1893 hammer2_iocom_t *iocom = state->iocom;
1898 fprintf(stderr, "terminate state %p id=%08x\n",
1899 state, (uint32_t)state->msgid);
1901 assert(state->any.any == NULL);
1905 hammer2_msg_free_locked(msg);
1909 * When an iocom error is present we are trying to close down the
1910 * iocom, but we have to wait for all states to terminate before
1911 * we can do so. The iocom rx code will terminate the receive side
1912 * for all transactions by simulating incoming DELETE messages,
1913 * but the state doesn't go away until both sides are terminated.
1915 * We may have to wake up the rx code.
1917 if (iocom->ioq_rx.error &&
1918 RB_EMPTY(&iocom->router->staterd_tree) &&
1919 RB_EMPTY(&iocom->router->statewr_tree)) {
1921 write(iocom->wakeupfds[1], &dummy, 1);
1925 /************************************************************************
1927 ************************************************************************
1929 * Incoming messages are routed by their spanid, matched up against
1930 * outgoing LNK_SPANs managed by h2span_relay structures (see msg_lnk.c).
1931 * Any replies run through the same router.
1933 * Originated messages are routed by their spanid, matched up against
1934 * incoming LNK_SPANs managed by h2span_link structures (see msg_lnk.c).
1935 * Replies come back through the same route.
1937 * Keep in mind that ALL MESSAGE TRAFFIC pertaining to a particular
1938 * transaction runs through the same route. Commands and replies both.
1940 * An originated message will use a different routing spanid to
1941 * reach a target node than a message which originates from that node.
1942 * They might use the same physical pipes (each pipe can have multiple
1943 * SPANs and RELAYs), but the routes are distinct from the perspective
1947 hammer2_router_alloc(void)
1949 hammer2_router_t *router;
1951 router = hammer2_alloc(sizeof(*router));
1952 TAILQ_INIT(&router->txmsgq);
1957 hammer2_router_connect(hammer2_router_t *router)
1959 hammer2_router_t *tmp;
1961 assert(router->link || router->relay);
1962 assert((router->flags & HAMMER2_ROUTER_CONNECTED) == 0);
1964 pthread_mutex_lock(&router_mtx);
1966 tmp = RB_INSERT(hammer2_router_tree, &router_ltree, router);
1968 tmp = RB_INSERT(hammer2_router_tree, &router_rtree, router);
1969 assert(tmp == NULL);
1970 router->flags |= HAMMER2_ROUTER_CONNECTED;
1971 pthread_mutex_unlock(&router_mtx);
1975 hammer2_router_disconnect(hammer2_router_t **routerp)
1977 hammer2_router_t *router;
1980 assert(router->link || router->relay);
1981 assert(router->flags & HAMMER2_ROUTER_CONNECTED);
1983 pthread_mutex_lock(&router_mtx);
1985 RB_REMOVE(hammer2_router_tree, &router_ltree, router);
1987 RB_REMOVE(hammer2_router_tree, &router_rtree, router);
1988 router->flags &= ~HAMMER2_ROUTER_CONNECTED;
1990 pthread_mutex_unlock(&router_mtx);
1998 hammer2_route_msg(hammer2_msg_t *msg)
2003 /************************************************************************
2005 ************************************************************************/
2008 hammer2_basecmd_str(uint32_t cmd)
2010 static char buf[64];
2013 const char *protostr;
2016 switch(cmd & HAMMER2_MSGF_PROTOS) {
2017 case HAMMER2_MSG_PROTO_LNK:
2020 case HAMMER2_MSG_PROTO_DBG:
2023 case HAMMER2_MSG_PROTO_DOM:
2026 case HAMMER2_MSG_PROTO_CAC:
2029 case HAMMER2_MSG_PROTO_QRM:
2032 case HAMMER2_MSG_PROTO_BLK:
2035 case HAMMER2_MSG_PROTO_VOP:
2039 snprintf(protobuf, sizeof(protobuf), "%x_",
2040 (cmd & HAMMER2_MSGF_PROTOS) >> 20);
2041 protostr = protobuf;
2045 switch(cmd & (HAMMER2_MSGF_PROTOS |
2047 HAMMER2_MSGF_SIZE)) {
2048 case HAMMER2_LNK_PAD:
2051 case HAMMER2_LNK_PING:
2054 case HAMMER2_LNK_AUTH:
2057 case HAMMER2_LNK_CONN:
2060 case HAMMER2_LNK_SPAN:
2063 case HAMMER2_LNK_ERROR:
2064 if (cmd & HAMMER2_MSGF_DELETE)
2069 case HAMMER2_DBG_SHELL:
2073 snprintf(cmdbuf, sizeof(cmdbuf),
2074 "%06x", (cmd & (HAMMER2_MSGF_PROTOS |
2076 HAMMER2_MSGF_SIZE)));
2080 snprintf(buf, sizeof(buf), "%s%s", protostr, cmdstr);
2085 hammer2_msg_str(hammer2_msg_t *msg)
2087 hammer2_state_t *state;
2088 static char buf[256];
2092 const char *statestr;
2100 if ((state = msg->state) != NULL) {
2101 basecmd = (state->rxcmd & HAMMER2_MSGF_REPLY) ?
2102 state->txcmd : state->rxcmd;
2103 snprintf(statebuf, sizeof(statebuf),
2104 " %s=%s,L=%s%s,R=%s%s",
2105 ((state->txcmd & HAMMER2_MSGF_REPLY) ?
2106 "rcvcmd" : "sndcmd"),
2107 hammer2_basecmd_str(basecmd),
2108 ((state->txcmd & HAMMER2_MSGF_CREATE) ? "C" : ""),
2109 ((state->txcmd & HAMMER2_MSGF_DELETE) ? "D" : ""),
2110 ((state->rxcmd & HAMMER2_MSGF_CREATE) ? "C" : ""),
2111 ((state->rxcmd & HAMMER2_MSGF_DELETE) ? "D" : "")
2113 statestr = statebuf;
2121 switch(msg->any.head.error) {
2125 case HAMMER2_IOQ_ERROR_SYNC:
2126 errstr = "err=IOQ:NOSYNC";
2128 case HAMMER2_IOQ_ERROR_EOF:
2129 errstr = "err=IOQ:STREAMEOF";
2131 case HAMMER2_IOQ_ERROR_SOCK:
2132 errstr = "err=IOQ:SOCKERR";
2134 case HAMMER2_IOQ_ERROR_FIELD:
2135 errstr = "err=IOQ:BADFIELD";
2137 case HAMMER2_IOQ_ERROR_HCRC:
2138 errstr = "err=IOQ:BADHCRC";
2140 case HAMMER2_IOQ_ERROR_XCRC:
2141 errstr = "err=IOQ:BADXCRC";
2143 case HAMMER2_IOQ_ERROR_ACRC:
2144 errstr = "err=IOQ:BADACRC";
2146 case HAMMER2_IOQ_ERROR_STATE:
2147 errstr = "err=IOQ:BADSTATE";
2149 case HAMMER2_IOQ_ERROR_NOPEER:
2150 errstr = "err=IOQ:PEERCONFIG";
2152 case HAMMER2_IOQ_ERROR_NORKEY:
2153 errstr = "err=IOQ:BADRKEY";
2155 case HAMMER2_IOQ_ERROR_NOLKEY:
2156 errstr = "err=IOQ:BADLKEY";
2158 case HAMMER2_IOQ_ERROR_KEYXCHGFAIL:
2159 errstr = "err=IOQ:BADKEYXCHG";
2161 case HAMMER2_IOQ_ERROR_KEYFMT:
2162 errstr = "err=IOQ:BADFMT";
2164 case HAMMER2_IOQ_ERROR_BADURANDOM:
2165 errstr = "err=IOQ:BADRANDOM";
2167 case HAMMER2_IOQ_ERROR_MSGSEQ:
2168 errstr = "err=IOQ:BADSEQ";
2170 case HAMMER2_IOQ_ERROR_EALREADY:
2171 errstr = "err=IOQ:DUPMSG";
2173 case HAMMER2_IOQ_ERROR_TRANS:
2174 errstr = "err=IOQ:BADTRANS";
2176 case HAMMER2_IOQ_ERROR_IVWRAP:
2177 errstr = "err=IOQ:IVWRAP";
2179 case HAMMER2_IOQ_ERROR_MACFAIL:
2180 errstr = "err=IOQ:MACFAIL";
2182 case HAMMER2_IOQ_ERROR_ALGO:
2183 errstr = "err=IOQ:ALGOFAIL";
2185 case HAMMER2_MSG_ERR_NOSUPP:
2186 errstr = "err=NOSUPPORT";
2189 snprintf(errbuf, sizeof(errbuf),
2190 " err=%d", msg->any.head.error);
2199 if (msg->any.head.cmd & (HAMMER2_MSGF_CREATE | HAMMER2_MSGF_DELETE |
2200 HAMMER2_MSGF_ABORT | HAMMER2_MSGF_REPLY)) {
2202 if (msg->any.head.cmd & HAMMER2_MSGF_CREATE)
2204 if (msg->any.head.cmd & HAMMER2_MSGF_DELETE)
2206 if (msg->any.head.cmd & HAMMER2_MSGF_REPLY)
2208 if (msg->any.head.cmd & HAMMER2_MSGF_ABORT)
2216 snprintf(buf, sizeof(buf),
2217 "msg=%s%s %s id=%08x span=%08x %s",
2218 hammer2_basecmd_str(msg->any.head.cmd),
2221 (uint32_t)(intmax_t)msg->any.head.msgid, /* for brevity */
2222 (uint32_t)(intmax_t)msg->any.head.spanid, /* for brevity */