f4cb65c1277a26fa930cc0f090463ed53143bbd9
[dragonfly.git] / sbin / hammer2 / msg.c
1 /*
2  * Copyright (c) 2011-2012 The DragonFly Project.  All rights reserved.
3  *
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>
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  *
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
17  *    distribution.
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.
21  *
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
33  * SUCH DAMAGE.
34  */
35
36 #include "hammer2.h"
37
38 static int hammer2_state_msgrx(hammer2_msg_t *msg);
39 static void hammer2_state_cleanuptx(hammer2_msg_t *msg);
40
41 /*
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).
45  */
46 int
47 hammer2_router_cmp(hammer2_router_t *router1, hammer2_router_t *router2)
48 {
49         if (router1->target < router2->target)
50                 return(-1);
51         if (router1->target > router2->target)
52                 return(1);
53         return(0);
54 }
55
56 RB_GENERATE(hammer2_router_tree, hammer2_router, rbnode, hammer2_router_cmp);
57
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);
61
62 /*
63  * STATE TREE - Represents open transactions which are indexed by their
64  *              {router,msgid} relative to the governing iocom.
65  *
66  *              router is usually iocom->router since state isn't stored
67  *              for relayed messages.
68  */
69 int
70 hammer2_state_cmp(hammer2_state_t *state1, hammer2_state_t *state2)
71 {
72 #if 0
73         if (state1->router < state2->router)
74                 return(-1);
75         if (state1->router > state2->router)
76                 return(1);
77 #endif
78         if (state1->msgid < state2->msgid)
79                 return(-1);
80         if (state1->msgid > state2->msgid)
81                 return(1);
82         return(0);
83 }
84
85 RB_GENERATE(hammer2_state_tree, hammer2_state, rbnode, hammer2_state_cmp);
86
87 /*
88  * Initialize a low-level ioq
89  */
90 void
91 hammer2_ioq_init(hammer2_iocom_t *iocom __unused, hammer2_ioq_t *ioq)
92 {
93         bzero(ioq, sizeof(*ioq));
94         ioq->state = HAMMER2_MSGQ_STATE_HEADER1;
95         TAILQ_INIT(&ioq->msgq);
96 }
97
98 /*
99  * Cleanup queue.
100  *
101  * caller holds iocom->mtx.
102  */
103 void
104 hammer2_ioq_done(hammer2_iocom_t *iocom __unused, hammer2_ioq_t *ioq)
105 {
106         hammer2_msg_t *msg;
107
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);
112         }
113         if ((msg = ioq->msg) != NULL) {
114                 ioq->msg = NULL;
115                 hammer2_msg_free(msg);
116         }
117 }
118
119 /*
120  * Initialize a low-level communications channel.
121  *
122  * NOTE: The signal_func() is called at least once from the loop and can be
123  *       re-armed via hammer2_iocom_restate().
124  */
125 void
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 *))
130 {
131         struct stat st;
132
133         bzero(iocom, sizeof(*iocom));
134
135         iocom->router = hammer2_router_alloc();
136         iocom->router->signal_callback = signal_func;
137         iocom->router->rcvmsg_callback = rcvmsg_func;
138         iocom->router->altmsg_callback = altmsg_func;
139         /* we do not call hammer2_router_connect() for iocom routers */
140
141         pthread_mutex_init(&iocom->mtx, NULL);
142         RB_INIT(&iocom->router->staterd_tree);
143         RB_INIT(&iocom->router->statewr_tree);
144         TAILQ_INIT(&iocom->freeq);
145         TAILQ_INIT(&iocom->freeq_aux);
146         TAILQ_INIT(&iocom->router->txmsgq);
147         iocom->router->iocom = iocom;
148         iocom->sock_fd = sock_fd;
149         iocom->alt_fd = alt_fd;
150         iocom->flags = HAMMER2_IOCOMF_RREQ;
151         if (signal_func)
152                 iocom->flags |= HAMMER2_IOCOMF_SWORK;
153         hammer2_ioq_init(iocom, &iocom->ioq_rx);
154         hammer2_ioq_init(iocom, &iocom->ioq_tx);
155         if (pipe(iocom->wakeupfds) < 0)
156                 assert(0);
157         fcntl(iocom->wakeupfds[0], F_SETFL, O_NONBLOCK);
158         fcntl(iocom->wakeupfds[1], F_SETFL, O_NONBLOCK);
159
160         /*
161          * Negotiate session crypto synchronously.  This will mark the
162          * connection as error'd if it fails.  If this is a pipe it's
163          * a linkage that we set up ourselves to the filesystem and there
164          * is no crypto.
165          */
166         if (fstat(sock_fd, &st) < 0)
167                 assert(0);
168         if (S_ISSOCK(st.st_mode))
169                 hammer2_crypto_negotiate(iocom);
170
171         /*
172          * Make sure our fds are set to non-blocking for the iocom core.
173          */
174         if (sock_fd >= 0)
175                 fcntl(sock_fd, F_SETFL, O_NONBLOCK);
176 #if 0
177         /* if line buffered our single fgets() should be fine */
178         if (alt_fd >= 0)
179                 fcntl(alt_fd, F_SETFL, O_NONBLOCK);
180 #endif
181 }
182
183 /*
184  * May only be called from a callback from iocom_core.
185  *
186  * Adjust state machine functions, set flags to guarantee that both
187  * the recevmsg_func and the sendmsg_func is called at least once.
188  */
189 void
190 hammer2_router_restate(hammer2_router_t *router,
191                    void (*signal_func)(hammer2_router_t *),
192                    void (*rcvmsg_func)(hammer2_msg_t *msg),
193                    void (*altmsg_func)(hammer2_iocom_t *))
194 {
195         router->signal_callback = signal_func;
196         router->rcvmsg_callback = rcvmsg_func;
197         router->altmsg_callback = altmsg_func;
198         if (signal_func)
199                 router->iocom->flags |= HAMMER2_IOCOMF_SWORK;
200         else
201                 router->iocom->flags &= ~HAMMER2_IOCOMF_SWORK;
202 }
203
204 void
205 hammer2_router_signal(hammer2_router_t *router)
206 {
207         if (router->signal_callback)
208                 router->iocom->flags |= HAMMER2_IOCOMF_SWORK;
209 }
210
211 /*
212  * Cleanup a terminating iocom.
213  *
214  * Caller should not hold iocom->mtx.  The iocom has already been disconnected
215  * from all possible references to it.
216  */
217 void
218 hammer2_iocom_done(hammer2_iocom_t *iocom)
219 {
220         hammer2_msg_t *msg;
221
222         if (iocom->sock_fd >= 0) {
223                 close(iocom->sock_fd);
224                 iocom->sock_fd = -1;
225         }
226         if (iocom->alt_fd >= 0) {
227                 close(iocom->alt_fd);
228                 iocom->alt_fd = -1;
229         }
230         hammer2_ioq_done(iocom, &iocom->ioq_rx);
231         hammer2_ioq_done(iocom, &iocom->ioq_tx);
232         if ((msg = TAILQ_FIRST(&iocom->freeq)) != NULL) {
233                 TAILQ_REMOVE(&iocom->freeq, msg, qentry);
234                 free(msg);
235         }
236         if ((msg = TAILQ_FIRST(&iocom->freeq_aux)) != NULL) {
237                 TAILQ_REMOVE(&iocom->freeq_aux, msg, qentry);
238                 free(msg->aux_data);
239                 msg->aux_data = NULL;
240                 free(msg);
241         }
242         if (iocom->wakeupfds[0] >= 0) {
243                 close(iocom->wakeupfds[0]);
244                 iocom->wakeupfds[0] = -1;
245         }
246         if (iocom->wakeupfds[1] >= 0) {
247                 close(iocom->wakeupfds[1]);
248                 iocom->wakeupfds[1] = -1;
249         }
250         pthread_mutex_destroy(&iocom->mtx);
251 }
252
253 /*
254  * Allocate a new one-way message.
255  */
256 hammer2_msg_t *
257 hammer2_msg_alloc(hammer2_router_t *router, size_t aux_size, uint32_t cmd,
258                   void (*func)(hammer2_msg_t *), void *data)
259 {
260         hammer2_state_t *state = NULL;
261         hammer2_iocom_t *iocom = router->iocom;
262         hammer2_msg_t *msg;
263         int hbytes;
264
265         pthread_mutex_lock(&iocom->mtx);
266         if (aux_size) {
267                 aux_size = (aux_size + HAMMER2_MSG_ALIGNMASK) &
268                            ~HAMMER2_MSG_ALIGNMASK;
269                 if ((msg = TAILQ_FIRST(&iocom->freeq_aux)) != NULL)
270                         TAILQ_REMOVE(&iocom->freeq_aux, msg, qentry);
271         } else {
272                 if ((msg = TAILQ_FIRST(&iocom->freeq)) != NULL)
273                         TAILQ_REMOVE(&iocom->freeq, msg, qentry);
274         }
275         if ((cmd & (HAMMER2_MSGF_CREATE | HAMMER2_MSGF_REPLY)) ==
276             HAMMER2_MSGF_CREATE) {
277                 /*
278                  * Create state when CREATE is set without REPLY.
279                  *
280                  * NOTE: CREATE in txcmd handled by hammer2_msg_write()
281                  * NOTE: DELETE in txcmd handled by hammer2_state_cleanuptx()
282                  */
283                 state = malloc(sizeof(*state));
284                 bzero(state, sizeof(*state));
285                 state->iocom = iocom;
286                 state->flags = HAMMER2_STATE_DYNAMIC;
287                 state->msgid = (uint64_t)(uintptr_t)state;
288                 state->router = router;
289                 state->txcmd = cmd & ~(HAMMER2_MSGF_CREATE |
290                                        HAMMER2_MSGF_DELETE);
291                 state->rxcmd = HAMMER2_MSGF_REPLY;
292                 state->func = func;
293                 state->any.any = data;
294                 pthread_mutex_lock(&iocom->mtx);
295                 RB_INSERT(hammer2_state_tree,
296                           &iocom->router->statewr_tree,
297                           state);
298                 pthread_mutex_unlock(&iocom->mtx);
299                 state->flags |= HAMMER2_STATE_INSERTED;
300         }
301         pthread_mutex_unlock(&iocom->mtx);
302         if (msg == NULL) {
303                 msg = malloc(sizeof(*msg));
304                 bzero(msg, sizeof(*msg));
305                 msg->aux_data = NULL;
306                 msg->aux_size = 0;
307         }
308         if (msg->aux_size != aux_size) {
309                 if (msg->aux_data) {
310                         free(msg->aux_data);
311                         msg->aux_data = NULL;
312                         msg->aux_size = 0;
313                 }
314                 if (aux_size) {
315                         msg->aux_data = malloc(aux_size);
316                         msg->aux_size = aux_size;
317                 }
318         }
319         hbytes = (cmd & HAMMER2_MSGF_SIZE) * HAMMER2_MSG_ALIGN;
320         if (hbytes)
321                 bzero(&msg->any.head, hbytes);
322         msg->hdr_size = hbytes;
323         msg->any.head.cmd = cmd;
324         msg->any.head.aux_descr = 0;
325         msg->any.head.aux_crc = 0;
326         msg->router = router;
327         if (state) {
328                 msg->state = state;
329                 state->msg = msg;
330                 msg->any.head.msgid = state->msgid;
331         }
332         return (msg);
333 }
334
335 /*
336  * Free a message so it can be reused afresh.
337  *
338  * NOTE: aux_size can be 0 with a non-NULL aux_data.
339  */
340 static
341 void
342 hammer2_msg_free_locked(hammer2_msg_t *msg)
343 {
344         hammer2_iocom_t *iocom = msg->router->iocom;
345
346         msg->state = NULL;
347         if (msg->aux_data)
348                 TAILQ_INSERT_TAIL(&iocom->freeq_aux, msg, qentry);
349         else
350                 TAILQ_INSERT_TAIL(&iocom->freeq, msg, qentry);
351 }
352
353 void
354 hammer2_msg_free(hammer2_msg_t *msg)
355 {
356         hammer2_iocom_t *iocom = msg->router->iocom;
357
358         pthread_mutex_lock(&iocom->mtx);
359         hammer2_msg_free_locked(msg);
360         pthread_mutex_unlock(&iocom->mtx);
361 }
362
363 /*
364  * I/O core loop for an iocom.
365  *
366  * Thread localized, iocom->mtx not held.
367  */
368 void
369 hammer2_iocom_core(hammer2_iocom_t *iocom)
370 {
371         struct pollfd fds[3];
372         char dummybuf[256];
373         hammer2_msg_t *msg;
374         int timeout;
375         int count;
376         int wi; /* wakeup pipe */
377         int si; /* socket */
378         int ai; /* alt bulk path socket */
379
380         while ((iocom->flags & HAMMER2_IOCOMF_EOF) == 0) {
381                 if ((iocom->flags & (HAMMER2_IOCOMF_RWORK |
382                                      HAMMER2_IOCOMF_WWORK |
383                                      HAMMER2_IOCOMF_PWORK |
384                                      HAMMER2_IOCOMF_SWORK |
385                                      HAMMER2_IOCOMF_ARWORK |
386                                      HAMMER2_IOCOMF_AWWORK)) == 0) {
387                         /*
388                          * Only poll if no immediate work is pending.
389                          * Otherwise we are just wasting our time calling
390                          * poll.
391                          */
392                         timeout = 5000;
393
394                         count = 0;
395                         wi = -1;
396                         si = -1;
397                         ai = -1;
398
399                         /*
400                          * Always check the inter-thread pipe, e.g.
401                          * for iocom->txmsgq work.
402                          */
403                         wi = count++;
404                         fds[wi].fd = iocom->wakeupfds[0];
405                         fds[wi].events = POLLIN;
406                         fds[wi].revents = 0;
407
408                         /*
409                          * Check the socket input/output direction as
410                          * requested
411                          */
412                         if (iocom->flags & (HAMMER2_IOCOMF_RREQ |
413                                             HAMMER2_IOCOMF_WREQ)) {
414                                 si = count++;
415                                 fds[si].fd = iocom->sock_fd;
416                                 fds[si].events = 0;
417                                 fds[si].revents = 0;
418
419                                 if (iocom->flags & HAMMER2_IOCOMF_RREQ)
420                                         fds[si].events |= POLLIN;
421                                 if (iocom->flags & HAMMER2_IOCOMF_WREQ)
422                                         fds[si].events |= POLLOUT;
423                         }
424
425                         /*
426                          * Check the alternative fd for work.
427                          */
428                         if (iocom->alt_fd >= 0) {
429                                 ai = count++;
430                                 fds[ai].fd = iocom->alt_fd;
431                                 fds[ai].events = POLLIN;
432                                 fds[ai].revents = 0;
433                         }
434                         poll(fds, count, timeout);
435
436                         if (wi >= 0 && (fds[wi].revents & POLLIN))
437                                 iocom->flags |= HAMMER2_IOCOMF_PWORK;
438                         if (si >= 0 && (fds[si].revents & POLLIN))
439                                 iocom->flags |= HAMMER2_IOCOMF_RWORK;
440                         if (si >= 0 && (fds[si].revents & POLLOUT))
441                                 iocom->flags |= HAMMER2_IOCOMF_WWORK;
442                         if (wi >= 0 && (fds[wi].revents & POLLOUT))
443                                 iocom->flags |= HAMMER2_IOCOMF_WWORK;
444                         if (ai >= 0 && (fds[ai].revents & POLLIN))
445                                 iocom->flags |= HAMMER2_IOCOMF_ARWORK;
446                 } else {
447                         /*
448                          * Always check the pipe
449                          */
450                         iocom->flags |= HAMMER2_IOCOMF_PWORK;
451                 }
452
453                 if (iocom->flags & HAMMER2_IOCOMF_SWORK) {
454                         iocom->flags &= ~HAMMER2_IOCOMF_SWORK;
455                         iocom->router->signal_callback(iocom->router);
456                 }
457
458                 /*
459                  * Pending message queues from other threads wake us up
460                  * with a write to the wakeupfds[] pipe.  We have to clear
461                  * the pipe with a dummy read.
462                  */
463                 if (iocom->flags & HAMMER2_IOCOMF_PWORK) {
464                         iocom->flags &= ~HAMMER2_IOCOMF_PWORK;
465                         read(iocom->wakeupfds[0], dummybuf, sizeof(dummybuf));
466                         iocom->flags |= HAMMER2_IOCOMF_RWORK;
467                         iocom->flags |= HAMMER2_IOCOMF_WWORK;
468                         if (TAILQ_FIRST(&iocom->router->txmsgq))
469                                 hammer2_iocom_flush1(iocom);
470                 }
471
472                 /*
473                  * Message write sequencing
474                  */
475                 if (iocom->flags & HAMMER2_IOCOMF_WWORK)
476                         hammer2_iocom_flush1(iocom);
477
478                 /*
479                  * Message read sequencing.  Run this after the write
480                  * sequencing in case the write sequencing allowed another
481                  * auto-DELETE to occur on the read side.
482                  */
483                 if (iocom->flags & HAMMER2_IOCOMF_RWORK) {
484                         while ((iocom->flags & HAMMER2_IOCOMF_EOF) == 0 &&
485                                (msg = hammer2_ioq_read(iocom)) != NULL) {
486                                 if (DebugOpt) {
487                                         fprintf(stderr, "receive %s\n",
488                                                 hammer2_msg_str(msg));
489                                 }
490                                 iocom->router->rcvmsg_callback(msg);
491                                 hammer2_state_cleanuprx(iocom, msg);
492                         }
493                 }
494
495                 if (iocom->flags & HAMMER2_IOCOMF_ARWORK) {
496                         iocom->flags &= ~HAMMER2_IOCOMF_ARWORK;
497                         iocom->router->altmsg_callback(iocom);
498                 }
499         }
500 }
501
502 /*
503  * Make sure there's enough room in the FIFO to hold the
504  * needed data.
505  *
506  * Assume worst case encrypted form is 2x the size of the
507  * plaintext equivalent.
508  */
509 static
510 size_t
511 hammer2_ioq_makeroom(hammer2_ioq_t *ioq, size_t needed)
512 {
513         size_t bytes;
514         size_t nmax;
515
516         bytes = ioq->fifo_cdx - ioq->fifo_beg;
517         nmax = sizeof(ioq->buf) - ioq->fifo_end;
518         if (bytes + nmax / 2 < needed) {
519                 if (bytes) {
520                         bcopy(ioq->buf + ioq->fifo_beg,
521                               ioq->buf,
522                               bytes);
523                 }
524                 ioq->fifo_cdx -= ioq->fifo_beg;
525                 ioq->fifo_beg = 0;
526                 if (ioq->fifo_cdn < ioq->fifo_end) {
527                         bcopy(ioq->buf + ioq->fifo_cdn,
528                               ioq->buf + ioq->fifo_cdx,
529                               ioq->fifo_end - ioq->fifo_cdn);
530                 }
531                 ioq->fifo_end -= ioq->fifo_cdn - ioq->fifo_cdx;
532                 ioq->fifo_cdn = ioq->fifo_cdx;
533                 nmax = sizeof(ioq->buf) - ioq->fifo_end;
534         }
535         return(nmax);
536 }
537
538 /*
539  * Read the next ready message from the ioq, issuing I/O if needed.
540  * Caller should retry on a read-event when NULL is returned.
541  *
542  * If an error occurs during reception a HAMMER2_LNK_ERROR msg will
543  * be returned for each open transaction, then the ioq and iocom
544  * will be errored out and a non-transactional HAMMER2_LNK_ERROR
545  * msg will be returned as the final message.  The caller should not call
546  * us again after the final message is returned.
547  *
548  * Thread localized, iocom->mtx not held.
549  */
550 hammer2_msg_t *
551 hammer2_ioq_read(hammer2_iocom_t *iocom)
552 {
553         hammer2_ioq_t *ioq = &iocom->ioq_rx;
554         hammer2_msg_t *msg;
555         hammer2_msg_hdr_t *head;
556         hammer2_state_t *state;
557         ssize_t n;
558         size_t bytes;
559         size_t nmax;
560         uint32_t xcrc32;
561         int error;
562
563 again:
564         iocom->flags &= ~(HAMMER2_IOCOMF_RREQ | HAMMER2_IOCOMF_RWORK);
565
566         /*
567          * If a message is already pending we can just remove and
568          * return it.  Message state has already been processed.
569          * (currently not implemented)
570          */
571         if ((msg = TAILQ_FIRST(&ioq->msgq)) != NULL) {
572                 TAILQ_REMOVE(&ioq->msgq, msg, qentry);
573                 return (msg);
574         }
575
576         /*
577          * If the stream is errored out we stop processing it.
578          */
579         if (ioq->error)
580                 goto skip;
581
582         /*
583          * Message read in-progress (msg is NULL at the moment).  We don't
584          * allocate a msg until we have its core header.
585          */
586         nmax = sizeof(ioq->buf) - ioq->fifo_end;
587         bytes = ioq->fifo_cdx - ioq->fifo_beg;          /* already decrypted */
588         msg = ioq->msg;
589
590         switch(ioq->state) {
591         case HAMMER2_MSGQ_STATE_HEADER1:
592                 /*
593                  * Load the primary header, fail on any non-trivial read
594                  * error or on EOF.  Since the primary header is the same
595                  * size is the message alignment it will never straddle
596                  * the end of the buffer.
597                  */
598                 nmax = hammer2_ioq_makeroom(ioq, sizeof(msg->any.head));
599                 if (bytes < sizeof(msg->any.head)) {
600                         n = read(iocom->sock_fd,
601                                  ioq->buf + ioq->fifo_end,
602                                  nmax);
603                         if (n <= 0) {
604                                 if (n == 0) {
605                                         ioq->error = HAMMER2_IOQ_ERROR_EOF;
606                                         break;
607                                 }
608                                 if (errno != EINTR &&
609                                     errno != EINPROGRESS &&
610                                     errno != EAGAIN) {
611                                         ioq->error = HAMMER2_IOQ_ERROR_SOCK;
612                                         break;
613                                 }
614                                 n = 0;
615                                 /* fall through */
616                         }
617                         ioq->fifo_end += (size_t)n;
618                         nmax -= (size_t)n;
619                 }
620
621                 /*
622                  * Decrypt data received so far.  Data will be decrypted
623                  * in-place but might create gaps in the FIFO.  Partial
624                  * blocks are not immediately decrypted.
625                  *
626                  * WARNING!  The header might be in the wrong endian, we
627                  *           do not fix it up until we get the entire
628                  *           extended header.
629                  */
630                 if (iocom->flags & HAMMER2_IOCOMF_CRYPTED) {
631                         hammer2_crypto_decrypt(iocom, ioq);
632                 } else {
633                         ioq->fifo_cdx = ioq->fifo_end;
634                         ioq->fifo_cdn = ioq->fifo_end;
635                 }
636                 bytes = ioq->fifo_cdx - ioq->fifo_beg;
637
638                 /*
639                  * Insufficient data accumulated (msg is NULL, caller will
640                  * retry on event).
641                  */
642                 assert(msg == NULL);
643                 if (bytes < sizeof(msg->any.head))
644                         break;
645
646                 /*
647                  * Check and fixup the core header.  Note that the icrc
648                  * has to be calculated before any fixups, but the crc
649                  * fields in the msg may have to be swapped like everything
650                  * else.
651                  */
652                 head = (void *)(ioq->buf + ioq->fifo_beg);
653                 if (head->magic != HAMMER2_MSGHDR_MAGIC &&
654                     head->magic != HAMMER2_MSGHDR_MAGIC_REV) {
655                         ioq->error = HAMMER2_IOQ_ERROR_SYNC;
656                         break;
657                 }
658
659                 /*
660                  * Calculate the full header size and aux data size
661                  */
662                 if (head->magic == HAMMER2_MSGHDR_MAGIC_REV) {
663                         ioq->hbytes = (bswap32(head->cmd) & HAMMER2_MSGF_SIZE) *
664                                       HAMMER2_MSG_ALIGN;
665                         ioq->abytes = bswap32(head->aux_bytes) *
666                                       HAMMER2_MSG_ALIGN;
667                 } else {
668                         ioq->hbytes = (head->cmd & HAMMER2_MSGF_SIZE) *
669                                       HAMMER2_MSG_ALIGN;
670                         ioq->abytes = head->aux_bytes * HAMMER2_MSG_ALIGN;
671                 }
672                 if (ioq->hbytes < sizeof(msg->any.head) ||
673                     ioq->hbytes > sizeof(msg->any) ||
674                     ioq->abytes > HAMMER2_MSGAUX_MAX) {
675                         ioq->error = HAMMER2_IOQ_ERROR_FIELD;
676                         break;
677                 }
678
679                 /*
680                  * Allocate the message, the next state will fill it in.
681                  */
682                 msg = hammer2_msg_alloc(iocom->router, ioq->abytes, 0,
683                                         NULL, NULL);
684                 ioq->msg = msg;
685
686                 /*
687                  * Fall through to the next state.  Make sure that the
688                  * extended header does not straddle the end of the buffer.
689                  * We still want to issue larger reads into our buffer,
690                  * book-keeping is easier if we don't bcopy() yet.
691                  *
692                  * Make sure there is enough room for bloated encrypt data.
693                  */
694                 nmax = hammer2_ioq_makeroom(ioq, ioq->hbytes);
695                 ioq->state = HAMMER2_MSGQ_STATE_HEADER2;
696                 /* fall through */
697         case HAMMER2_MSGQ_STATE_HEADER2:
698                 /*
699                  * Fill out the extended header.
700                  */
701                 assert(msg != NULL);
702                 if (bytes < ioq->hbytes) {
703                         n = read(iocom->sock_fd,
704                                  ioq->buf + ioq->fifo_end,
705                                  nmax);
706                         if (n <= 0) {
707                                 if (n == 0) {
708                                         ioq->error = HAMMER2_IOQ_ERROR_EOF;
709                                         break;
710                                 }
711                                 if (errno != EINTR &&
712                                     errno != EINPROGRESS &&
713                                     errno != EAGAIN) {
714                                         ioq->error = HAMMER2_IOQ_ERROR_SOCK;
715                                         break;
716                                 }
717                                 n = 0;
718                                 /* fall through */
719                         }
720                         ioq->fifo_end += (size_t)n;
721                         nmax -= (size_t)n;
722                 }
723
724                 if (iocom->flags & HAMMER2_IOCOMF_CRYPTED) {
725                         hammer2_crypto_decrypt(iocom, ioq);
726                 } else {
727                         ioq->fifo_cdx = ioq->fifo_end;
728                         ioq->fifo_cdn = ioq->fifo_end;
729                 }
730                 bytes = ioq->fifo_cdx - ioq->fifo_beg;
731
732                 /*
733                  * Insufficient data accumulated (set msg NULL so caller will
734                  * retry on event).
735                  */
736                 if (bytes < ioq->hbytes) {
737                         msg = NULL;
738                         break;
739                 }
740
741                 /*
742                  * Calculate the extended header, decrypt data received
743                  * so far.  Handle endian-conversion for the entire extended
744                  * header.
745                  */
746                 head = (void *)(ioq->buf + ioq->fifo_beg);
747
748                 /*
749                  * Check the CRC.
750                  */
751                 if (head->magic == HAMMER2_MSGHDR_MAGIC_REV)
752                         xcrc32 = bswap32(head->hdr_crc);
753                 else
754                         xcrc32 = head->hdr_crc;
755                 head->hdr_crc = 0;
756                 if (hammer2_icrc32(head, ioq->hbytes) != xcrc32) {
757                         ioq->error = HAMMER2_IOQ_ERROR_XCRC;
758                         fprintf(stderr, "BAD-XCRC(%08x,%08x) %s\n",
759                                 xcrc32, hammer2_icrc32(head, ioq->hbytes),
760                                 hammer2_msg_str(msg));
761                         assert(0);
762                         break;
763                 }
764                 head->hdr_crc = xcrc32;
765
766                 if (head->magic == HAMMER2_MSGHDR_MAGIC_REV) {
767                         hammer2_bswap_head(head);
768                 }
769
770                 /*
771                  * Copy the extended header into the msg and adjust the
772                  * FIFO.
773                  */
774                 bcopy(head, &msg->any, ioq->hbytes);
775
776                 /*
777                  * We are either done or we fall-through.
778                  */
779                 if (ioq->abytes == 0) {
780                         ioq->fifo_beg += ioq->hbytes;
781                         break;
782                 }
783
784                 /*
785                  * Must adjust bytes (and the state) when falling through.
786                  * nmax doesn't change.
787                  */
788                 ioq->fifo_beg += ioq->hbytes;
789                 bytes -= ioq->hbytes;
790                 ioq->state = HAMMER2_MSGQ_STATE_AUXDATA1;
791                 /* fall through */
792         case HAMMER2_MSGQ_STATE_AUXDATA1:
793                 /*
794                  * Copy the partial or complete payload from remaining
795                  * bytes in the FIFO in order to optimize the makeroom call
796                  * in the AUXDATA2 state.  We have to fall-through either
797                  * way so we can check the crc.
798                  *
799                  * msg->aux_size tracks our aux data.
800                  */
801                 if (bytes >= ioq->abytes) {
802                         bcopy(ioq->buf + ioq->fifo_beg, msg->aux_data,
803                               ioq->abytes);
804                         msg->aux_size = ioq->abytes;
805                         ioq->fifo_beg += ioq->abytes;
806                         assert(ioq->fifo_beg <= ioq->fifo_cdx);
807                         assert(ioq->fifo_cdx <= ioq->fifo_cdn);
808                         bytes -= ioq->abytes;
809                 } else if (bytes) {
810                         bcopy(ioq->buf + ioq->fifo_beg, msg->aux_data,
811                               bytes);
812                         msg->aux_size = bytes;
813                         ioq->fifo_beg += bytes;
814                         if (ioq->fifo_cdx < ioq->fifo_beg)
815                                 ioq->fifo_cdx = ioq->fifo_beg;
816                         assert(ioq->fifo_beg <= ioq->fifo_cdx);
817                         assert(ioq->fifo_cdx <= ioq->fifo_cdn);
818                         bytes = 0;
819                 } else {
820                         msg->aux_size = 0;
821                 }
822                 ioq->state = HAMMER2_MSGQ_STATE_AUXDATA2;
823                 /* fall through */
824         case HAMMER2_MSGQ_STATE_AUXDATA2:
825                 /*
826                  * Make sure there is enough room for more data.
827                  */
828                 assert(msg);
829                 nmax = hammer2_ioq_makeroom(ioq, ioq->abytes - msg->aux_size);
830
831                 /*
832                  * Read and decrypt more of the payload.
833                  */
834                 if (msg->aux_size < ioq->abytes) {
835                         assert(bytes == 0);
836                         n = read(iocom->sock_fd,
837                                  ioq->buf + ioq->fifo_end,
838                                  nmax);
839                         if (n <= 0) {
840                                 if (n == 0) {
841                                         ioq->error = HAMMER2_IOQ_ERROR_EOF;
842                                         break;
843                                 }
844                                 if (errno != EINTR &&
845                                     errno != EINPROGRESS &&
846                                     errno != EAGAIN) {
847                                         ioq->error = HAMMER2_IOQ_ERROR_SOCK;
848                                         break;
849                                 }
850                                 n = 0;
851                                 /* fall through */
852                         }
853                         ioq->fifo_end += (size_t)n;
854                         nmax -= (size_t)n;
855                 }
856
857                 if (iocom->flags & HAMMER2_IOCOMF_CRYPTED) {
858                         hammer2_crypto_decrypt(iocom, ioq);
859                 } else {
860                         ioq->fifo_cdx = ioq->fifo_end;
861                         ioq->fifo_cdn = ioq->fifo_end;
862                 }
863                 bytes = ioq->fifo_cdx - ioq->fifo_beg;
864
865                 if (bytes > ioq->abytes - msg->aux_size)
866                         bytes = ioq->abytes - msg->aux_size;
867
868                 if (bytes) {
869                         bcopy(ioq->buf + ioq->fifo_beg,
870                               msg->aux_data + msg->aux_size,
871                               bytes);
872                         msg->aux_size += bytes;
873                         ioq->fifo_beg += bytes;
874                 }
875
876                 /*
877                  * Insufficient data accumulated (set msg NULL so caller will
878                  * retry on event).
879                  */
880                 if (msg->aux_size < ioq->abytes) {
881                         msg = NULL;
882                         break;
883                 }
884                 assert(msg->aux_size == ioq->abytes);
885
886                 /*
887                  * Check aux_crc, then we are done.
888                  */
889                 xcrc32 = hammer2_icrc32(msg->aux_data, msg->aux_size);
890                 if (xcrc32 != msg->any.head.aux_crc) {
891                         ioq->error = HAMMER2_IOQ_ERROR_ACRC;
892                         break;
893                 }
894                 break;
895         case HAMMER2_MSGQ_STATE_ERROR:
896                 /*
897                  * Continued calls to drain recorded transactions (returning
898                  * a LNK_ERROR for each one), before we return the final
899                  * LNK_ERROR.
900                  */
901                 assert(msg == NULL);
902                 break;
903         default:
904                 /*
905                  * We don't double-return errors, the caller should not
906                  * have called us again after getting an error msg.
907                  */
908                 assert(0);
909                 break;
910         }
911
912         /*
913          * Check the message sequence.  The iv[] should prevent any
914          * possibility of a replay but we add this check anyway.
915          */
916         if (msg && ioq->error == 0) {
917                 if ((msg->any.head.salt & 255) != (ioq->seq & 255)) {
918                         ioq->error = HAMMER2_IOQ_ERROR_MSGSEQ;
919                 } else {
920                         ++ioq->seq;
921                 }
922         }
923
924         /*
925          * Process transactional state for the message.
926          */
927         if (msg && ioq->error == 0) {
928                 error = hammer2_state_msgrx(msg);
929                 if (error) {
930                         if (error == HAMMER2_IOQ_ERROR_EALREADY) {
931                                 hammer2_msg_free(msg);
932                                 goto again;
933                         }
934                         ioq->error = error;
935                 }
936         }
937
938         /*
939          * Handle error, RREQ, or completion
940          *
941          * NOTE: nmax and bytes are invalid at this point, we don't bother
942          *       to update them when breaking out.
943          */
944         if (ioq->error) {
945 skip:
946                 /*
947                  * An unrecoverable error causes all active receive
948                  * transactions to be terminated with a LNK_ERROR message.
949                  *
950                  * Once all active transactions are exhausted we set the
951                  * iocom ERROR flag and return a non-transactional LNK_ERROR
952                  * message, which should cause master processing loops to
953                  * terminate.
954                  */
955                 assert(ioq->msg == msg);
956                 if (msg) {
957                         hammer2_msg_free(msg);
958                         ioq->msg = NULL;
959                 }
960
961                 /*
962                  * No more I/O read processing
963                  */
964                 ioq->state = HAMMER2_MSGQ_STATE_ERROR;
965
966                 /*
967                  * Simulate a remote LNK_ERROR DELETE msg for any open
968                  * transactions, ending with a final non-transactional
969                  * LNK_ERROR (that the session can detect) when no
970                  * transactions remain.
971                  */
972                 msg = hammer2_msg_alloc(iocom->router, 0, 0, NULL, NULL);
973                 bzero(&msg->any.head, sizeof(msg->any.head));
974                 msg->any.head.magic = HAMMER2_MSGHDR_MAGIC;
975                 msg->any.head.cmd = HAMMER2_LNK_ERROR;
976                 msg->any.head.error = ioq->error;
977
978                 pthread_mutex_lock(&iocom->mtx);
979                 hammer2_iocom_drain(iocom);
980                 if ((state = RB_ROOT(&iocom->router->staterd_tree)) != NULL) {
981                         /*
982                          * Active remote transactions are still present.
983                          * Simulate the other end sending us a DELETE.
984                          */
985                         if (state->rxcmd & HAMMER2_MSGF_DELETE) {
986                                 hammer2_msg_free(msg);
987                                 msg = NULL;
988                         } else {
989                                 /*state->txcmd |= HAMMER2_MSGF_DELETE;*/
990                                 msg->state = state;
991                                 msg->router = state->router;
992                                 msg->any.head.msgid = state->msgid;
993                                 msg->any.head.cmd |= HAMMER2_MSGF_ABORT |
994                                                      HAMMER2_MSGF_DELETE;
995                         }
996                 } else if ((state = RB_ROOT(&iocom->router->statewr_tree)) !=
997                            NULL) {
998                         /*
999                          * Active local transactions are still present.
1000                          * Simulate the other end sending us a DELETE.
1001                          */
1002                         if (state->rxcmd & HAMMER2_MSGF_DELETE) {
1003                                 hammer2_msg_free(msg);
1004                                 msg = NULL;
1005                         } else {
1006                                 msg->state = state;
1007                                 msg->router = state->router;
1008                                 msg->any.head.msgid = state->msgid;
1009                                 msg->any.head.cmd |= HAMMER2_MSGF_ABORT |
1010                                                      HAMMER2_MSGF_DELETE |
1011                                                      HAMMER2_MSGF_REPLY;
1012                                 if ((state->rxcmd & HAMMER2_MSGF_CREATE) == 0) {
1013                                         msg->any.head.cmd |=
1014                                                      HAMMER2_MSGF_CREATE;
1015                                 }
1016                         }
1017                 } else {
1018                         /*
1019                          * No active local or remote transactions remain.
1020                          * Generate a final LNK_ERROR and flag EOF.
1021                          */
1022                         msg->state = NULL;
1023                         iocom->flags |= HAMMER2_IOCOMF_EOF;
1024                         fprintf(stderr, "EOF ON SOCKET %d\n", iocom->sock_fd);
1025                 }
1026                 pthread_mutex_unlock(&iocom->mtx);
1027
1028                 /*
1029                  * For the iocom error case we want to set RWORK to indicate
1030                  * that more messages might be pending.
1031                  *
1032                  * It is possible to return NULL when there is more work to
1033                  * do because each message has to be DELETEd in both
1034                  * directions before we continue on with the next (though
1035                  * this could be optimized).  The transmit direction will
1036                  * re-set RWORK.
1037                  */
1038                 if (msg)
1039                         iocom->flags |= HAMMER2_IOCOMF_RWORK;
1040         } else if (msg == NULL) {
1041                 /*
1042                  * Insufficient data received to finish building the message,
1043                  * set RREQ and return NULL.
1044                  *
1045                  * Leave ioq->msg intact.
1046                  * Leave the FIFO intact.
1047                  */
1048                 iocom->flags |= HAMMER2_IOCOMF_RREQ;
1049         } else {
1050                 /*
1051                  * Return msg.
1052                  *
1053                  * The fifo has already been advanced past the message.
1054                  * Trivially reset the FIFO indices if possible.
1055                  *
1056                  * clear the FIFO if it is now empty and set RREQ to wait
1057                  * for more from the socket.  If the FIFO is not empty set
1058                  * TWORK to bypass the poll so we loop immediately.
1059                  */
1060                 if (ioq->fifo_beg == ioq->fifo_cdx &&
1061                     ioq->fifo_cdn == ioq->fifo_end) {
1062                         iocom->flags |= HAMMER2_IOCOMF_RREQ;
1063                         ioq->fifo_cdx = 0;
1064                         ioq->fifo_cdn = 0;
1065                         ioq->fifo_beg = 0;
1066                         ioq->fifo_end = 0;
1067                 } else {
1068                         iocom->flags |= HAMMER2_IOCOMF_RWORK;
1069                 }
1070                 ioq->state = HAMMER2_MSGQ_STATE_HEADER1;
1071                 ioq->msg = NULL;
1072         }
1073         return (msg);
1074 }
1075
1076 /*
1077  * Calculate the header and data crc's and write a low-level message to
1078  * the connection.  If aux_crc is non-zero the aux_data crc is already
1079  * assumed to have been set.
1080  *
1081  * A non-NULL msg is added to the queue but not necessarily flushed.
1082  * Calling this function with msg == NULL will get a flush going.
1083  *
1084  * Caller must hold iocom->mtx.
1085  */
1086 void
1087 hammer2_iocom_flush1(hammer2_iocom_t *iocom)
1088 {
1089         hammer2_ioq_t *ioq = &iocom->ioq_tx;
1090         hammer2_msg_t *msg;
1091         uint32_t xcrc32;
1092         int hbytes;
1093         hammer2_msg_queue_t tmpq;
1094
1095         iocom->flags &= ~(HAMMER2_IOCOMF_WREQ | HAMMER2_IOCOMF_WWORK);
1096         TAILQ_INIT(&tmpq);
1097         pthread_mutex_lock(&iocom->mtx);
1098         while ((msg = TAILQ_FIRST(&iocom->router->txmsgq)) != NULL) {
1099                 TAILQ_REMOVE(&iocom->router->txmsgq, msg, qentry);
1100                 TAILQ_INSERT_TAIL(&tmpq, msg, qentry);
1101         }
1102         pthread_mutex_unlock(&iocom->mtx);
1103
1104         while ((msg = TAILQ_FIRST(&tmpq)) != NULL) {
1105                 /*
1106                  * Process terminal connection errors.
1107                  */
1108                 TAILQ_REMOVE(&tmpq, msg, qentry);
1109                 if (ioq->error) {
1110                         TAILQ_INSERT_TAIL(&ioq->msgq, msg, qentry);
1111                         ++ioq->msgcount;
1112                         continue;
1113                 }
1114
1115                 /*
1116                  * Finish populating the msg fields.  The salt ensures that
1117                  * the iv[] array is ridiculously randomized and we also
1118                  * re-seed our PRNG every 32768 messages just to be sure.
1119                  */
1120                 msg->any.head.magic = HAMMER2_MSGHDR_MAGIC;
1121                 msg->any.head.salt = (random() << 8) | (ioq->seq & 255);
1122                 ++ioq->seq;
1123                 if ((ioq->seq & 32767) == 0)
1124                         srandomdev();
1125
1126                 /*
1127                  * Calculate aux_crc if 0, then calculate hdr_crc.
1128                  */
1129                 if (msg->aux_size && msg->any.head.aux_crc == 0) {
1130                         assert((msg->aux_size & HAMMER2_MSG_ALIGNMASK) == 0);
1131                         xcrc32 = hammer2_icrc32(msg->aux_data, msg->aux_size);
1132                         msg->any.head.aux_crc = xcrc32;
1133                 }
1134                 msg->any.head.aux_bytes = msg->aux_size / HAMMER2_MSG_ALIGN;
1135                 assert((msg->aux_size & HAMMER2_MSG_ALIGNMASK) == 0);
1136
1137                 hbytes = (msg->any.head.cmd & HAMMER2_MSGF_SIZE) *
1138                          HAMMER2_MSG_ALIGN;
1139                 msg->any.head.hdr_crc = 0;
1140                 msg->any.head.hdr_crc = hammer2_icrc32(&msg->any.head, hbytes);
1141
1142                 /*
1143                  * Enqueue the message (the flush codes handles stream
1144                  * encryption).
1145                  */
1146                 TAILQ_INSERT_TAIL(&ioq->msgq, msg, qentry);
1147                 ++ioq->msgcount;
1148         }
1149         hammer2_iocom_flush2(iocom);
1150 }
1151
1152 /*
1153  * Thread localized, iocom->mtx not held by caller.
1154  */
1155 void
1156 hammer2_iocom_flush2(hammer2_iocom_t *iocom)
1157 {
1158         hammer2_ioq_t *ioq = &iocom->ioq_tx;
1159         hammer2_msg_t *msg;
1160         ssize_t n;
1161         struct iovec iov[HAMMER2_IOQ_MAXIOVEC];
1162         size_t nact;
1163         size_t hbytes;
1164         size_t abytes;
1165         size_t hoff;
1166         size_t aoff;
1167         int iovcnt;
1168
1169         if (ioq->error) {
1170                 hammer2_iocom_drain(iocom);
1171                 return;
1172         }
1173
1174         /*
1175          * Pump messages out the connection by building an iovec.
1176          *
1177          * ioq->hbytes/ioq->abytes tracks how much of the first message
1178          * in the queue has been successfully written out, so we can
1179          * resume writing.
1180          */
1181         iovcnt = 0;
1182         nact = 0;
1183         hoff = ioq->hbytes;
1184         aoff = ioq->abytes;
1185
1186         TAILQ_FOREACH(msg, &ioq->msgq, qentry) {
1187                 hbytes = (msg->any.head.cmd & HAMMER2_MSGF_SIZE) *
1188                          HAMMER2_MSG_ALIGN;
1189                 abytes = msg->aux_size;
1190                 assert(hoff <= hbytes && aoff <= abytes);
1191
1192                 if (hoff < hbytes) {
1193                         iov[iovcnt].iov_base = (char *)&msg->any.head + hoff;
1194                         iov[iovcnt].iov_len = hbytes - hoff;
1195                         nact += hbytes - hoff;
1196                         ++iovcnt;
1197                         if (iovcnt == HAMMER2_IOQ_MAXIOVEC)
1198                                 break;
1199                 }
1200                 if (aoff < abytes) {
1201                         assert(msg->aux_data != NULL);
1202                         iov[iovcnt].iov_base = (char *)msg->aux_data + aoff;
1203                         iov[iovcnt].iov_len = abytes - aoff;
1204                         nact += abytes - aoff;
1205                         ++iovcnt;
1206                         if (iovcnt == HAMMER2_IOQ_MAXIOVEC)
1207                                 break;
1208                 }
1209                 hoff = 0;
1210                 aoff = 0;
1211         }
1212         if (iovcnt == 0)
1213                 return;
1214
1215         /*
1216          * Encrypt and write the data.  The crypto code will move the
1217          * data into the fifo and adjust the iov as necessary.  If
1218          * encryption is disabled the iov is left alone.
1219          *
1220          * May return a smaller iov (thus a smaller n), with aggregated
1221          * chunks.  May reduce nmax to what fits in the FIFO.
1222          *
1223          * This function sets nact to the number of original bytes now
1224          * encrypted, adding to the FIFO some number of bytes that might
1225          * be greater depending on the crypto mechanic.  iov[] is adjusted
1226          * to point at the FIFO if necessary.
1227          *
1228          * NOTE: The return value from the writev() is the post-encrypted
1229          *       byte count, not the plaintext count.
1230          */
1231         if (iocom->flags & HAMMER2_IOCOMF_CRYPTED) {
1232                 /*
1233                  * Make sure the FIFO has a reasonable amount of space
1234                  * left (if not completely full).
1235                  */
1236                 if (ioq->fifo_beg > sizeof(ioq->buf) / 2 &&
1237                     sizeof(ioq->buf) - ioq->fifo_end >= HAMMER2_MSG_ALIGN * 2) {
1238                         bcopy(ioq->buf + ioq->fifo_beg, ioq->buf,
1239                               ioq->fifo_end - ioq->fifo_beg);
1240                         ioq->fifo_cdx -= ioq->fifo_beg;
1241                         ioq->fifo_cdn -= ioq->fifo_beg;
1242                         ioq->fifo_end -= ioq->fifo_beg;
1243                         ioq->fifo_beg = 0;
1244                 }
1245
1246                 iovcnt = hammer2_crypto_encrypt(iocom, ioq, iov, iovcnt, &nact);
1247                 n = writev(iocom->sock_fd, iov, iovcnt);
1248                 if (n > 0) {
1249                         ioq->fifo_beg += n;
1250                         ioq->fifo_cdn += n;
1251                         ioq->fifo_cdx += n;
1252                         if (ioq->fifo_beg == ioq->fifo_end) {
1253                                 ioq->fifo_beg = 0;
1254                                 ioq->fifo_cdn = 0;
1255                                 ioq->fifo_cdx = 0;
1256                                 ioq->fifo_end = 0;
1257                         }
1258                 }
1259         } else {
1260                 n = writev(iocom->sock_fd, iov, iovcnt);
1261                 if (n > 0)
1262                         nact = n;
1263                 else
1264                         nact = 0;
1265         }
1266
1267         /*
1268          * Clean out the transmit queue based on what we successfully
1269          * sent (nact is the plaintext count).  ioq->hbytes/abytes
1270          * represents the portion of the first message previously sent.
1271          */
1272         while ((msg = TAILQ_FIRST(&ioq->msgq)) != NULL) {
1273                 hbytes = (msg->any.head.cmd & HAMMER2_MSGF_SIZE) *
1274                          HAMMER2_MSG_ALIGN;
1275                 abytes = msg->aux_size;
1276
1277                 if ((size_t)nact < hbytes - ioq->hbytes) {
1278                         ioq->hbytes += nact;
1279                         nact = 0;
1280                         break;
1281                 }
1282                 nact -= hbytes - ioq->hbytes;
1283                 ioq->hbytes = hbytes;
1284                 if ((size_t)nact < abytes - ioq->abytes) {
1285                         ioq->abytes += nact;
1286                         nact = 0;
1287                         break;
1288                 }
1289                 nact -= abytes - ioq->abytes;
1290
1291                 TAILQ_REMOVE(&ioq->msgq, msg, qentry);
1292                 --ioq->msgcount;
1293                 ioq->hbytes = 0;
1294                 ioq->abytes = 0;
1295
1296                 hammer2_state_cleanuptx(msg);
1297         }
1298         assert(nact == 0);
1299
1300         /*
1301          * Process the return value from the write w/regards to blocking.
1302          */
1303         if (n < 0) {
1304                 if (errno != EINTR &&
1305                     errno != EINPROGRESS &&
1306                     errno != EAGAIN) {
1307                         /*
1308                          * Fatal write error
1309                          */
1310                         ioq->error = HAMMER2_IOQ_ERROR_SOCK;
1311                         hammer2_iocom_drain(iocom);
1312                 } else {
1313                         /*
1314                          * Wait for socket buffer space
1315                          */
1316                         iocom->flags |= HAMMER2_IOCOMF_WREQ;
1317                 }
1318         } else {
1319                 iocom->flags |= HAMMER2_IOCOMF_WREQ;
1320         }
1321         if (ioq->error) {
1322                 hammer2_iocom_drain(iocom);
1323         }
1324 }
1325
1326 /*
1327  * Kill pending msgs on ioq_tx and adjust the flags such that no more
1328  * write events will occur.  We don't kill read msgs because we want
1329  * the caller to pull off our contrived terminal error msg to detect
1330  * the connection failure.
1331  *
1332  * Thread localized, iocom->mtx not held by caller.
1333  */
1334 void
1335 hammer2_iocom_drain(hammer2_iocom_t *iocom)
1336 {
1337         hammer2_ioq_t *ioq = &iocom->ioq_tx;
1338         hammer2_msg_t *msg;
1339
1340         iocom->flags &= ~(HAMMER2_IOCOMF_WREQ | HAMMER2_IOCOMF_WWORK);
1341         ioq->hbytes = 0;
1342         ioq->abytes = 0;
1343
1344         while ((msg = TAILQ_FIRST(&ioq->msgq)) != NULL) {
1345                 TAILQ_REMOVE(&ioq->msgq, msg, qentry);
1346                 --ioq->msgcount;
1347                 hammer2_state_cleanuptx(msg);
1348         }
1349 }
1350
1351 /*
1352  * Write a message to an iocom, with additional state processing.
1353  */
1354 void
1355 hammer2_msg_write(hammer2_msg_t *msg)
1356 {
1357         hammer2_iocom_t *iocom = msg->router->iocom;
1358         hammer2_state_t *state;
1359         char dummy;
1360
1361         /*
1362          * Handle state processing, create state if necessary.
1363          */
1364         pthread_mutex_lock(&iocom->mtx);
1365         if ((state = msg->state) != NULL) {
1366                 /*
1367                  * Existing transaction (could be reply).  It is also
1368                  * possible for this to be the first reply (CREATE is set),
1369                  * in which case we populate state->txcmd.
1370                  *
1371                  * state->txcmd is adjusted to hold the final message cmd,
1372                  * and we also be sure to set the CREATE bit here.  We did
1373                  * not set it in hammer2_msg_alloc() because that would have
1374                  * not been serialized (state could have gotten ripped out
1375                  * from under the message prior to it being transmitted).
1376                  */
1377                 if ((msg->any.head.cmd & (HAMMER2_MSGF_CREATE |
1378                                           HAMMER2_MSGF_REPLY)) ==
1379                     HAMMER2_MSGF_CREATE) {
1380                         state->txcmd = msg->any.head.cmd & ~HAMMER2_MSGF_DELETE;
1381                 }
1382                 msg->any.head.msgid = state->msgid;
1383                 assert(((state->txcmd ^ msg->any.head.cmd) &
1384                         HAMMER2_MSGF_REPLY) == 0);
1385                 if (msg->any.head.cmd & HAMMER2_MSGF_CREATE)
1386                         state->txcmd = msg->any.head.cmd & ~HAMMER2_MSGF_DELETE;
1387         } else {
1388                 msg->any.head.msgid = 0;
1389                 /* XXX set spanid by router */
1390         }
1391         msg->any.head.source = 0;
1392         msg->any.head.target = msg->router->target;
1393
1394         /*
1395          * Queue it for output, wake up the I/O pthread.  Note that the
1396          * I/O thread is responsible for generating the CRCs and encryption.
1397          */
1398         TAILQ_INSERT_TAIL(&iocom->router->txmsgq, msg, qentry);
1399         dummy = 0;
1400         write(iocom->wakeupfds[1], &dummy, 1);  /* XXX optimize me */
1401         pthread_mutex_unlock(&iocom->mtx);
1402 }
1403
1404 /*
1405  * This is a shortcut to formulate a reply to msg with a simple error code,
1406  * It can reply to and terminate a transaction, or it can reply to a one-way
1407  * messages.  A HAMMER2_LNK_ERROR command code is utilized to encode
1408  * the error code (which can be 0).  Not all transactions are terminated
1409  * with HAMMER2_LNK_ERROR status (the low level only cares about the
1410  * MSGF_DELETE flag), but most are.
1411  *
1412  * Replies to one-way messages are a bit of an oxymoron but the feature
1413  * is used by the debug (DBG) protocol.
1414  *
1415  * The reply contains no extended data.
1416  */
1417 void
1418 hammer2_msg_reply(hammer2_msg_t *msg, uint32_t error)
1419 {
1420         hammer2_iocom_t *iocom = msg->router->iocom;
1421         hammer2_state_t *state = msg->state;
1422         hammer2_msg_t *nmsg;
1423         uint32_t cmd;
1424
1425
1426         /*
1427          * Reply with a simple error code and terminate the transaction.
1428          */
1429         cmd = HAMMER2_LNK_ERROR;
1430
1431         /*
1432          * Check if our direction has even been initiated yet, set CREATE.
1433          *
1434          * Check what direction this is (command or reply direction).  Note
1435          * that txcmd might not have been initiated yet.
1436          *
1437          * If our direction has already been closed we just return without
1438          * doing anything.
1439          */
1440         if (state) {
1441                 if (state->txcmd & HAMMER2_MSGF_DELETE)
1442                         return;
1443                 if (state->txcmd & HAMMER2_MSGF_REPLY)
1444                         cmd |= HAMMER2_MSGF_REPLY;
1445                 cmd |= HAMMER2_MSGF_DELETE;
1446         } else {
1447                 if ((msg->any.head.cmd & HAMMER2_MSGF_REPLY) == 0)
1448                         cmd |= HAMMER2_MSGF_REPLY;
1449         }
1450
1451         /*
1452          * Allocate the message and associate it with the existing state.
1453          * We cannot pass MSGF_CREATE to msg_alloc() because that may
1454          * allocate new state.  We have our state already.
1455          */
1456         nmsg = hammer2_msg_alloc(iocom->router, 0, cmd, NULL, NULL);
1457         if (state) {
1458                 if ((state->txcmd & HAMMER2_MSGF_CREATE) == 0)
1459                         nmsg->any.head.cmd |= HAMMER2_MSGF_CREATE;
1460         }
1461         nmsg->any.head.error = error;
1462         nmsg->state = state;
1463         hammer2_msg_write(nmsg);
1464 }
1465
1466 /*
1467  * Similar to hammer2_msg_reply() but leave the transaction open.  That is,
1468  * we are generating a streaming reply or an intermediate acknowledgement
1469  * of some sort as part of the higher level protocol, with more to come
1470  * later.
1471  */
1472 void
1473 hammer2_msg_result(hammer2_msg_t *msg, uint32_t error)
1474 {
1475         hammer2_iocom_t *iocom = msg->router->iocom;
1476         hammer2_state_t *state = msg->state;
1477         hammer2_msg_t *nmsg;
1478         uint32_t cmd;
1479
1480
1481         /*
1482          * Reply with a simple error code and terminate the transaction.
1483          */
1484         cmd = HAMMER2_LNK_ERROR;
1485
1486         /*
1487          * Check if our direction has even been initiated yet, set CREATE.
1488          *
1489          * Check what direction this is (command or reply direction).  Note
1490          * that txcmd might not have been initiated yet.
1491          *
1492          * If our direction has already been closed we just return without
1493          * doing anything.
1494          */
1495         if (state) {
1496                 if (state->txcmd & HAMMER2_MSGF_DELETE)
1497                         return;
1498                 if (state->txcmd & HAMMER2_MSGF_REPLY)
1499                         cmd |= HAMMER2_MSGF_REPLY;
1500                 /* continuing transaction, do not set MSGF_DELETE */
1501         } else {
1502                 if ((msg->any.head.cmd & HAMMER2_MSGF_REPLY) == 0)
1503                         cmd |= HAMMER2_MSGF_REPLY;
1504         }
1505
1506         nmsg = hammer2_msg_alloc(iocom->router, 0, cmd, NULL, NULL);
1507         if (state) {
1508                 if ((state->txcmd & HAMMER2_MSGF_CREATE) == 0)
1509                         nmsg->any.head.cmd |= HAMMER2_MSGF_CREATE;
1510         }
1511         nmsg->any.head.error = error;
1512         nmsg->state = state;
1513         hammer2_msg_write(nmsg);
1514 }
1515
1516 /*
1517  * Terminate a transaction given a state structure by issuing a DELETE.
1518  */
1519 void
1520 hammer2_state_reply(hammer2_state_t *state, uint32_t error)
1521 {
1522         hammer2_msg_t *nmsg;
1523         uint32_t cmd = HAMMER2_LNK_ERROR | HAMMER2_MSGF_DELETE;
1524
1525         /*
1526          * Nothing to do if we already transmitted a delete
1527          */
1528         if (state->txcmd & HAMMER2_MSGF_DELETE)
1529                 return;
1530
1531         /*
1532          * Set REPLY if the other end initiated the command.  Otherwise
1533          * we are the command direction.
1534          */
1535         if (state->txcmd & HAMMER2_MSGF_REPLY)
1536                 cmd |= HAMMER2_MSGF_REPLY;
1537
1538         nmsg = hammer2_msg_alloc(state->iocom->router, 0, cmd, NULL, NULL);
1539         if (state) {
1540                 if ((state->txcmd & HAMMER2_MSGF_CREATE) == 0)
1541                         nmsg->any.head.cmd |= HAMMER2_MSGF_CREATE;
1542         }
1543         nmsg->any.head.error = error;
1544         nmsg->state = state;
1545         hammer2_msg_write(nmsg);
1546 }
1547
1548 /************************************************************************
1549  *                      TRANSACTION STATE HANDLING                      *
1550  ************************************************************************
1551  *
1552  */
1553
1554 /*
1555  * Process state tracking for a message after reception, prior to
1556  * execution.
1557  *
1558  * Called with msglk held and the msg dequeued.
1559  *
1560  * All messages are called with dummy state and return actual state.
1561  * (One-off messages often just return the same dummy state).
1562  *
1563  * May request that caller discard the message by setting *discardp to 1.
1564  * The returned state is not used in this case and is allowed to be NULL.
1565  *
1566  * --
1567  *
1568  * These routines handle persistent and command/reply message state via the
1569  * CREATE and DELETE flags.  The first message in a command or reply sequence
1570  * sets CREATE, the last message in a command or reply sequence sets DELETE.
1571  *
1572  * There can be any number of intermediate messages belonging to the same
1573  * sequence sent inbetween the CREATE message and the DELETE message,
1574  * which set neither flag.  This represents a streaming command or reply.
1575  *
1576  * Any command message received with CREATE set expects a reply sequence to
1577  * be returned.  Reply sequences work the same as command sequences except the
1578  * REPLY bit is also sent.  Both the command side and reply side can
1579  * degenerate into a single message with both CREATE and DELETE set.  Note
1580  * that one side can be streaming and the other side not, or neither, or both.
1581  *
1582  * The msgid is unique for the initiator.  That is, two sides sending a new
1583  * message can use the same msgid without colliding.
1584  *
1585  * --
1586  *
1587  * ABORT sequences work by setting the ABORT flag along with normal message
1588  * state.  However, ABORTs can also be sent on half-closed messages, that is
1589  * even if the command or reply side has already sent a DELETE, as long as
1590  * the message has not been fully closed it can still send an ABORT+DELETE
1591  * to terminate the half-closed message state.
1592  *
1593  * Since ABORT+DELETEs can race we silently discard ABORT's for message
1594  * state which has already been fully closed.  REPLY+ABORT+DELETEs can
1595  * also race, and in this situation the other side might have already
1596  * initiated a new unrelated command with the same message id.  Since
1597  * the abort has not set the CREATE flag the situation can be detected
1598  * and the message will also be discarded.
1599  *
1600  * Non-blocking requests can be initiated with ABORT+CREATE[+DELETE].
1601  * The ABORT request is essentially integrated into the command instead
1602  * of being sent later on.  In this situation the command implementation
1603  * detects that CREATE and ABORT are both set (vs ABORT alone) and can
1604  * special-case non-blocking operation for the command.
1605  *
1606  * NOTE!  Messages with ABORT set without CREATE or DELETE are considered
1607  *        to be mid-stream aborts for command/reply sequences.  ABORTs on
1608  *        one-way messages are not supported.
1609  *
1610  * NOTE!  If a command sequence does not support aborts the ABORT flag is
1611  *        simply ignored.
1612  *
1613  * --
1614  *
1615  * One-off messages (no reply expected) are sent with neither CREATE or DELETE
1616  * set.  One-off messages cannot be aborted and typically aren't processed
1617  * by these routines.  The REPLY bit can be used to distinguish whether a
1618  * one-off message is a command or reply.  For example, one-off replies
1619  * will typically just contain status updates.
1620  */
1621 static int
1622 hammer2_state_msgrx(hammer2_msg_t *msg)
1623 {
1624         hammer2_iocom_t *iocom = msg->router->iocom;
1625         hammer2_state_t *state;
1626         hammer2_state_t dummy;
1627         int error;
1628
1629         /*
1630          * Lock RB tree and locate existing persistent state, if any.
1631          *
1632          * If received msg is a command state is on staterd_tree.
1633          * If received msg is a reply state is on statewr_tree.
1634          */
1635         dummy.msgid = msg->any.head.msgid;
1636         pthread_mutex_lock(&iocom->mtx);
1637         if (msg->any.head.cmd & HAMMER2_MSGF_REPLY) {
1638                 state = RB_FIND(hammer2_state_tree,
1639                                 &iocom->router->statewr_tree, &dummy);
1640         } else {
1641                 state = RB_FIND(hammer2_state_tree,
1642                                 &iocom->router->staterd_tree, &dummy);
1643         }
1644         msg->state = state;
1645         pthread_mutex_unlock(&iocom->mtx);
1646
1647         /*
1648          * Short-cut one-off or mid-stream messages (state may be NULL).
1649          */
1650         if ((msg->any.head.cmd & (HAMMER2_MSGF_CREATE | HAMMER2_MSGF_DELETE |
1651                                   HAMMER2_MSGF_ABORT)) == 0) {
1652                 return(0);
1653         }
1654
1655         /*
1656          * Switch on CREATE, DELETE, REPLY, and also handle ABORT from
1657          * inside the case statements.
1658          */
1659         switch(msg->any.head.cmd & (HAMMER2_MSGF_CREATE | HAMMER2_MSGF_DELETE |
1660                                     HAMMER2_MSGF_REPLY)) {
1661         case HAMMER2_MSGF_CREATE:
1662         case HAMMER2_MSGF_CREATE | HAMMER2_MSGF_DELETE:
1663                 /*
1664                  * New persistant command received.
1665                  */
1666                 if (state) {
1667                         fprintf(stderr, "duplicate-trans %s\n",
1668                                 hammer2_msg_str(msg));
1669                         error = HAMMER2_IOQ_ERROR_TRANS;
1670                         assert(0);
1671                         break;
1672                 }
1673                 state = malloc(sizeof(*state));
1674                 bzero(state, sizeof(*state));
1675                 state->iocom = iocom;
1676                 state->flags = HAMMER2_STATE_DYNAMIC;
1677                 state->msg = msg;
1678                 state->txcmd = HAMMER2_MSGF_REPLY;
1679                 state->rxcmd = msg->any.head.cmd & ~HAMMER2_MSGF_DELETE;
1680                 state->flags |= HAMMER2_STATE_INSERTED;
1681                 state->msgid = msg->any.head.msgid;
1682                 state->router = msg->router;
1683                 msg->state = state;
1684                 pthread_mutex_lock(&iocom->mtx);
1685                 RB_INSERT(hammer2_state_tree,
1686                           &iocom->router->staterd_tree, state);
1687                 pthread_mutex_unlock(&iocom->mtx);
1688                 error = 0;
1689                 if (DebugOpt) {
1690                         fprintf(stderr, "create state %p id=%08x on iocom staterd %p\n",
1691                                 state, (uint32_t)state->msgid, iocom);
1692                 }
1693                 break;
1694         case HAMMER2_MSGF_DELETE:
1695                 /*
1696                  * Persistent state is expected but might not exist if an
1697                  * ABORT+DELETE races the close.
1698                  */
1699                 if (state == NULL) {
1700                         if (msg->any.head.cmd & HAMMER2_MSGF_ABORT) {
1701                                 error = HAMMER2_IOQ_ERROR_EALREADY;
1702                         } else {
1703                                 fprintf(stderr, "missing-state %s\n",
1704                                         hammer2_msg_str(msg));
1705                                 error = HAMMER2_IOQ_ERROR_TRANS;
1706                         assert(0);
1707                         }
1708                         break;
1709                 }
1710
1711                 /*
1712                  * Handle another ABORT+DELETE case if the msgid has already
1713                  * been reused.
1714                  */
1715                 if ((state->rxcmd & HAMMER2_MSGF_CREATE) == 0) {
1716                         if (msg->any.head.cmd & HAMMER2_MSGF_ABORT) {
1717                                 error = HAMMER2_IOQ_ERROR_EALREADY;
1718                         } else {
1719                                 fprintf(stderr, "reused-state %s\n",
1720                                         hammer2_msg_str(msg));
1721                                 error = HAMMER2_IOQ_ERROR_TRANS;
1722                         assert(0);
1723                         }
1724                         break;
1725                 }
1726                 error = 0;
1727                 break;
1728         default:
1729                 /*
1730                  * Check for mid-stream ABORT command received, otherwise
1731                  * allow.
1732                  */
1733                 if (msg->any.head.cmd & HAMMER2_MSGF_ABORT) {
1734                         if (state == NULL ||
1735                             (state->rxcmd & HAMMER2_MSGF_CREATE) == 0) {
1736                                 error = HAMMER2_IOQ_ERROR_EALREADY;
1737                                 break;
1738                         }
1739                 }
1740                 error = 0;
1741                 break;
1742         case HAMMER2_MSGF_REPLY | HAMMER2_MSGF_CREATE:
1743         case HAMMER2_MSGF_REPLY | HAMMER2_MSGF_CREATE | HAMMER2_MSGF_DELETE:
1744                 /*
1745                  * When receiving a reply with CREATE set the original
1746                  * persistent state message should already exist.
1747                  */
1748                 if (state == NULL) {
1749                         fprintf(stderr, "no-state(r) %s\n",
1750                                 hammer2_msg_str(msg));
1751                         error = HAMMER2_IOQ_ERROR_TRANS;
1752                         assert(0);
1753                         break;
1754                 }
1755                 assert(((state->rxcmd ^ msg->any.head.cmd) &
1756                         HAMMER2_MSGF_REPLY) == 0);
1757                 state->rxcmd = msg->any.head.cmd & ~HAMMER2_MSGF_DELETE;
1758                 error = 0;
1759                 break;
1760         case HAMMER2_MSGF_REPLY | HAMMER2_MSGF_DELETE:
1761                 /*
1762                  * Received REPLY+ABORT+DELETE in case where msgid has
1763                  * already been fully closed, ignore the message.
1764                  */
1765                 if (state == NULL) {
1766                         if (msg->any.head.cmd & HAMMER2_MSGF_ABORT) {
1767                                 error = HAMMER2_IOQ_ERROR_EALREADY;
1768                         } else {
1769                                 fprintf(stderr, "no-state(r,d) %s\n",
1770                                         hammer2_msg_str(msg));
1771                                 error = HAMMER2_IOQ_ERROR_TRANS;
1772                         assert(0);
1773                         }
1774                         break;
1775                 }
1776
1777                 /*
1778                  * Received REPLY+ABORT+DELETE in case where msgid has
1779                  * already been reused for an unrelated message,
1780                  * ignore the message.
1781                  */
1782                 if ((state->rxcmd & HAMMER2_MSGF_CREATE) == 0) {
1783                         if (msg->any.head.cmd & HAMMER2_MSGF_ABORT) {
1784                                 error = HAMMER2_IOQ_ERROR_EALREADY;
1785                         } else {
1786                                 fprintf(stderr, "reused-state(r,d) %s\n",
1787                                         hammer2_msg_str(msg));
1788                                 error = HAMMER2_IOQ_ERROR_TRANS;
1789                         assert(0);
1790                         }
1791                         break;
1792                 }
1793                 error = 0;
1794                 break;
1795         case HAMMER2_MSGF_REPLY:
1796                 /*
1797                  * Check for mid-stream ABORT reply received to sent command.
1798                  */
1799                 if (msg->any.head.cmd & HAMMER2_MSGF_ABORT) {
1800                         if (state == NULL ||
1801                             (state->rxcmd & HAMMER2_MSGF_CREATE) == 0) {
1802                                 error = HAMMER2_IOQ_ERROR_EALREADY;
1803                                 break;
1804                         }
1805                 }
1806                 error = 0;
1807                 break;
1808         }
1809         return (error);
1810 }
1811
1812 void
1813 hammer2_state_cleanuprx(hammer2_iocom_t *iocom, hammer2_msg_t *msg)
1814 {
1815         hammer2_state_t *state;
1816
1817         if ((state = msg->state) == NULL) {
1818                 /*
1819                  * Free a non-transactional message, there is no state
1820                  * to worry about.
1821                  */
1822                 hammer2_msg_free(msg);
1823         } else if (msg->any.head.cmd & HAMMER2_MSGF_DELETE) {
1824                 /*
1825                  * Message terminating transaction, destroy the related
1826                  * state, the original message, and this message (if it
1827                  * isn't the original message due to a CREATE|DELETE).
1828                  */
1829                 pthread_mutex_lock(&iocom->mtx);
1830                 state->rxcmd |= HAMMER2_MSGF_DELETE;
1831                 if (state->txcmd & HAMMER2_MSGF_DELETE) {
1832                         if (state->msg == msg)
1833                                 state->msg = NULL;
1834                         assert(state->flags & HAMMER2_STATE_INSERTED);
1835                         if (state->rxcmd & HAMMER2_MSGF_REPLY) {
1836                                 assert(msg->any.head.cmd & HAMMER2_MSGF_REPLY);
1837                                 RB_REMOVE(hammer2_state_tree,
1838                                           &iocom->router->statewr_tree, state);
1839                         } else {
1840                                 assert((msg->any.head.cmd & HAMMER2_MSGF_REPLY) == 0);
1841                                 RB_REMOVE(hammer2_state_tree,
1842                                           &iocom->router->staterd_tree, state);
1843                         }
1844                         state->flags &= ~HAMMER2_STATE_INSERTED;
1845                         hammer2_state_free(state);
1846                 } else {
1847                         ;
1848                 }
1849                 pthread_mutex_unlock(&iocom->mtx);
1850                 hammer2_msg_free(msg);
1851         } else if (state->msg != msg) {
1852                 /*
1853                  * Message not terminating transaction, leave state intact
1854                  * and free message if it isn't the CREATE message.
1855                  */
1856                 hammer2_msg_free(msg);
1857         }
1858 }
1859
1860 static void
1861 hammer2_state_cleanuptx(hammer2_msg_t *msg)
1862 {
1863         hammer2_iocom_t *iocom = msg->router->iocom;
1864         hammer2_state_t *state;
1865
1866         if ((state = msg->state) == NULL) {
1867                 hammer2_msg_free(msg);
1868         } else if (msg->any.head.cmd & HAMMER2_MSGF_DELETE) {
1869                 pthread_mutex_lock(&iocom->mtx);
1870                 state->txcmd |= HAMMER2_MSGF_DELETE;
1871                 if (state->rxcmd & HAMMER2_MSGF_DELETE) {
1872                         if (state->msg == msg)
1873                                 state->msg = NULL;
1874                         assert(state->flags & HAMMER2_STATE_INSERTED);
1875                         if (state->txcmd & HAMMER2_MSGF_REPLY) {
1876                                 assert(msg->any.head.cmd & HAMMER2_MSGF_REPLY);
1877                                 RB_REMOVE(hammer2_state_tree,
1878                                           &iocom->router->staterd_tree, state);
1879                         } else {
1880                                 assert((msg->any.head.cmd & HAMMER2_MSGF_REPLY) == 0);
1881                                 RB_REMOVE(hammer2_state_tree,
1882                                           &iocom->router->statewr_tree, state);
1883                         }
1884                         state->flags &= ~HAMMER2_STATE_INSERTED;
1885                         hammer2_state_free(state);
1886                 } else {
1887                         ;
1888                 }
1889                 pthread_mutex_unlock(&iocom->mtx);
1890                 hammer2_msg_free(msg);
1891         } else if (state->msg != msg) {
1892                 hammer2_msg_free(msg);
1893         }
1894 }
1895
1896 /*
1897  * Called with iocom locked
1898  */
1899 void
1900 hammer2_state_free(hammer2_state_t *state)
1901 {
1902         hammer2_iocom_t *iocom = state->iocom;
1903         hammer2_msg_t *msg;
1904         char dummy;
1905
1906         if (DebugOpt) {
1907                 fprintf(stderr, "terminate state %p id=%08x\n",
1908                         state, (uint32_t)state->msgid);
1909         }
1910         assert(state->any.any == NULL);
1911         msg = state->msg;
1912         state->msg = NULL;
1913         if (msg)
1914                 hammer2_msg_free_locked(msg);
1915         free(state);
1916
1917         /*
1918          * When an iocom error is present we are trying to close down the
1919          * iocom, but we have to wait for all states to terminate before
1920          * we can do so.  The iocom rx code will terminate the receive side
1921          * for all transactions by simulating incoming DELETE messages,
1922          * but the state doesn't go away until both sides are terminated.
1923          *
1924          * We may have to wake up the rx code.
1925          */
1926         if (iocom->ioq_rx.error &&
1927             RB_EMPTY(&iocom->router->staterd_tree) &&
1928             RB_EMPTY(&iocom->router->statewr_tree)) {
1929                 dummy = 0;
1930                 write(iocom->wakeupfds[1], &dummy, 1);
1931         }
1932 }
1933
1934 /************************************************************************
1935  *                              ROUTING                                 *
1936  ************************************************************************
1937  *
1938  * Incoming messages are routed by their spanid, matched up against
1939  * outgoing LNK_SPANs managed by h2span_relay structures (see msg_lnk.c).
1940  * Any replies run through the same router.
1941  *
1942  * Originated messages are routed by their spanid, matched up against
1943  * incoming LNK_SPANs managed by h2span_link structures (see msg_lnk.c).
1944  * Replies come back through the same route.
1945  *
1946  * Keep in mind that ALL MESSAGE TRAFFIC pertaining to a particular
1947  * transaction runs through the same route.  Commands and replies both.
1948  *
1949  * An originated message will use a different routing spanid to
1950  * reach a target node than a message which originates from that node.
1951  * They might use the same physical pipes (each pipe can have multiple
1952  * SPANs and RELAYs), but the routes are distinct from the perspective
1953  * of the router.
1954  */
1955 hammer2_router_t *
1956 hammer2_router_alloc(void)
1957 {
1958         hammer2_router_t *router;
1959
1960         router = hammer2_alloc(sizeof(*router));
1961         TAILQ_INIT(&router->txmsgq);
1962         return (router);
1963 }
1964
1965 void
1966 hammer2_router_connect(hammer2_router_t *router)
1967 {
1968         hammer2_router_t *tmp;
1969
1970         assert(router->link || router->relay);
1971         assert((router->flags & HAMMER2_ROUTER_CONNECTED) == 0);
1972
1973         pthread_mutex_lock(&router_mtx);
1974         if (router->link)
1975                 tmp = RB_INSERT(hammer2_router_tree, &router_ltree, router);
1976         else
1977                 tmp = RB_INSERT(hammer2_router_tree, &router_rtree, router);
1978         assert(tmp == NULL);
1979         router->flags |= HAMMER2_ROUTER_CONNECTED;
1980         pthread_mutex_unlock(&router_mtx);
1981 }
1982
1983 void
1984 hammer2_router_disconnect(hammer2_router_t **routerp)
1985 {
1986         hammer2_router_t *router;
1987
1988         router = *routerp;
1989         assert(router->link || router->relay);
1990         assert(router->flags & HAMMER2_ROUTER_CONNECTED);
1991
1992         pthread_mutex_lock(&router_mtx);
1993         if (router->link)
1994                 RB_REMOVE(hammer2_router_tree, &router_ltree, router);
1995         else
1996                 RB_REMOVE(hammer2_router_tree, &router_rtree, router);
1997         router->flags &= ~HAMMER2_ROUTER_CONNECTED;
1998         *routerp = NULL;
1999         pthread_mutex_unlock(&router_mtx);
2000 }
2001
2002 #if 0
2003 /*
2004  * XXX
2005  */
2006 hammer2_router_t *
2007 hammer2_route_msg(hammer2_msg_t *msg)
2008 {
2009 }
2010 #endif
2011
2012 /************************************************************************
2013  *                              DEBUGGING                               *
2014  ************************************************************************/
2015
2016 const char *
2017 hammer2_basecmd_str(uint32_t cmd)
2018 {
2019         static char buf[64];
2020         char protobuf[32];
2021         char cmdbuf[32];
2022         const char *protostr;
2023         const char *cmdstr;
2024
2025         switch(cmd & HAMMER2_MSGF_PROTOS) {
2026         case HAMMER2_MSG_PROTO_LNK:
2027                 protostr = "LNK_";
2028                 break;
2029         case HAMMER2_MSG_PROTO_DBG:
2030                 protostr = "DBG_";
2031                 break;
2032         case HAMMER2_MSG_PROTO_DOM:
2033                 protostr = "DOM_";
2034                 break;
2035         case HAMMER2_MSG_PROTO_CAC:
2036                 protostr = "CAC_";
2037                 break;
2038         case HAMMER2_MSG_PROTO_QRM:
2039                 protostr = "QRM_";
2040                 break;
2041         case HAMMER2_MSG_PROTO_BLK:
2042                 protostr = "BLK_";
2043                 break;
2044         case HAMMER2_MSG_PROTO_VOP:
2045                 protostr = "VOP_";
2046                 break;
2047         default:
2048                 snprintf(protobuf, sizeof(protobuf), "%x_",
2049                         (cmd & HAMMER2_MSGF_PROTOS) >> 20);
2050                 protostr = protobuf;
2051                 break;
2052         }
2053
2054         switch(cmd & (HAMMER2_MSGF_PROTOS |
2055                       HAMMER2_MSGF_CMDS |
2056                       HAMMER2_MSGF_SIZE)) {
2057         case HAMMER2_LNK_PAD:
2058                 cmdstr = "PAD";
2059                 break;
2060         case HAMMER2_LNK_PING:
2061                 cmdstr = "PING";
2062                 break;
2063         case HAMMER2_LNK_AUTH:
2064                 cmdstr = "AUTH";
2065                 break;
2066         case HAMMER2_LNK_CONN:
2067                 cmdstr = "CONN";
2068                 break;
2069         case HAMMER2_LNK_SPAN:
2070                 cmdstr = "SPAN";
2071                 break;
2072         case HAMMER2_LNK_VOLCONF:
2073                 cmdstr = "VOLCONF";
2074                 break;
2075         case HAMMER2_LNK_ERROR:
2076                 if (cmd & HAMMER2_MSGF_DELETE)
2077                         cmdstr = "RETURN";
2078                 else
2079                         cmdstr = "RESULT";
2080                 break;
2081         case HAMMER2_DBG_SHELL:
2082                 cmdstr = "SHELL";
2083                 break;
2084         default:
2085                 snprintf(cmdbuf, sizeof(cmdbuf),
2086                          "%06x", (cmd & (HAMMER2_MSGF_PROTOS |
2087                                          HAMMER2_MSGF_CMDS |
2088                                          HAMMER2_MSGF_SIZE)));
2089                 cmdstr = cmdbuf;
2090                 break;
2091         }
2092         snprintf(buf, sizeof(buf), "%s%s", protostr, cmdstr);
2093         return (buf);
2094 }
2095
2096 const char *
2097 hammer2_msg_str(hammer2_msg_t *msg)
2098 {
2099         hammer2_state_t *state;
2100         static char buf[256];
2101         char errbuf[16];
2102         char statebuf[64];
2103         char flagbuf[64];
2104         const char *statestr;
2105         const char *errstr;
2106         uint32_t basecmd;
2107         int i;
2108
2109         /*
2110          * Parse the state
2111          */
2112         if ((state = msg->state) != NULL) {
2113                 basecmd = (state->rxcmd & HAMMER2_MSGF_REPLY) ?
2114                           state->txcmd : state->rxcmd;
2115                 snprintf(statebuf, sizeof(statebuf),
2116                          " %s=%s,L=%s%s,R=%s%s",
2117                          ((state->txcmd & HAMMER2_MSGF_REPLY) ?
2118                                 "rcvcmd" : "sndcmd"),
2119                          hammer2_basecmd_str(basecmd),
2120                          ((state->txcmd & HAMMER2_MSGF_CREATE) ? "C" : ""),
2121                          ((state->txcmd & HAMMER2_MSGF_DELETE) ? "D" : ""),
2122                          ((state->rxcmd & HAMMER2_MSGF_CREATE) ? "C" : ""),
2123                          ((state->rxcmd & HAMMER2_MSGF_DELETE) ? "D" : "")
2124                 );
2125                 statestr = statebuf;
2126         } else {
2127                 statestr = "";
2128         }
2129
2130         /*
2131          * Parse the error
2132          */
2133         switch(msg->any.head.error) {
2134         case 0:
2135                 errstr = "";
2136                 break;
2137         case HAMMER2_IOQ_ERROR_SYNC:
2138                 errstr = "err=IOQ:NOSYNC";
2139                 break;
2140         case HAMMER2_IOQ_ERROR_EOF:
2141                 errstr = "err=IOQ:STREAMEOF";
2142                 break;
2143         case HAMMER2_IOQ_ERROR_SOCK:
2144                 errstr = "err=IOQ:SOCKERR";
2145                 break;
2146         case HAMMER2_IOQ_ERROR_FIELD:
2147                 errstr = "err=IOQ:BADFIELD";
2148                 break;
2149         case HAMMER2_IOQ_ERROR_HCRC:
2150                 errstr = "err=IOQ:BADHCRC";
2151                 break;
2152         case HAMMER2_IOQ_ERROR_XCRC:
2153                 errstr = "err=IOQ:BADXCRC";
2154                 break;
2155         case HAMMER2_IOQ_ERROR_ACRC:
2156                 errstr = "err=IOQ:BADACRC";
2157                 break;
2158         case HAMMER2_IOQ_ERROR_STATE:
2159                 errstr = "err=IOQ:BADSTATE";
2160                 break;
2161         case HAMMER2_IOQ_ERROR_NOPEER:
2162                 errstr = "err=IOQ:PEERCONFIG";
2163                 break;
2164         case HAMMER2_IOQ_ERROR_NORKEY:
2165                 errstr = "err=IOQ:BADRKEY";
2166                 break;
2167         case HAMMER2_IOQ_ERROR_NOLKEY:
2168                 errstr = "err=IOQ:BADLKEY";
2169                 break;
2170         case HAMMER2_IOQ_ERROR_KEYXCHGFAIL:
2171                 errstr = "err=IOQ:BADKEYXCHG";
2172                 break;
2173         case HAMMER2_IOQ_ERROR_KEYFMT:
2174                 errstr = "err=IOQ:BADFMT";
2175                 break;
2176         case HAMMER2_IOQ_ERROR_BADURANDOM:
2177                 errstr = "err=IOQ:BADRANDOM";
2178                 break;
2179         case HAMMER2_IOQ_ERROR_MSGSEQ:
2180                 errstr = "err=IOQ:BADSEQ";
2181                 break;
2182         case HAMMER2_IOQ_ERROR_EALREADY:
2183                 errstr = "err=IOQ:DUPMSG";
2184                 break;
2185         case HAMMER2_IOQ_ERROR_TRANS:
2186                 errstr = "err=IOQ:BADTRANS";
2187                 break;
2188         case HAMMER2_IOQ_ERROR_IVWRAP:
2189                 errstr = "err=IOQ:IVWRAP";
2190                 break;
2191         case HAMMER2_IOQ_ERROR_MACFAIL:
2192                 errstr = "err=IOQ:MACFAIL";
2193                 break;
2194         case HAMMER2_IOQ_ERROR_ALGO:
2195                 errstr = "err=IOQ:ALGOFAIL";
2196                 break;
2197         case HAMMER2_MSG_ERR_NOSUPP:
2198                 errstr = "err=NOSUPPORT";
2199                 break;
2200         default:
2201                 snprintf(errbuf, sizeof(errbuf),
2202                          " err=%d", msg->any.head.error);
2203                 errstr = errbuf;
2204                 break;
2205         }
2206
2207         /*
2208          * Message flags
2209          */
2210         i = 0;
2211         if (msg->any.head.cmd & (HAMMER2_MSGF_CREATE | HAMMER2_MSGF_DELETE |
2212                                  HAMMER2_MSGF_ABORT | HAMMER2_MSGF_REPLY)) {
2213                 flagbuf[i++] = '|';
2214                 if (msg->any.head.cmd & HAMMER2_MSGF_CREATE)
2215                         flagbuf[i++] = 'C';
2216                 if (msg->any.head.cmd & HAMMER2_MSGF_DELETE)
2217                         flagbuf[i++] = 'D';
2218                 if (msg->any.head.cmd & HAMMER2_MSGF_REPLY)
2219                         flagbuf[i++] = 'R';
2220                 if (msg->any.head.cmd & HAMMER2_MSGF_ABORT)
2221                         flagbuf[i++] = 'A';
2222         }
2223         flagbuf[i] = 0;
2224
2225         /*
2226          * Generate the buf
2227          */
2228         snprintf(buf, sizeof(buf),
2229                 "msg=%s%s %s id=%08x src=%08x tgt=%08x %s",
2230                  hammer2_basecmd_str(msg->any.head.cmd),
2231                  flagbuf,
2232                  errstr,
2233                  (uint32_t)(intmax_t)msg->any.head.msgid,   /* for brevity */
2234                  (uint32_t)(intmax_t)msg->any.head.source,  /* for brevity */
2235                  (uint32_t)(intmax_t)msg->any.head.target,  /* for brevity */
2236                  statestr);
2237
2238         return(buf);
2239 }