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