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
36 #include "dmsg_local.h"
40 static int dmsg_state_msgrx(dmsg_msg_t *msg);
41 static void dmsg_state_cleanuptx(dmsg_msg_t *msg);
43 RB_GENERATE(dmsg_state_tree, dmsg_state, rbnode, dmsg_state_cmp);
44 RB_GENERATE(dmsg_circuit_tree, dmsg_circuit, rbnode, dmsg_circuit_cmp);
47 * STATE TREE - Represents open transactions which are indexed by their
48 * { msgid } relative to the governing iocom.
51 dmsg_state_cmp(dmsg_state_t *state1, dmsg_state_t *state2)
53 if (state1->msgid < state2->msgid)
55 if (state1->msgid > state2->msgid)
61 * CIRCUIT TREE - Represents open circuits which are indexed by their
62 * { msgid } relative to the governing iocom.
65 dmsg_circuit_cmp(dmsg_circuit_t *circuit1, dmsg_circuit_t *circuit2)
67 if (circuit1->msgid < circuit2->msgid)
69 if (circuit1->msgid > circuit2->msgid)
75 * Initialize a low-level ioq
78 dmsg_ioq_init(dmsg_iocom_t *iocom __unused, dmsg_ioq_t *ioq)
80 bzero(ioq, sizeof(*ioq));
81 ioq->state = DMSG_MSGQ_STATE_HEADER1;
82 TAILQ_INIT(&ioq->msgq);
88 * caller holds iocom->mtx.
91 dmsg_ioq_done(dmsg_iocom_t *iocom __unused, dmsg_ioq_t *ioq)
95 while ((msg = TAILQ_FIRST(&ioq->msgq)) != NULL) {
96 assert(0); /* shouldn't happen */
97 TAILQ_REMOVE(&ioq->msgq, msg, qentry);
100 if ((msg = ioq->msg) != NULL) {
107 * Initialize a low-level communications channel.
109 * NOTE: The signal_func() is called at least once from the loop and can be
110 * re-armed via dmsg_iocom_restate().
113 dmsg_iocom_init(dmsg_iocom_t *iocom, int sock_fd, int alt_fd,
114 void (*signal_func)(dmsg_iocom_t *),
115 void (*rcvmsg_func)(dmsg_msg_t *),
116 void (*dbgmsg_func)(dmsg_msg_t *),
117 void (*altmsg_func)(dmsg_iocom_t *))
121 bzero(iocom, sizeof(*iocom));
123 asprintf(&iocom->label, "iocom-%p", iocom);
124 iocom->signal_callback = signal_func;
125 iocom->rcvmsg_callback = rcvmsg_func;
126 iocom->altmsg_callback = altmsg_func;
127 iocom->dbgmsg_callback = dbgmsg_func;
129 pthread_mutex_init(&iocom->mtx, NULL);
130 RB_INIT(&iocom->circuit_tree);
131 TAILQ_INIT(&iocom->freeq);
132 TAILQ_INIT(&iocom->freeq_aux);
133 TAILQ_INIT(&iocom->txmsgq);
134 iocom->sock_fd = sock_fd;
135 iocom->alt_fd = alt_fd;
136 iocom->flags = DMSG_IOCOMF_RREQ;
138 iocom->flags |= DMSG_IOCOMF_SWORK;
139 dmsg_ioq_init(iocom, &iocom->ioq_rx);
140 dmsg_ioq_init(iocom, &iocom->ioq_tx);
141 if (pipe(iocom->wakeupfds) < 0)
143 fcntl(iocom->wakeupfds[0], F_SETFL, O_NONBLOCK);
144 fcntl(iocom->wakeupfds[1], F_SETFL, O_NONBLOCK);
146 dmsg_circuit_init(iocom, &iocom->circuit0);
149 * Negotiate session crypto synchronously. This will mark the
150 * connection as error'd if it fails. If this is a pipe it's
151 * a linkage that we set up ourselves to the filesystem and there
154 if (fstat(sock_fd, &st) < 0)
156 if (S_ISSOCK(st.st_mode))
157 dmsg_crypto_negotiate(iocom);
160 * Make sure our fds are set to non-blocking for the iocom core.
163 fcntl(sock_fd, F_SETFL, O_NONBLOCK);
165 /* if line buffered our single fgets() should be fine */
167 fcntl(alt_fd, F_SETFL, O_NONBLOCK);
172 dmsg_iocom_label(dmsg_iocom_t *iocom, const char *ctl, ...)
179 vasprintf(&iocom->label, ctl, va);
186 * May only be called from a callback from iocom_core.
188 * Adjust state machine functions, set flags to guarantee that both
189 * the recevmsg_func and the sendmsg_func is called at least once.
192 dmsg_iocom_restate(dmsg_iocom_t *iocom,
193 void (*signal_func)(dmsg_iocom_t *),
194 void (*rcvmsg_func)(dmsg_msg_t *msg),
195 void (*altmsg_func)(dmsg_iocom_t *))
197 iocom->signal_callback = signal_func;
198 iocom->rcvmsg_callback = rcvmsg_func;
199 iocom->altmsg_callback = altmsg_func;
201 iocom->flags |= DMSG_IOCOMF_SWORK;
203 iocom->flags &= ~DMSG_IOCOMF_SWORK;
207 dmsg_iocom_signal(dmsg_iocom_t *iocom)
209 if (iocom->signal_callback)
210 iocom->flags |= DMSG_IOCOMF_SWORK;
214 * Cleanup a terminating iocom.
216 * Caller should not hold iocom->mtx. The iocom has already been disconnected
217 * from all possible references to it.
220 dmsg_iocom_done(dmsg_iocom_t *iocom)
224 if (iocom->sock_fd >= 0) {
225 close(iocom->sock_fd);
228 if (iocom->alt_fd >= 0) {
229 close(iocom->alt_fd);
232 dmsg_ioq_done(iocom, &iocom->ioq_rx);
233 dmsg_ioq_done(iocom, &iocom->ioq_tx);
234 if ((msg = TAILQ_FIRST(&iocom->freeq)) != NULL) {
235 TAILQ_REMOVE(&iocom->freeq, msg, qentry);
238 if ((msg = TAILQ_FIRST(&iocom->freeq_aux)) != NULL) {
239 TAILQ_REMOVE(&iocom->freeq_aux, msg, qentry);
241 msg->aux_data = NULL;
244 if (iocom->wakeupfds[0] >= 0) {
245 close(iocom->wakeupfds[0]);
246 iocom->wakeupfds[0] = -1;
248 if (iocom->wakeupfds[1] >= 0) {
249 close(iocom->wakeupfds[1]);
250 iocom->wakeupfds[1] = -1;
252 pthread_mutex_destroy(&iocom->mtx);
256 * Initialize a circuit structure and add it to the iocom's circuit_tree.
257 * circuit0 is left out and will not be added to the tree.
260 dmsg_circuit_init(dmsg_iocom_t *iocom, dmsg_circuit_t *circuit)
262 circuit->iocom = iocom;
263 RB_INIT(&circuit->staterd_tree);
264 RB_INIT(&circuit->statewr_tree);
266 RB_INSERT(dmsg_circuit_tree, &iocom->circuit_tree, circuit);
270 * Allocate a new one-way message.
273 dmsg_msg_alloc(dmsg_circuit_t *circuit,
274 size_t aux_size, uint32_t cmd,
275 void (*func)(dmsg_msg_t *), void *data)
277 dmsg_iocom_t *iocom = circuit->iocom;
278 dmsg_state_t *state = NULL;
283 pthread_mutex_lock(&iocom->mtx);
285 aligned_size = DMSG_DOALIGN(aux_size);
286 if ((msg = TAILQ_FIRST(&iocom->freeq_aux)) != NULL)
287 TAILQ_REMOVE(&iocom->freeq_aux, msg, qentry);
290 if ((msg = TAILQ_FIRST(&iocom->freeq)) != NULL)
291 TAILQ_REMOVE(&iocom->freeq, msg, qentry);
293 if ((cmd & (DMSGF_CREATE | DMSGF_REPLY)) == DMSGF_CREATE) {
295 * Create state when CREATE is set without REPLY.
296 * Assign a unique msgid, in this case simply using
297 * the pointer value for 'state'.
299 * NOTE: CREATE in txcmd handled by dmsg_msg_write()
300 * NOTE: DELETE in txcmd handled by dmsg_state_cleanuptx()
302 * NOTE: state initiated by us and state initiated by
303 * a remote create are placed in different RB trees.
304 * The msgid for SPAN state is used in source/target
305 * for message routing as appropriate.
307 state = malloc(sizeof(*state));
308 bzero(state, sizeof(*state));
309 state->iocom = iocom;
310 state->circuit = circuit;
311 state->flags = DMSG_STATE_DYNAMIC;
312 state->msgid = (uint64_t)(uintptr_t)state;
313 state->txcmd = cmd & ~(DMSGF_CREATE | DMSGF_DELETE);
314 state->rxcmd = DMSGF_REPLY;
315 state->icmd = state->txcmd & DMSGF_BASECMDMASK;
317 state->any.any = data;
318 pthread_mutex_lock(&iocom->mtx);
319 RB_INSERT(dmsg_state_tree, &circuit->statewr_tree, state);
320 pthread_mutex_unlock(&iocom->mtx);
321 state->flags |= DMSG_STATE_INSERTED;
323 pthread_mutex_unlock(&iocom->mtx);
325 msg = malloc(sizeof(*msg));
326 bzero(msg, sizeof(*msg));
327 msg->aux_data = NULL;
332 * [re]allocate the auxillary data buffer. The caller knows that
333 * a size-aligned buffer will be allocated but we do not want to
334 * force the caller to zero any tail piece, so we do that ourself.
336 if (msg->aux_size != aux_size) {
339 msg->aux_data = NULL;
343 msg->aux_data = malloc(aligned_size);
344 msg->aux_size = aux_size;
345 if (aux_size != aligned_size) {
346 bzero(msg->aux_data + aux_size,
347 aligned_size - aux_size);
351 hbytes = (cmd & DMSGF_SIZE) * DMSG_ALIGN;
353 bzero(&msg->any.head, hbytes);
354 msg->hdr_size = hbytes;
355 msg->any.head.magic = DMSG_HDR_MAGIC;
356 msg->any.head.cmd = cmd;
357 msg->any.head.aux_descr = 0;
358 msg->any.head.aux_crc = 0;
359 msg->any.head.circuit = 0;
360 msg->circuit = circuit;
365 msg->any.head.msgid = state->msgid;
367 msg->any.head.msgid = 0;
373 * Free a message so it can be reused afresh.
375 * NOTE: aux_size can be 0 with a non-NULL aux_data.
379 dmsg_msg_free_locked(dmsg_msg_t *msg)
381 dmsg_iocom_t *iocom = msg->iocom;
385 TAILQ_INSERT_TAIL(&iocom->freeq_aux, msg, qentry);
387 TAILQ_INSERT_TAIL(&iocom->freeq, msg, qentry);
391 dmsg_msg_free(dmsg_msg_t *msg)
393 dmsg_iocom_t *iocom = msg->iocom;
395 pthread_mutex_lock(&iocom->mtx);
396 dmsg_msg_free_locked(msg);
397 pthread_mutex_unlock(&iocom->mtx);
401 * I/O core loop for an iocom.
403 * Thread localized, iocom->mtx not held.
406 dmsg_iocom_core(dmsg_iocom_t *iocom)
408 struct pollfd fds[3];
413 int wi; /* wakeup pipe */
415 int ai; /* alt bulk path socket */
417 while ((iocom->flags & DMSG_IOCOMF_EOF) == 0) {
418 if ((iocom->flags & (DMSG_IOCOMF_RWORK |
423 DMSG_IOCOMF_AWWORK)) == 0) {
425 * Only poll if no immediate work is pending.
426 * Otherwise we are just wasting our time calling
437 * Always check the inter-thread pipe, e.g.
438 * for iocom->txmsgq work.
441 fds[wi].fd = iocom->wakeupfds[0];
442 fds[wi].events = POLLIN;
446 * Check the socket input/output direction as
449 if (iocom->flags & (DMSG_IOCOMF_RREQ |
452 fds[si].fd = iocom->sock_fd;
456 if (iocom->flags & DMSG_IOCOMF_RREQ)
457 fds[si].events |= POLLIN;
458 if (iocom->flags & DMSG_IOCOMF_WREQ)
459 fds[si].events |= POLLOUT;
463 * Check the alternative fd for work.
465 if (iocom->alt_fd >= 0) {
467 fds[ai].fd = iocom->alt_fd;
468 fds[ai].events = POLLIN;
471 poll(fds, count, timeout);
473 if (wi >= 0 && (fds[wi].revents & POLLIN))
474 iocom->flags |= DMSG_IOCOMF_PWORK;
475 if (si >= 0 && (fds[si].revents & POLLIN))
476 iocom->flags |= DMSG_IOCOMF_RWORK;
477 if (si >= 0 && (fds[si].revents & POLLOUT))
478 iocom->flags |= DMSG_IOCOMF_WWORK;
479 if (wi >= 0 && (fds[wi].revents & POLLOUT))
480 iocom->flags |= DMSG_IOCOMF_WWORK;
481 if (ai >= 0 && (fds[ai].revents & POLLIN))
482 iocom->flags |= DMSG_IOCOMF_ARWORK;
485 * Always check the pipe
487 iocom->flags |= DMSG_IOCOMF_PWORK;
490 if (iocom->flags & DMSG_IOCOMF_SWORK) {
491 iocom->flags &= ~DMSG_IOCOMF_SWORK;
492 iocom->signal_callback(iocom);
496 * Pending message queues from other threads wake us up
497 * with a write to the wakeupfds[] pipe. We have to clear
498 * the pipe with a dummy read.
500 if (iocom->flags & DMSG_IOCOMF_PWORK) {
501 iocom->flags &= ~DMSG_IOCOMF_PWORK;
502 read(iocom->wakeupfds[0], dummybuf, sizeof(dummybuf));
503 iocom->flags |= DMSG_IOCOMF_RWORK;
504 iocom->flags |= DMSG_IOCOMF_WWORK;
505 if (TAILQ_FIRST(&iocom->txmsgq))
506 dmsg_iocom_flush1(iocom);
510 * Message write sequencing
512 if (iocom->flags & DMSG_IOCOMF_WWORK)
513 dmsg_iocom_flush1(iocom);
516 * Message read sequencing. Run this after the write
517 * sequencing in case the write sequencing allowed another
518 * auto-DELETE to occur on the read side.
520 if (iocom->flags & DMSG_IOCOMF_RWORK) {
521 while ((iocom->flags & DMSG_IOCOMF_EOF) == 0 &&
522 (msg = dmsg_ioq_read(iocom)) != NULL) {
524 fprintf(stderr, "receive %s\n",
527 iocom->rcvmsg_callback(msg);
528 dmsg_state_cleanuprx(iocom, msg);
532 if (iocom->flags & DMSG_IOCOMF_ARWORK) {
533 iocom->flags &= ~DMSG_IOCOMF_ARWORK;
534 iocom->altmsg_callback(iocom);
540 * Make sure there's enough room in the FIFO to hold the
543 * Assume worst case encrypted form is 2x the size of the
544 * plaintext equivalent.
548 dmsg_ioq_makeroom(dmsg_ioq_t *ioq, size_t needed)
553 bytes = ioq->fifo_cdx - ioq->fifo_beg;
554 nmax = sizeof(ioq->buf) - ioq->fifo_end;
555 if (bytes + nmax / 2 < needed) {
557 bcopy(ioq->buf + ioq->fifo_beg,
561 ioq->fifo_cdx -= ioq->fifo_beg;
563 if (ioq->fifo_cdn < ioq->fifo_end) {
564 bcopy(ioq->buf + ioq->fifo_cdn,
565 ioq->buf + ioq->fifo_cdx,
566 ioq->fifo_end - ioq->fifo_cdn);
568 ioq->fifo_end -= ioq->fifo_cdn - ioq->fifo_cdx;
569 ioq->fifo_cdn = ioq->fifo_cdx;
570 nmax = sizeof(ioq->buf) - ioq->fifo_end;
576 * Read the next ready message from the ioq, issuing I/O if needed.
577 * Caller should retry on a read-event when NULL is returned.
579 * If an error occurs during reception a DMSG_LNK_ERROR msg will
580 * be returned for each open transaction, then the ioq and iocom
581 * will be errored out and a non-transactional DMSG_LNK_ERROR
582 * msg will be returned as the final message. The caller should not call
583 * us again after the final message is returned.
585 * Thread localized, iocom->mtx not held.
588 dmsg_ioq_read(dmsg_iocom_t *iocom)
590 dmsg_ioq_t *ioq = &iocom->ioq_rx;
593 dmsg_circuit_t *circuit0;
603 iocom->flags &= ~(DMSG_IOCOMF_RREQ | DMSG_IOCOMF_RWORK);
606 * If a message is already pending we can just remove and
607 * return it. Message state has already been processed.
608 * (currently not implemented)
610 if ((msg = TAILQ_FIRST(&ioq->msgq)) != NULL) {
611 TAILQ_REMOVE(&ioq->msgq, msg, qentry);
616 * If the stream is errored out we stop processing it.
622 * Message read in-progress (msg is NULL at the moment). We don't
623 * allocate a msg until we have its core header.
625 nmax = sizeof(ioq->buf) - ioq->fifo_end;
626 bytes = ioq->fifo_cdx - ioq->fifo_beg; /* already decrypted */
630 case DMSG_MSGQ_STATE_HEADER1:
632 * Load the primary header, fail on any non-trivial read
633 * error or on EOF. Since the primary header is the same
634 * size is the message alignment it will never straddle
635 * the end of the buffer.
637 nmax = dmsg_ioq_makeroom(ioq, sizeof(msg->any.head));
638 if (bytes < sizeof(msg->any.head)) {
639 n = read(iocom->sock_fd,
640 ioq->buf + ioq->fifo_end,
644 ioq->error = DMSG_IOQ_ERROR_EOF;
647 if (errno != EINTR &&
648 errno != EINPROGRESS &&
650 ioq->error = DMSG_IOQ_ERROR_SOCK;
656 ioq->fifo_end += (size_t)n;
661 * Decrypt data received so far. Data will be decrypted
662 * in-place but might create gaps in the FIFO. Partial
663 * blocks are not immediately decrypted.
665 * WARNING! The header might be in the wrong endian, we
666 * do not fix it up until we get the entire
669 if (iocom->flags & DMSG_IOCOMF_CRYPTED) {
670 dmsg_crypto_decrypt(iocom, ioq);
672 ioq->fifo_cdx = ioq->fifo_end;
673 ioq->fifo_cdn = ioq->fifo_end;
675 bytes = ioq->fifo_cdx - ioq->fifo_beg;
678 * Insufficient data accumulated (msg is NULL, caller will
682 if (bytes < sizeof(msg->any.head))
686 * Check and fixup the core header. Note that the icrc
687 * has to be calculated before any fixups, but the crc
688 * fields in the msg may have to be swapped like everything
691 head = (void *)(ioq->buf + ioq->fifo_beg);
692 if (head->magic != DMSG_HDR_MAGIC &&
693 head->magic != DMSG_HDR_MAGIC_REV) {
694 fprintf(stderr, "%s: head->magic is bad %02x\n",
695 iocom->label, head->magic);
696 if (iocom->flags & DMSG_IOCOMF_CRYPTED)
697 fprintf(stderr, "(on encrypted link)\n");
698 ioq->error = DMSG_IOQ_ERROR_SYNC;
703 * Calculate the full header size and aux data size
705 if (head->magic == DMSG_HDR_MAGIC_REV) {
706 ioq->hbytes = (bswap32(head->cmd) & DMSGF_SIZE) *
708 aux_size = bswap32(head->aux_bytes);
710 ioq->hbytes = (head->cmd & DMSGF_SIZE) *
712 aux_size = head->aux_bytes;
714 ioq->abytes = DMSG_DOALIGN(aux_size);
715 ioq->unaligned_aux_size = aux_size;
716 if (ioq->hbytes < sizeof(msg->any.head) ||
717 ioq->hbytes > sizeof(msg->any) ||
718 ioq->abytes > DMSG_AUX_MAX) {
719 ioq->error = DMSG_IOQ_ERROR_FIELD;
724 * Allocate the message, the next state will fill it in.
725 * Note that the actual buffer will be sized to an aligned
726 * value and the aligned remainder zero'd for convenience.
728 msg = dmsg_msg_alloc(&iocom->circuit0, aux_size, 0,
733 * Fall through to the next state. Make sure that the
734 * extended header does not straddle the end of the buffer.
735 * We still want to issue larger reads into our buffer,
736 * book-keeping is easier if we don't bcopy() yet.
738 * Make sure there is enough room for bloated encrypt data.
740 nmax = dmsg_ioq_makeroom(ioq, ioq->hbytes);
741 ioq->state = DMSG_MSGQ_STATE_HEADER2;
743 case DMSG_MSGQ_STATE_HEADER2:
745 * Fill out the extended header.
748 if (bytes < ioq->hbytes) {
749 n = read(iocom->sock_fd,
750 ioq->buf + ioq->fifo_end,
754 ioq->error = DMSG_IOQ_ERROR_EOF;
757 if (errno != EINTR &&
758 errno != EINPROGRESS &&
760 ioq->error = DMSG_IOQ_ERROR_SOCK;
766 ioq->fifo_end += (size_t)n;
770 if (iocom->flags & DMSG_IOCOMF_CRYPTED) {
771 dmsg_crypto_decrypt(iocom, ioq);
773 ioq->fifo_cdx = ioq->fifo_end;
774 ioq->fifo_cdn = ioq->fifo_end;
776 bytes = ioq->fifo_cdx - ioq->fifo_beg;
779 * Insufficient data accumulated (set msg NULL so caller will
782 if (bytes < ioq->hbytes) {
788 * Calculate the extended header, decrypt data received
789 * so far. Handle endian-conversion for the entire extended
792 head = (void *)(ioq->buf + ioq->fifo_beg);
797 if (head->magic == DMSG_HDR_MAGIC_REV)
798 xcrc32 = bswap32(head->hdr_crc);
800 xcrc32 = head->hdr_crc;
802 if (dmsg_icrc32(head, ioq->hbytes) != xcrc32) {
803 ioq->error = DMSG_IOQ_ERROR_XCRC;
804 fprintf(stderr, "BAD-XCRC(%08x,%08x) %s\n",
805 xcrc32, dmsg_icrc32(head, ioq->hbytes),
810 head->hdr_crc = xcrc32;
812 if (head->magic == DMSG_HDR_MAGIC_REV) {
813 dmsg_bswap_head(head);
817 * Copy the extended header into the msg and adjust the
820 bcopy(head, &msg->any, ioq->hbytes);
823 * We are either done or we fall-through.
825 if (ioq->abytes == 0) {
826 ioq->fifo_beg += ioq->hbytes;
831 * Must adjust bytes (and the state) when falling through.
832 * nmax doesn't change.
834 ioq->fifo_beg += ioq->hbytes;
835 bytes -= ioq->hbytes;
836 ioq->state = DMSG_MSGQ_STATE_AUXDATA1;
838 case DMSG_MSGQ_STATE_AUXDATA1:
840 * Copy the partial or complete payload from remaining
841 * bytes in the FIFO in order to optimize the makeroom call
842 * in the AUXDATA2 state. We have to fall-through either
843 * way so we can check the crc.
845 * msg->aux_size tracks our aux data.
847 if (bytes >= ioq->abytes) {
848 bcopy(ioq->buf + ioq->fifo_beg, msg->aux_data,
850 msg->aux_size = ioq->abytes;
851 ioq->fifo_beg += ioq->abytes;
852 assert(ioq->fifo_beg <= ioq->fifo_cdx);
853 assert(ioq->fifo_cdx <= ioq->fifo_cdn);
854 bytes -= ioq->abytes;
856 bcopy(ioq->buf + ioq->fifo_beg, msg->aux_data,
858 msg->aux_size = bytes;
859 ioq->fifo_beg += bytes;
860 if (ioq->fifo_cdx < ioq->fifo_beg)
861 ioq->fifo_cdx = ioq->fifo_beg;
862 assert(ioq->fifo_beg <= ioq->fifo_cdx);
863 assert(ioq->fifo_cdx <= ioq->fifo_cdn);
868 ioq->state = DMSG_MSGQ_STATE_AUXDATA2;
870 case DMSG_MSGQ_STATE_AUXDATA2:
872 * Make sure there is enough room for more data.
875 nmax = dmsg_ioq_makeroom(ioq, ioq->abytes - msg->aux_size);
878 * Read and decrypt more of the payload.
880 if (msg->aux_size < ioq->abytes) {
882 n = read(iocom->sock_fd,
883 ioq->buf + ioq->fifo_end,
887 ioq->error = DMSG_IOQ_ERROR_EOF;
890 if (errno != EINTR &&
891 errno != EINPROGRESS &&
893 ioq->error = DMSG_IOQ_ERROR_SOCK;
899 ioq->fifo_end += (size_t)n;
903 if (iocom->flags & DMSG_IOCOMF_CRYPTED) {
904 dmsg_crypto_decrypt(iocom, ioq);
906 ioq->fifo_cdx = ioq->fifo_end;
907 ioq->fifo_cdn = ioq->fifo_end;
909 bytes = ioq->fifo_cdx - ioq->fifo_beg;
911 if (bytes > ioq->abytes - msg->aux_size)
912 bytes = ioq->abytes - msg->aux_size;
915 bcopy(ioq->buf + ioq->fifo_beg,
916 msg->aux_data + msg->aux_size,
918 msg->aux_size += bytes;
919 ioq->fifo_beg += bytes;
923 * Insufficient data accumulated (set msg NULL so caller will
926 * Assert the auxillary data size is correct, then record the
927 * original unaligned size from the message header.
929 if (msg->aux_size < ioq->abytes) {
933 assert(msg->aux_size == ioq->abytes);
934 msg->aux_size = ioq->unaligned_aux_size;
937 * Check aux_crc, then we are done. Note that the crc
938 * is calculated over the aligned size, not the actual
941 xcrc32 = dmsg_icrc32(msg->aux_data, ioq->abytes);
942 if (xcrc32 != msg->any.head.aux_crc) {
943 ioq->error = DMSG_IOQ_ERROR_ACRC;
947 case DMSG_MSGQ_STATE_ERROR:
949 * Continued calls to drain recorded transactions (returning
950 * a LNK_ERROR for each one), before we return the final
957 * We don't double-return errors, the caller should not
958 * have called us again after getting an error msg.
965 * Check the message sequence. The iv[] should prevent any
966 * possibility of a replay but we add this check anyway.
968 if (msg && ioq->error == 0) {
969 if ((msg->any.head.salt & 255) != (ioq->seq & 255)) {
970 ioq->error = DMSG_IOQ_ERROR_MSGSEQ;
977 * Handle error, RREQ, or completion
979 * NOTE: nmax and bytes are invalid at this point, we don't bother
980 * to update them when breaking out.
985 * An unrecoverable error causes all active receive
986 * transactions to be terminated with a LNK_ERROR message.
988 * Once all active transactions are exhausted we set the
989 * iocom ERROR flag and return a non-transactional LNK_ERROR
990 * message, which should cause master processing loops to
993 assert(ioq->msg == msg);
1000 * No more I/O read processing
1002 ioq->state = DMSG_MSGQ_STATE_ERROR;
1005 * Simulate a remote LNK_ERROR DELETE msg for any open
1006 * transactions, ending with a final non-transactional
1007 * LNK_ERROR (that the session can detect) when no
1008 * transactions remain.
1010 * We only need to scan transactions on circuit0 as these
1011 * will contain all circuit forges, and terminating circuit
1012 * forges will automatically terminate the transactions on
1013 * any other circuits as well as those circuits.
1015 circuit0 = &iocom->circuit0;
1016 msg = dmsg_msg_alloc(circuit0, 0, DMSG_LNK_ERROR, NULL, NULL);
1017 msg->any.head.error = ioq->error;
1019 pthread_mutex_lock(&iocom->mtx);
1020 dmsg_iocom_drain(iocom);
1022 if ((state = RB_ROOT(&circuit0->staterd_tree)) != NULL) {
1024 * Active remote transactions are still present.
1025 * Simulate the other end sending us a DELETE.
1027 if (state->rxcmd & DMSGF_DELETE) {
1031 /*state->txcmd |= DMSGF_DELETE;*/
1034 msg->any.head.msgid = state->msgid;
1035 msg->any.head.cmd |= DMSGF_ABORT |
1038 } else if ((state = RB_ROOT(&circuit0->statewr_tree)) != NULL) {
1040 * Active local transactions are still present.
1041 * Simulate the other end sending us a DELETE.
1043 if (state->rxcmd & DMSGF_DELETE) {
1049 msg->any.head.msgid = state->msgid;
1050 msg->any.head.cmd |= DMSGF_ABORT |
1053 if ((state->rxcmd & DMSGF_CREATE) == 0) {
1054 msg->any.head.cmd |=
1060 * No active local or remote transactions remain.
1061 * Generate a final LNK_ERROR and flag EOF.
1064 iocom->flags |= DMSG_IOCOMF_EOF;
1065 fprintf(stderr, "EOF ON SOCKET %d\n", iocom->sock_fd);
1067 pthread_mutex_unlock(&iocom->mtx);
1070 * For the iocom error case we want to set RWORK to indicate
1071 * that more messages might be pending.
1073 * It is possible to return NULL when there is more work to
1074 * do because each message has to be DELETEd in both
1075 * directions before we continue on with the next (though
1076 * this could be optimized). The transmit direction will
1080 iocom->flags |= DMSG_IOCOMF_RWORK;
1081 } else if (msg == NULL) {
1083 * Insufficient data received to finish building the message,
1084 * set RREQ and return NULL.
1086 * Leave ioq->msg intact.
1087 * Leave the FIFO intact.
1089 iocom->flags |= DMSG_IOCOMF_RREQ;
1092 * Continue processing msg.
1094 * The fifo has already been advanced past the message.
1095 * Trivially reset the FIFO indices if possible.
1097 * clear the FIFO if it is now empty and set RREQ to wait
1098 * for more from the socket. If the FIFO is not empty set
1099 * TWORK to bypass the poll so we loop immediately.
1101 if (ioq->fifo_beg == ioq->fifo_cdx &&
1102 ioq->fifo_cdn == ioq->fifo_end) {
1103 iocom->flags |= DMSG_IOCOMF_RREQ;
1109 iocom->flags |= DMSG_IOCOMF_RWORK;
1111 ioq->state = DMSG_MSGQ_STATE_HEADER1;
1115 * Handle message routing. Validates non-zero sources
1116 * and routes message. Error will be 0 if the message is
1119 * State processing only occurs for messages destined for us.
1121 if (msg->any.head.circuit)
1122 error = dmsg_circuit_relay(msg);
1124 error = dmsg_state_msgrx(msg);
1128 * Abort-after-closure, throw message away and
1129 * start reading another.
1131 if (error == DMSG_IOQ_ERROR_EALREADY) {
1137 * msg routed, msg pointer no longer owned by us.
1138 * Go to the top and start reading another.
1140 if (error == DMSG_IOQ_ERROR_ROUTED)
1144 * Process real error and throw away message.
1149 /* no error, not routed. Fall through and return msg */
1155 * Calculate the header and data crc's and write a low-level message to
1156 * the connection. If aux_crc is non-zero the aux_data crc is already
1157 * assumed to have been set.
1159 * A non-NULL msg is added to the queue but not necessarily flushed.
1160 * Calling this function with msg == NULL will get a flush going.
1162 * Caller must hold iocom->mtx.
1165 dmsg_iocom_flush1(dmsg_iocom_t *iocom)
1167 dmsg_ioq_t *ioq = &iocom->ioq_tx;
1172 dmsg_msg_queue_t tmpq;
1174 iocom->flags &= ~(DMSG_IOCOMF_WREQ | DMSG_IOCOMF_WWORK);
1176 pthread_mutex_lock(&iocom->mtx);
1177 while ((msg = TAILQ_FIRST(&iocom->txmsgq)) != NULL) {
1178 TAILQ_REMOVE(&iocom->txmsgq, msg, qentry);
1179 TAILQ_INSERT_TAIL(&tmpq, msg, qentry);
1181 pthread_mutex_unlock(&iocom->mtx);
1183 while ((msg = TAILQ_FIRST(&tmpq)) != NULL) {
1185 * Process terminal connection errors.
1187 TAILQ_REMOVE(&tmpq, msg, qentry);
1189 TAILQ_INSERT_TAIL(&ioq->msgq, msg, qentry);
1195 * Finish populating the msg fields. The salt ensures that
1196 * the iv[] array is ridiculously randomized and we also
1197 * re-seed our PRNG every 32768 messages just to be sure.
1199 msg->any.head.magic = DMSG_HDR_MAGIC;
1200 msg->any.head.salt = (random() << 8) | (ioq->seq & 255);
1202 if ((ioq->seq & 32767) == 0)
1206 * Calculate aux_crc if 0, then calculate hdr_crc.
1208 if (msg->aux_size && msg->any.head.aux_crc == 0) {
1209 abytes = DMSG_DOALIGN(msg->aux_size);
1210 xcrc32 = dmsg_icrc32(msg->aux_data, abytes);
1211 msg->any.head.aux_crc = xcrc32;
1213 msg->any.head.aux_bytes = msg->aux_size;
1215 hbytes = (msg->any.head.cmd & DMSGF_SIZE) *
1217 msg->any.head.hdr_crc = 0;
1218 msg->any.head.hdr_crc = dmsg_icrc32(&msg->any.head, hbytes);
1221 * Enqueue the message (the flush codes handles stream
1224 TAILQ_INSERT_TAIL(&ioq->msgq, msg, qentry);
1227 dmsg_iocom_flush2(iocom);
1231 * Thread localized, iocom->mtx not held by caller.
1234 dmsg_iocom_flush2(dmsg_iocom_t *iocom)
1236 dmsg_ioq_t *ioq = &iocom->ioq_tx;
1239 struct iovec iov[DMSG_IOQ_MAXIOVEC];
1248 dmsg_iocom_drain(iocom);
1253 * Pump messages out the connection by building an iovec.
1255 * ioq->hbytes/ioq->abytes tracks how much of the first message
1256 * in the queue has been successfully written out, so we can
1264 TAILQ_FOREACH(msg, &ioq->msgq, qentry) {
1265 hbytes = (msg->any.head.cmd & DMSGF_SIZE) *
1267 abytes = msg->aux_size;
1268 assert(hoff <= hbytes && aoff <= abytes);
1270 if (hoff < hbytes) {
1271 iov[iovcnt].iov_base = (char *)&msg->any.head + hoff;
1272 iov[iovcnt].iov_len = hbytes - hoff;
1273 nact += hbytes - hoff;
1275 if (iovcnt == DMSG_IOQ_MAXIOVEC)
1278 if (aoff < abytes) {
1279 assert(msg->aux_data != NULL);
1280 iov[iovcnt].iov_base = (char *)msg->aux_data + aoff;
1281 iov[iovcnt].iov_len = abytes - aoff;
1282 nact += abytes - aoff;
1284 if (iovcnt == DMSG_IOQ_MAXIOVEC)
1294 * Encrypt and write the data. The crypto code will move the
1295 * data into the fifo and adjust the iov as necessary. If
1296 * encryption is disabled the iov is left alone.
1298 * May return a smaller iov (thus a smaller n), with aggregated
1299 * chunks. May reduce nmax to what fits in the FIFO.
1301 * This function sets nact to the number of original bytes now
1302 * encrypted, adding to the FIFO some number of bytes that might
1303 * be greater depending on the crypto mechanic. iov[] is adjusted
1304 * to point at the FIFO if necessary.
1306 * NOTE: The return value from the writev() is the post-encrypted
1307 * byte count, not the plaintext count.
1309 if (iocom->flags & DMSG_IOCOMF_CRYPTED) {
1311 * Make sure the FIFO has a reasonable amount of space
1312 * left (if not completely full).
1314 if (ioq->fifo_beg > sizeof(ioq->buf) / 2 &&
1315 sizeof(ioq->buf) - ioq->fifo_end >= DMSG_ALIGN * 2) {
1316 bcopy(ioq->buf + ioq->fifo_beg, ioq->buf,
1317 ioq->fifo_end - ioq->fifo_beg);
1318 ioq->fifo_cdx -= ioq->fifo_beg;
1319 ioq->fifo_cdn -= ioq->fifo_beg;
1320 ioq->fifo_end -= ioq->fifo_beg;
1324 iovcnt = dmsg_crypto_encrypt(iocom, ioq, iov, iovcnt, &nact);
1325 n = writev(iocom->sock_fd, iov, iovcnt);
1330 if (ioq->fifo_beg == ioq->fifo_end) {
1341 n = writev(iocom->sock_fd, iov, iovcnt);
1349 * Clean out the transmit queue based on what we successfully
1350 * sent (nact is the plaintext count). ioq->hbytes/abytes
1351 * represents the portion of the first message previously sent.
1353 while ((msg = TAILQ_FIRST(&ioq->msgq)) != NULL) {
1354 hbytes = (msg->any.head.cmd & DMSGF_SIZE) *
1356 abytes = msg->aux_size;
1358 if ((size_t)nact < hbytes - ioq->hbytes) {
1359 ioq->hbytes += nact;
1363 nact -= hbytes - ioq->hbytes;
1364 ioq->hbytes = hbytes;
1365 if ((size_t)nact < abytes - ioq->abytes) {
1366 ioq->abytes += nact;
1370 nact -= abytes - ioq->abytes;
1372 TAILQ_REMOVE(&ioq->msgq, msg, qentry);
1377 dmsg_state_cleanuptx(msg);
1382 * Process the return value from the write w/regards to blocking.
1385 if (errno != EINTR &&
1386 errno != EINPROGRESS &&
1391 ioq->error = DMSG_IOQ_ERROR_SOCK;
1392 dmsg_iocom_drain(iocom);
1395 * Wait for socket buffer space
1397 iocom->flags |= DMSG_IOCOMF_WREQ;
1400 iocom->flags |= DMSG_IOCOMF_WREQ;
1403 dmsg_iocom_drain(iocom);
1408 * Kill pending msgs on ioq_tx and adjust the flags such that no more
1409 * write events will occur. We don't kill read msgs because we want
1410 * the caller to pull off our contrived terminal error msg to detect
1411 * the connection failure.
1413 * Thread localized, iocom->mtx not held by caller.
1416 dmsg_iocom_drain(dmsg_iocom_t *iocom)
1418 dmsg_ioq_t *ioq = &iocom->ioq_tx;
1421 iocom->flags &= ~(DMSG_IOCOMF_WREQ | DMSG_IOCOMF_WWORK);
1425 while ((msg = TAILQ_FIRST(&ioq->msgq)) != NULL) {
1426 TAILQ_REMOVE(&ioq->msgq, msg, qentry);
1428 dmsg_state_cleanuptx(msg);
1433 * Write a message to an iocom, with additional state processing.
1436 dmsg_msg_write(dmsg_msg_t *msg)
1438 dmsg_iocom_t *iocom = msg->iocom;
1439 dmsg_state_t *state;
1443 * Handle state processing, create state if necessary.
1445 pthread_mutex_lock(&iocom->mtx);
1446 if ((state = msg->state) != NULL) {
1448 * Existing transaction (could be reply). It is also
1449 * possible for this to be the first reply (CREATE is set),
1450 * in which case we populate state->txcmd.
1452 * state->txcmd is adjusted to hold the final message cmd,
1453 * and we also be sure to set the CREATE bit here. We did
1454 * not set it in dmsg_msg_alloc() because that would have
1455 * not been serialized (state could have gotten ripped out
1456 * from under the message prior to it being transmitted).
1458 if ((msg->any.head.cmd & (DMSGF_CREATE | DMSGF_REPLY)) ==
1460 state->txcmd = msg->any.head.cmd & ~DMSGF_DELETE;
1461 state->icmd = state->txcmd & DMSGF_BASECMDMASK;
1463 msg->any.head.msgid = state->msgid;
1464 assert(((state->txcmd ^ msg->any.head.cmd) & DMSGF_REPLY) == 0);
1465 if (msg->any.head.cmd & DMSGF_CREATE) {
1466 state->txcmd = msg->any.head.cmd & ~DMSGF_DELETE;
1471 * Queue it for output, wake up the I/O pthread. Note that the
1472 * I/O thread is responsible for generating the CRCs and encryption.
1474 TAILQ_INSERT_TAIL(&iocom->txmsgq, msg, qentry);
1476 write(iocom->wakeupfds[1], &dummy, 1); /* XXX optimize me */
1477 pthread_mutex_unlock(&iocom->mtx);
1481 * This is a shortcut to formulate a reply to msg with a simple error code,
1482 * It can reply to and terminate a transaction, or it can reply to a one-way
1483 * messages. A DMSG_LNK_ERROR command code is utilized to encode
1484 * the error code (which can be 0). Not all transactions are terminated
1485 * with DMSG_LNK_ERROR status (the low level only cares about the
1486 * MSGF_DELETE flag), but most are.
1488 * Replies to one-way messages are a bit of an oxymoron but the feature
1489 * is used by the debug (DBG) protocol.
1491 * The reply contains no extended data.
1494 dmsg_msg_reply(dmsg_msg_t *msg, uint32_t error)
1496 dmsg_state_t *state = msg->state;
1502 * Reply with a simple error code and terminate the transaction.
1504 cmd = DMSG_LNK_ERROR;
1507 * Check if our direction has even been initiated yet, set CREATE.
1509 * Check what direction this is (command or reply direction). Note
1510 * that txcmd might not have been initiated yet.
1512 * If our direction has already been closed we just return without
1516 if (state->txcmd & DMSGF_DELETE)
1518 if (state->txcmd & DMSGF_REPLY)
1520 cmd |= DMSGF_DELETE;
1522 if ((msg->any.head.cmd & DMSGF_REPLY) == 0)
1527 * Allocate the message and associate it with the existing state.
1528 * We cannot pass DMSGF_CREATE to msg_alloc() because that may
1529 * allocate new state. We have our state already.
1531 nmsg = dmsg_msg_alloc(msg->circuit, 0, cmd, NULL, NULL);
1533 if ((state->txcmd & DMSGF_CREATE) == 0)
1534 nmsg->any.head.cmd |= DMSGF_CREATE;
1536 nmsg->any.head.error = error;
1537 nmsg->any.head.msgid = msg->any.head.msgid;
1538 nmsg->any.head.circuit = msg->any.head.circuit;
1539 nmsg->state = state;
1540 dmsg_msg_write(nmsg);
1544 * Similar to dmsg_msg_reply() but leave the transaction open. That is,
1545 * we are generating a streaming reply or an intermediate acknowledgement
1546 * of some sort as part of the higher level protocol, with more to come
1550 dmsg_msg_result(dmsg_msg_t *msg, uint32_t error)
1552 dmsg_state_t *state = msg->state;
1558 * Reply with a simple error code and terminate the transaction.
1560 cmd = DMSG_LNK_ERROR;
1563 * Check if our direction has even been initiated yet, set CREATE.
1565 * Check what direction this is (command or reply direction). Note
1566 * that txcmd might not have been initiated yet.
1568 * If our direction has already been closed we just return without
1572 if (state->txcmd & DMSGF_DELETE)
1574 if (state->txcmd & DMSGF_REPLY)
1576 /* continuing transaction, do not set MSGF_DELETE */
1578 if ((msg->any.head.cmd & DMSGF_REPLY) == 0)
1582 nmsg = dmsg_msg_alloc(msg->circuit, 0, cmd, NULL, NULL);
1584 if ((state->txcmd & DMSGF_CREATE) == 0)
1585 nmsg->any.head.cmd |= DMSGF_CREATE;
1587 nmsg->any.head.error = error;
1588 nmsg->any.head.msgid = msg->any.head.msgid;
1589 nmsg->any.head.circuit = msg->any.head.circuit;
1590 nmsg->state = state;
1591 dmsg_msg_write(nmsg);
1595 * Terminate a transaction given a state structure by issuing a DELETE.
1598 dmsg_state_reply(dmsg_state_t *state, uint32_t error)
1601 uint32_t cmd = DMSG_LNK_ERROR | DMSGF_DELETE;
1604 * Nothing to do if we already transmitted a delete
1606 if (state->txcmd & DMSGF_DELETE)
1610 * Set REPLY if the other end initiated the command. Otherwise
1611 * we are the command direction.
1613 if (state->txcmd & DMSGF_REPLY)
1616 nmsg = dmsg_msg_alloc(state->circuit, 0, cmd, NULL, NULL);
1618 if ((state->txcmd & DMSGF_CREATE) == 0)
1619 nmsg->any.head.cmd |= DMSGF_CREATE;
1621 nmsg->any.head.error = error;
1622 nmsg->any.head.msgid = state->msgid;
1623 nmsg->any.head.circuit = state->msg->any.head.circuit;
1624 nmsg->state = state;
1625 dmsg_msg_write(nmsg);
1629 * Terminate a transaction given a state structure by issuing a DELETE.
1632 dmsg_state_result(dmsg_state_t *state, uint32_t error)
1635 uint32_t cmd = DMSG_LNK_ERROR;
1638 * Nothing to do if we already transmitted a delete
1640 if (state->txcmd & DMSGF_DELETE)
1644 * Set REPLY if the other end initiated the command. Otherwise
1645 * we are the command direction.
1647 if (state->txcmd & DMSGF_REPLY)
1650 nmsg = dmsg_msg_alloc(state->circuit, 0, cmd, NULL, NULL);
1652 if ((state->txcmd & DMSGF_CREATE) == 0)
1653 nmsg->any.head.cmd |= DMSGF_CREATE;
1655 nmsg->any.head.error = error;
1656 nmsg->any.head.msgid = state->msgid;
1657 nmsg->any.head.circuit = state->msg->any.head.circuit;
1658 nmsg->state = state;
1659 dmsg_msg_write(nmsg);
1662 /************************************************************************
1663 * TRANSACTION STATE HANDLING *
1664 ************************************************************************
1669 * Process circuit and state tracking for a message after reception, prior
1672 * Called with msglk held and the msg dequeued.
1674 * All messages are called with dummy state and return actual state.
1675 * (One-off messages often just return the same dummy state).
1677 * May request that caller discard the message by setting *discardp to 1.
1678 * The returned state is not used in this case and is allowed to be NULL.
1682 * These routines handle persistent and command/reply message state via the
1683 * CREATE and DELETE flags. The first message in a command or reply sequence
1684 * sets CREATE, the last message in a command or reply sequence sets DELETE.
1686 * There can be any number of intermediate messages belonging to the same
1687 * sequence sent inbetween the CREATE message and the DELETE message,
1688 * which set neither flag. This represents a streaming command or reply.
1690 * Any command message received with CREATE set expects a reply sequence to
1691 * be returned. Reply sequences work the same as command sequences except the
1692 * REPLY bit is also sent. Both the command side and reply side can
1693 * degenerate into a single message with both CREATE and DELETE set. Note
1694 * that one side can be streaming and the other side not, or neither, or both.
1696 * The msgid is unique for the initiator. That is, two sides sending a new
1697 * message can use the same msgid without colliding.
1701 * ABORT sequences work by setting the ABORT flag along with normal message
1702 * state. However, ABORTs can also be sent on half-closed messages, that is
1703 * even if the command or reply side has already sent a DELETE, as long as
1704 * the message has not been fully closed it can still send an ABORT+DELETE
1705 * to terminate the half-closed message state.
1707 * Since ABORT+DELETEs can race we silently discard ABORT's for message
1708 * state which has already been fully closed. REPLY+ABORT+DELETEs can
1709 * also race, and in this situation the other side might have already
1710 * initiated a new unrelated command with the same message id. Since
1711 * the abort has not set the CREATE flag the situation can be detected
1712 * and the message will also be discarded.
1714 * Non-blocking requests can be initiated with ABORT+CREATE[+DELETE].
1715 * The ABORT request is essentially integrated into the command instead
1716 * of being sent later on. In this situation the command implementation
1717 * detects that CREATE and ABORT are both set (vs ABORT alone) and can
1718 * special-case non-blocking operation for the command.
1720 * NOTE! Messages with ABORT set without CREATE or DELETE are considered
1721 * to be mid-stream aborts for command/reply sequences. ABORTs on
1722 * one-way messages are not supported.
1724 * NOTE! If a command sequence does not support aborts the ABORT flag is
1729 * One-off messages (no reply expected) are sent with neither CREATE or DELETE
1730 * set. One-off messages cannot be aborted and typically aren't processed
1731 * by these routines. The REPLY bit can be used to distinguish whether a
1732 * one-off message is a command or reply. For example, one-off replies
1733 * will typically just contain status updates.
1736 dmsg_state_msgrx(dmsg_msg_t *msg)
1738 dmsg_iocom_t *iocom = msg->iocom;
1739 dmsg_circuit_t *circuit;
1740 dmsg_state_t *state;
1741 dmsg_state_t sdummy;
1742 dmsg_circuit_t cdummy;
1745 pthread_mutex_lock(&iocom->mtx);
1748 * Locate existing persistent circuit and state, if any.
1750 if (msg->any.head.circuit == 0) {
1751 circuit = &iocom->circuit0;
1753 cdummy.msgid = msg->any.head.circuit;
1754 circuit = RB_FIND(dmsg_circuit_tree, &iocom->circuit_tree,
1756 if (circuit == NULL)
1757 return (DMSG_IOQ_ERROR_BAD_CIRCUIT);
1759 msg->circuit = circuit;
1763 * If received msg is a command state is on staterd_tree.
1764 * If received msg is a reply state is on statewr_tree.
1766 sdummy.msgid = msg->any.head.msgid;
1767 if (msg->any.head.cmd & DMSGF_REPLY) {
1768 state = RB_FIND(dmsg_state_tree, &circuit->statewr_tree,
1771 state = RB_FIND(dmsg_state_tree, &circuit->staterd_tree,
1775 pthread_mutex_unlock(&iocom->mtx);
1778 * Short-cut one-off or mid-stream messages (state may be NULL).
1780 if ((msg->any.head.cmd & (DMSGF_CREATE | DMSGF_DELETE |
1781 DMSGF_ABORT)) == 0) {
1786 * Switch on CREATE, DELETE, REPLY, and also handle ABORT from
1787 * inside the case statements.
1789 switch(msg->any.head.cmd & (DMSGF_CREATE | DMSGF_DELETE |
1792 case DMSGF_CREATE | DMSGF_DELETE:
1794 * New persistant command received.
1797 fprintf(stderr, "duplicate-trans %s\n",
1799 error = DMSG_IOQ_ERROR_TRANS;
1803 state = malloc(sizeof(*state));
1804 bzero(state, sizeof(*state));
1805 state->iocom = iocom;
1806 state->circuit = circuit;
1807 state->flags = DMSG_STATE_DYNAMIC;
1809 state->txcmd = DMSGF_REPLY;
1810 state->rxcmd = msg->any.head.cmd & ~DMSGF_DELETE;
1811 state->icmd = state->rxcmd & DMSGF_BASECMDMASK;
1812 state->flags |= DMSG_STATE_INSERTED;
1813 state->msgid = msg->any.head.msgid;
1815 pthread_mutex_lock(&iocom->mtx);
1816 RB_INSERT(dmsg_state_tree, &circuit->staterd_tree, state);
1817 pthread_mutex_unlock(&iocom->mtx);
1820 fprintf(stderr, "create state %p id=%08x on iocom staterd %p\n",
1821 state, (uint32_t)state->msgid, iocom);
1826 * Persistent state is expected but might not exist if an
1827 * ABORT+DELETE races the close.
1829 if (state == NULL) {
1830 if (msg->any.head.cmd & DMSGF_ABORT) {
1831 error = DMSG_IOQ_ERROR_EALREADY;
1833 fprintf(stderr, "missing-state %s\n",
1835 error = DMSG_IOQ_ERROR_TRANS;
1842 * Handle another ABORT+DELETE case if the msgid has already
1845 if ((state->rxcmd & DMSGF_CREATE) == 0) {
1846 if (msg->any.head.cmd & DMSGF_ABORT) {
1847 error = DMSG_IOQ_ERROR_EALREADY;
1849 fprintf(stderr, "reused-state %s\n",
1851 error = DMSG_IOQ_ERROR_TRANS;
1860 * Check for mid-stream ABORT command received, otherwise
1863 if (msg->any.head.cmd & DMSGF_ABORT) {
1864 if (state == NULL ||
1865 (state->rxcmd & DMSGF_CREATE) == 0) {
1866 error = DMSG_IOQ_ERROR_EALREADY;
1872 case DMSGF_REPLY | DMSGF_CREATE:
1873 case DMSGF_REPLY | DMSGF_CREATE | DMSGF_DELETE:
1875 * When receiving a reply with CREATE set the original
1876 * persistent state message should already exist.
1878 if (state == NULL) {
1879 fprintf(stderr, "no-state(r) %s\n",
1881 error = DMSG_IOQ_ERROR_TRANS;
1885 assert(((state->rxcmd ^ msg->any.head.cmd) &
1887 state->rxcmd = msg->any.head.cmd & ~DMSGF_DELETE;
1890 case DMSGF_REPLY | DMSGF_DELETE:
1892 * Received REPLY+ABORT+DELETE in case where msgid has
1893 * already been fully closed, ignore the message.
1895 if (state == NULL) {
1896 if (msg->any.head.cmd & DMSGF_ABORT) {
1897 error = DMSG_IOQ_ERROR_EALREADY;
1899 fprintf(stderr, "no-state(r,d) %s\n",
1901 error = DMSG_IOQ_ERROR_TRANS;
1908 * Received REPLY+ABORT+DELETE in case where msgid has
1909 * already been reused for an unrelated message,
1910 * ignore the message.
1912 if ((state->rxcmd & DMSGF_CREATE) == 0) {
1913 if (msg->any.head.cmd & DMSGF_ABORT) {
1914 error = DMSG_IOQ_ERROR_EALREADY;
1916 fprintf(stderr, "reused-state(r,d) %s\n",
1918 error = DMSG_IOQ_ERROR_TRANS;
1927 * Check for mid-stream ABORT reply received to sent command.
1929 if (msg->any.head.cmd & DMSGF_ABORT) {
1930 if (state == NULL ||
1931 (state->rxcmd & DMSGF_CREATE) == 0) {
1932 error = DMSG_IOQ_ERROR_EALREADY;
1943 dmsg_state_cleanuprx(dmsg_iocom_t *iocom, dmsg_msg_t *msg)
1945 dmsg_state_t *state;
1947 if ((state = msg->state) == NULL) {
1949 * Free a non-transactional message, there is no state
1953 } else if (msg->any.head.cmd & DMSGF_DELETE) {
1955 * Message terminating transaction, destroy the related
1956 * state, the original message, and this message (if it
1957 * isn't the original message due to a CREATE|DELETE).
1959 pthread_mutex_lock(&iocom->mtx);
1960 state->rxcmd |= DMSGF_DELETE;
1961 if (state->txcmd & DMSGF_DELETE) {
1962 if (state->msg == msg)
1964 assert(state->flags & DMSG_STATE_INSERTED);
1965 if (state->rxcmd & DMSGF_REPLY) {
1966 assert(msg->any.head.cmd & DMSGF_REPLY);
1967 RB_REMOVE(dmsg_state_tree,
1968 &msg->circuit->statewr_tree, state);
1970 assert((msg->any.head.cmd & DMSGF_REPLY) == 0);
1971 RB_REMOVE(dmsg_state_tree,
1972 &msg->circuit->staterd_tree, state);
1974 state->flags &= ~DMSG_STATE_INSERTED;
1975 dmsg_state_free(state);
1979 pthread_mutex_unlock(&iocom->mtx);
1981 } else if (state->msg != msg) {
1983 * Message not terminating transaction, leave state intact
1984 * and free message if it isn't the CREATE message.
1991 dmsg_state_cleanuptx(dmsg_msg_t *msg)
1993 dmsg_iocom_t *iocom = msg->iocom;
1994 dmsg_state_t *state;
1996 if ((state = msg->state) == NULL) {
1998 } else if (msg->any.head.cmd & DMSGF_DELETE) {
1999 pthread_mutex_lock(&iocom->mtx);
2000 assert((state->txcmd & DMSGF_DELETE) == 0);
2001 state->txcmd |= DMSGF_DELETE;
2002 if (state->rxcmd & DMSGF_DELETE) {
2003 if (state->msg == msg)
2005 assert(state->flags & DMSG_STATE_INSERTED);
2006 if (state->txcmd & DMSGF_REPLY) {
2007 assert(msg->any.head.cmd & DMSGF_REPLY);
2008 RB_REMOVE(dmsg_state_tree,
2009 &msg->circuit->staterd_tree, state);
2011 assert((msg->any.head.cmd & DMSGF_REPLY) == 0);
2012 RB_REMOVE(dmsg_state_tree,
2013 &msg->circuit->statewr_tree, state);
2015 state->flags &= ~DMSG_STATE_INSERTED;
2016 dmsg_state_free(state);
2020 pthread_mutex_unlock(&iocom->mtx);
2022 } else if (state->msg != msg) {
2028 * Called with iocom locked
2031 dmsg_state_free(dmsg_state_t *state)
2036 fprintf(stderr, "terminate state %p id=%08x\n",
2037 state, (uint32_t)state->msgid);
2040 "dmsg_state_free state %p any.any %p func %p icmd %08x\n",
2041 state, state->any.any, state->func, state->icmd);
2042 if (state->any.any != NULL) /* XXX avoid deadlock w/exit & kernel */
2044 assert(state->any.any == NULL);
2048 dmsg_msg_free_locked(msg);
2053 * Called with iocom locked
2056 dmsg_circuit_drop(dmsg_circuit_t *circuit)
2058 dmsg_iocom_t *iocom = circuit->iocom;
2061 assert(circuit->refs > 0);
2065 * Decrement circuit refs, destroy circuit when refs drops to 0.
2067 if (--circuit->refs > 0)
2070 assert(RB_EMPTY(&circuit->staterd_tree));
2071 assert(RB_EMPTY(&circuit->statewr_tree));
2072 RB_REMOVE(dmsg_circuit_tree, &iocom->circuit_tree, circuit);
2073 circuit->iocom = NULL;
2077 * When an iocom error is present the rx code will terminate the
2078 * receive side for all transactions and (indirectly) all circuits
2079 * by simulating DELETE messages. The state and related circuits
2080 * don't disappear until the related states are closed in both
2083 * Detect the case where the last circuit is now gone (and thus all
2084 * states for all circuits are gone), and wakeup the rx thread to
2085 * complete the termination.
2087 if (iocom->ioq_rx.error && RB_EMPTY(&iocom->circuit_tree)) {
2089 write(iocom->wakeupfds[1], &dummy, 1);
2094 * This swaps endian for a hammer2_msg_hdr. Note that the extended
2095 * header is not adjusted, just the core header.
2098 dmsg_bswap_head(dmsg_hdr_t *head)
2100 head->magic = bswap16(head->magic);
2101 head->reserved02 = bswap16(head->reserved02);
2102 head->salt = bswap32(head->salt);
2104 head->msgid = bswap64(head->msgid);
2105 head->circuit = bswap64(head->circuit);
2106 head->reserved18= bswap64(head->reserved18);
2108 head->cmd = bswap32(head->cmd);
2109 head->aux_crc = bswap32(head->aux_crc);
2110 head->aux_bytes = bswap32(head->aux_bytes);
2111 head->error = bswap32(head->error);
2112 head->aux_descr = bswap64(head->aux_descr);
2113 head->reserved38= bswap32(head->reserved38);
2114 head->hdr_crc = bswap32(head->hdr_crc);