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