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_msg_t *msg);
39 static void hammer2_state_cleanuptx(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->target < router2->target)
51 if (router1->target > router2->target)
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 * {router,msgid} relative to the governing iocom.
66 * router is usually iocom->router since state isn't stored
67 * for relayed messages.
70 hammer2_state_cmp(hammer2_state_t *state1, hammer2_state_t *state2)
73 if (state1->router < state2->router)
75 if (state1->router > state2->router)
78 if (state1->msgid < state2->msgid)
80 if (state1->msgid > state2->msgid)
85 RB_GENERATE(hammer2_state_tree, hammer2_state, rbnode, hammer2_state_cmp);
88 * Initialize a low-level ioq
91 hammer2_ioq_init(hammer2_iocom_t *iocom __unused, hammer2_ioq_t *ioq)
93 bzero(ioq, sizeof(*ioq));
94 ioq->state = HAMMER2_MSGQ_STATE_HEADER1;
95 TAILQ_INIT(&ioq->msgq);
101 * caller holds iocom->mtx.
104 hammer2_ioq_done(hammer2_iocom_t *iocom __unused, hammer2_ioq_t *ioq)
108 while ((msg = TAILQ_FIRST(&ioq->msgq)) != NULL) {
109 assert(0); /* shouldn't happen */
110 TAILQ_REMOVE(&ioq->msgq, msg, qentry);
111 hammer2_msg_free(msg);
113 if ((msg = ioq->msg) != NULL) {
115 hammer2_msg_free(msg);
120 * Initialize a low-level communications channel.
122 * NOTE: The signal_func() is called at least once from the loop and can be
123 * re-armed via hammer2_iocom_restate().
126 hammer2_iocom_init(hammer2_iocom_t *iocom, int sock_fd, int alt_fd,
127 void (*signal_func)(hammer2_router_t *),
128 void (*rcvmsg_func)(hammer2_msg_t *),
129 void (*altmsg_func)(hammer2_iocom_t *))
133 bzero(iocom, sizeof(*iocom));
135 iocom->router = hammer2_router_alloc();
136 iocom->router->signal_callback = signal_func;
137 iocom->router->rcvmsg_callback = rcvmsg_func;
138 iocom->router->altmsg_callback = altmsg_func;
139 /* we do not call hammer2_router_connect() for iocom routers */
141 pthread_mutex_init(&iocom->mtx, NULL);
142 RB_INIT(&iocom->router->staterd_tree);
143 RB_INIT(&iocom->router->statewr_tree);
144 TAILQ_INIT(&iocom->freeq);
145 TAILQ_INIT(&iocom->freeq_aux);
146 TAILQ_INIT(&iocom->router->txmsgq);
147 iocom->router->iocom = iocom;
148 iocom->sock_fd = sock_fd;
149 iocom->alt_fd = alt_fd;
150 iocom->flags = HAMMER2_IOCOMF_RREQ;
152 iocom->flags |= HAMMER2_IOCOMF_SWORK;
153 hammer2_ioq_init(iocom, &iocom->ioq_rx);
154 hammer2_ioq_init(iocom, &iocom->ioq_tx);
155 if (pipe(iocom->wakeupfds) < 0)
157 fcntl(iocom->wakeupfds[0], F_SETFL, O_NONBLOCK);
158 fcntl(iocom->wakeupfds[1], F_SETFL, O_NONBLOCK);
161 * Negotiate session crypto synchronously. This will mark the
162 * connection as error'd if it fails. If this is a pipe it's
163 * a linkage that we set up ourselves to the filesystem and there
166 if (fstat(sock_fd, &st) < 0)
168 if (S_ISSOCK(st.st_mode))
169 hammer2_crypto_negotiate(iocom);
172 * Make sure our fds are set to non-blocking for the iocom core.
175 fcntl(sock_fd, F_SETFL, O_NONBLOCK);
177 /* if line buffered our single fgets() should be fine */
179 fcntl(alt_fd, F_SETFL, O_NONBLOCK);
184 * May only be called from a callback from iocom_core.
186 * Adjust state machine functions, set flags to guarantee that both
187 * the recevmsg_func and the sendmsg_func is called at least once.
190 hammer2_router_restate(hammer2_router_t *router,
191 void (*signal_func)(hammer2_router_t *),
192 void (*rcvmsg_func)(hammer2_msg_t *msg),
193 void (*altmsg_func)(hammer2_iocom_t *))
195 router->signal_callback = signal_func;
196 router->rcvmsg_callback = rcvmsg_func;
197 router->altmsg_callback = altmsg_func;
199 router->iocom->flags |= HAMMER2_IOCOMF_SWORK;
201 router->iocom->flags &= ~HAMMER2_IOCOMF_SWORK;
205 hammer2_router_signal(hammer2_router_t *router)
207 if (router->signal_callback)
208 router->iocom->flags |= HAMMER2_IOCOMF_SWORK;
212 * Cleanup a terminating iocom.
214 * Caller should not hold iocom->mtx. The iocom has already been disconnected
215 * from all possible references to it.
218 hammer2_iocom_done(hammer2_iocom_t *iocom)
222 if (iocom->sock_fd >= 0) {
223 close(iocom->sock_fd);
226 if (iocom->alt_fd >= 0) {
227 close(iocom->alt_fd);
230 hammer2_ioq_done(iocom, &iocom->ioq_rx);
231 hammer2_ioq_done(iocom, &iocom->ioq_tx);
232 if ((msg = TAILQ_FIRST(&iocom->freeq)) != NULL) {
233 TAILQ_REMOVE(&iocom->freeq, msg, qentry);
236 if ((msg = TAILQ_FIRST(&iocom->freeq_aux)) != NULL) {
237 TAILQ_REMOVE(&iocom->freeq_aux, msg, qentry);
239 msg->aux_data = NULL;
242 if (iocom->wakeupfds[0] >= 0) {
243 close(iocom->wakeupfds[0]);
244 iocom->wakeupfds[0] = -1;
246 if (iocom->wakeupfds[1] >= 0) {
247 close(iocom->wakeupfds[1]);
248 iocom->wakeupfds[1] = -1;
250 pthread_mutex_destroy(&iocom->mtx);
254 * Allocate a new one-way message.
257 hammer2_msg_alloc(hammer2_router_t *router, size_t aux_size, uint32_t cmd,
258 void (*func)(hammer2_msg_t *), void *data)
260 hammer2_state_t *state = NULL;
261 hammer2_iocom_t *iocom = router->iocom;
265 pthread_mutex_lock(&iocom->mtx);
267 aux_size = (aux_size + HAMMER2_MSG_ALIGNMASK) &
268 ~HAMMER2_MSG_ALIGNMASK;
269 if ((msg = TAILQ_FIRST(&iocom->freeq_aux)) != NULL)
270 TAILQ_REMOVE(&iocom->freeq_aux, msg, qentry);
272 if ((msg = TAILQ_FIRST(&iocom->freeq)) != NULL)
273 TAILQ_REMOVE(&iocom->freeq, msg, qentry);
275 if ((cmd & (HAMMER2_MSGF_CREATE | HAMMER2_MSGF_REPLY)) ==
276 HAMMER2_MSGF_CREATE) {
278 * Create state when CREATE is set without REPLY.
280 * NOTE: CREATE in txcmd handled by hammer2_msg_write()
281 * NOTE: DELETE in txcmd handled by hammer2_state_cleanuptx()
283 state = malloc(sizeof(*state));
284 bzero(state, sizeof(*state));
285 state->iocom = iocom;
286 state->flags = HAMMER2_STATE_DYNAMIC;
287 state->msgid = (uint64_t)(uintptr_t)state;
288 state->router = router;
289 state->txcmd = cmd & ~(HAMMER2_MSGF_CREATE |
290 HAMMER2_MSGF_DELETE);
291 state->rxcmd = HAMMER2_MSGF_REPLY;
293 state->any.any = data;
294 pthread_mutex_lock(&iocom->mtx);
295 RB_INSERT(hammer2_state_tree,
296 &iocom->router->statewr_tree,
298 pthread_mutex_unlock(&iocom->mtx);
299 state->flags |= HAMMER2_STATE_INSERTED;
301 pthread_mutex_unlock(&iocom->mtx);
303 msg = malloc(sizeof(*msg));
304 bzero(msg, sizeof(*msg));
305 msg->aux_data = NULL;
308 if (msg->aux_size != aux_size) {
311 msg->aux_data = NULL;
315 msg->aux_data = malloc(aux_size);
316 msg->aux_size = aux_size;
319 hbytes = (cmd & HAMMER2_MSGF_SIZE) * HAMMER2_MSG_ALIGN;
321 bzero(&msg->any.head, hbytes);
322 msg->hdr_size = hbytes;
323 msg->any.head.cmd = cmd;
324 msg->any.head.aux_descr = 0;
325 msg->any.head.aux_crc = 0;
326 msg->router = router;
330 msg->any.head.msgid = state->msgid;
336 * Free a message so it can be reused afresh.
338 * NOTE: aux_size can be 0 with a non-NULL aux_data.
342 hammer2_msg_free_locked(hammer2_msg_t *msg)
344 hammer2_iocom_t *iocom = msg->router->iocom;
348 TAILQ_INSERT_TAIL(&iocom->freeq_aux, msg, qentry);
350 TAILQ_INSERT_TAIL(&iocom->freeq, msg, qentry);
354 hammer2_msg_free(hammer2_msg_t *msg)
356 hammer2_iocom_t *iocom = msg->router->iocom;
358 pthread_mutex_lock(&iocom->mtx);
359 hammer2_msg_free_locked(msg);
360 pthread_mutex_unlock(&iocom->mtx);
364 * I/O core loop for an iocom.
366 * Thread localized, iocom->mtx not held.
369 hammer2_iocom_core(hammer2_iocom_t *iocom)
371 struct pollfd fds[3];
376 int wi; /* wakeup pipe */
378 int ai; /* alt bulk path socket */
380 while ((iocom->flags & HAMMER2_IOCOMF_EOF) == 0) {
381 if ((iocom->flags & (HAMMER2_IOCOMF_RWORK |
382 HAMMER2_IOCOMF_WWORK |
383 HAMMER2_IOCOMF_PWORK |
384 HAMMER2_IOCOMF_SWORK |
385 HAMMER2_IOCOMF_ARWORK |
386 HAMMER2_IOCOMF_AWWORK)) == 0) {
388 * Only poll if no immediate work is pending.
389 * Otherwise we are just wasting our time calling
400 * Always check the inter-thread pipe, e.g.
401 * for iocom->txmsgq work.
404 fds[wi].fd = iocom->wakeupfds[0];
405 fds[wi].events = POLLIN;
409 * Check the socket input/output direction as
412 if (iocom->flags & (HAMMER2_IOCOMF_RREQ |
413 HAMMER2_IOCOMF_WREQ)) {
415 fds[si].fd = iocom->sock_fd;
419 if (iocom->flags & HAMMER2_IOCOMF_RREQ)
420 fds[si].events |= POLLIN;
421 if (iocom->flags & HAMMER2_IOCOMF_WREQ)
422 fds[si].events |= POLLOUT;
426 * Check the alternative fd for work.
428 if (iocom->alt_fd >= 0) {
430 fds[ai].fd = iocom->alt_fd;
431 fds[ai].events = POLLIN;
434 poll(fds, count, timeout);
436 if (wi >= 0 && (fds[wi].revents & POLLIN))
437 iocom->flags |= HAMMER2_IOCOMF_PWORK;
438 if (si >= 0 && (fds[si].revents & POLLIN))
439 iocom->flags |= HAMMER2_IOCOMF_RWORK;
440 if (si >= 0 && (fds[si].revents & POLLOUT))
441 iocom->flags |= HAMMER2_IOCOMF_WWORK;
442 if (wi >= 0 && (fds[wi].revents & POLLOUT))
443 iocom->flags |= HAMMER2_IOCOMF_WWORK;
444 if (ai >= 0 && (fds[ai].revents & POLLIN))
445 iocom->flags |= HAMMER2_IOCOMF_ARWORK;
448 * Always check the pipe
450 iocom->flags |= HAMMER2_IOCOMF_PWORK;
453 if (iocom->flags & HAMMER2_IOCOMF_SWORK) {
454 iocom->flags &= ~HAMMER2_IOCOMF_SWORK;
455 iocom->router->signal_callback(iocom->router);
459 * Pending message queues from other threads wake us up
460 * with a write to the wakeupfds[] pipe. We have to clear
461 * the pipe with a dummy read.
463 if (iocom->flags & HAMMER2_IOCOMF_PWORK) {
464 iocom->flags &= ~HAMMER2_IOCOMF_PWORK;
465 read(iocom->wakeupfds[0], dummybuf, sizeof(dummybuf));
466 iocom->flags |= HAMMER2_IOCOMF_RWORK;
467 iocom->flags |= HAMMER2_IOCOMF_WWORK;
468 if (TAILQ_FIRST(&iocom->router->txmsgq))
469 hammer2_iocom_flush1(iocom);
473 * Message write sequencing
475 if (iocom->flags & HAMMER2_IOCOMF_WWORK)
476 hammer2_iocom_flush1(iocom);
479 * Message read sequencing. Run this after the write
480 * sequencing in case the write sequencing allowed another
481 * auto-DELETE to occur on the read side.
483 if (iocom->flags & HAMMER2_IOCOMF_RWORK) {
484 while ((iocom->flags & HAMMER2_IOCOMF_EOF) == 0 &&
485 (msg = hammer2_ioq_read(iocom)) != NULL) {
487 fprintf(stderr, "receive %s\n",
488 hammer2_msg_str(msg));
490 iocom->router->rcvmsg_callback(msg);
491 hammer2_state_cleanuprx(iocom, msg);
495 if (iocom->flags & HAMMER2_IOCOMF_ARWORK) {
496 iocom->flags &= ~HAMMER2_IOCOMF_ARWORK;
497 iocom->router->altmsg_callback(iocom);
503 * Make sure there's enough room in the FIFO to hold the
506 * Assume worst case encrypted form is 2x the size of the
507 * plaintext equivalent.
511 hammer2_ioq_makeroom(hammer2_ioq_t *ioq, size_t needed)
516 bytes = ioq->fifo_cdx - ioq->fifo_beg;
517 nmax = sizeof(ioq->buf) - ioq->fifo_end;
518 if (bytes + nmax / 2 < needed) {
520 bcopy(ioq->buf + ioq->fifo_beg,
524 ioq->fifo_cdx -= ioq->fifo_beg;
526 if (ioq->fifo_cdn < ioq->fifo_end) {
527 bcopy(ioq->buf + ioq->fifo_cdn,
528 ioq->buf + ioq->fifo_cdx,
529 ioq->fifo_end - ioq->fifo_cdn);
531 ioq->fifo_end -= ioq->fifo_cdn - ioq->fifo_cdx;
532 ioq->fifo_cdn = ioq->fifo_cdx;
533 nmax = sizeof(ioq->buf) - ioq->fifo_end;
539 * Read the next ready message from the ioq, issuing I/O if needed.
540 * Caller should retry on a read-event when NULL is returned.
542 * If an error occurs during reception a HAMMER2_LNK_ERROR msg will
543 * be returned for each open transaction, then the ioq and iocom
544 * will be errored out and a non-transactional HAMMER2_LNK_ERROR
545 * msg will be returned as the final message. The caller should not call
546 * us again after the final message is returned.
548 * Thread localized, iocom->mtx not held.
551 hammer2_ioq_read(hammer2_iocom_t *iocom)
553 hammer2_ioq_t *ioq = &iocom->ioq_rx;
555 hammer2_msg_hdr_t *head;
556 hammer2_state_t *state;
564 iocom->flags &= ~(HAMMER2_IOCOMF_RREQ | HAMMER2_IOCOMF_RWORK);
567 * If a message is already pending we can just remove and
568 * return it. Message state has already been processed.
569 * (currently not implemented)
571 if ((msg = TAILQ_FIRST(&ioq->msgq)) != NULL) {
572 TAILQ_REMOVE(&ioq->msgq, msg, qentry);
577 * If the stream is errored out we stop processing it.
583 * Message read in-progress (msg is NULL at the moment). We don't
584 * allocate a msg until we have its core header.
586 nmax = sizeof(ioq->buf) - ioq->fifo_end;
587 bytes = ioq->fifo_cdx - ioq->fifo_beg; /* already decrypted */
591 case HAMMER2_MSGQ_STATE_HEADER1:
593 * Load the primary header, fail on any non-trivial read
594 * error or on EOF. Since the primary header is the same
595 * size is the message alignment it will never straddle
596 * the end of the buffer.
598 nmax = hammer2_ioq_makeroom(ioq, sizeof(msg->any.head));
599 if (bytes < sizeof(msg->any.head)) {
600 n = read(iocom->sock_fd,
601 ioq->buf + ioq->fifo_end,
605 ioq->error = HAMMER2_IOQ_ERROR_EOF;
608 if (errno != EINTR &&
609 errno != EINPROGRESS &&
611 ioq->error = HAMMER2_IOQ_ERROR_SOCK;
617 ioq->fifo_end += (size_t)n;
622 * Decrypt data received so far. Data will be decrypted
623 * in-place but might create gaps in the FIFO. Partial
624 * blocks are not immediately decrypted.
626 * WARNING! The header might be in the wrong endian, we
627 * do not fix it up until we get the entire
630 if (iocom->flags & HAMMER2_IOCOMF_CRYPTED) {
631 hammer2_crypto_decrypt(iocom, ioq);
633 ioq->fifo_cdx = ioq->fifo_end;
634 ioq->fifo_cdn = ioq->fifo_end;
636 bytes = ioq->fifo_cdx - ioq->fifo_beg;
639 * Insufficient data accumulated (msg is NULL, caller will
643 if (bytes < sizeof(msg->any.head))
647 * Check and fixup the core header. Note that the icrc
648 * has to be calculated before any fixups, but the crc
649 * fields in the msg may have to be swapped like everything
652 head = (void *)(ioq->buf + ioq->fifo_beg);
653 if (head->magic != HAMMER2_MSGHDR_MAGIC &&
654 head->magic != HAMMER2_MSGHDR_MAGIC_REV) {
655 ioq->error = HAMMER2_IOQ_ERROR_SYNC;
660 * Calculate the full header size and aux data size
662 if (head->magic == HAMMER2_MSGHDR_MAGIC_REV) {
663 ioq->hbytes = (bswap32(head->cmd) & HAMMER2_MSGF_SIZE) *
665 ioq->abytes = bswap32(head->aux_bytes) *
668 ioq->hbytes = (head->cmd & HAMMER2_MSGF_SIZE) *
670 ioq->abytes = head->aux_bytes * HAMMER2_MSG_ALIGN;
672 if (ioq->hbytes < sizeof(msg->any.head) ||
673 ioq->hbytes > sizeof(msg->any) ||
674 ioq->abytes > HAMMER2_MSGAUX_MAX) {
675 ioq->error = HAMMER2_IOQ_ERROR_FIELD;
680 * Allocate the message, the next state will fill it in.
682 msg = hammer2_msg_alloc(iocom->router, ioq->abytes, 0,
687 * Fall through to the next state. Make sure that the
688 * extended header does not straddle the end of the buffer.
689 * We still want to issue larger reads into our buffer,
690 * book-keeping is easier if we don't bcopy() yet.
692 * Make sure there is enough room for bloated encrypt data.
694 nmax = hammer2_ioq_makeroom(ioq, ioq->hbytes);
695 ioq->state = HAMMER2_MSGQ_STATE_HEADER2;
697 case HAMMER2_MSGQ_STATE_HEADER2:
699 * Fill out the extended header.
702 if (bytes < ioq->hbytes) {
703 n = read(iocom->sock_fd,
704 ioq->buf + ioq->fifo_end,
708 ioq->error = HAMMER2_IOQ_ERROR_EOF;
711 if (errno != EINTR &&
712 errno != EINPROGRESS &&
714 ioq->error = HAMMER2_IOQ_ERROR_SOCK;
720 ioq->fifo_end += (size_t)n;
724 if (iocom->flags & HAMMER2_IOCOMF_CRYPTED) {
725 hammer2_crypto_decrypt(iocom, ioq);
727 ioq->fifo_cdx = ioq->fifo_end;
728 ioq->fifo_cdn = ioq->fifo_end;
730 bytes = ioq->fifo_cdx - ioq->fifo_beg;
733 * Insufficient data accumulated (set msg NULL so caller will
736 if (bytes < ioq->hbytes) {
742 * Calculate the extended header, decrypt data received
743 * so far. Handle endian-conversion for the entire extended
746 head = (void *)(ioq->buf + ioq->fifo_beg);
751 if (head->magic == HAMMER2_MSGHDR_MAGIC_REV)
752 xcrc32 = bswap32(head->hdr_crc);
754 xcrc32 = head->hdr_crc;
756 if (hammer2_icrc32(head, ioq->hbytes) != xcrc32) {
757 ioq->error = HAMMER2_IOQ_ERROR_XCRC;
758 fprintf(stderr, "BAD-XCRC(%08x,%08x) %s\n",
759 xcrc32, hammer2_icrc32(head, ioq->hbytes),
760 hammer2_msg_str(msg));
764 head->hdr_crc = xcrc32;
766 if (head->magic == HAMMER2_MSGHDR_MAGIC_REV) {
767 hammer2_bswap_head(head);
771 * Copy the extended header into the msg and adjust the
774 bcopy(head, &msg->any, ioq->hbytes);
777 * We are either done or we fall-through.
779 if (ioq->abytes == 0) {
780 ioq->fifo_beg += ioq->hbytes;
785 * Must adjust bytes (and the state) when falling through.
786 * nmax doesn't change.
788 ioq->fifo_beg += ioq->hbytes;
789 bytes -= ioq->hbytes;
790 ioq->state = HAMMER2_MSGQ_STATE_AUXDATA1;
792 case HAMMER2_MSGQ_STATE_AUXDATA1:
794 * Copy the partial or complete payload from remaining
795 * bytes in the FIFO in order to optimize the makeroom call
796 * in the AUXDATA2 state. We have to fall-through either
797 * way so we can check the crc.
799 * msg->aux_size tracks our aux data.
801 if (bytes >= ioq->abytes) {
802 bcopy(ioq->buf + ioq->fifo_beg, msg->aux_data,
804 msg->aux_size = ioq->abytes;
805 ioq->fifo_beg += ioq->abytes;
806 assert(ioq->fifo_beg <= ioq->fifo_cdx);
807 assert(ioq->fifo_cdx <= ioq->fifo_cdn);
808 bytes -= ioq->abytes;
810 bcopy(ioq->buf + ioq->fifo_beg, msg->aux_data,
812 msg->aux_size = bytes;
813 ioq->fifo_beg += bytes;
814 if (ioq->fifo_cdx < ioq->fifo_beg)
815 ioq->fifo_cdx = ioq->fifo_beg;
816 assert(ioq->fifo_beg <= ioq->fifo_cdx);
817 assert(ioq->fifo_cdx <= ioq->fifo_cdn);
822 ioq->state = HAMMER2_MSGQ_STATE_AUXDATA2;
824 case HAMMER2_MSGQ_STATE_AUXDATA2:
826 * Make sure there is enough room for more data.
829 nmax = hammer2_ioq_makeroom(ioq, ioq->abytes - msg->aux_size);
832 * Read and decrypt more of the payload.
834 if (msg->aux_size < ioq->abytes) {
836 n = read(iocom->sock_fd,
837 ioq->buf + ioq->fifo_end,
841 ioq->error = HAMMER2_IOQ_ERROR_EOF;
844 if (errno != EINTR &&
845 errno != EINPROGRESS &&
847 ioq->error = HAMMER2_IOQ_ERROR_SOCK;
853 ioq->fifo_end += (size_t)n;
857 if (iocom->flags & HAMMER2_IOCOMF_CRYPTED) {
858 hammer2_crypto_decrypt(iocom, ioq);
860 ioq->fifo_cdx = ioq->fifo_end;
861 ioq->fifo_cdn = ioq->fifo_end;
863 bytes = ioq->fifo_cdx - ioq->fifo_beg;
865 if (bytes > ioq->abytes - msg->aux_size)
866 bytes = ioq->abytes - msg->aux_size;
869 bcopy(ioq->buf + ioq->fifo_beg,
870 msg->aux_data + msg->aux_size,
872 msg->aux_size += bytes;
873 ioq->fifo_beg += bytes;
877 * Insufficient data accumulated (set msg NULL so caller will
880 if (msg->aux_size < ioq->abytes) {
884 assert(msg->aux_size == ioq->abytes);
887 * Check aux_crc, then we are done.
889 xcrc32 = hammer2_icrc32(msg->aux_data, msg->aux_size);
890 if (xcrc32 != msg->any.head.aux_crc) {
891 ioq->error = HAMMER2_IOQ_ERROR_ACRC;
895 case HAMMER2_MSGQ_STATE_ERROR:
897 * Continued calls to drain recorded transactions (returning
898 * a LNK_ERROR for each one), before we return the final
905 * We don't double-return errors, the caller should not
906 * have called us again after getting an error msg.
913 * Check the message sequence. The iv[] should prevent any
914 * possibility of a replay but we add this check anyway.
916 if (msg && ioq->error == 0) {
917 if ((msg->any.head.salt & 255) != (ioq->seq & 255)) {
918 ioq->error = HAMMER2_IOQ_ERROR_MSGSEQ;
925 * Process transactional state for the message.
927 if (msg && ioq->error == 0) {
928 error = hammer2_state_msgrx(msg);
930 if (error == HAMMER2_IOQ_ERROR_EALREADY) {
931 hammer2_msg_free(msg);
939 * Handle error, RREQ, or completion
941 * NOTE: nmax and bytes are invalid at this point, we don't bother
942 * to update them when breaking out.
947 * An unrecoverable error causes all active receive
948 * transactions to be terminated with a LNK_ERROR message.
950 * Once all active transactions are exhausted we set the
951 * iocom ERROR flag and return a non-transactional LNK_ERROR
952 * message, which should cause master processing loops to
955 assert(ioq->msg == msg);
957 hammer2_msg_free(msg);
962 * No more I/O read processing
964 ioq->state = HAMMER2_MSGQ_STATE_ERROR;
967 * Simulate a remote LNK_ERROR DELETE msg for any open
968 * transactions, ending with a final non-transactional
969 * LNK_ERROR (that the session can detect) when no
970 * transactions remain.
972 msg = hammer2_msg_alloc(iocom->router, 0, 0, NULL, NULL);
973 bzero(&msg->any.head, sizeof(msg->any.head));
974 msg->any.head.magic = HAMMER2_MSGHDR_MAGIC;
975 msg->any.head.cmd = HAMMER2_LNK_ERROR;
976 msg->any.head.error = ioq->error;
978 pthread_mutex_lock(&iocom->mtx);
979 hammer2_iocom_drain(iocom);
980 if ((state = RB_ROOT(&iocom->router->staterd_tree)) != NULL) {
982 * Active remote transactions are still present.
983 * Simulate the other end sending us a DELETE.
985 if (state->rxcmd & HAMMER2_MSGF_DELETE) {
986 hammer2_msg_free(msg);
989 /*state->txcmd |= HAMMER2_MSGF_DELETE;*/
991 msg->router = state->router;
992 msg->any.head.msgid = state->msgid;
993 msg->any.head.cmd |= HAMMER2_MSGF_ABORT |
996 } else if ((state = RB_ROOT(&iocom->router->statewr_tree)) !=
999 * Active local transactions are still present.
1000 * Simulate the other end sending us a DELETE.
1002 if (state->rxcmd & HAMMER2_MSGF_DELETE) {
1003 hammer2_msg_free(msg);
1007 msg->router = state->router;
1008 msg->any.head.msgid = state->msgid;
1009 msg->any.head.cmd |= HAMMER2_MSGF_ABORT |
1010 HAMMER2_MSGF_DELETE |
1012 if ((state->rxcmd & HAMMER2_MSGF_CREATE) == 0) {
1013 msg->any.head.cmd |=
1014 HAMMER2_MSGF_CREATE;
1019 * No active local or remote transactions remain.
1020 * Generate a final LNK_ERROR and flag EOF.
1023 iocom->flags |= HAMMER2_IOCOMF_EOF;
1024 fprintf(stderr, "EOF ON SOCKET %d\n", iocom->sock_fd);
1026 pthread_mutex_unlock(&iocom->mtx);
1029 * For the iocom error case we want to set RWORK to indicate
1030 * that more messages might be pending.
1032 * It is possible to return NULL when there is more work to
1033 * do because each message has to be DELETEd in both
1034 * directions before we continue on with the next (though
1035 * this could be optimized). The transmit direction will
1039 iocom->flags |= HAMMER2_IOCOMF_RWORK;
1040 } else if (msg == NULL) {
1042 * Insufficient data received to finish building the message,
1043 * set RREQ and return NULL.
1045 * Leave ioq->msg intact.
1046 * Leave the FIFO intact.
1048 iocom->flags |= HAMMER2_IOCOMF_RREQ;
1053 * The fifo has already been advanced past the message.
1054 * Trivially reset the FIFO indices if possible.
1056 * clear the FIFO if it is now empty and set RREQ to wait
1057 * for more from the socket. If the FIFO is not empty set
1058 * TWORK to bypass the poll so we loop immediately.
1060 if (ioq->fifo_beg == ioq->fifo_cdx &&
1061 ioq->fifo_cdn == ioq->fifo_end) {
1062 iocom->flags |= HAMMER2_IOCOMF_RREQ;
1068 iocom->flags |= HAMMER2_IOCOMF_RWORK;
1070 ioq->state = HAMMER2_MSGQ_STATE_HEADER1;
1077 * Calculate the header and data crc's and write a low-level message to
1078 * the connection. If aux_crc is non-zero the aux_data crc is already
1079 * assumed to have been set.
1081 * A non-NULL msg is added to the queue but not necessarily flushed.
1082 * Calling this function with msg == NULL will get a flush going.
1084 * Caller must hold iocom->mtx.
1087 hammer2_iocom_flush1(hammer2_iocom_t *iocom)
1089 hammer2_ioq_t *ioq = &iocom->ioq_tx;
1093 hammer2_msg_queue_t tmpq;
1095 iocom->flags &= ~(HAMMER2_IOCOMF_WREQ | HAMMER2_IOCOMF_WWORK);
1097 pthread_mutex_lock(&iocom->mtx);
1098 while ((msg = TAILQ_FIRST(&iocom->router->txmsgq)) != NULL) {
1099 TAILQ_REMOVE(&iocom->router->txmsgq, msg, qentry);
1100 TAILQ_INSERT_TAIL(&tmpq, msg, qentry);
1102 pthread_mutex_unlock(&iocom->mtx);
1104 while ((msg = TAILQ_FIRST(&tmpq)) != NULL) {
1106 * Process terminal connection errors.
1108 TAILQ_REMOVE(&tmpq, msg, qentry);
1110 TAILQ_INSERT_TAIL(&ioq->msgq, msg, qentry);
1116 * Finish populating the msg fields. The salt ensures that
1117 * the iv[] array is ridiculously randomized and we also
1118 * re-seed our PRNG every 32768 messages just to be sure.
1120 msg->any.head.magic = HAMMER2_MSGHDR_MAGIC;
1121 msg->any.head.salt = (random() << 8) | (ioq->seq & 255);
1123 if ((ioq->seq & 32767) == 0)
1127 * Calculate aux_crc if 0, then calculate hdr_crc.
1129 if (msg->aux_size && msg->any.head.aux_crc == 0) {
1130 assert((msg->aux_size & HAMMER2_MSG_ALIGNMASK) == 0);
1131 xcrc32 = hammer2_icrc32(msg->aux_data, msg->aux_size);
1132 msg->any.head.aux_crc = xcrc32;
1134 msg->any.head.aux_bytes = msg->aux_size / HAMMER2_MSG_ALIGN;
1135 assert((msg->aux_size & HAMMER2_MSG_ALIGNMASK) == 0);
1137 hbytes = (msg->any.head.cmd & HAMMER2_MSGF_SIZE) *
1139 msg->any.head.hdr_crc = 0;
1140 msg->any.head.hdr_crc = hammer2_icrc32(&msg->any.head, hbytes);
1143 * Enqueue the message (the flush codes handles stream
1146 TAILQ_INSERT_TAIL(&ioq->msgq, msg, qentry);
1149 hammer2_iocom_flush2(iocom);
1153 * Thread localized, iocom->mtx not held by caller.
1156 hammer2_iocom_flush2(hammer2_iocom_t *iocom)
1158 hammer2_ioq_t *ioq = &iocom->ioq_tx;
1161 struct iovec iov[HAMMER2_IOQ_MAXIOVEC];
1170 hammer2_iocom_drain(iocom);
1175 * Pump messages out the connection by building an iovec.
1177 * ioq->hbytes/ioq->abytes tracks how much of the first message
1178 * in the queue has been successfully written out, so we can
1186 TAILQ_FOREACH(msg, &ioq->msgq, qentry) {
1187 hbytes = (msg->any.head.cmd & HAMMER2_MSGF_SIZE) *
1189 abytes = msg->aux_size;
1190 assert(hoff <= hbytes && aoff <= abytes);
1192 if (hoff < hbytes) {
1193 iov[iovcnt].iov_base = (char *)&msg->any.head + hoff;
1194 iov[iovcnt].iov_len = hbytes - hoff;
1195 nact += hbytes - hoff;
1197 if (iovcnt == HAMMER2_IOQ_MAXIOVEC)
1200 if (aoff < abytes) {
1201 assert(msg->aux_data != NULL);
1202 iov[iovcnt].iov_base = (char *)msg->aux_data + aoff;
1203 iov[iovcnt].iov_len = abytes - aoff;
1204 nact += abytes - aoff;
1206 if (iovcnt == HAMMER2_IOQ_MAXIOVEC)
1216 * Encrypt and write the data. The crypto code will move the
1217 * data into the fifo and adjust the iov as necessary. If
1218 * encryption is disabled the iov is left alone.
1220 * May return a smaller iov (thus a smaller n), with aggregated
1221 * chunks. May reduce nmax to what fits in the FIFO.
1223 * This function sets nact to the number of original bytes now
1224 * encrypted, adding to the FIFO some number of bytes that might
1225 * be greater depending on the crypto mechanic. iov[] is adjusted
1226 * to point at the FIFO if necessary.
1228 * NOTE: The return value from the writev() is the post-encrypted
1229 * byte count, not the plaintext count.
1231 if (iocom->flags & HAMMER2_IOCOMF_CRYPTED) {
1233 * Make sure the FIFO has a reasonable amount of space
1234 * left (if not completely full).
1236 if (ioq->fifo_beg > sizeof(ioq->buf) / 2 &&
1237 sizeof(ioq->buf) - ioq->fifo_end >= HAMMER2_MSG_ALIGN * 2) {
1238 bcopy(ioq->buf + ioq->fifo_beg, ioq->buf,
1239 ioq->fifo_end - ioq->fifo_beg);
1240 ioq->fifo_cdx -= ioq->fifo_beg;
1241 ioq->fifo_cdn -= ioq->fifo_beg;
1242 ioq->fifo_end -= ioq->fifo_beg;
1246 iovcnt = hammer2_crypto_encrypt(iocom, ioq, iov, iovcnt, &nact);
1247 n = writev(iocom->sock_fd, iov, iovcnt);
1252 if (ioq->fifo_beg == ioq->fifo_end) {
1260 n = writev(iocom->sock_fd, iov, iovcnt);
1268 * Clean out the transmit queue based on what we successfully
1269 * sent (nact is the plaintext count). ioq->hbytes/abytes
1270 * represents the portion of the first message previously sent.
1272 while ((msg = TAILQ_FIRST(&ioq->msgq)) != NULL) {
1273 hbytes = (msg->any.head.cmd & HAMMER2_MSGF_SIZE) *
1275 abytes = msg->aux_size;
1277 if ((size_t)nact < hbytes - ioq->hbytes) {
1278 ioq->hbytes += nact;
1282 nact -= hbytes - ioq->hbytes;
1283 ioq->hbytes = hbytes;
1284 if ((size_t)nact < abytes - ioq->abytes) {
1285 ioq->abytes += nact;
1289 nact -= abytes - ioq->abytes;
1291 TAILQ_REMOVE(&ioq->msgq, msg, qentry);
1296 hammer2_state_cleanuptx(msg);
1301 * Process the return value from the write w/regards to blocking.
1304 if (errno != EINTR &&
1305 errno != EINPROGRESS &&
1310 ioq->error = HAMMER2_IOQ_ERROR_SOCK;
1311 hammer2_iocom_drain(iocom);
1314 * Wait for socket buffer space
1316 iocom->flags |= HAMMER2_IOCOMF_WREQ;
1319 iocom->flags |= HAMMER2_IOCOMF_WREQ;
1322 hammer2_iocom_drain(iocom);
1327 * Kill pending msgs on ioq_tx and adjust the flags such that no more
1328 * write events will occur. We don't kill read msgs because we want
1329 * the caller to pull off our contrived terminal error msg to detect
1330 * the connection failure.
1332 * Thread localized, iocom->mtx not held by caller.
1335 hammer2_iocom_drain(hammer2_iocom_t *iocom)
1337 hammer2_ioq_t *ioq = &iocom->ioq_tx;
1340 iocom->flags &= ~(HAMMER2_IOCOMF_WREQ | HAMMER2_IOCOMF_WWORK);
1344 while ((msg = TAILQ_FIRST(&ioq->msgq)) != NULL) {
1345 TAILQ_REMOVE(&ioq->msgq, msg, qentry);
1347 hammer2_state_cleanuptx(msg);
1352 * Write a message to an iocom, with additional state processing.
1355 hammer2_msg_write(hammer2_msg_t *msg)
1357 hammer2_iocom_t *iocom = msg->router->iocom;
1358 hammer2_state_t *state;
1362 * Handle state processing, create state if necessary.
1364 pthread_mutex_lock(&iocom->mtx);
1365 if ((state = msg->state) != NULL) {
1367 * Existing transaction (could be reply). It is also
1368 * possible for this to be the first reply (CREATE is set),
1369 * in which case we populate state->txcmd.
1371 * state->txcmd is adjusted to hold the final message cmd,
1372 * and we also be sure to set the CREATE bit here. We did
1373 * not set it in hammer2_msg_alloc() because that would have
1374 * not been serialized (state could have gotten ripped out
1375 * from under the message prior to it being transmitted).
1377 if ((msg->any.head.cmd & (HAMMER2_MSGF_CREATE |
1378 HAMMER2_MSGF_REPLY)) ==
1379 HAMMER2_MSGF_CREATE) {
1380 state->txcmd = msg->any.head.cmd & ~HAMMER2_MSGF_DELETE;
1382 msg->any.head.msgid = state->msgid;
1383 assert(((state->txcmd ^ msg->any.head.cmd) &
1384 HAMMER2_MSGF_REPLY) == 0);
1385 if (msg->any.head.cmd & HAMMER2_MSGF_CREATE)
1386 state->txcmd = msg->any.head.cmd & ~HAMMER2_MSGF_DELETE;
1388 msg->any.head.msgid = 0;
1389 /* XXX set spanid by router */
1391 msg->any.head.source = 0;
1392 msg->any.head.target = msg->router->target;
1395 * Queue it for output, wake up the I/O pthread. Note that the
1396 * I/O thread is responsible for generating the CRCs and encryption.
1398 TAILQ_INSERT_TAIL(&iocom->router->txmsgq, msg, qentry);
1400 write(iocom->wakeupfds[1], &dummy, 1); /* XXX optimize me */
1401 pthread_mutex_unlock(&iocom->mtx);
1405 * This is a shortcut to formulate a reply to msg with a simple error code,
1406 * It can reply to and terminate a transaction, or it can reply to a one-way
1407 * messages. A HAMMER2_LNK_ERROR command code is utilized to encode
1408 * the error code (which can be 0). Not all transactions are terminated
1409 * with HAMMER2_LNK_ERROR status (the low level only cares about the
1410 * MSGF_DELETE flag), but most are.
1412 * Replies to one-way messages are a bit of an oxymoron but the feature
1413 * is used by the debug (DBG) protocol.
1415 * The reply contains no extended data.
1418 hammer2_msg_reply(hammer2_msg_t *msg, uint32_t error)
1420 hammer2_iocom_t *iocom = msg->router->iocom;
1421 hammer2_state_t *state = msg->state;
1422 hammer2_msg_t *nmsg;
1427 * Reply with a simple error code and terminate the transaction.
1429 cmd = HAMMER2_LNK_ERROR;
1432 * Check if our direction has even been initiated yet, set CREATE.
1434 * Check what direction this is (command or reply direction). Note
1435 * that txcmd might not have been initiated yet.
1437 * If our direction has already been closed we just return without
1441 if (state->txcmd & HAMMER2_MSGF_DELETE)
1443 if (state->txcmd & HAMMER2_MSGF_REPLY)
1444 cmd |= HAMMER2_MSGF_REPLY;
1445 cmd |= HAMMER2_MSGF_DELETE;
1447 if ((msg->any.head.cmd & HAMMER2_MSGF_REPLY) == 0)
1448 cmd |= HAMMER2_MSGF_REPLY;
1452 * Allocate the message and associate it with the existing state.
1453 * We cannot pass MSGF_CREATE to msg_alloc() because that may
1454 * allocate new state. We have our state already.
1456 nmsg = hammer2_msg_alloc(iocom->router, 0, cmd, NULL, NULL);
1458 if ((state->txcmd & HAMMER2_MSGF_CREATE) == 0)
1459 nmsg->any.head.cmd |= HAMMER2_MSGF_CREATE;
1461 nmsg->any.head.error = error;
1462 nmsg->state = state;
1463 hammer2_msg_write(nmsg);
1467 * Similar to hammer2_msg_reply() but leave the transaction open. That is,
1468 * we are generating a streaming reply or an intermediate acknowledgement
1469 * of some sort as part of the higher level protocol, with more to come
1473 hammer2_msg_result(hammer2_msg_t *msg, uint32_t error)
1475 hammer2_iocom_t *iocom = msg->router->iocom;
1476 hammer2_state_t *state = msg->state;
1477 hammer2_msg_t *nmsg;
1482 * Reply with a simple error code and terminate the transaction.
1484 cmd = HAMMER2_LNK_ERROR;
1487 * Check if our direction has even been initiated yet, set CREATE.
1489 * Check what direction this is (command or reply direction). Note
1490 * that txcmd might not have been initiated yet.
1492 * If our direction has already been closed we just return without
1496 if (state->txcmd & HAMMER2_MSGF_DELETE)
1498 if (state->txcmd & HAMMER2_MSGF_REPLY)
1499 cmd |= HAMMER2_MSGF_REPLY;
1500 /* continuing transaction, do not set MSGF_DELETE */
1502 if ((msg->any.head.cmd & HAMMER2_MSGF_REPLY) == 0)
1503 cmd |= HAMMER2_MSGF_REPLY;
1506 nmsg = hammer2_msg_alloc(iocom->router, 0, cmd, NULL, NULL);
1508 if ((state->txcmd & HAMMER2_MSGF_CREATE) == 0)
1509 nmsg->any.head.cmd |= HAMMER2_MSGF_CREATE;
1511 nmsg->any.head.error = error;
1512 nmsg->state = state;
1513 hammer2_msg_write(nmsg);
1517 * Terminate a transaction given a state structure by issuing a DELETE.
1520 hammer2_state_reply(hammer2_state_t *state, uint32_t error)
1522 hammer2_msg_t *nmsg;
1523 uint32_t cmd = HAMMER2_LNK_ERROR | HAMMER2_MSGF_DELETE;
1526 * Nothing to do if we already transmitted a delete
1528 if (state->txcmd & HAMMER2_MSGF_DELETE)
1532 * Set REPLY if the other end initiated the command. Otherwise
1533 * we are the command direction.
1535 if (state->txcmd & HAMMER2_MSGF_REPLY)
1536 cmd |= HAMMER2_MSGF_REPLY;
1538 nmsg = hammer2_msg_alloc(state->iocom->router, 0, cmd, NULL, NULL);
1540 if ((state->txcmd & HAMMER2_MSGF_CREATE) == 0)
1541 nmsg->any.head.cmd |= HAMMER2_MSGF_CREATE;
1543 nmsg->any.head.error = error;
1544 nmsg->state = state;
1545 hammer2_msg_write(nmsg);
1548 /************************************************************************
1549 * TRANSACTION STATE HANDLING *
1550 ************************************************************************
1555 * Process state tracking for a message after reception, prior to
1558 * Called with msglk held and the msg dequeued.
1560 * All messages are called with dummy state and return actual state.
1561 * (One-off messages often just return the same dummy state).
1563 * May request that caller discard the message by setting *discardp to 1.
1564 * The returned state is not used in this case and is allowed to be NULL.
1568 * These routines handle persistent and command/reply message state via the
1569 * CREATE and DELETE flags. The first message in a command or reply sequence
1570 * sets CREATE, the last message in a command or reply sequence sets DELETE.
1572 * There can be any number of intermediate messages belonging to the same
1573 * sequence sent inbetween the CREATE message and the DELETE message,
1574 * which set neither flag. This represents a streaming command or reply.
1576 * Any command message received with CREATE set expects a reply sequence to
1577 * be returned. Reply sequences work the same as command sequences except the
1578 * REPLY bit is also sent. Both the command side and reply side can
1579 * degenerate into a single message with both CREATE and DELETE set. Note
1580 * that one side can be streaming and the other side not, or neither, or both.
1582 * The msgid is unique for the initiator. That is, two sides sending a new
1583 * message can use the same msgid without colliding.
1587 * ABORT sequences work by setting the ABORT flag along with normal message
1588 * state. However, ABORTs can also be sent on half-closed messages, that is
1589 * even if the command or reply side has already sent a DELETE, as long as
1590 * the message has not been fully closed it can still send an ABORT+DELETE
1591 * to terminate the half-closed message state.
1593 * Since ABORT+DELETEs can race we silently discard ABORT's for message
1594 * state which has already been fully closed. REPLY+ABORT+DELETEs can
1595 * also race, and in this situation the other side might have already
1596 * initiated a new unrelated command with the same message id. Since
1597 * the abort has not set the CREATE flag the situation can be detected
1598 * and the message will also be discarded.
1600 * Non-blocking requests can be initiated with ABORT+CREATE[+DELETE].
1601 * The ABORT request is essentially integrated into the command instead
1602 * of being sent later on. In this situation the command implementation
1603 * detects that CREATE and ABORT are both set (vs ABORT alone) and can
1604 * special-case non-blocking operation for the command.
1606 * NOTE! Messages with ABORT set without CREATE or DELETE are considered
1607 * to be mid-stream aborts for command/reply sequences. ABORTs on
1608 * one-way messages are not supported.
1610 * NOTE! If a command sequence does not support aborts the ABORT flag is
1615 * One-off messages (no reply expected) are sent with neither CREATE or DELETE
1616 * set. One-off messages cannot be aborted and typically aren't processed
1617 * by these routines. The REPLY bit can be used to distinguish whether a
1618 * one-off message is a command or reply. For example, one-off replies
1619 * will typically just contain status updates.
1622 hammer2_state_msgrx(hammer2_msg_t *msg)
1624 hammer2_iocom_t *iocom = msg->router->iocom;
1625 hammer2_state_t *state;
1626 hammer2_state_t dummy;
1630 * Lock RB tree and locate existing persistent state, if any.
1632 * If received msg is a command state is on staterd_tree.
1633 * If received msg is a reply state is on statewr_tree.
1635 dummy.msgid = msg->any.head.msgid;
1636 pthread_mutex_lock(&iocom->mtx);
1637 if (msg->any.head.cmd & HAMMER2_MSGF_REPLY) {
1638 state = RB_FIND(hammer2_state_tree,
1639 &iocom->router->statewr_tree, &dummy);
1641 state = RB_FIND(hammer2_state_tree,
1642 &iocom->router->staterd_tree, &dummy);
1645 pthread_mutex_unlock(&iocom->mtx);
1648 * Short-cut one-off or mid-stream messages (state may be NULL).
1650 if ((msg->any.head.cmd & (HAMMER2_MSGF_CREATE | HAMMER2_MSGF_DELETE |
1651 HAMMER2_MSGF_ABORT)) == 0) {
1656 * Switch on CREATE, DELETE, REPLY, and also handle ABORT from
1657 * inside the case statements.
1659 switch(msg->any.head.cmd & (HAMMER2_MSGF_CREATE | HAMMER2_MSGF_DELETE |
1660 HAMMER2_MSGF_REPLY)) {
1661 case HAMMER2_MSGF_CREATE:
1662 case HAMMER2_MSGF_CREATE | HAMMER2_MSGF_DELETE:
1664 * New persistant command received.
1667 fprintf(stderr, "duplicate-trans %s\n",
1668 hammer2_msg_str(msg));
1669 error = HAMMER2_IOQ_ERROR_TRANS;
1673 state = malloc(sizeof(*state));
1674 bzero(state, sizeof(*state));
1675 state->iocom = iocom;
1676 state->flags = HAMMER2_STATE_DYNAMIC;
1678 state->txcmd = HAMMER2_MSGF_REPLY;
1679 state->rxcmd = msg->any.head.cmd & ~HAMMER2_MSGF_DELETE;
1680 state->flags |= HAMMER2_STATE_INSERTED;
1681 state->msgid = msg->any.head.msgid;
1682 state->router = msg->router;
1684 pthread_mutex_lock(&iocom->mtx);
1685 RB_INSERT(hammer2_state_tree,
1686 &iocom->router->staterd_tree, state);
1687 pthread_mutex_unlock(&iocom->mtx);
1690 fprintf(stderr, "create state %p id=%08x on iocom staterd %p\n",
1691 state, (uint32_t)state->msgid, iocom);
1694 case HAMMER2_MSGF_DELETE:
1696 * Persistent state is expected but might not exist if an
1697 * ABORT+DELETE races the close.
1699 if (state == NULL) {
1700 if (msg->any.head.cmd & HAMMER2_MSGF_ABORT) {
1701 error = HAMMER2_IOQ_ERROR_EALREADY;
1703 fprintf(stderr, "missing-state %s\n",
1704 hammer2_msg_str(msg));
1705 error = HAMMER2_IOQ_ERROR_TRANS;
1712 * Handle another ABORT+DELETE case if the msgid has already
1715 if ((state->rxcmd & HAMMER2_MSGF_CREATE) == 0) {
1716 if (msg->any.head.cmd & HAMMER2_MSGF_ABORT) {
1717 error = HAMMER2_IOQ_ERROR_EALREADY;
1719 fprintf(stderr, "reused-state %s\n",
1720 hammer2_msg_str(msg));
1721 error = HAMMER2_IOQ_ERROR_TRANS;
1730 * Check for mid-stream ABORT command received, otherwise
1733 if (msg->any.head.cmd & HAMMER2_MSGF_ABORT) {
1734 if (state == NULL ||
1735 (state->rxcmd & HAMMER2_MSGF_CREATE) == 0) {
1736 error = HAMMER2_IOQ_ERROR_EALREADY;
1742 case HAMMER2_MSGF_REPLY | HAMMER2_MSGF_CREATE:
1743 case HAMMER2_MSGF_REPLY | HAMMER2_MSGF_CREATE | HAMMER2_MSGF_DELETE:
1745 * When receiving a reply with CREATE set the original
1746 * persistent state message should already exist.
1748 if (state == NULL) {
1749 fprintf(stderr, "no-state(r) %s\n",
1750 hammer2_msg_str(msg));
1751 error = HAMMER2_IOQ_ERROR_TRANS;
1755 assert(((state->rxcmd ^ msg->any.head.cmd) &
1756 HAMMER2_MSGF_REPLY) == 0);
1757 state->rxcmd = msg->any.head.cmd & ~HAMMER2_MSGF_DELETE;
1760 case HAMMER2_MSGF_REPLY | HAMMER2_MSGF_DELETE:
1762 * Received REPLY+ABORT+DELETE in case where msgid has
1763 * already been fully closed, ignore the message.
1765 if (state == NULL) {
1766 if (msg->any.head.cmd & HAMMER2_MSGF_ABORT) {
1767 error = HAMMER2_IOQ_ERROR_EALREADY;
1769 fprintf(stderr, "no-state(r,d) %s\n",
1770 hammer2_msg_str(msg));
1771 error = HAMMER2_IOQ_ERROR_TRANS;
1778 * Received REPLY+ABORT+DELETE in case where msgid has
1779 * already been reused for an unrelated message,
1780 * ignore the message.
1782 if ((state->rxcmd & HAMMER2_MSGF_CREATE) == 0) {
1783 if (msg->any.head.cmd & HAMMER2_MSGF_ABORT) {
1784 error = HAMMER2_IOQ_ERROR_EALREADY;
1786 fprintf(stderr, "reused-state(r,d) %s\n",
1787 hammer2_msg_str(msg));
1788 error = HAMMER2_IOQ_ERROR_TRANS;
1795 case HAMMER2_MSGF_REPLY:
1797 * Check for mid-stream ABORT reply received to sent command.
1799 if (msg->any.head.cmd & HAMMER2_MSGF_ABORT) {
1800 if (state == NULL ||
1801 (state->rxcmd & HAMMER2_MSGF_CREATE) == 0) {
1802 error = HAMMER2_IOQ_ERROR_EALREADY;
1813 hammer2_state_cleanuprx(hammer2_iocom_t *iocom, hammer2_msg_t *msg)
1815 hammer2_state_t *state;
1817 if ((state = msg->state) == NULL) {
1819 * Free a non-transactional message, there is no state
1822 hammer2_msg_free(msg);
1823 } else if (msg->any.head.cmd & HAMMER2_MSGF_DELETE) {
1825 * Message terminating transaction, destroy the related
1826 * state, the original message, and this message (if it
1827 * isn't the original message due to a CREATE|DELETE).
1829 pthread_mutex_lock(&iocom->mtx);
1830 state->rxcmd |= HAMMER2_MSGF_DELETE;
1831 if (state->txcmd & HAMMER2_MSGF_DELETE) {
1832 if (state->msg == msg)
1834 assert(state->flags & HAMMER2_STATE_INSERTED);
1835 if (state->rxcmd & HAMMER2_MSGF_REPLY) {
1836 assert(msg->any.head.cmd & HAMMER2_MSGF_REPLY);
1837 RB_REMOVE(hammer2_state_tree,
1838 &iocom->router->statewr_tree, state);
1840 assert((msg->any.head.cmd & HAMMER2_MSGF_REPLY) == 0);
1841 RB_REMOVE(hammer2_state_tree,
1842 &iocom->router->staterd_tree, state);
1844 state->flags &= ~HAMMER2_STATE_INSERTED;
1845 hammer2_state_free(state);
1849 pthread_mutex_unlock(&iocom->mtx);
1850 hammer2_msg_free(msg);
1851 } else if (state->msg != msg) {
1853 * Message not terminating transaction, leave state intact
1854 * and free message if it isn't the CREATE message.
1856 hammer2_msg_free(msg);
1861 hammer2_state_cleanuptx(hammer2_msg_t *msg)
1863 hammer2_iocom_t *iocom = msg->router->iocom;
1864 hammer2_state_t *state;
1866 if ((state = msg->state) == NULL) {
1867 hammer2_msg_free(msg);
1868 } else if (msg->any.head.cmd & HAMMER2_MSGF_DELETE) {
1869 pthread_mutex_lock(&iocom->mtx);
1870 state->txcmd |= HAMMER2_MSGF_DELETE;
1871 if (state->rxcmd & HAMMER2_MSGF_DELETE) {
1872 if (state->msg == msg)
1874 assert(state->flags & HAMMER2_STATE_INSERTED);
1875 if (state->txcmd & HAMMER2_MSGF_REPLY) {
1876 assert(msg->any.head.cmd & HAMMER2_MSGF_REPLY);
1877 RB_REMOVE(hammer2_state_tree,
1878 &iocom->router->staterd_tree, state);
1880 assert((msg->any.head.cmd & HAMMER2_MSGF_REPLY) == 0);
1881 RB_REMOVE(hammer2_state_tree,
1882 &iocom->router->statewr_tree, state);
1884 state->flags &= ~HAMMER2_STATE_INSERTED;
1885 hammer2_state_free(state);
1889 pthread_mutex_unlock(&iocom->mtx);
1890 hammer2_msg_free(msg);
1891 } else if (state->msg != msg) {
1892 hammer2_msg_free(msg);
1897 * Called with iocom locked
1900 hammer2_state_free(hammer2_state_t *state)
1902 hammer2_iocom_t *iocom = state->iocom;
1907 fprintf(stderr, "terminate state %p id=%08x\n",
1908 state, (uint32_t)state->msgid);
1910 assert(state->any.any == NULL);
1914 hammer2_msg_free_locked(msg);
1918 * When an iocom error is present we are trying to close down the
1919 * iocom, but we have to wait for all states to terminate before
1920 * we can do so. The iocom rx code will terminate the receive side
1921 * for all transactions by simulating incoming DELETE messages,
1922 * but the state doesn't go away until both sides are terminated.
1924 * We may have to wake up the rx code.
1926 if (iocom->ioq_rx.error &&
1927 RB_EMPTY(&iocom->router->staterd_tree) &&
1928 RB_EMPTY(&iocom->router->statewr_tree)) {
1930 write(iocom->wakeupfds[1], &dummy, 1);
1934 /************************************************************************
1936 ************************************************************************
1938 * Incoming messages are routed by their spanid, matched up against
1939 * outgoing LNK_SPANs managed by h2span_relay structures (see msg_lnk.c).
1940 * Any replies run through the same router.
1942 * Originated messages are routed by their spanid, matched up against
1943 * incoming LNK_SPANs managed by h2span_link structures (see msg_lnk.c).
1944 * Replies come back through the same route.
1946 * Keep in mind that ALL MESSAGE TRAFFIC pertaining to a particular
1947 * transaction runs through the same route. Commands and replies both.
1949 * An originated message will use a different routing spanid to
1950 * reach a target node than a message which originates from that node.
1951 * They might use the same physical pipes (each pipe can have multiple
1952 * SPANs and RELAYs), but the routes are distinct from the perspective
1956 hammer2_router_alloc(void)
1958 hammer2_router_t *router;
1960 router = hammer2_alloc(sizeof(*router));
1961 TAILQ_INIT(&router->txmsgq);
1966 hammer2_router_connect(hammer2_router_t *router)
1968 hammer2_router_t *tmp;
1970 assert(router->link || router->relay);
1971 assert((router->flags & HAMMER2_ROUTER_CONNECTED) == 0);
1973 pthread_mutex_lock(&router_mtx);
1975 tmp = RB_INSERT(hammer2_router_tree, &router_ltree, router);
1977 tmp = RB_INSERT(hammer2_router_tree, &router_rtree, router);
1978 assert(tmp == NULL);
1979 router->flags |= HAMMER2_ROUTER_CONNECTED;
1980 pthread_mutex_unlock(&router_mtx);
1984 hammer2_router_disconnect(hammer2_router_t **routerp)
1986 hammer2_router_t *router;
1989 assert(router->link || router->relay);
1990 assert(router->flags & HAMMER2_ROUTER_CONNECTED);
1992 pthread_mutex_lock(&router_mtx);
1994 RB_REMOVE(hammer2_router_tree, &router_ltree, router);
1996 RB_REMOVE(hammer2_router_tree, &router_rtree, router);
1997 router->flags &= ~HAMMER2_ROUTER_CONNECTED;
1999 pthread_mutex_unlock(&router_mtx);
2007 hammer2_route_msg(hammer2_msg_t *msg)
2012 /************************************************************************
2014 ************************************************************************/
2017 hammer2_basecmd_str(uint32_t cmd)
2019 static char buf[64];
2022 const char *protostr;
2025 switch(cmd & HAMMER2_MSGF_PROTOS) {
2026 case HAMMER2_MSG_PROTO_LNK:
2029 case HAMMER2_MSG_PROTO_DBG:
2032 case HAMMER2_MSG_PROTO_DOM:
2035 case HAMMER2_MSG_PROTO_CAC:
2038 case HAMMER2_MSG_PROTO_QRM:
2041 case HAMMER2_MSG_PROTO_BLK:
2044 case HAMMER2_MSG_PROTO_VOP:
2048 snprintf(protobuf, sizeof(protobuf), "%x_",
2049 (cmd & HAMMER2_MSGF_PROTOS) >> 20);
2050 protostr = protobuf;
2054 switch(cmd & (HAMMER2_MSGF_PROTOS |
2056 HAMMER2_MSGF_SIZE)) {
2057 case HAMMER2_LNK_PAD:
2060 case HAMMER2_LNK_PING:
2063 case HAMMER2_LNK_AUTH:
2066 case HAMMER2_LNK_CONN:
2069 case HAMMER2_LNK_SPAN:
2072 case HAMMER2_LNK_VOLCONF:
2075 case HAMMER2_LNK_ERROR:
2076 if (cmd & HAMMER2_MSGF_DELETE)
2081 case HAMMER2_DBG_SHELL:
2085 snprintf(cmdbuf, sizeof(cmdbuf),
2086 "%06x", (cmd & (HAMMER2_MSGF_PROTOS |
2088 HAMMER2_MSGF_SIZE)));
2092 snprintf(buf, sizeof(buf), "%s%s", protostr, cmdstr);
2097 hammer2_msg_str(hammer2_msg_t *msg)
2099 hammer2_state_t *state;
2100 static char buf[256];
2104 const char *statestr;
2112 if ((state = msg->state) != NULL) {
2113 basecmd = (state->rxcmd & HAMMER2_MSGF_REPLY) ?
2114 state->txcmd : state->rxcmd;
2115 snprintf(statebuf, sizeof(statebuf),
2116 " %s=%s,L=%s%s,R=%s%s",
2117 ((state->txcmd & HAMMER2_MSGF_REPLY) ?
2118 "rcvcmd" : "sndcmd"),
2119 hammer2_basecmd_str(basecmd),
2120 ((state->txcmd & HAMMER2_MSGF_CREATE) ? "C" : ""),
2121 ((state->txcmd & HAMMER2_MSGF_DELETE) ? "D" : ""),
2122 ((state->rxcmd & HAMMER2_MSGF_CREATE) ? "C" : ""),
2123 ((state->rxcmd & HAMMER2_MSGF_DELETE) ? "D" : "")
2125 statestr = statebuf;
2133 switch(msg->any.head.error) {
2137 case HAMMER2_IOQ_ERROR_SYNC:
2138 errstr = "err=IOQ:NOSYNC";
2140 case HAMMER2_IOQ_ERROR_EOF:
2141 errstr = "err=IOQ:STREAMEOF";
2143 case HAMMER2_IOQ_ERROR_SOCK:
2144 errstr = "err=IOQ:SOCKERR";
2146 case HAMMER2_IOQ_ERROR_FIELD:
2147 errstr = "err=IOQ:BADFIELD";
2149 case HAMMER2_IOQ_ERROR_HCRC:
2150 errstr = "err=IOQ:BADHCRC";
2152 case HAMMER2_IOQ_ERROR_XCRC:
2153 errstr = "err=IOQ:BADXCRC";
2155 case HAMMER2_IOQ_ERROR_ACRC:
2156 errstr = "err=IOQ:BADACRC";
2158 case HAMMER2_IOQ_ERROR_STATE:
2159 errstr = "err=IOQ:BADSTATE";
2161 case HAMMER2_IOQ_ERROR_NOPEER:
2162 errstr = "err=IOQ:PEERCONFIG";
2164 case HAMMER2_IOQ_ERROR_NORKEY:
2165 errstr = "err=IOQ:BADRKEY";
2167 case HAMMER2_IOQ_ERROR_NOLKEY:
2168 errstr = "err=IOQ:BADLKEY";
2170 case HAMMER2_IOQ_ERROR_KEYXCHGFAIL:
2171 errstr = "err=IOQ:BADKEYXCHG";
2173 case HAMMER2_IOQ_ERROR_KEYFMT:
2174 errstr = "err=IOQ:BADFMT";
2176 case HAMMER2_IOQ_ERROR_BADURANDOM:
2177 errstr = "err=IOQ:BADRANDOM";
2179 case HAMMER2_IOQ_ERROR_MSGSEQ:
2180 errstr = "err=IOQ:BADSEQ";
2182 case HAMMER2_IOQ_ERROR_EALREADY:
2183 errstr = "err=IOQ:DUPMSG";
2185 case HAMMER2_IOQ_ERROR_TRANS:
2186 errstr = "err=IOQ:BADTRANS";
2188 case HAMMER2_IOQ_ERROR_IVWRAP:
2189 errstr = "err=IOQ:IVWRAP";
2191 case HAMMER2_IOQ_ERROR_MACFAIL:
2192 errstr = "err=IOQ:MACFAIL";
2194 case HAMMER2_IOQ_ERROR_ALGO:
2195 errstr = "err=IOQ:ALGOFAIL";
2197 case HAMMER2_MSG_ERR_NOSUPP:
2198 errstr = "err=NOSUPPORT";
2201 snprintf(errbuf, sizeof(errbuf),
2202 " err=%d", msg->any.head.error);
2211 if (msg->any.head.cmd & (HAMMER2_MSGF_CREATE | HAMMER2_MSGF_DELETE |
2212 HAMMER2_MSGF_ABORT | HAMMER2_MSGF_REPLY)) {
2214 if (msg->any.head.cmd & HAMMER2_MSGF_CREATE)
2216 if (msg->any.head.cmd & HAMMER2_MSGF_DELETE)
2218 if (msg->any.head.cmd & HAMMER2_MSGF_REPLY)
2220 if (msg->any.head.cmd & HAMMER2_MSGF_ABORT)
2228 snprintf(buf, sizeof(buf),
2229 "msg=%s%s %s id=%08x src=%08x tgt=%08x %s",
2230 hammer2_basecmd_str(msg->any.head.cmd),
2233 (uint32_t)(intmax_t)msg->any.head.msgid, /* for brevity */
2234 (uint32_t)(intmax_t)msg->any.head.source, /* for brevity */
2235 (uint32_t)(intmax_t)msg->any.head.target, /* for brevity */