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