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 *))
131 bzero(iocom, sizeof(*iocom));
133 iocom->router = hammer2_router_alloc();
134 iocom->router->signal_callback = signal_func;
135 iocom->router->rcvmsg_callback = rcvmsg_func;
136 iocom->router->altmsg_callback = altmsg_func;
137 /* we do not call hammer2_router_connect() for iocom routers */
139 pthread_mutex_init(&iocom->mtx, NULL);
140 RB_INIT(&iocom->router->staterd_tree);
141 RB_INIT(&iocom->router->statewr_tree);
142 TAILQ_INIT(&iocom->freeq);
143 TAILQ_INIT(&iocom->freeq_aux);
144 TAILQ_INIT(&iocom->router->txmsgq);
145 iocom->router->iocom = iocom;
146 iocom->sock_fd = sock_fd;
147 iocom->alt_fd = alt_fd;
148 iocom->flags = HAMMER2_IOCOMF_RREQ;
150 iocom->flags |= HAMMER2_IOCOMF_SWORK;
151 hammer2_ioq_init(iocom, &iocom->ioq_rx);
152 hammer2_ioq_init(iocom, &iocom->ioq_tx);
153 if (pipe(iocom->wakeupfds) < 0)
155 fcntl(iocom->wakeupfds[0], F_SETFL, O_NONBLOCK);
156 fcntl(iocom->wakeupfds[1], F_SETFL, O_NONBLOCK);
159 * Negotiate session crypto synchronously. This will mark the
160 * connection as error'd if it fails.
162 hammer2_crypto_negotiate(iocom);
165 * Make sure our fds are set to non-blocking for the iocom core.
168 fcntl(sock_fd, F_SETFL, O_NONBLOCK);
170 /* if line buffered our single fgets() should be fine */
172 fcntl(alt_fd, F_SETFL, O_NONBLOCK);
177 * May only be called from a callback from iocom_core.
179 * Adjust state machine functions, set flags to guarantee that both
180 * the recevmsg_func and the sendmsg_func is called at least once.
183 hammer2_router_restate(hammer2_router_t *router,
184 void (*signal_func)(hammer2_router_t *),
185 void (*rcvmsg_func)(hammer2_msg_t *msg),
186 void (*altmsg_func)(hammer2_iocom_t *))
188 router->signal_callback = signal_func;
189 router->rcvmsg_callback = rcvmsg_func;
190 router->altmsg_callback = altmsg_func;
192 router->iocom->flags |= HAMMER2_IOCOMF_SWORK;
194 router->iocom->flags &= ~HAMMER2_IOCOMF_SWORK;
198 hammer2_router_signal(hammer2_router_t *router)
200 if (router->signal_callback)
201 router->iocom->flags |= HAMMER2_IOCOMF_SWORK;
205 * Cleanup a terminating iocom.
207 * Caller should not hold iocom->mtx. The iocom has already been disconnected
208 * from all possible references to it.
211 hammer2_iocom_done(hammer2_iocom_t *iocom)
215 if (iocom->sock_fd >= 0) {
216 close(iocom->sock_fd);
219 if (iocom->alt_fd >= 0) {
220 close(iocom->alt_fd);
223 hammer2_ioq_done(iocom, &iocom->ioq_rx);
224 hammer2_ioq_done(iocom, &iocom->ioq_tx);
225 if ((msg = TAILQ_FIRST(&iocom->freeq)) != NULL) {
226 TAILQ_REMOVE(&iocom->freeq, msg, qentry);
229 if ((msg = TAILQ_FIRST(&iocom->freeq_aux)) != NULL) {
230 TAILQ_REMOVE(&iocom->freeq_aux, msg, qentry);
232 msg->aux_data = NULL;
235 if (iocom->wakeupfds[0] >= 0) {
236 close(iocom->wakeupfds[0]);
237 iocom->wakeupfds[0] = -1;
239 if (iocom->wakeupfds[1] >= 0) {
240 close(iocom->wakeupfds[1]);
241 iocom->wakeupfds[1] = -1;
243 pthread_mutex_destroy(&iocom->mtx);
247 * Allocate a new one-way message.
250 hammer2_msg_alloc(hammer2_router_t *router, size_t aux_size, uint32_t cmd,
251 void (*func)(hammer2_msg_t *), void *data)
253 hammer2_state_t *state = NULL;
254 hammer2_iocom_t *iocom = router->iocom;
258 pthread_mutex_lock(&iocom->mtx);
260 aux_size = (aux_size + HAMMER2_MSG_ALIGNMASK) &
261 ~HAMMER2_MSG_ALIGNMASK;
262 if ((msg = TAILQ_FIRST(&iocom->freeq_aux)) != NULL)
263 TAILQ_REMOVE(&iocom->freeq_aux, msg, qentry);
265 if ((msg = TAILQ_FIRST(&iocom->freeq)) != NULL)
266 TAILQ_REMOVE(&iocom->freeq, msg, qentry);
268 if ((cmd & (HAMMER2_MSGF_CREATE | HAMMER2_MSGF_REPLY)) ==
269 HAMMER2_MSGF_CREATE) {
271 * Create state when CREATE is set without REPLY.
273 * NOTE: CREATE in txcmd handled by hammer2_msg_write()
274 * NOTE: DELETE in txcmd handled by hammer2_state_cleanuptx()
276 state = malloc(sizeof(*state));
277 bzero(state, sizeof(*state));
278 state->iocom = iocom;
279 state->flags = HAMMER2_STATE_DYNAMIC;
280 state->msgid = (uint64_t)(uintptr_t)state;
281 state->router = router;
282 state->txcmd = cmd & ~(HAMMER2_MSGF_CREATE |
283 HAMMER2_MSGF_DELETE);
284 state->rxcmd = HAMMER2_MSGF_REPLY;
286 state->any.any = data;
287 pthread_mutex_lock(&iocom->mtx);
288 RB_INSERT(hammer2_state_tree,
289 &iocom->router->statewr_tree,
291 pthread_mutex_unlock(&iocom->mtx);
292 state->flags |= HAMMER2_STATE_INSERTED;
294 pthread_mutex_unlock(&iocom->mtx);
296 msg = malloc(sizeof(*msg));
297 bzero(msg, sizeof(*msg));
298 msg->aux_data = NULL;
301 if (msg->aux_size != aux_size) {
304 msg->aux_data = NULL;
308 msg->aux_data = malloc(aux_size);
309 msg->aux_size = aux_size;
312 hbytes = (cmd & HAMMER2_MSGF_SIZE) * HAMMER2_MSG_ALIGN;
314 bzero(&msg->any.head, hbytes);
315 msg->hdr_size = hbytes;
316 msg->any.head.cmd = cmd;
317 msg->any.head.aux_descr = 0;
318 msg->any.head.aux_crc = 0;
319 msg->router = router;
323 msg->any.head.msgid = state->msgid;
329 * Free a message so it can be reused afresh.
331 * NOTE: aux_size can be 0 with a non-NULL aux_data.
335 hammer2_msg_free_locked(hammer2_msg_t *msg)
337 hammer2_iocom_t *iocom = msg->router->iocom;
341 TAILQ_INSERT_TAIL(&iocom->freeq_aux, msg, qentry);
343 TAILQ_INSERT_TAIL(&iocom->freeq, msg, qentry);
347 hammer2_msg_free(hammer2_msg_t *msg)
349 hammer2_iocom_t *iocom = msg->router->iocom;
351 pthread_mutex_lock(&iocom->mtx);
352 hammer2_msg_free_locked(msg);
353 pthread_mutex_unlock(&iocom->mtx);
357 * I/O core loop for an iocom.
359 * Thread localized, iocom->mtx not held.
362 hammer2_iocom_core(hammer2_iocom_t *iocom)
364 struct pollfd fds[3];
369 int wi; /* wakeup pipe */
371 int ai; /* alt bulk path socket */
373 while ((iocom->flags & HAMMER2_IOCOMF_EOF) == 0) {
374 if ((iocom->flags & (HAMMER2_IOCOMF_RWORK |
375 HAMMER2_IOCOMF_WWORK |
376 HAMMER2_IOCOMF_PWORK |
377 HAMMER2_IOCOMF_SWORK |
378 HAMMER2_IOCOMF_ARWORK |
379 HAMMER2_IOCOMF_AWWORK)) == 0) {
381 * Only poll if no immediate work is pending.
382 * Otherwise we are just wasting our time calling
393 * Always check the inter-thread pipe, e.g.
394 * for iocom->txmsgq work.
397 fds[wi].fd = iocom->wakeupfds[0];
398 fds[wi].events = POLLIN;
402 * Check the socket input/output direction as
405 if (iocom->flags & (HAMMER2_IOCOMF_RREQ |
406 HAMMER2_IOCOMF_WREQ)) {
408 fds[si].fd = iocom->sock_fd;
412 if (iocom->flags & HAMMER2_IOCOMF_RREQ)
413 fds[si].events |= POLLIN;
414 if (iocom->flags & HAMMER2_IOCOMF_WREQ)
415 fds[si].events |= POLLOUT;
419 * Check the alternative fd for work.
421 if (iocom->alt_fd >= 0) {
423 fds[ai].fd = iocom->alt_fd;
424 fds[ai].events = POLLIN;
427 poll(fds, count, timeout);
429 if (wi >= 0 && (fds[wi].revents & POLLIN))
430 iocom->flags |= HAMMER2_IOCOMF_PWORK;
431 if (si >= 0 && (fds[si].revents & POLLIN))
432 iocom->flags |= HAMMER2_IOCOMF_RWORK;
433 if (si >= 0 && (fds[si].revents & POLLOUT))
434 iocom->flags |= HAMMER2_IOCOMF_WWORK;
435 if (wi >= 0 && (fds[wi].revents & POLLOUT))
436 iocom->flags |= HAMMER2_IOCOMF_WWORK;
437 if (ai >= 0 && (fds[ai].revents & POLLIN))
438 iocom->flags |= HAMMER2_IOCOMF_ARWORK;
441 * Always check the pipe
443 iocom->flags |= HAMMER2_IOCOMF_PWORK;
446 if (iocom->flags & HAMMER2_IOCOMF_SWORK) {
447 iocom->flags &= ~HAMMER2_IOCOMF_SWORK;
448 iocom->router->signal_callback(iocom->router);
452 * Pending message queues from other threads wake us up
453 * with a write to the wakeupfds[] pipe. We have to clear
454 * the pipe with a dummy read.
456 if (iocom->flags & HAMMER2_IOCOMF_PWORK) {
457 iocom->flags &= ~HAMMER2_IOCOMF_PWORK;
458 read(iocom->wakeupfds[0], dummybuf, sizeof(dummybuf));
459 iocom->flags |= HAMMER2_IOCOMF_RWORK;
460 iocom->flags |= HAMMER2_IOCOMF_WWORK;
461 if (TAILQ_FIRST(&iocom->router->txmsgq))
462 hammer2_iocom_flush1(iocom);
466 * Message write sequencing
468 if (iocom->flags & HAMMER2_IOCOMF_WWORK)
469 hammer2_iocom_flush1(iocom);
472 * Message read sequencing. Run this after the write
473 * sequencing in case the write sequencing allowed another
474 * auto-DELETE to occur on the read side.
476 if (iocom->flags & HAMMER2_IOCOMF_RWORK) {
477 while ((iocom->flags & HAMMER2_IOCOMF_EOF) == 0 &&
478 (msg = hammer2_ioq_read(iocom)) != NULL) {
480 fprintf(stderr, "receive %s\n",
481 hammer2_msg_str(msg));
483 iocom->router->rcvmsg_callback(msg);
484 hammer2_state_cleanuprx(iocom, msg);
488 if (iocom->flags & HAMMER2_IOCOMF_ARWORK) {
489 iocom->flags &= ~HAMMER2_IOCOMF_ARWORK;
490 iocom->router->altmsg_callback(iocom);
496 * Make sure there's enough room in the FIFO to hold the
499 * Assume worst case encrypted form is 2x the size of the
500 * plaintext equivalent.
504 hammer2_ioq_makeroom(hammer2_ioq_t *ioq, size_t needed)
509 bytes = ioq->fifo_cdx - ioq->fifo_beg;
510 nmax = sizeof(ioq->buf) - ioq->fifo_end;
511 if (bytes + nmax / 2 < needed) {
513 bcopy(ioq->buf + ioq->fifo_beg,
517 ioq->fifo_cdx -= ioq->fifo_beg;
519 if (ioq->fifo_cdn < ioq->fifo_end) {
520 bcopy(ioq->buf + ioq->fifo_cdn,
521 ioq->buf + ioq->fifo_cdx,
522 ioq->fifo_end - ioq->fifo_cdn);
524 ioq->fifo_end -= ioq->fifo_cdn - ioq->fifo_cdx;
525 ioq->fifo_cdn = ioq->fifo_cdx;
526 nmax = sizeof(ioq->buf) - ioq->fifo_end;
532 * Read the next ready message from the ioq, issuing I/O if needed.
533 * Caller should retry on a read-event when NULL is returned.
535 * If an error occurs during reception a HAMMER2_LNK_ERROR msg will
536 * be returned for each open transaction, then the ioq and iocom
537 * will be errored out and a non-transactional HAMMER2_LNK_ERROR
538 * msg will be returned as the final message. The caller should not call
539 * us again after the final message is returned.
541 * Thread localized, iocom->mtx not held.
544 hammer2_ioq_read(hammer2_iocom_t *iocom)
546 hammer2_ioq_t *ioq = &iocom->ioq_rx;
548 hammer2_msg_hdr_t *head;
549 hammer2_state_t *state;
557 iocom->flags &= ~(HAMMER2_IOCOMF_RREQ | HAMMER2_IOCOMF_RWORK);
560 * If a message is already pending we can just remove and
561 * return it. Message state has already been processed.
562 * (currently not implemented)
564 if ((msg = TAILQ_FIRST(&ioq->msgq)) != NULL) {
565 TAILQ_REMOVE(&ioq->msgq, msg, qentry);
570 * If the stream is errored out we stop processing it.
576 * Message read in-progress (msg is NULL at the moment). We don't
577 * allocate a msg until we have its core header.
579 nmax = sizeof(ioq->buf) - ioq->fifo_end;
580 bytes = ioq->fifo_cdx - ioq->fifo_beg; /* already decrypted */
584 case HAMMER2_MSGQ_STATE_HEADER1:
586 * Load the primary header, fail on any non-trivial read
587 * error or on EOF. Since the primary header is the same
588 * size is the message alignment it will never straddle
589 * the end of the buffer.
591 nmax = hammer2_ioq_makeroom(ioq, sizeof(msg->any.head));
592 if (bytes < sizeof(msg->any.head)) {
593 n = read(iocom->sock_fd,
594 ioq->buf + ioq->fifo_end,
598 ioq->error = HAMMER2_IOQ_ERROR_EOF;
601 if (errno != EINTR &&
602 errno != EINPROGRESS &&
604 ioq->error = HAMMER2_IOQ_ERROR_SOCK;
610 ioq->fifo_end += (size_t)n;
615 * Decrypt data received so far. Data will be decrypted
616 * in-place but might create gaps in the FIFO. Partial
617 * blocks are not immediately decrypted.
619 * WARNING! The header might be in the wrong endian, we
620 * do not fix it up until we get the entire
623 if (iocom->flags & HAMMER2_IOCOMF_CRYPTED) {
624 hammer2_crypto_decrypt(iocom, ioq);
626 ioq->fifo_cdx = ioq->fifo_end;
627 ioq->fifo_cdn = ioq->fifo_end;
629 bytes = ioq->fifo_cdx - ioq->fifo_beg;
632 * Insufficient data accumulated (msg is NULL, caller will
636 if (bytes < sizeof(msg->any.head))
640 * Check and fixup the core header. Note that the icrc
641 * has to be calculated before any fixups, but the crc
642 * fields in the msg may have to be swapped like everything
645 head = (void *)(ioq->buf + ioq->fifo_beg);
646 if (head->magic != HAMMER2_MSGHDR_MAGIC &&
647 head->magic != HAMMER2_MSGHDR_MAGIC_REV) {
648 ioq->error = HAMMER2_IOQ_ERROR_SYNC;
653 * Calculate the full header size and aux data size
655 if (head->magic == HAMMER2_MSGHDR_MAGIC_REV) {
656 ioq->hbytes = (bswap32(head->cmd) & HAMMER2_MSGF_SIZE) *
658 ioq->abytes = bswap32(head->aux_bytes) *
661 ioq->hbytes = (head->cmd & HAMMER2_MSGF_SIZE) *
663 ioq->abytes = head->aux_bytes * HAMMER2_MSG_ALIGN;
665 if (ioq->hbytes < sizeof(msg->any.head) ||
666 ioq->hbytes > sizeof(msg->any) ||
667 ioq->abytes > HAMMER2_MSGAUX_MAX) {
668 ioq->error = HAMMER2_IOQ_ERROR_FIELD;
673 * Allocate the message, the next state will fill it in.
675 msg = hammer2_msg_alloc(iocom->router, ioq->abytes, 0,
680 * Fall through to the next state. Make sure that the
681 * extended header does not straddle the end of the buffer.
682 * We still want to issue larger reads into our buffer,
683 * book-keeping is easier if we don't bcopy() yet.
685 * Make sure there is enough room for bloated encrypt data.
687 nmax = hammer2_ioq_makeroom(ioq, ioq->hbytes);
688 ioq->state = HAMMER2_MSGQ_STATE_HEADER2;
690 case HAMMER2_MSGQ_STATE_HEADER2:
692 * Fill out the extended header.
695 if (bytes < ioq->hbytes) {
696 n = read(iocom->sock_fd,
697 ioq->buf + ioq->fifo_end,
701 ioq->error = HAMMER2_IOQ_ERROR_EOF;
704 if (errno != EINTR &&
705 errno != EINPROGRESS &&
707 ioq->error = HAMMER2_IOQ_ERROR_SOCK;
713 ioq->fifo_end += (size_t)n;
717 if (iocom->flags & HAMMER2_IOCOMF_CRYPTED) {
718 hammer2_crypto_decrypt(iocom, ioq);
720 ioq->fifo_cdx = ioq->fifo_end;
721 ioq->fifo_cdn = ioq->fifo_end;
723 bytes = ioq->fifo_cdx - ioq->fifo_beg;
726 * Insufficient data accumulated (set msg NULL so caller will
729 if (bytes < ioq->hbytes) {
735 * Calculate the extended header, decrypt data received
736 * so far. Handle endian-conversion for the entire extended
739 head = (void *)(ioq->buf + ioq->fifo_beg);
744 if (head->magic == HAMMER2_MSGHDR_MAGIC_REV)
745 xcrc32 = bswap32(head->hdr_crc);
747 xcrc32 = head->hdr_crc;
749 if (hammer2_icrc32(head, ioq->hbytes) != xcrc32) {
750 ioq->error = HAMMER2_IOQ_ERROR_XCRC;
751 fprintf(stderr, "BAD-XCRC(%08x,%08x) %s\n",
752 xcrc32, hammer2_icrc32(head, ioq->hbytes),
753 hammer2_msg_str(msg));
757 head->hdr_crc = xcrc32;
759 if (head->magic == HAMMER2_MSGHDR_MAGIC_REV) {
760 hammer2_bswap_head(head);
764 * Copy the extended header into the msg and adjust the
767 bcopy(head, &msg->any, ioq->hbytes);
770 * We are either done or we fall-through.
772 if (ioq->abytes == 0) {
773 ioq->fifo_beg += ioq->hbytes;
778 * Must adjust bytes (and the state) when falling through.
779 * nmax doesn't change.
781 ioq->fifo_beg += ioq->hbytes;
782 bytes -= ioq->hbytes;
783 ioq->state = HAMMER2_MSGQ_STATE_AUXDATA1;
785 case HAMMER2_MSGQ_STATE_AUXDATA1:
787 * Copy the partial or complete payload from remaining
788 * bytes in the FIFO in order to optimize the makeroom call
789 * in the AUXDATA2 state. We have to fall-through either
790 * way so we can check the crc.
792 * msg->aux_size tracks our aux data.
794 if (bytes >= ioq->abytes) {
795 bcopy(ioq->buf + ioq->fifo_beg, msg->aux_data,
797 msg->aux_size = ioq->abytes;
798 ioq->fifo_beg += ioq->abytes;
799 assert(ioq->fifo_beg <= ioq->fifo_cdx);
800 assert(ioq->fifo_cdx <= ioq->fifo_cdn);
801 bytes -= ioq->abytes;
803 bcopy(ioq->buf + ioq->fifo_beg, msg->aux_data,
805 msg->aux_size = bytes;
806 ioq->fifo_beg += bytes;
807 if (ioq->fifo_cdx < ioq->fifo_beg)
808 ioq->fifo_cdx = ioq->fifo_beg;
809 assert(ioq->fifo_beg <= ioq->fifo_cdx);
810 assert(ioq->fifo_cdx <= ioq->fifo_cdn);
815 ioq->state = HAMMER2_MSGQ_STATE_AUXDATA2;
817 case HAMMER2_MSGQ_STATE_AUXDATA2:
819 * Make sure there is enough room for more data.
822 nmax = hammer2_ioq_makeroom(ioq, ioq->abytes - msg->aux_size);
825 * Read and decrypt more of the payload.
827 if (msg->aux_size < ioq->abytes) {
829 n = read(iocom->sock_fd,
830 ioq->buf + ioq->fifo_end,
834 ioq->error = HAMMER2_IOQ_ERROR_EOF;
837 if (errno != EINTR &&
838 errno != EINPROGRESS &&
840 ioq->error = HAMMER2_IOQ_ERROR_SOCK;
846 ioq->fifo_end += (size_t)n;
850 if (iocom->flags & HAMMER2_IOCOMF_CRYPTED) {
851 hammer2_crypto_decrypt(iocom, ioq);
853 ioq->fifo_cdx = ioq->fifo_end;
854 ioq->fifo_cdn = ioq->fifo_end;
856 bytes = ioq->fifo_cdx - ioq->fifo_beg;
858 if (bytes > ioq->abytes - msg->aux_size)
859 bytes = ioq->abytes - msg->aux_size;
862 bcopy(ioq->buf + ioq->fifo_beg,
863 msg->aux_data + msg->aux_size,
865 msg->aux_size += bytes;
866 ioq->fifo_beg += bytes;
870 * Insufficient data accumulated (set msg NULL so caller will
873 if (msg->aux_size < ioq->abytes) {
877 assert(msg->aux_size == ioq->abytes);
880 * Check aux_crc, then we are done.
882 xcrc32 = hammer2_icrc32(msg->aux_data, msg->aux_size);
883 if (xcrc32 != msg->any.head.aux_crc) {
884 ioq->error = HAMMER2_IOQ_ERROR_ACRC;
888 case HAMMER2_MSGQ_STATE_ERROR:
890 * Continued calls to drain recorded transactions (returning
891 * a LNK_ERROR for each one), before we return the final
898 * We don't double-return errors, the caller should not
899 * have called us again after getting an error msg.
906 * Check the message sequence. The iv[] should prevent any
907 * possibility of a replay but we add this check anyway.
909 if (msg && ioq->error == 0) {
910 if ((msg->any.head.salt & 255) != (ioq->seq & 255)) {
911 ioq->error = HAMMER2_IOQ_ERROR_MSGSEQ;
918 * Process transactional state for the message.
920 if (msg && ioq->error == 0) {
921 error = hammer2_state_msgrx(msg);
923 if (error == HAMMER2_IOQ_ERROR_EALREADY) {
924 hammer2_msg_free(msg);
932 * Handle error, RREQ, or completion
934 * NOTE: nmax and bytes are invalid at this point, we don't bother
935 * to update them when breaking out.
940 * An unrecoverable error causes all active receive
941 * transactions to be terminated with a LNK_ERROR message.
943 * Once all active transactions are exhausted we set the
944 * iocom ERROR flag and return a non-transactional LNK_ERROR
945 * message, which should cause master processing loops to
948 assert(ioq->msg == msg);
950 hammer2_msg_free(msg);
955 * No more I/O read processing
957 ioq->state = HAMMER2_MSGQ_STATE_ERROR;
960 * Simulate a remote LNK_ERROR DELETE msg for any open
961 * transactions, ending with a final non-transactional
962 * LNK_ERROR (that the session can detect) when no
963 * transactions remain.
965 msg = hammer2_msg_alloc(iocom->router, 0, 0, NULL, NULL);
966 bzero(&msg->any.head, sizeof(msg->any.head));
967 msg->any.head.magic = HAMMER2_MSGHDR_MAGIC;
968 msg->any.head.cmd = HAMMER2_LNK_ERROR;
969 msg->any.head.error = ioq->error;
971 pthread_mutex_lock(&iocom->mtx);
972 hammer2_iocom_drain(iocom);
973 if ((state = RB_ROOT(&iocom->router->staterd_tree)) != NULL) {
975 * Active remote transactions are still present.
976 * Simulate the other end sending us a DELETE.
978 if (state->rxcmd & HAMMER2_MSGF_DELETE) {
979 hammer2_msg_free(msg);
982 /*state->txcmd |= HAMMER2_MSGF_DELETE;*/
984 msg->router = state->router;
985 msg->any.head.msgid = state->msgid;
986 msg->any.head.cmd |= HAMMER2_MSGF_ABORT |
989 } else if ((state = RB_ROOT(&iocom->router->statewr_tree)) !=
992 * Active local transactions are still present.
993 * Simulate the other end sending us a DELETE.
995 if (state->rxcmd & HAMMER2_MSGF_DELETE) {
996 hammer2_msg_free(msg);
1000 msg->router = state->router;
1001 msg->any.head.msgid = state->msgid;
1002 msg->any.head.cmd |= HAMMER2_MSGF_ABORT |
1003 HAMMER2_MSGF_DELETE |
1005 if ((state->rxcmd & HAMMER2_MSGF_CREATE) == 0) {
1006 msg->any.head.cmd |=
1007 HAMMER2_MSGF_CREATE;
1012 * No active local or remote transactions remain.
1013 * Generate a final LNK_ERROR and flag EOF.
1016 iocom->flags |= HAMMER2_IOCOMF_EOF;
1017 fprintf(stderr, "EOF ON SOCKET %d\n", iocom->sock_fd);
1019 pthread_mutex_unlock(&iocom->mtx);
1022 * For the iocom error case we want to set RWORK to indicate
1023 * that more messages might be pending.
1025 * It is possible to return NULL when there is more work to
1026 * do because each message has to be DELETEd in both
1027 * directions before we continue on with the next (though
1028 * this could be optimized). The transmit direction will
1032 iocom->flags |= HAMMER2_IOCOMF_RWORK;
1033 } else if (msg == NULL) {
1035 * Insufficient data received to finish building the message,
1036 * set RREQ and return NULL.
1038 * Leave ioq->msg intact.
1039 * Leave the FIFO intact.
1041 iocom->flags |= HAMMER2_IOCOMF_RREQ;
1046 * The fifo has already been advanced past the message.
1047 * Trivially reset the FIFO indices if possible.
1049 * clear the FIFO if it is now empty and set RREQ to wait
1050 * for more from the socket. If the FIFO is not empty set
1051 * TWORK to bypass the poll so we loop immediately.
1053 if (ioq->fifo_beg == ioq->fifo_cdx &&
1054 ioq->fifo_cdn == ioq->fifo_end) {
1055 iocom->flags |= HAMMER2_IOCOMF_RREQ;
1061 iocom->flags |= HAMMER2_IOCOMF_RWORK;
1063 ioq->state = HAMMER2_MSGQ_STATE_HEADER1;
1070 * Calculate the header and data crc's and write a low-level message to
1071 * the connection. If aux_crc is non-zero the aux_data crc is already
1072 * assumed to have been set.
1074 * A non-NULL msg is added to the queue but not necessarily flushed.
1075 * Calling this function with msg == NULL will get a flush going.
1077 * Caller must hold iocom->mtx.
1080 hammer2_iocom_flush1(hammer2_iocom_t *iocom)
1082 hammer2_ioq_t *ioq = &iocom->ioq_tx;
1086 hammer2_msg_queue_t tmpq;
1088 iocom->flags &= ~(HAMMER2_IOCOMF_WREQ | HAMMER2_IOCOMF_WWORK);
1090 pthread_mutex_lock(&iocom->mtx);
1091 while ((msg = TAILQ_FIRST(&iocom->router->txmsgq)) != NULL) {
1092 TAILQ_REMOVE(&iocom->router->txmsgq, msg, qentry);
1093 TAILQ_INSERT_TAIL(&tmpq, msg, qentry);
1095 pthread_mutex_unlock(&iocom->mtx);
1097 while ((msg = TAILQ_FIRST(&tmpq)) != NULL) {
1099 * Process terminal connection errors.
1101 TAILQ_REMOVE(&tmpq, msg, qentry);
1103 TAILQ_INSERT_TAIL(&ioq->msgq, msg, qentry);
1109 * Finish populating the msg fields. The salt ensures that
1110 * the iv[] array is ridiculously randomized and we also
1111 * re-seed our PRNG every 32768 messages just to be sure.
1113 msg->any.head.magic = HAMMER2_MSGHDR_MAGIC;
1114 msg->any.head.salt = (random() << 8) | (ioq->seq & 255);
1116 if ((ioq->seq & 32767) == 0)
1120 * Calculate aux_crc if 0, then calculate hdr_crc.
1122 if (msg->aux_size && msg->any.head.aux_crc == 0) {
1123 assert((msg->aux_size & HAMMER2_MSG_ALIGNMASK) == 0);
1124 xcrc32 = hammer2_icrc32(msg->aux_data, msg->aux_size);
1125 msg->any.head.aux_crc = xcrc32;
1127 msg->any.head.aux_bytes = msg->aux_size / HAMMER2_MSG_ALIGN;
1128 assert((msg->aux_size & HAMMER2_MSG_ALIGNMASK) == 0);
1130 hbytes = (msg->any.head.cmd & HAMMER2_MSGF_SIZE) *
1132 msg->any.head.hdr_crc = 0;
1133 msg->any.head.hdr_crc = hammer2_icrc32(&msg->any.head, hbytes);
1136 * Enqueue the message (the flush codes handles stream
1139 TAILQ_INSERT_TAIL(&ioq->msgq, msg, qentry);
1142 hammer2_iocom_flush2(iocom);
1146 * Thread localized, iocom->mtx not held by caller.
1149 hammer2_iocom_flush2(hammer2_iocom_t *iocom)
1151 hammer2_ioq_t *ioq = &iocom->ioq_tx;
1154 struct iovec iov[HAMMER2_IOQ_MAXIOVEC];
1163 hammer2_iocom_drain(iocom);
1168 * Pump messages out the connection by building an iovec.
1170 * ioq->hbytes/ioq->abytes tracks how much of the first message
1171 * in the queue has been successfully written out, so we can
1179 TAILQ_FOREACH(msg, &ioq->msgq, qentry) {
1180 hbytes = (msg->any.head.cmd & HAMMER2_MSGF_SIZE) *
1182 abytes = msg->aux_size;
1183 assert(hoff <= hbytes && aoff <= abytes);
1185 if (hoff < hbytes) {
1186 iov[iovcnt].iov_base = (char *)&msg->any.head + hoff;
1187 iov[iovcnt].iov_len = hbytes - hoff;
1188 nact += hbytes - hoff;
1190 if (iovcnt == HAMMER2_IOQ_MAXIOVEC)
1193 if (aoff < abytes) {
1194 assert(msg->aux_data != NULL);
1195 iov[iovcnt].iov_base = (char *)msg->aux_data + aoff;
1196 iov[iovcnt].iov_len = abytes - aoff;
1197 nact += abytes - aoff;
1199 if (iovcnt == HAMMER2_IOQ_MAXIOVEC)
1209 * Encrypt and write the data. The crypto code will move the
1210 * data into the fifo and adjust the iov as necessary. If
1211 * encryption is disabled the iov is left alone.
1213 * May return a smaller iov (thus a smaller n), with aggregated
1214 * chunks. May reduce nmax to what fits in the FIFO.
1216 * This function sets nact to the number of original bytes now
1217 * encrypted, adding to the FIFO some number of bytes that might
1218 * be greater depending on the crypto mechanic. iov[] is adjusted
1219 * to point at the FIFO if necessary.
1221 * NOTE: The return value from the writev() is the post-encrypted
1222 * byte count, not the plaintext count.
1224 if (iocom->flags & HAMMER2_IOCOMF_CRYPTED) {
1226 * Make sure the FIFO has a reasonable amount of space
1227 * left (if not completely full).
1229 if (ioq->fifo_beg > sizeof(ioq->buf) / 2 &&
1230 sizeof(ioq->buf) - ioq->fifo_end >= HAMMER2_MSG_ALIGN * 2) {
1231 bcopy(ioq->buf + ioq->fifo_beg, ioq->buf,
1232 ioq->fifo_end - ioq->fifo_beg);
1233 ioq->fifo_cdx -= ioq->fifo_beg;
1234 ioq->fifo_cdn -= ioq->fifo_beg;
1235 ioq->fifo_end -= ioq->fifo_beg;
1239 iovcnt = hammer2_crypto_encrypt(iocom, ioq, iov, iovcnt, &nact);
1240 n = writev(iocom->sock_fd, iov, iovcnt);
1245 if (ioq->fifo_beg == ioq->fifo_end) {
1253 n = writev(iocom->sock_fd, iov, iovcnt);
1261 * Clean out the transmit queue based on what we successfully
1262 * sent (nact is the plaintext count). ioq->hbytes/abytes
1263 * represents the portion of the first message previously sent.
1265 while ((msg = TAILQ_FIRST(&ioq->msgq)) != NULL) {
1266 hbytes = (msg->any.head.cmd & HAMMER2_MSGF_SIZE) *
1268 abytes = msg->aux_size;
1270 if ((size_t)nact < hbytes - ioq->hbytes) {
1271 ioq->hbytes += nact;
1275 nact -= hbytes - ioq->hbytes;
1276 ioq->hbytes = hbytes;
1277 if ((size_t)nact < abytes - ioq->abytes) {
1278 ioq->abytes += nact;
1282 nact -= abytes - ioq->abytes;
1284 TAILQ_REMOVE(&ioq->msgq, msg, qentry);
1289 hammer2_state_cleanuptx(msg);
1294 * Process the return value from the write w/regards to blocking.
1297 if (errno != EINTR &&
1298 errno != EINPROGRESS &&
1303 ioq->error = HAMMER2_IOQ_ERROR_SOCK;
1304 hammer2_iocom_drain(iocom);
1307 * Wait for socket buffer space
1309 iocom->flags |= HAMMER2_IOCOMF_WREQ;
1312 iocom->flags |= HAMMER2_IOCOMF_WREQ;
1315 hammer2_iocom_drain(iocom);
1320 * Kill pending msgs on ioq_tx and adjust the flags such that no more
1321 * write events will occur. We don't kill read msgs because we want
1322 * the caller to pull off our contrived terminal error msg to detect
1323 * the connection failure.
1325 * Thread localized, iocom->mtx not held by caller.
1328 hammer2_iocom_drain(hammer2_iocom_t *iocom)
1330 hammer2_ioq_t *ioq = &iocom->ioq_tx;
1333 iocom->flags &= ~(HAMMER2_IOCOMF_WREQ | HAMMER2_IOCOMF_WWORK);
1337 while ((msg = TAILQ_FIRST(&ioq->msgq)) != NULL) {
1338 TAILQ_REMOVE(&ioq->msgq, msg, qentry);
1340 hammer2_state_cleanuptx(msg);
1345 * Write a message to an iocom, with additional state processing.
1348 hammer2_msg_write(hammer2_msg_t *msg)
1350 hammer2_iocom_t *iocom = msg->router->iocom;
1351 hammer2_state_t *state;
1355 * Handle state processing, create state if necessary.
1357 pthread_mutex_lock(&iocom->mtx);
1358 if ((state = msg->state) != NULL) {
1360 * Existing transaction (could be reply). It is also
1361 * possible for this to be the first reply (CREATE is set),
1362 * in which case we populate state->txcmd.
1364 * state->txcmd is adjusted to hold the final message cmd,
1365 * and we also be sure to set the CREATE bit here. We did
1366 * not set it in hammer2_msg_alloc() because that would have
1367 * not been serialized (state could have gotten ripped out
1368 * from under the message prior to it being transmitted).
1370 if ((msg->any.head.cmd & (HAMMER2_MSGF_CREATE |
1371 HAMMER2_MSGF_REPLY)) ==
1372 HAMMER2_MSGF_CREATE) {
1373 state->txcmd = msg->any.head.cmd & ~HAMMER2_MSGF_DELETE;
1375 msg->any.head.msgid = state->msgid;
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 */
1384 msg->any.head.source = 0;
1385 msg->any.head.target = msg->router->target;
1388 * Queue it for output, wake up the I/O pthread. Note that the
1389 * I/O thread is responsible for generating the CRCs and encryption.
1391 TAILQ_INSERT_TAIL(&iocom->router->txmsgq, msg, qentry);
1393 write(iocom->wakeupfds[1], &dummy, 1); /* XXX optimize me */
1394 pthread_mutex_unlock(&iocom->mtx);
1398 * This is a shortcut to formulate a reply to msg with a simple error code,
1399 * It can reply to and terminate a transaction, or it can reply to a one-way
1400 * messages. A HAMMER2_LNK_ERROR command code is utilized to encode
1401 * the error code (which can be 0). Not all transactions are terminated
1402 * with HAMMER2_LNK_ERROR status (the low level only cares about the
1403 * MSGF_DELETE flag), but most are.
1405 * Replies to one-way messages are a bit of an oxymoron but the feature
1406 * is used by the debug (DBG) protocol.
1408 * The reply contains no extended data.
1411 hammer2_msg_reply(hammer2_msg_t *msg, uint32_t error)
1413 hammer2_iocom_t *iocom = msg->router->iocom;
1414 hammer2_state_t *state = msg->state;
1415 hammer2_msg_t *nmsg;
1420 * Reply with a simple error code and terminate the transaction.
1422 cmd = HAMMER2_LNK_ERROR;
1425 * Check if our direction has even been initiated yet, set CREATE.
1427 * Check what direction this is (command or reply direction). Note
1428 * that txcmd might not have been initiated yet.
1430 * If our direction has already been closed we just return without
1434 if (state->txcmd & HAMMER2_MSGF_DELETE)
1436 if (state->txcmd & HAMMER2_MSGF_REPLY)
1437 cmd |= HAMMER2_MSGF_REPLY;
1438 cmd |= HAMMER2_MSGF_DELETE;
1440 if ((msg->any.head.cmd & HAMMER2_MSGF_REPLY) == 0)
1441 cmd |= HAMMER2_MSGF_REPLY;
1445 * Allocate the message and associate it with the existing state.
1446 * We cannot pass MSGF_CREATE to msg_alloc() because that may
1447 * allocate new state. We have our state already.
1449 nmsg = hammer2_msg_alloc(iocom->router, 0, cmd, NULL, NULL);
1451 if ((state->txcmd & HAMMER2_MSGF_CREATE) == 0)
1452 nmsg->any.head.cmd |= HAMMER2_MSGF_CREATE;
1454 nmsg->any.head.error = error;
1455 nmsg->state = state;
1456 hammer2_msg_write(nmsg);
1460 * Similar to hammer2_msg_reply() but leave the transaction open. That is,
1461 * we are generating a streaming reply or an intermediate acknowledgement
1462 * of some sort as part of the higher level protocol, with more to come
1466 hammer2_msg_result(hammer2_msg_t *msg, uint32_t error)
1468 hammer2_iocom_t *iocom = msg->router->iocom;
1469 hammer2_state_t *state = msg->state;
1470 hammer2_msg_t *nmsg;
1475 * Reply with a simple error code and terminate the transaction.
1477 cmd = HAMMER2_LNK_ERROR;
1480 * Check if our direction has even been initiated yet, set CREATE.
1482 * Check what direction this is (command or reply direction). Note
1483 * that txcmd might not have been initiated yet.
1485 * If our direction has already been closed we just return without
1489 if (state->txcmd & HAMMER2_MSGF_DELETE)
1491 if (state->txcmd & HAMMER2_MSGF_REPLY)
1492 cmd |= HAMMER2_MSGF_REPLY;
1493 /* continuing transaction, do not set MSGF_DELETE */
1495 if ((msg->any.head.cmd & HAMMER2_MSGF_REPLY) == 0)
1496 cmd |= HAMMER2_MSGF_REPLY;
1499 nmsg = hammer2_msg_alloc(iocom->router, 0, cmd, NULL, NULL);
1501 if ((state->txcmd & HAMMER2_MSGF_CREATE) == 0)
1502 nmsg->any.head.cmd |= HAMMER2_MSGF_CREATE;
1504 nmsg->any.head.error = error;
1505 nmsg->state = state;
1506 hammer2_msg_write(nmsg);
1510 * Terminate a transaction given a state structure by issuing a DELETE.
1513 hammer2_state_reply(hammer2_state_t *state, uint32_t error)
1515 hammer2_msg_t *nmsg;
1516 uint32_t cmd = HAMMER2_LNK_ERROR | HAMMER2_MSGF_DELETE;
1519 * Nothing to do if we already transmitted a delete
1521 if (state->txcmd & HAMMER2_MSGF_DELETE)
1525 * Set REPLY if the other end initiated the command. Otherwise
1526 * we are the command direction.
1528 if (state->txcmd & HAMMER2_MSGF_REPLY)
1529 cmd |= HAMMER2_MSGF_REPLY;
1531 nmsg = hammer2_msg_alloc(state->iocom->router, 0, cmd, NULL, NULL);
1533 if ((state->txcmd & HAMMER2_MSGF_CREATE) == 0)
1534 nmsg->any.head.cmd |= HAMMER2_MSGF_CREATE;
1536 nmsg->any.head.error = error;
1537 nmsg->state = state;
1538 hammer2_msg_write(nmsg);
1541 /************************************************************************
1542 * TRANSACTION STATE HANDLING *
1543 ************************************************************************
1548 * Process state tracking for a message after reception, prior to
1551 * Called with msglk held and the msg dequeued.
1553 * All messages are called with dummy state and return actual state.
1554 * (One-off messages often just return the same dummy state).
1556 * May request that caller discard the message by setting *discardp to 1.
1557 * The returned state is not used in this case and is allowed to be NULL.
1561 * These routines handle persistent and command/reply message state via the
1562 * CREATE and DELETE flags. The first message in a command or reply sequence
1563 * sets CREATE, the last message in a command or reply sequence sets DELETE.
1565 * There can be any number of intermediate messages belonging to the same
1566 * sequence sent inbetween the CREATE message and the DELETE message,
1567 * which set neither flag. This represents a streaming command or reply.
1569 * Any command message received with CREATE set expects a reply sequence to
1570 * be returned. Reply sequences work the same as command sequences except the
1571 * REPLY bit is also sent. Both the command side and reply side can
1572 * degenerate into a single message with both CREATE and DELETE set. Note
1573 * that one side can be streaming and the other side not, or neither, or both.
1575 * The msgid is unique for the initiator. That is, two sides sending a new
1576 * message can use the same msgid without colliding.
1580 * ABORT sequences work by setting the ABORT flag along with normal message
1581 * state. However, ABORTs can also be sent on half-closed messages, that is
1582 * even if the command or reply side has already sent a DELETE, as long as
1583 * the message has not been fully closed it can still send an ABORT+DELETE
1584 * to terminate the half-closed message state.
1586 * Since ABORT+DELETEs can race we silently discard ABORT's for message
1587 * state which has already been fully closed. REPLY+ABORT+DELETEs can
1588 * also race, and in this situation the other side might have already
1589 * initiated a new unrelated command with the same message id. Since
1590 * the abort has not set the CREATE flag the situation can be detected
1591 * and the message will also be discarded.
1593 * Non-blocking requests can be initiated with ABORT+CREATE[+DELETE].
1594 * The ABORT request is essentially integrated into the command instead
1595 * of being sent later on. In this situation the command implementation
1596 * detects that CREATE and ABORT are both set (vs ABORT alone) and can
1597 * special-case non-blocking operation for the command.
1599 * NOTE! Messages with ABORT set without CREATE or DELETE are considered
1600 * to be mid-stream aborts for command/reply sequences. ABORTs on
1601 * one-way messages are not supported.
1603 * NOTE! If a command sequence does not support aborts the ABORT flag is
1608 * One-off messages (no reply expected) are sent with neither CREATE or DELETE
1609 * set. One-off messages cannot be aborted and typically aren't processed
1610 * by these routines. The REPLY bit can be used to distinguish whether a
1611 * one-off message is a command or reply. For example, one-off replies
1612 * will typically just contain status updates.
1615 hammer2_state_msgrx(hammer2_msg_t *msg)
1617 hammer2_iocom_t *iocom = msg->router->iocom;
1618 hammer2_state_t *state;
1619 hammer2_state_t dummy;
1623 * Lock RB tree and locate existing persistent state, if any.
1625 * If received msg is a command state is on staterd_tree.
1626 * If received msg is a reply state is on statewr_tree.
1628 dummy.msgid = msg->any.head.msgid;
1629 pthread_mutex_lock(&iocom->mtx);
1630 if (msg->any.head.cmd & HAMMER2_MSGF_REPLY) {
1631 state = RB_FIND(hammer2_state_tree,
1632 &iocom->router->statewr_tree, &dummy);
1634 state = RB_FIND(hammer2_state_tree,
1635 &iocom->router->staterd_tree, &dummy);
1638 pthread_mutex_unlock(&iocom->mtx);
1641 * Short-cut one-off or mid-stream messages (state may be NULL).
1643 if ((msg->any.head.cmd & (HAMMER2_MSGF_CREATE | HAMMER2_MSGF_DELETE |
1644 HAMMER2_MSGF_ABORT)) == 0) {
1649 * Switch on CREATE, DELETE, REPLY, and also handle ABORT from
1650 * inside the case statements.
1652 switch(msg->any.head.cmd & (HAMMER2_MSGF_CREATE | HAMMER2_MSGF_DELETE |
1653 HAMMER2_MSGF_REPLY)) {
1654 case HAMMER2_MSGF_CREATE:
1655 case HAMMER2_MSGF_CREATE | HAMMER2_MSGF_DELETE:
1657 * New persistant command received.
1660 fprintf(stderr, "duplicate-trans %s\n",
1661 hammer2_msg_str(msg));
1662 error = HAMMER2_IOQ_ERROR_TRANS;
1666 state = malloc(sizeof(*state));
1667 bzero(state, sizeof(*state));
1668 state->iocom = iocom;
1669 state->flags = HAMMER2_STATE_DYNAMIC;
1671 state->txcmd = HAMMER2_MSGF_REPLY;
1672 state->rxcmd = msg->any.head.cmd & ~HAMMER2_MSGF_DELETE;
1673 state->flags |= HAMMER2_STATE_INSERTED;
1674 state->msgid = msg->any.head.msgid;
1675 state->router = msg->router;
1677 pthread_mutex_lock(&iocom->mtx);
1678 RB_INSERT(hammer2_state_tree,
1679 &iocom->router->staterd_tree, state);
1680 pthread_mutex_unlock(&iocom->mtx);
1683 fprintf(stderr, "create state %p id=%08x on iocom staterd %p\n",
1684 state, (uint32_t)state->msgid, iocom);
1687 case HAMMER2_MSGF_DELETE:
1689 * Persistent state is expected but might not exist if an
1690 * ABORT+DELETE races the close.
1692 if (state == NULL) {
1693 if (msg->any.head.cmd & HAMMER2_MSGF_ABORT) {
1694 error = HAMMER2_IOQ_ERROR_EALREADY;
1696 fprintf(stderr, "missing-state %s\n",
1697 hammer2_msg_str(msg));
1698 error = HAMMER2_IOQ_ERROR_TRANS;
1705 * Handle another ABORT+DELETE case if the msgid has already
1708 if ((state->rxcmd & HAMMER2_MSGF_CREATE) == 0) {
1709 if (msg->any.head.cmd & HAMMER2_MSGF_ABORT) {
1710 error = HAMMER2_IOQ_ERROR_EALREADY;
1712 fprintf(stderr, "reused-state %s\n",
1713 hammer2_msg_str(msg));
1714 error = HAMMER2_IOQ_ERROR_TRANS;
1723 * Check for mid-stream ABORT command received, otherwise
1726 if (msg->any.head.cmd & HAMMER2_MSGF_ABORT) {
1727 if (state == NULL ||
1728 (state->rxcmd & HAMMER2_MSGF_CREATE) == 0) {
1729 error = HAMMER2_IOQ_ERROR_EALREADY;
1735 case HAMMER2_MSGF_REPLY | HAMMER2_MSGF_CREATE:
1736 case HAMMER2_MSGF_REPLY | HAMMER2_MSGF_CREATE | HAMMER2_MSGF_DELETE:
1738 * When receiving a reply with CREATE set the original
1739 * persistent state message should already exist.
1741 if (state == NULL) {
1742 fprintf(stderr, "no-state(r) %s\n",
1743 hammer2_msg_str(msg));
1744 error = HAMMER2_IOQ_ERROR_TRANS;
1748 assert(((state->rxcmd ^ msg->any.head.cmd) &
1749 HAMMER2_MSGF_REPLY) == 0);
1750 state->rxcmd = msg->any.head.cmd & ~HAMMER2_MSGF_DELETE;
1753 case HAMMER2_MSGF_REPLY | HAMMER2_MSGF_DELETE:
1755 * Received REPLY+ABORT+DELETE in case where msgid has
1756 * already been fully closed, ignore the message.
1758 if (state == NULL) {
1759 if (msg->any.head.cmd & HAMMER2_MSGF_ABORT) {
1760 error = HAMMER2_IOQ_ERROR_EALREADY;
1762 fprintf(stderr, "no-state(r,d) %s\n",
1763 hammer2_msg_str(msg));
1764 error = HAMMER2_IOQ_ERROR_TRANS;
1771 * Received REPLY+ABORT+DELETE in case where msgid has
1772 * already been reused for an unrelated message,
1773 * ignore the message.
1775 if ((state->rxcmd & HAMMER2_MSGF_CREATE) == 0) {
1776 if (msg->any.head.cmd & HAMMER2_MSGF_ABORT) {
1777 error = HAMMER2_IOQ_ERROR_EALREADY;
1779 fprintf(stderr, "reused-state(r,d) %s\n",
1780 hammer2_msg_str(msg));
1781 error = HAMMER2_IOQ_ERROR_TRANS;
1788 case HAMMER2_MSGF_REPLY:
1790 * Check for mid-stream ABORT reply received to sent command.
1792 if (msg->any.head.cmd & HAMMER2_MSGF_ABORT) {
1793 if (state == NULL ||
1794 (state->rxcmd & HAMMER2_MSGF_CREATE) == 0) {
1795 error = HAMMER2_IOQ_ERROR_EALREADY;
1806 hammer2_state_cleanuprx(hammer2_iocom_t *iocom, hammer2_msg_t *msg)
1808 hammer2_state_t *state;
1810 if ((state = msg->state) == NULL) {
1812 * Free a non-transactional message, there is no state
1815 hammer2_msg_free(msg);
1816 } else if (msg->any.head.cmd & HAMMER2_MSGF_DELETE) {
1818 * Message terminating transaction, destroy the related
1819 * state, the original message, and this message (if it
1820 * isn't the original message due to a CREATE|DELETE).
1822 pthread_mutex_lock(&iocom->mtx);
1823 state->rxcmd |= HAMMER2_MSGF_DELETE;
1824 if (state->txcmd & HAMMER2_MSGF_DELETE) {
1825 if (state->msg == msg)
1827 assert(state->flags & HAMMER2_STATE_INSERTED);
1828 if (state->rxcmd & HAMMER2_MSGF_REPLY) {
1829 assert(msg->any.head.cmd & HAMMER2_MSGF_REPLY);
1830 RB_REMOVE(hammer2_state_tree,
1831 &iocom->router->statewr_tree, state);
1833 assert((msg->any.head.cmd & HAMMER2_MSGF_REPLY) == 0);
1834 RB_REMOVE(hammer2_state_tree,
1835 &iocom->router->staterd_tree, state);
1837 state->flags &= ~HAMMER2_STATE_INSERTED;
1838 hammer2_state_free(state);
1842 pthread_mutex_unlock(&iocom->mtx);
1843 hammer2_msg_free(msg);
1844 } else if (state->msg != msg) {
1846 * Message not terminating transaction, leave state intact
1847 * and free message if it isn't the CREATE message.
1849 hammer2_msg_free(msg);
1854 hammer2_state_cleanuptx(hammer2_msg_t *msg)
1856 hammer2_iocom_t *iocom = msg->router->iocom;
1857 hammer2_state_t *state;
1859 if ((state = msg->state) == NULL) {
1860 hammer2_msg_free(msg);
1861 } else if (msg->any.head.cmd & HAMMER2_MSGF_DELETE) {
1862 pthread_mutex_lock(&iocom->mtx);
1863 state->txcmd |= HAMMER2_MSGF_DELETE;
1864 if (state->rxcmd & HAMMER2_MSGF_DELETE) {
1865 if (state->msg == msg)
1867 assert(state->flags & HAMMER2_STATE_INSERTED);
1868 if (state->txcmd & HAMMER2_MSGF_REPLY) {
1869 assert(msg->any.head.cmd & HAMMER2_MSGF_REPLY);
1870 RB_REMOVE(hammer2_state_tree,
1871 &iocom->router->staterd_tree, state);
1873 assert((msg->any.head.cmd & HAMMER2_MSGF_REPLY) == 0);
1874 RB_REMOVE(hammer2_state_tree,
1875 &iocom->router->statewr_tree, state);
1877 state->flags &= ~HAMMER2_STATE_INSERTED;
1878 hammer2_state_free(state);
1882 pthread_mutex_unlock(&iocom->mtx);
1883 hammer2_msg_free(msg);
1884 } else if (state->msg != msg) {
1885 hammer2_msg_free(msg);
1890 * Called with iocom locked
1893 hammer2_state_free(hammer2_state_t *state)
1895 hammer2_iocom_t *iocom = state->iocom;
1900 fprintf(stderr, "terminate state %p id=%08x\n",
1901 state, (uint32_t)state->msgid);
1903 assert(state->any.any == NULL);
1907 hammer2_msg_free_locked(msg);
1911 * When an iocom error is present we are trying to close down the
1912 * iocom, but we have to wait for all states to terminate before
1913 * we can do so. The iocom rx code will terminate the receive side
1914 * for all transactions by simulating incoming DELETE messages,
1915 * but the state doesn't go away until both sides are terminated.
1917 * We may have to wake up the rx code.
1919 if (iocom->ioq_rx.error &&
1920 RB_EMPTY(&iocom->router->staterd_tree) &&
1921 RB_EMPTY(&iocom->router->statewr_tree)) {
1923 write(iocom->wakeupfds[1], &dummy, 1);
1927 /************************************************************************
1929 ************************************************************************
1931 * Incoming messages are routed by their spanid, matched up against
1932 * outgoing LNK_SPANs managed by h2span_relay structures (see msg_lnk.c).
1933 * Any replies run through the same router.
1935 * Originated messages are routed by their spanid, matched up against
1936 * incoming LNK_SPANs managed by h2span_link structures (see msg_lnk.c).
1937 * Replies come back through the same route.
1939 * Keep in mind that ALL MESSAGE TRAFFIC pertaining to a particular
1940 * transaction runs through the same route. Commands and replies both.
1942 * An originated message will use a different routing spanid to
1943 * reach a target node than a message which originates from that node.
1944 * They might use the same physical pipes (each pipe can have multiple
1945 * SPANs and RELAYs), but the routes are distinct from the perspective
1949 hammer2_router_alloc(void)
1951 hammer2_router_t *router;
1953 router = hammer2_alloc(sizeof(*router));
1954 TAILQ_INIT(&router->txmsgq);
1959 hammer2_router_connect(hammer2_router_t *router)
1961 hammer2_router_t *tmp;
1963 assert(router->link || router->relay);
1964 assert((router->flags & HAMMER2_ROUTER_CONNECTED) == 0);
1966 pthread_mutex_lock(&router_mtx);
1968 tmp = RB_INSERT(hammer2_router_tree, &router_ltree, router);
1970 tmp = RB_INSERT(hammer2_router_tree, &router_rtree, router);
1971 assert(tmp == NULL);
1972 router->flags |= HAMMER2_ROUTER_CONNECTED;
1973 pthread_mutex_unlock(&router_mtx);
1977 hammer2_router_disconnect(hammer2_router_t **routerp)
1979 hammer2_router_t *router;
1982 assert(router->link || router->relay);
1983 assert(router->flags & HAMMER2_ROUTER_CONNECTED);
1985 pthread_mutex_lock(&router_mtx);
1987 RB_REMOVE(hammer2_router_tree, &router_ltree, router);
1989 RB_REMOVE(hammer2_router_tree, &router_rtree, router);
1990 router->flags &= ~HAMMER2_ROUTER_CONNECTED;
1992 pthread_mutex_unlock(&router_mtx);
2000 hammer2_route_msg(hammer2_msg_t *msg)
2005 /************************************************************************
2007 ************************************************************************/
2010 hammer2_basecmd_str(uint32_t cmd)
2012 static char buf[64];
2015 const char *protostr;
2018 switch(cmd & HAMMER2_MSGF_PROTOS) {
2019 case HAMMER2_MSG_PROTO_LNK:
2022 case HAMMER2_MSG_PROTO_DBG:
2025 case HAMMER2_MSG_PROTO_DOM:
2028 case HAMMER2_MSG_PROTO_CAC:
2031 case HAMMER2_MSG_PROTO_QRM:
2034 case HAMMER2_MSG_PROTO_BLK:
2037 case HAMMER2_MSG_PROTO_VOP:
2041 snprintf(protobuf, sizeof(protobuf), "%x_",
2042 (cmd & HAMMER2_MSGF_PROTOS) >> 20);
2043 protostr = protobuf;
2047 switch(cmd & (HAMMER2_MSGF_PROTOS |
2049 HAMMER2_MSGF_SIZE)) {
2050 case HAMMER2_LNK_PAD:
2053 case HAMMER2_LNK_PING:
2056 case HAMMER2_LNK_AUTH:
2059 case HAMMER2_LNK_CONN:
2062 case HAMMER2_LNK_SPAN:
2065 case HAMMER2_LNK_ERROR:
2066 if (cmd & HAMMER2_MSGF_DELETE)
2071 case HAMMER2_DBG_SHELL:
2075 snprintf(cmdbuf, sizeof(cmdbuf),
2076 "%06x", (cmd & (HAMMER2_MSGF_PROTOS |
2078 HAMMER2_MSGF_SIZE)));
2082 snprintf(buf, sizeof(buf), "%s%s", protostr, cmdstr);
2087 hammer2_msg_str(hammer2_msg_t *msg)
2089 hammer2_state_t *state;
2090 static char buf[256];
2094 const char *statestr;
2102 if ((state = msg->state) != NULL) {
2103 basecmd = (state->rxcmd & HAMMER2_MSGF_REPLY) ?
2104 state->txcmd : state->rxcmd;
2105 snprintf(statebuf, sizeof(statebuf),
2106 " %s=%s,L=%s%s,R=%s%s",
2107 ((state->txcmd & HAMMER2_MSGF_REPLY) ?
2108 "rcvcmd" : "sndcmd"),
2109 hammer2_basecmd_str(basecmd),
2110 ((state->txcmd & HAMMER2_MSGF_CREATE) ? "C" : ""),
2111 ((state->txcmd & HAMMER2_MSGF_DELETE) ? "D" : ""),
2112 ((state->rxcmd & HAMMER2_MSGF_CREATE) ? "C" : ""),
2113 ((state->rxcmd & HAMMER2_MSGF_DELETE) ? "D" : "")
2115 statestr = statebuf;
2123 switch(msg->any.head.error) {
2127 case HAMMER2_IOQ_ERROR_SYNC:
2128 errstr = "err=IOQ:NOSYNC";
2130 case HAMMER2_IOQ_ERROR_EOF:
2131 errstr = "err=IOQ:STREAMEOF";
2133 case HAMMER2_IOQ_ERROR_SOCK:
2134 errstr = "err=IOQ:SOCKERR";
2136 case HAMMER2_IOQ_ERROR_FIELD:
2137 errstr = "err=IOQ:BADFIELD";
2139 case HAMMER2_IOQ_ERROR_HCRC:
2140 errstr = "err=IOQ:BADHCRC";
2142 case HAMMER2_IOQ_ERROR_XCRC:
2143 errstr = "err=IOQ:BADXCRC";
2145 case HAMMER2_IOQ_ERROR_ACRC:
2146 errstr = "err=IOQ:BADACRC";
2148 case HAMMER2_IOQ_ERROR_STATE:
2149 errstr = "err=IOQ:BADSTATE";
2151 case HAMMER2_IOQ_ERROR_NOPEER:
2152 errstr = "err=IOQ:PEERCONFIG";
2154 case HAMMER2_IOQ_ERROR_NORKEY:
2155 errstr = "err=IOQ:BADRKEY";
2157 case HAMMER2_IOQ_ERROR_NOLKEY:
2158 errstr = "err=IOQ:BADLKEY";
2160 case HAMMER2_IOQ_ERROR_KEYXCHGFAIL:
2161 errstr = "err=IOQ:BADKEYXCHG";
2163 case HAMMER2_IOQ_ERROR_KEYFMT:
2164 errstr = "err=IOQ:BADFMT";
2166 case HAMMER2_IOQ_ERROR_BADURANDOM:
2167 errstr = "err=IOQ:BADRANDOM";
2169 case HAMMER2_IOQ_ERROR_MSGSEQ:
2170 errstr = "err=IOQ:BADSEQ";
2172 case HAMMER2_IOQ_ERROR_EALREADY:
2173 errstr = "err=IOQ:DUPMSG";
2175 case HAMMER2_IOQ_ERROR_TRANS:
2176 errstr = "err=IOQ:BADTRANS";
2178 case HAMMER2_IOQ_ERROR_IVWRAP:
2179 errstr = "err=IOQ:IVWRAP";
2181 case HAMMER2_IOQ_ERROR_MACFAIL:
2182 errstr = "err=IOQ:MACFAIL";
2184 case HAMMER2_IOQ_ERROR_ALGO:
2185 errstr = "err=IOQ:ALGOFAIL";
2187 case HAMMER2_MSG_ERR_NOSUPP:
2188 errstr = "err=NOSUPPORT";
2191 snprintf(errbuf, sizeof(errbuf),
2192 " err=%d", msg->any.head.error);
2201 if (msg->any.head.cmd & (HAMMER2_MSGF_CREATE | HAMMER2_MSGF_DELETE |
2202 HAMMER2_MSGF_ABORT | HAMMER2_MSGF_REPLY)) {
2204 if (msg->any.head.cmd & HAMMER2_MSGF_CREATE)
2206 if (msg->any.head.cmd & HAMMER2_MSGF_DELETE)
2208 if (msg->any.head.cmd & HAMMER2_MSGF_REPLY)
2210 if (msg->any.head.cmd & HAMMER2_MSGF_ABORT)
2218 snprintf(buf, sizeof(buf),
2219 "msg=%s%s %s id=%08x src=%08x tgt=%08x %s",
2220 hammer2_basecmd_str(msg->any.head.cmd),
2223 (uint32_t)(intmax_t)msg->any.head.msgid, /* for brevity */
2224 (uint32_t)(intmax_t)msg->any.head.source, /* for brevity */
2225 (uint32_t)(intmax_t)msg->any.head.target, /* for brevity */