hammer2 - Flesh out span code, API cleanups
[dragonfly.git] / sbin / hammer2 / msg.c
1 /*
2  * Copyright (c) 2011-2012 The DragonFly Project.  All rights reserved.
3  *
4  * This code is derived from software contributed to The DragonFly Project
5  * by Matthew Dillon <dillon@dragonflybsd.org>
6  * by Venkatesh Srinivas <vsrinivas@dragonflybsd.org>
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  *
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in
16  *    the documentation and/or other materials provided with the
17  *    distribution.
18  * 3. Neither the name of The DragonFly Project nor the names of its
19  *    contributors may be used to endorse or promote products derived
20  *    from this software without specific, prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
23  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
24  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
25  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
26  * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
27  * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
28  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
29  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
30  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
31  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
32  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33  * SUCH DAMAGE.
34  */
35
36 #include "hammer2.h"
37
38 static int hammer2_state_msgrx(hammer2_iocom_t *iocom, hammer2_msg_t *msg);
39 static void hammer2_state_cleanuptx(hammer2_iocom_t *iocom, hammer2_msg_t *msg);
40
41 /*
42  * Initialize a low-level ioq
43  */
44 void
45 hammer2_ioq_init(hammer2_iocom_t *iocom __unused, hammer2_ioq_t *ioq)
46 {
47         bzero(ioq, sizeof(*ioq));
48         ioq->state = HAMMER2_MSGQ_STATE_HEADER1;
49         TAILQ_INIT(&ioq->msgq);
50 }
51
52 void
53 hammer2_ioq_done(hammer2_iocom_t *iocom __unused, hammer2_ioq_t *ioq)
54 {
55         hammer2_msg_t *msg;
56
57         while ((msg = TAILQ_FIRST(&ioq->msgq)) != NULL) {
58                 TAILQ_REMOVE(&ioq->msgq, msg, qentry);
59                 hammer2_msg_free(iocom, msg);
60         }
61         if ((msg = ioq->msg) != NULL) {
62                 ioq->msg = NULL;
63                 hammer2_msg_free(iocom, msg);
64         }
65 }
66
67 /*
68  * Initialize a low-level communications channel
69  */
70 void
71 hammer2_iocom_init(hammer2_iocom_t *iocom, int sock_fd, int alt_fd)
72 {
73         bzero(iocom, sizeof(*iocom));
74
75         RB_INIT(&iocom->staterd_tree);
76         RB_INIT(&iocom->statewr_tree);
77         TAILQ_INIT(&iocom->freeq);
78         TAILQ_INIT(&iocom->freeq_aux);
79         TAILQ_INIT(&iocom->addrq);
80         iocom->sock_fd = sock_fd;
81         iocom->alt_fd = alt_fd;
82         iocom->flags = HAMMER2_IOCOMF_RREQ | HAMMER2_IOCOMF_WIDLE;
83         hammer2_ioq_init(iocom, &iocom->ioq_rx);
84         hammer2_ioq_init(iocom, &iocom->ioq_tx);
85
86         /*
87          * Negotiate session crypto synchronously.  This will mark the
88          * connection as error'd if it fails.
89          */
90         hammer2_crypto_negotiate(iocom);
91
92         /*
93          * Make sure our fds are set to non-blocking for the iocom core.
94          */
95         if (sock_fd >= 0)
96                 fcntl(sock_fd, F_SETFL, O_NONBLOCK);
97 #if 0
98         /* if line buffered our single fgets() should be fine */
99         if (alt_fd >= 0)
100                 fcntl(alt_fd, F_SETFL, O_NONBLOCK);
101 #endif
102 }
103
104 void
105 hammer2_iocom_done(hammer2_iocom_t *iocom)
106 {
107         hammer2_msg_t *msg;
108
109         iocom->sock_fd = -1;
110         hammer2_ioq_done(iocom, &iocom->ioq_rx);
111         hammer2_ioq_done(iocom, &iocom->ioq_tx);
112         if ((msg = TAILQ_FIRST(&iocom->freeq)) != NULL) {
113                 TAILQ_REMOVE(&iocom->freeq, msg, qentry);
114                 free(msg);
115         }
116         if ((msg = TAILQ_FIRST(&iocom->freeq_aux)) != NULL) {
117                 TAILQ_REMOVE(&iocom->freeq_aux, msg, qentry);
118                 free(msg->aux_data);
119                 msg->aux_data = NULL;
120                 free(msg);
121         }
122 }
123
124 /*
125  * Allocate a new one-way message.
126  */
127 hammer2_msg_t *
128 hammer2_msg_alloc(hammer2_iocom_t *iocom, size_t aux_size, uint32_t cmd)
129 {
130         hammer2_msg_t *msg;
131         int hbytes;
132
133         if (aux_size) {
134                 aux_size = (aux_size + HAMMER2_MSG_ALIGNMASK) &
135                            ~HAMMER2_MSG_ALIGNMASK;
136                 if ((msg = TAILQ_FIRST(&iocom->freeq_aux)) != NULL)
137                         TAILQ_REMOVE(&iocom->freeq_aux, msg, qentry);
138         } else {
139                 if ((msg = TAILQ_FIRST(&iocom->freeq)) != NULL)
140                         TAILQ_REMOVE(&iocom->freeq, msg, qentry);
141         }
142         if (msg == NULL) {
143                 msg = malloc(sizeof(*msg));
144                 bzero(msg, sizeof(*msg));
145                 msg->aux_data = NULL;
146                 msg->aux_size = 0;
147         }
148         if (msg->aux_size != aux_size) {
149                 if (msg->aux_data) {
150                         free(msg->aux_data);
151                         msg->aux_data = NULL;
152                         msg->aux_size = 0;
153                 }
154                 if (aux_size) {
155                         msg->aux_data = malloc(aux_size);
156                         msg->aux_size = aux_size;
157                 }
158         }
159         hbytes = (cmd & HAMMER2_MSGF_SIZE) * HAMMER2_MSG_ALIGN;
160         if (hbytes)
161                 bzero(&msg->any.head, hbytes);
162         msg->hdr_size = hbytes;
163         msg->any.head.cmd = cmd;
164         msg->any.head.aux_descr = 0;
165         msg->any.head.aux_crc = 0;
166
167         return (msg);
168 }
169
170 /*
171  * Free a message so it can be reused afresh.
172  *
173  * NOTE: aux_size can be 0 with a non-NULL aux_data.
174  */
175 void
176 hammer2_msg_free(hammer2_iocom_t *iocom, hammer2_msg_t *msg)
177 {
178         if (msg->aux_data)
179                 TAILQ_INSERT_TAIL(&iocom->freeq_aux, msg, qentry);
180         else
181                 TAILQ_INSERT_TAIL(&iocom->freeq, msg, qentry);
182 }
183
184 /*
185  * I/O core loop for an iocom.
186  */
187 void
188 hammer2_iocom_core(hammer2_iocom_t *iocom,
189                    void (*recvmsg_func)(hammer2_iocom_t *),
190                    void (*sendmsg_func)(hammer2_iocom_t *),
191                    void (*altmsg_func)(hammer2_iocom_t *))
192 {
193         struct pollfd fds[2];
194         int timeout;
195
196         iocom->recvmsg_callback = recvmsg_func;
197         iocom->sendmsg_callback = sendmsg_func;
198         iocom->altmsg_callback = altmsg_func;
199
200         while ((iocom->flags & HAMMER2_IOCOMF_EOF) == 0) {
201                 timeout = 5000;
202
203                 fds[0].fd = iocom->sock_fd;
204                 fds[0].events = 0;
205                 fds[0].revents = 0;
206
207                 if (iocom->flags & HAMMER2_IOCOMF_RREQ)
208                         fds[0].events |= POLLIN;
209                 else
210                         timeout = 0;
211                 if ((iocom->flags & HAMMER2_IOCOMF_WIDLE) == 0) {
212                         if (iocom->flags & HAMMER2_IOCOMF_WREQ)
213                                 fds[0].events |= POLLOUT;
214                         else
215                                 timeout = 0;
216                 }
217
218                 if (iocom->alt_fd >= 0) {
219                         fds[1].fd = iocom->alt_fd;
220                         fds[1].events |= POLLIN;
221                         fds[1].revents = 0;
222                         poll(fds, 2, timeout);
223                 } else {
224                         poll(fds, 1, timeout);
225                 }
226                 if ((fds[0].revents & POLLIN) ||
227                     (iocom->flags & HAMMER2_IOCOMF_RREQ) == 0) {
228                         iocom->recvmsg_callback(iocom);
229                 }
230                 if ((iocom->flags & HAMMER2_IOCOMF_WIDLE) == 0) {
231                         if ((fds[0].revents & POLLOUT) ||
232                             (iocom->flags & HAMMER2_IOCOMF_WREQ) == 0) {
233                                 iocom->sendmsg_callback(iocom);
234                         }
235                 }
236                 if (iocom->alt_fd >= 0 && (fds[1].revents & POLLIN))
237                         iocom->altmsg_callback(iocom);
238         }
239 }
240
241 /*
242  * Read the next ready message from the ioq, issuing I/O if needed.
243  * Caller should retry on a read-event when NULL is returned.
244  *
245  * If an error occurs during reception a HAMMER2_LNK_ERROR msg will
246  * be returned for each open transaction, then the ioq and iocom
247  * will be errored out and a non-transactional HAMMER2_LNK_ERROR
248  * msg will be returned as the final message.  The caller should not call
249  * us again after the final message is returned.
250  */
251 hammer2_msg_t *
252 hammer2_ioq_read(hammer2_iocom_t *iocom)
253 {
254         hammer2_ioq_t *ioq = &iocom->ioq_rx;
255         hammer2_msg_t *msg;
256         hammer2_msg_hdr_t *head;
257         hammer2_state_t *state;
258         ssize_t n;
259         size_t bytes;
260         size_t nmax;
261         uint32_t xcrc32;
262         int error;
263
264 again:
265         /*
266          * If a message is already pending we can just remove and
267          * return it.  Message state has already been processed.
268          */
269         if ((msg = TAILQ_FIRST(&ioq->msgq)) != NULL) {
270                 TAILQ_REMOVE(&ioq->msgq, msg, qentry);
271                 return (msg);
272         }
273
274         /*
275          * Message read in-progress (msg is NULL at the moment).  We don't
276          * allocate a msg until we have its core header.
277          */
278         bytes = ioq->fifo_end - ioq->fifo_beg;
279         nmax = sizeof(ioq->buf) - ioq->fifo_end;
280         msg = ioq->msg;
281
282         switch(ioq->state) {
283         case HAMMER2_MSGQ_STATE_HEADER1:
284                 /*
285                  * Load the primary header, fail on any non-trivial read
286                  * error or on EOF.  Since the primary header is the same
287                  * size is the message alignment it will never straddle
288                  * the end of the buffer.
289                  */
290                 if (bytes < (int)sizeof(msg->any.head)) {
291                         n = read(iocom->sock_fd,
292                                  ioq->buf + ioq->fifo_end,
293                                  nmax);
294                         if (n <= 0) {
295                                 if (n == 0) {
296                                         ioq->error = HAMMER2_IOQ_ERROR_EOF;
297                                         break;
298                                 }
299                                 if (errno != EINTR &&
300                                     errno != EINPROGRESS &&
301                                     errno != EAGAIN) {
302                                         ioq->error = HAMMER2_IOQ_ERROR_SOCK;
303                                         break;
304                                 }
305                                 n = 0;
306                                 /* fall through */
307                         }
308                         ioq->fifo_end += n;
309                         bytes += n;
310                         nmax -= n;
311                 }
312
313                 /*
314                  * Insufficient data accumulated (msg is NULL, caller will
315                  * retry on event).
316                  */
317                 assert(msg == NULL);
318                 if (bytes < (int)sizeof(msg->any.head))
319                         break;
320
321                 /*
322                  * Calculate the header, decrypt data received so far.
323                  * Data will be decrypted in-place.  Partial blocks are
324                  * not immediately decrypted.
325                  *
326                  * WARNING!  The header might be in the wrong endian, we
327                  *           do not fix it up until we get the entire
328                  *           extended header.
329                  */
330                 hammer2_crypto_decrypt(iocom, ioq);
331                 head = (void *)(ioq->buf + ioq->fifo_beg);
332
333                 /*
334                  * Check and fixup the core header.  Note that the icrc
335                  * has to be calculated before any fixups, but the crc
336                  * fields in the msg may have to be swapped like everything
337                  * else.
338                  */
339                 if (head->magic != HAMMER2_MSGHDR_MAGIC &&
340                     head->magic != HAMMER2_MSGHDR_MAGIC_REV) {
341                         ioq->error = HAMMER2_IOQ_ERROR_SYNC;
342                         break;
343                 }
344
345                 /*
346                  * Calculate the full header size and aux data size
347                  */
348                 if (head->magic == HAMMER2_MSGHDR_MAGIC_REV) {
349                         ioq->hbytes = (bswap32(head->cmd) & HAMMER2_MSGF_SIZE) *
350                                       HAMMER2_MSG_ALIGN;
351                         ioq->abytes = bswap32(head->aux_bytes) *
352                                       HAMMER2_MSG_ALIGN;
353                 } else {
354                         ioq->hbytes = (head->cmd & HAMMER2_MSGF_SIZE) *
355                                       HAMMER2_MSG_ALIGN;
356                         ioq->abytes = head->aux_bytes * HAMMER2_MSG_ALIGN;
357                 }
358                 if (ioq->hbytes < sizeof(msg->any.head) ||
359                     ioq->hbytes > sizeof(msg->any) ||
360                     ioq->abytes > HAMMER2_MSGAUX_MAX) {
361                         ioq->error = HAMMER2_IOQ_ERROR_FIELD;
362                         break;
363                 }
364
365                 /*
366                  * Finally allocate the message and copy the core header
367                  * to the embedded extended header.
368                  *
369                  * Initialize msg->aux_size to 0 and use it to track
370                  * the amount of data copied from the stream.
371                  */
372                 msg = hammer2_msg_alloc(iocom, ioq->abytes, 0);
373                 ioq->msg = msg;
374
375                 /*
376                  * We are either done or we fall-through
377                  */
378                 if (ioq->hbytes == sizeof(msg->any.head) && ioq->abytes == 0) {
379                         bcopy(head, &msg->any.head, sizeof(msg->any.head));
380                         ioq->fifo_beg += ioq->hbytes;
381                         break;
382                 }
383
384                 /*
385                  * Fall through to the next state.  Make sure that the
386                  * extended header does not straddle the end of the buffer.
387                  * We still want to issue larger reads into our buffer,
388                  * book-keeping is easier if we don't bcopy() yet.
389                  */
390                 if (bytes + nmax < ioq->hbytes) {
391                         bcopy(ioq->buf + ioq->fifo_beg, ioq->buf, bytes);
392                         ioq->fifo_cdx -= ioq->fifo_beg;
393                         ioq->fifo_beg = 0;
394                         ioq->fifo_end = bytes;
395                         nmax = sizeof(ioq->buf) - ioq->fifo_end;
396                 }
397                 ioq->state = HAMMER2_MSGQ_STATE_HEADER2;
398                 /* fall through */
399         case HAMMER2_MSGQ_STATE_HEADER2:
400                 /*
401                  * Fill out the extended header.
402                  */
403                 assert(msg != NULL);
404                 if (bytes < ioq->hbytes) {
405                         n = read(iocom->sock_fd,
406                                  msg->any.buf + ioq->fifo_end,
407                                  nmax);
408                         if (n <= 0) {
409                                 if (n == 0) {
410                                         ioq->error = HAMMER2_IOQ_ERROR_EOF;
411                                         break;
412                                 }
413                                 if (errno != EINTR &&
414                                     errno != EINPROGRESS &&
415                                     errno != EAGAIN) {
416                                         ioq->error = HAMMER2_IOQ_ERROR_SOCK;
417                                         break;
418                                 }
419                                 n = 0;
420                                 /* fall through */
421                         }
422                         ioq->fifo_end += n;
423                         bytes += n;
424                         nmax -= n;
425                 }
426
427                 /*
428                  * Insufficient data accumulated (set msg NULL so caller will
429                  * retry on event).
430                  */
431                 if (bytes < ioq->hbytes) {
432                         msg = NULL;
433                         break;
434                 }
435
436                 /*
437                  * Calculate the extended header, decrypt data received
438                  * so far.  Handle endian-conversion for the entire extended
439                  * header.
440                  */
441                 hammer2_crypto_decrypt(iocom, ioq);
442                 head = (void *)(ioq->buf + ioq->fifo_beg);
443
444                 /*
445                  * Check the CRC.
446                  */
447                 if (head->magic == HAMMER2_MSGHDR_MAGIC_REV)
448                         xcrc32 = bswap32(head->hdr_crc);
449                 else
450                         xcrc32 = head->hdr_crc;
451                 head->hdr_crc = 0;
452                 if (hammer2_icrc32(head, ioq->hbytes) != xcrc32) {
453                         ioq->error = HAMMER2_IOQ_ERROR_XCRC;
454                         break;
455                 }
456                 head->hdr_crc = xcrc32;
457
458                 if (head->magic == HAMMER2_MSGHDR_MAGIC_REV) {
459                         hammer2_bswap_head(head);
460                 }
461
462                 /*
463                  * Copy the extended header into the msg and adjust the
464                  * FIFO.
465                  */
466                 bcopy(head, &msg->any, ioq->hbytes);
467
468                 /*
469                  * We are either done or we fall-through.
470                  */
471                 if (ioq->abytes == 0) {
472                         ioq->fifo_beg += ioq->hbytes;
473                         break;
474                 }
475
476                 /*
477                  * Must adjust nmax and bytes (and the state) when falling
478                  * through.
479                  */
480                 ioq->fifo_beg += ioq->hbytes;
481                 nmax -= ioq->hbytes;
482                 bytes -= ioq->hbytes;
483                 ioq->state = HAMMER2_MSGQ_STATE_AUXDATA1;
484                 /* fall through */
485         case HAMMER2_MSGQ_STATE_AUXDATA1:
486                 /*
487                  * Copy the partial or complete payload from remaining
488                  * bytes in the FIFO.  We have to fall-through either
489                  * way so we can check the crc.
490                  *
491                  * Adjust msg->aux_size to the final actual value.
492                  */
493                 ioq->already = ioq->fifo_cdx - ioq->fifo_beg;
494                 if (ioq->already > ioq->abytes)
495                         ioq->already = ioq->abytes;
496                 if (bytes >= ioq->abytes) {
497                         bcopy(ioq->buf + ioq->fifo_beg, msg->aux_data,
498                               ioq->abytes);
499                         msg->aux_size = ioq->abytes;
500                         ioq->fifo_beg += ioq->abytes;
501                         if (ioq->fifo_cdx < ioq->fifo_beg)
502                                 ioq->fifo_cdx = ioq->fifo_beg;
503                         bytes -= ioq->abytes;
504                 } else if (bytes) {
505                         bcopy(ioq->buf + ioq->fifo_beg, msg->aux_data,
506                               bytes);
507                         msg->aux_size = bytes;
508                         ioq->fifo_beg += bytes;
509                         if (ioq->fifo_cdx < ioq->fifo_beg)
510                                 ioq->fifo_cdx = ioq->fifo_beg;
511                         bytes = 0;
512                 } else {
513                         msg->aux_size = 0;
514                 }
515                 ioq->state = HAMMER2_MSGQ_STATE_AUXDATA2;
516                 /* fall through */
517         case HAMMER2_MSGQ_STATE_AUXDATA2:
518                 /*
519                  * Read the remainder of the payload directly into the
520                  * msg->aux_data buffer.
521                  */
522                 assert(msg);
523                 if (msg->aux_size < ioq->abytes) {
524                         assert(bytes == 0);
525                         n = read(iocom->sock_fd,
526                                  msg->aux_data + msg->aux_size,
527                                  ioq->abytes - msg->aux_size);
528                         if (n <= 0) {
529                                 if (n == 0) {
530                                         ioq->error = HAMMER2_IOQ_ERROR_EOF;
531                                         break;
532                                 }
533                                 if (errno != EINTR &&
534                                     errno != EINPROGRESS &&
535                                     errno != EAGAIN) {
536                                         ioq->error = HAMMER2_IOQ_ERROR_SOCK;
537                                         break;
538                                 }
539                                 n = 0;
540                                 /* fall through */
541                         }
542                         msg->aux_size += n;
543                 }
544
545                 /*
546                  * Insufficient data accumulated (set msg NULL so caller will
547                  * retry on event).
548                  */
549                 if (msg->aux_size < ioq->abytes) {
550                         msg = NULL;
551                         break;
552                 }
553                 assert(msg->aux_size == ioq->abytes);
554                 hammer2_crypto_decrypt_aux(iocom, ioq, msg, ioq->already);
555
556                 /*
557                  * Check aux_crc, then we are done.
558                  */
559                 xcrc32 = hammer2_icrc32(msg->aux_data, msg->aux_size);
560                 if (xcrc32 != msg->any.head.aux_crc) {
561                         ioq->error = HAMMER2_IOQ_ERROR_ACRC;
562                         break;
563                 }
564                 break;
565         case HAMMER2_MSGQ_STATE_ERROR:
566                 /*
567                  * Continued calls to drain recorded transactions (returning
568                  * a LNK_ERROR for each one), before we return the final
569                  * LNK_ERROR.
570                  */
571                 assert(msg == NULL);
572                 break;
573         default:
574                 /*
575                  * We don't double-return errors, the caller should not
576                  * have called us again after getting an error msg.
577                  */
578                 assert(0);
579                 break;
580         }
581
582         /*
583          * Check the message sequence.  The iv[] should prevent any
584          * possibility of a replay but we add this check anyway.
585          */
586         if (msg && ioq->error == 0) {
587                 if ((msg->any.head.salt & 255) != (ioq->seq & 255)) {
588                         ioq->error = HAMMER2_IOQ_ERROR_MSGSEQ;
589                 } else {
590                         ++ioq->seq;
591                 }
592         }
593
594         /*
595          * Process transactional state for the message.
596          */
597         if (msg && ioq->error == 0) {
598                 error = hammer2_state_msgrx(iocom, msg);
599                 if (error) {
600                         if (error == HAMMER2_IOQ_ERROR_EALREADY) {
601                                 hammer2_msg_free(iocom, msg);
602                                 goto again;
603                         }
604                         ioq->error = error;
605                 }
606         }
607
608         /*
609          * Handle error, RREQ, or completion
610          *
611          * NOTE: nmax and bytes are invalid at this point, we don't bother
612          *       to update them when breaking out.
613          */
614         if (ioq->error) {
615                 /*
616                  * An unrecoverable error causes all active receive
617                  * transactions to be terminated with a LNK_ERROR message.
618                  *
619                  * Once all active transactions are exhausted we set the
620                  * iocom ERROR flag and return a non-transactional LNK_ERROR
621                  * message, which should cause master processing loops to
622                  * terminate.
623                  */
624                 assert(ioq->msg == msg);
625                 if (msg) {
626                         hammer2_msg_free(iocom, msg);
627                         ioq->msg = NULL;
628                 }
629
630                 /*
631                  * No more I/O read processing
632                  */
633                 ioq->state = HAMMER2_MSGQ_STATE_ERROR;
634
635                 /*
636                  * Return LNK_ERROR for any open transaction, and finally
637                  * as a non-transactional message when no transactions are
638                  * left.
639                  */
640                 msg = hammer2_msg_alloc(iocom, 0, 0);
641                 bzero(&msg->any.head, sizeof(msg->any.head));
642                 msg->any.head.magic = HAMMER2_MSGHDR_MAGIC;
643                 msg->any.head.cmd = HAMMER2_LNK_ERROR;
644                 msg->any.head.error = ioq->error;
645
646                 if ((state = RB_ROOT(&iocom->staterd_tree)) != NULL) {
647                         /*
648                          * Active transactions are still present.  Simulate
649                          * the other end sending us a DELETE.
650                          */
651                         state->txcmd |= HAMMER2_MSGF_DELETE;
652                         msg->state = state;
653                         msg->any.head.spanid = state->spanid;
654                         msg->any.head.cmd |= HAMMER2_MSGF_ABORT |
655                                              HAMMER2_MSGF_DELETE;
656                 } else {
657                         /*
658                          * No active transactions remain
659                          */
660                         msg->state = NULL;
661                         iocom->flags |= HAMMER2_IOCOMF_EOF;
662                 }
663         } else if (msg == NULL) {
664                 /*
665                  * Insufficient data received to finish building the message,
666                  * set RREQ and return NULL.
667                  *
668                  * Leave ioq->msg intact.
669                  * Leave the FIFO intact.
670                  */
671                 iocom->flags |= HAMMER2_IOCOMF_RREQ;
672 #if 0
673                 ioq->fifo_cdx = 0;
674                 ioq->fifo_beg = 0;
675                 ioq->fifo_end = 0;
676 #endif
677         } else {
678                 /*
679                  * Return msg, clear the FIFO if it is now empty.
680                  * Flag RREQ if the caller needs to wait for a read-event
681                  * or not.
682                  *
683                  * The fifo has already been advanced past the message.
684                  * Trivially reset the FIFO indices if possible.
685                  */
686                 if (ioq->fifo_beg == ioq->fifo_end) {
687                         iocom->flags |= HAMMER2_IOCOMF_RREQ;
688                         ioq->fifo_cdx = 0;
689                         ioq->fifo_beg = 0;
690                         ioq->fifo_end = 0;
691                 } else {
692                         iocom->flags &= ~HAMMER2_IOCOMF_RREQ;
693                 }
694                 ioq->state = HAMMER2_MSGQ_STATE_HEADER1;
695                 ioq->msg = NULL;
696         }
697         return (msg);
698 }
699
700 /*
701  * Calculate the header and data crc's and write a low-level message to
702  * the connection.  If aux_crc is non-zero the aux_data crc is already
703  * assumed to have been set.
704  *
705  * A non-NULL msg is added to the queue but not necessarily flushed.
706  * Calling this function with msg == NULL will get a flush going.
707  */
708 static void
709 hammer2_ioq_write(hammer2_iocom_t *iocom, hammer2_msg_t *msg)
710 {
711         hammer2_ioq_t *ioq = &iocom->ioq_tx;
712         uint32_t xcrc32;
713         int hbytes;
714
715         assert(msg);
716
717         /*
718          * Process terminal connection errors.
719          */
720         if (ioq->error) {
721                 TAILQ_INSERT_TAIL(&ioq->msgq, msg, qentry);
722                 ++ioq->msgcount;
723                 hammer2_iocom_drain(iocom);
724                 return;
725         }
726
727         /*
728          * Finish populating the msg fields.  The salt ensures that the iv[]
729          * array is ridiculously randomized and we also re-seed our PRNG
730          * every 32768 messages just to be sure.
731          */
732         msg->any.head.magic = HAMMER2_MSGHDR_MAGIC;
733         msg->any.head.salt = (random() << 8) | (ioq->seq & 255);
734         ++ioq->seq;
735         if ((ioq->seq & 32767) == 0)
736                 srandomdev();
737
738         /*
739          * Calculate aux_crc if 0, then calculate hdr_crc.
740          */
741         if (msg->aux_size && msg->any.head.aux_crc == 0) {
742                 assert((msg->aux_size & HAMMER2_MSG_ALIGNMASK) == 0);
743                 xcrc32 = hammer2_icrc32(msg->aux_data, msg->aux_size);
744                 msg->any.head.aux_crc = xcrc32;
745         }
746         msg->any.head.aux_bytes = msg->aux_size / HAMMER2_MSG_ALIGN;
747         assert((msg->aux_size & HAMMER2_MSG_ALIGNMASK) == 0);
748
749         hbytes = (msg->any.head.cmd & HAMMER2_MSGF_SIZE) * HAMMER2_MSG_ALIGN;
750         msg->any.head.hdr_crc = 0;
751         msg->any.head.hdr_crc = hammer2_icrc32(&msg->any.head, hbytes);
752
753         /*
754          * Enqueue the message (the flush codes handles stream encryption).
755          */
756         TAILQ_INSERT_TAIL(&ioq->msgq, msg, qentry);
757         ++ioq->msgcount;
758         iocom->flags &= ~HAMMER2_IOCOMF_WIDLE;
759
760         /*
761          * Flush if we know we can write (WREQ not set) and if
762          * sufficient messages have accumulated.  Otherwise hold
763          * off to avoid piecemeal system calls.
764          */
765         if (iocom->flags & HAMMER2_IOCOMF_WREQ)
766                 return;
767         if (ioq->msgcount < HAMMER2_IOQ_MAXIOVEC / 2)
768                 return;
769         hammer2_iocom_flush(iocom);
770 }
771
772 void
773 hammer2_iocom_flush(hammer2_iocom_t *iocom)
774 {
775         hammer2_ioq_t *ioq = &iocom->ioq_tx;
776         hammer2_msg_t *msg;
777         ssize_t nmax;
778         ssize_t nact;
779         struct iovec iov[HAMMER2_IOQ_MAXIOVEC];
780         size_t hbytes;
781         size_t abytes;
782         int hoff;
783         int aoff;
784         int n;
785
786         /*
787          * Pump messages out the connection by building an iovec.
788          */
789         n = 0;
790         nmax = 0;
791
792         TAILQ_FOREACH(msg, &ioq->msgq, qentry) {
793                 hoff = 0;
794                 hbytes = (msg->any.head.cmd & HAMMER2_MSGF_SIZE) *
795                          HAMMER2_MSG_ALIGN;
796                 aoff = 0;
797                 abytes = msg->aux_size;
798                 if (n == 0) {
799                         hoff += ioq->hbytes;
800                         aoff += ioq->abytes;
801                 }
802                 if (hbytes - hoff > 0) {
803                         iov[n].iov_base = (char *)&msg->any.head + hoff;
804                         iov[n].iov_len = hbytes - hoff;
805                         nmax += hbytes - hoff;
806                         ++n;
807                         if (n == HAMMER2_IOQ_MAXIOVEC)
808                                 break;
809                 }
810                 if (abytes - aoff > 0) {
811                         assert(msg->aux_data != NULL);
812                         iov[n].iov_base = msg->aux_data + aoff;
813                         iov[n].iov_len = abytes - aoff;
814                         nmax += abytes - aoff;
815                         ++n;
816                         if (n == HAMMER2_IOQ_MAXIOVEC)
817                                 break;
818                 }
819         }
820         if (n == 0)
821                 return;
822
823         /*
824          * Encrypt and write the data.  The crypto code will move the
825          * data into the fifo and adjust the iov as necessary.  If
826          * encryption is disabled the iov is left alone.
827          *
828          * hammer2_crypto_encrypt_wrote()
829          */
830         n = hammer2_crypto_encrypt(iocom, ioq, iov, n);
831
832         /*
833          * Execute the writev() then figure out what happened.
834          */
835         nact = writev(iocom->sock_fd, iov, n);
836         if (nact < 0) {
837                 if (errno != EINTR &&
838                     errno != EINPROGRESS &&
839                     errno != EAGAIN) {
840                         ioq->error = HAMMER2_IOQ_ERROR_SOCK;
841                         hammer2_iocom_drain(iocom);
842                 } else {
843                         iocom->flags |= HAMMER2_IOCOMF_WREQ;
844                 }
845                 return;
846         }
847         hammer2_crypto_encrypt_wrote(iocom, ioq, nact);
848         if (nact == nmax)
849                 iocom->flags &= ~HAMMER2_IOCOMF_WREQ;
850         else
851                 iocom->flags |= HAMMER2_IOCOMF_WREQ;
852
853         while ((msg = TAILQ_FIRST(&ioq->msgq)) != NULL) {
854                 hbytes = (msg->any.head.cmd & HAMMER2_MSGF_SIZE) *
855                          HAMMER2_MSG_ALIGN;
856                 abytes = msg->aux_size;
857
858                 if ((size_t)nact < hbytes - ioq->hbytes) {
859                         ioq->hbytes += nact;
860                         break;
861                 }
862                 nact -= hbytes - ioq->hbytes;
863                 ioq->hbytes = hbytes;
864                 if ((size_t)nact < abytes - ioq->abytes) {
865                         ioq->abytes += nact;
866                         break;
867                 }
868                 nact -= abytes - ioq->abytes;
869
870                 TAILQ_REMOVE(&ioq->msgq, msg, qentry);
871                 --ioq->msgcount;
872                 ioq->hbytes = 0;
873                 ioq->abytes = 0;
874
875                 hammer2_state_cleanuptx(iocom, msg);
876         }
877         if (msg == NULL) {
878                 iocom->flags |= HAMMER2_IOCOMF_WIDLE;
879                 iocom->flags &= ~HAMMER2_IOCOMF_WREQ;
880         }
881         if (ioq->error) {
882                 iocom->flags |= HAMMER2_IOCOMF_EOF |
883                                 HAMMER2_IOCOMF_WIDLE;
884                 iocom->flags &= ~HAMMER2_IOCOMF_WREQ;
885         }
886 }
887
888 /*
889  * Kill pending msgs on ioq_tx and adjust the flags such that no more
890  * write events will occur.  We don't kill read msgs because we want
891  * the caller to pull off our contrived terminal error msg to detect
892  * the connection failure.
893  */
894 void
895 hammer2_iocom_drain(hammer2_iocom_t *iocom)
896 {
897         hammer2_ioq_t *ioq = &iocom->ioq_tx;
898         hammer2_msg_t *msg;
899
900         while ((msg = TAILQ_FIRST(&ioq->msgq)) != NULL) {
901                 TAILQ_REMOVE(&ioq->msgq, msg, qentry);
902                 --ioq->msgcount;
903                 hammer2_msg_free(iocom, msg);
904         }
905         iocom->flags |= HAMMER2_IOCOMF_WIDLE;
906         iocom->flags &= ~HAMMER2_IOCOMF_WREQ;
907 }
908
909 /*
910  * Write a message to an iocom, with additional state processing.
911  *
912  * The iocom lock must be held by the caller. XXX
913  */
914 void
915 hammer2_msg_write(hammer2_iocom_t *iocom, hammer2_msg_t *msg,
916                   void (*func)(hammer2_state_t *, hammer2_msg_t *),
917                   void *data)
918 {
919         hammer2_state_t *state;
920
921         /*
922          * Handle state processing, create state if necessary.
923          */
924         if ((state = msg->state) != NULL) {
925                 /*
926                  * Existing transaction (could be reply).  It is also
927                  * possible for this to be the first reply (CREATE is set),
928                  * in which case we populate state->txcmd.
929                  */
930                 msg->any.head.msgid = state->msgid;
931                 msg->any.head.spanid = state->spanid;
932                 if (func) {
933                         state->func = func;
934                         state->any.any = data;
935                 }
936                 if (msg->any.head.cmd & HAMMER2_MSGF_CREATE)
937                         state->txcmd = msg->any.head.cmd & ~HAMMER2_MSGF_DELETE;
938                 fprintf(stderr, "MSGWRITE IN REPLY msgid %016jx\n",
939                         (intmax_t)msg->any.head.msgid);
940         } else if (msg->any.head.cmd & HAMMER2_MSGF_CREATE) {
941                 fprintf(stderr, "MSGWRITE NEW MSG\n");
942                 /*
943                  * No existing state and CREATE is set, create new
944                  * state for outgoing command.  This can't happen if
945                  * REPLY is set as the state would already exist for
946                  * a transaction reply.
947                  */
948                 assert((msg->any.head.cmd & HAMMER2_MSGF_REPLY) == 0);
949
950                 state = malloc(sizeof(*state));
951                 bzero(state, sizeof(*state));
952                 state->iocom = iocom;
953                 state->flags = HAMMER2_STATE_DYNAMIC;
954                 state->msg = msg;
955                 state->msgid = (uint64_t)(uintptr_t)state;
956                 state->spanid = msg->any.head.spanid;
957                 state->txcmd = msg->any.head.cmd & ~HAMMER2_MSGF_DELETE;
958                 state->func = func;
959                 state->any.any = data;
960                 RB_INSERT(hammer2_state_tree, &iocom->statewr_tree, state);
961                 state->flags |= HAMMER2_STATE_INSERTED;
962                 msg->state = state;
963                 msg->any.head.msgid = state->msgid;
964                 /* spanid set by caller */
965         } else {
966                 fprintf(stderr, "MSGWRITE ONE-OFF\n");
967                 msg->any.head.msgid = 0;
968                 /* spanid set by caller */
969         }
970
971         /*
972          * Queue it for output
973          */
974         hammer2_ioq_write(iocom, msg);
975 }
976
977 #if 0
978
979         case HAMMER2_MSGF_DELETE:
980                 /*
981                  * Sent ABORT+DELETE in case where msgid has already
982                  * been fully closed, ignore the message.
983                  */
984                 if (state == NULL) {
985                         if (msg->any.head.cmd & HAMMER2_MSGF_ABORT) {
986                                 error = HAMMER2_IOQ_ERROR_EALREADY;
987                         } else {
988                                 iocom_printf(iocom, msg->any.head.cmd,
989                                              "hammer2_state_msgtx: "
990                                              "no state match for DELETE\n");
991                                 error = HAMMER2_IOQ_ERROR_TRANS;
992                         }
993                         break;
994                 }
995
996                 /*
997                  * Sent ABORT+DELETE in case where msgid has
998                  * already been reused for an unrelated message,
999                  * ignore the message.
1000                  */
1001                 if ((state->txcmd & HAMMER2_MSGF_CREATE) == 0) {
1002                         if (msg->any.head.cmd & HAMMER2_MSGF_ABORT) {
1003                                 error = HAMMER2_IOQ_ERROR_EALREADY;
1004                         } else {
1005                                 iocom_printf(iocom, msg->any.head.cmd,
1006                                              "hammer2_state_msgtx: "
1007                                              "state reused for DELETE\n");
1008                                 error = HAMMER2_IOQ_ERROR_TRANS;
1009                         }
1010                         break;
1011                 }
1012                 error = 0;
1013
1014
1015         case HAMMER2_MSGF_REPLY | HAMMER2_MSGF_DELETE:
1016                 /*
1017                  * When transmitting a reply with DELETE set the original
1018                  * persistent state message should already exist.
1019                  *
1020                  * This is very similar to the REPLY|CREATE|* case except
1021                  * txcmd is already stored, so we just add the DELETE flag.
1022                  *
1023                  * Sent REPLY+ABORT+DELETE in case where msgid has
1024                  * already been fully closed, ignore the message.
1025                  */
1026                 if (state == NULL) {
1027                         if (msg->any.head.cmd & HAMMER2_MSGF_ABORT) {
1028                                 error = HAMMER2_IOQ_ERROR_EALREADY;
1029                         } else {
1030                                 iocom_printf(iocom, msg->any.head.cmd,
1031                                              "hammer2_state_msgtx: "
1032                                              "no state match for "
1033                                              "REPLY | DELETE\n");
1034                                 error = HAMMER2_IOQ_ERROR_TRANS;
1035                         }
1036                         break;
1037                 }
1038
1039                 /*
1040                  * Sent REPLY+ABORT+DELETE in case where msgid has already
1041                  * been reused for an unrelated message, ignore the message.
1042                  */
1043                 if ((state->txcmd & HAMMER2_MSGF_CREATE) == 0) {
1044                         if (msg->any.head.cmd & HAMMER2_MSGF_ABORT) {
1045                                 error = HAMMER2_IOQ_ERROR_EALREADY;
1046                         } else {
1047                                 iocom_printf(iocom, msg->any.head.cmd,
1048                                              "hammer2_state_msgtx: "
1049                                              "state reused for "
1050                                              "REPLY | DELETE\n");
1051                                 error = HAMMER2_IOQ_ERROR_TRANS;
1052                         }
1053                         break;
1054                 }
1055                 error = 0;
1056                 break;
1057         case HAMMER2_MSGF_REPLY:
1058                 /*
1059                  * Check for mid-stream ABORT reply sent.
1060                  *
1061                  * One-off REPLY messages are allowed for e.g. status updates.
1062                  */
1063                 if (msg->any.head.cmd & HAMMER2_MSGF_ABORT) {
1064                         if (state == NULL ||
1065                             (state->txcmd & HAMMER2_MSGF_CREATE) == 0) {
1066                                 error = HAMMER2_IOQ_ERROR_EALREADY;
1067                                 break;
1068                         }
1069                 }
1070                 error = 0;
1071                 break;
1072         }
1073         /*lockmgr(&pmp->msglk, LK_RELEASE);*/
1074         return (error);
1075 #endif
1076
1077
1078 /*
1079  * This is a shortcut to formulate a reply to msg with a simple error code,
1080  * It can reply to and terminate a transaction, or it can reply to a one-way
1081  * messages.  A HAMMER2_LNK_ERROR command code is utilized to encode
1082  * the error code (which can be 0).  Not all transactions are terminated
1083  * with HAMMER2_LNK_ERROR status (the low level only cares about the
1084  * MSGF_DELETE flag), but most are.
1085  *
1086  * Replies to one-way messages are a bit of an oxymoron but the feature
1087  * is used by the debug (DBG) protocol.
1088  *
1089  * The reply contains no extended data.
1090  */
1091 void
1092 hammer2_msg_reply(hammer2_iocom_t *iocom, hammer2_msg_t *msg, uint32_t error)
1093 {
1094         hammer2_state_t *state = msg->state;
1095         hammer2_msg_t *nmsg;
1096         uint32_t cmd;
1097
1098
1099         /*
1100          * Reply with a simple error code and terminate the transaction.
1101          */
1102         cmd = HAMMER2_LNK_ERROR;
1103
1104         /*
1105          * Check if our direction has even been initiated yet, set CREATE.
1106          *
1107          * Check what direction this is (command or reply direction).  Note
1108          * that txcmd might not have been initiated yet.
1109          *
1110          * If our direction has already been closed we just return without
1111          * doing anything.
1112          */
1113         if (state) {
1114                 if (state->txcmd & HAMMER2_MSGF_DELETE)
1115                         return;
1116                 if ((state->txcmd & HAMMER2_MSGF_CREATE) == 0)
1117                         cmd |= HAMMER2_MSGF_CREATE;
1118                 if ((state->rxcmd & HAMMER2_MSGF_REPLY) == 0)
1119                         cmd |= HAMMER2_MSGF_REPLY;
1120                 cmd |= HAMMER2_MSGF_DELETE;
1121         } else {
1122                 if ((msg->any.head.cmd & HAMMER2_MSGF_REPLY) == 0)
1123                         cmd |= HAMMER2_MSGF_REPLY;
1124         }
1125
1126         nmsg = hammer2_msg_alloc(iocom, 0, cmd);
1127         nmsg->any.head.error = error;
1128         nmsg->state = msg->state;
1129         hammer2_msg_write(iocom, nmsg, NULL, 0);
1130 }
1131
1132 /*
1133  * Similar to hammer2_msg_reply() but leave the transaction open.  That is,
1134  * we are generating a streaming reply or an intermediate acknowledgement
1135  * of some sort as part of the higher level protocol, with more to come
1136  * later.
1137  */
1138 void
1139 hammer2_msg_result(hammer2_iocom_t *iocom, hammer2_msg_t *msg, uint32_t error)
1140 {
1141         hammer2_state_t *state = msg->state;
1142         hammer2_msg_t *nmsg;
1143         uint32_t cmd;
1144
1145
1146         /*
1147          * Reply with a simple error code and terminate the transaction.
1148          */
1149         cmd = HAMMER2_LNK_ERROR;
1150
1151         /*
1152          * Check if our direction has even been initiated yet, set CREATE.
1153          *
1154          * Check what direction this is (command or reply direction).  Note
1155          * that txcmd might not have been initiated yet.
1156          *
1157          * If our direction has already been closed we just return without
1158          * doing anything.
1159          */
1160         if (state) {
1161                 if (state->txcmd & HAMMER2_MSGF_DELETE)
1162                         return;
1163                 if ((state->txcmd & HAMMER2_MSGF_CREATE) == 0)
1164                         cmd |= HAMMER2_MSGF_CREATE;
1165                 if ((state->rxcmd & HAMMER2_MSGF_REPLY) == 0)
1166                         cmd |= HAMMER2_MSGF_REPLY;
1167                 /* continuing transaction, do not set MSGF_DELETE */
1168         } else {
1169                 if ((msg->any.head.cmd & HAMMER2_MSGF_REPLY) == 0)
1170                         cmd |= HAMMER2_MSGF_REPLY;
1171         }
1172
1173         nmsg = hammer2_msg_alloc(iocom, 0, cmd);
1174         nmsg->any.head.error = error;
1175         nmsg->state = state;
1176         hammer2_msg_write(iocom, nmsg, NULL, 0);
1177 }
1178
1179 /*
1180  * Terminate a transaction given a state structure by issuing a DELETE.
1181  */
1182 void
1183 hammer2_state_reply(hammer2_state_t *state, uint32_t error)
1184 {
1185         hammer2_msg_t *nmsg;
1186         uint32_t cmd = HAMMER2_LNK_ERROR | HAMMER2_MSGF_DELETE;
1187
1188         /*
1189          * Nothing to do if we already transmitted a delete
1190          */
1191         if (state->txcmd & HAMMER2_MSGF_DELETE)
1192                 return;
1193
1194         /*
1195          * We must also set CREATE if this is our first response to a
1196          * remote command.
1197          */
1198         if ((state->txcmd & HAMMER2_MSGF_CREATE) == 0)
1199                 cmd |= HAMMER2_MSGF_CREATE;
1200
1201         /*
1202          * Set REPLY if the other end initiated the command.  Otherwise
1203          * we are the command direction.
1204          */
1205         if ((state->rxcmd & HAMMER2_MSGF_REPLY) == 0)
1206                 cmd |= HAMMER2_MSGF_REPLY;
1207
1208         nmsg = hammer2_msg_alloc(state->iocom, 0, cmd);
1209         nmsg->any.head.error = error;
1210         nmsg->state = state;
1211         hammer2_msg_write(state->iocom, nmsg, NULL, 0);
1212 }
1213
1214 /************************************************************************
1215  *                      TRANSACTION STATE HANDLING                      *
1216  ************************************************************************
1217  *
1218  */
1219
1220 RB_GENERATE(hammer2_state_tree, hammer2_state, rbnode, hammer2_state_cmp);
1221
1222 /*
1223  * Process state tracking for a message after reception, prior to
1224  * execution.
1225  *
1226  * Called with msglk held and the msg dequeued.
1227  *
1228  * All messages are called with dummy state and return actual state.
1229  * (One-off messages often just return the same dummy state).
1230  *
1231  * May request that caller discard the message by setting *discardp to 1.
1232  * The returned state is not used in this case and is allowed to be NULL.
1233  *
1234  * --
1235  *
1236  * These routines handle persistent and command/reply message state via the
1237  * CREATE and DELETE flags.  The first message in a command or reply sequence
1238  * sets CREATE, the last message in a command or reply sequence sets DELETE.
1239  *
1240  * There can be any number of intermediate messages belonging to the same
1241  * sequence sent inbetween the CREATE message and the DELETE message,
1242  * which set neither flag.  This represents a streaming command or reply.
1243  *
1244  * Any command message received with CREATE set expects a reply sequence to
1245  * be returned.  Reply sequences work the same as command sequences except the
1246  * REPLY bit is also sent.  Both the command side and reply side can
1247  * degenerate into a single message with both CREATE and DELETE set.  Note
1248  * that one side can be streaming and the other side not, or neither, or both.
1249  *
1250  * The msgid is unique for the initiator.  That is, two sides sending a new
1251  * message can use the same msgid without colliding.
1252  *
1253  * --
1254  *
1255  * ABORT sequences work by setting the ABORT flag along with normal message
1256  * state.  However, ABORTs can also be sent on half-closed messages, that is
1257  * even if the command or reply side has already sent a DELETE, as long as
1258  * the message has not been fully closed it can still send an ABORT+DELETE
1259  * to terminate the half-closed message state.
1260  *
1261  * Since ABORT+DELETEs can race we silently discard ABORT's for message
1262  * state which has already been fully closed.  REPLY+ABORT+DELETEs can
1263  * also race, and in this situation the other side might have already
1264  * initiated a new unrelated command with the same message id.  Since
1265  * the abort has not set the CREATE flag the situation can be detected
1266  * and the message will also be discarded.
1267  *
1268  * Non-blocking requests can be initiated with ABORT+CREATE[+DELETE].
1269  * The ABORT request is essentially integrated into the command instead
1270  * of being sent later on.  In this situation the command implementation
1271  * detects that CREATE and ABORT are both set (vs ABORT alone) and can
1272  * special-case non-blocking operation for the command.
1273  *
1274  * NOTE!  Messages with ABORT set without CREATE or DELETE are considered
1275  *        to be mid-stream aborts for command/reply sequences.  ABORTs on
1276  *        one-way messages are not supported.
1277  *
1278  * NOTE!  If a command sequence does not support aborts the ABORT flag is
1279  *        simply ignored.
1280  *
1281  * --
1282  *
1283  * One-off messages (no reply expected) are sent with neither CREATE or DELETE
1284  * set.  One-off messages cannot be aborted and typically aren't processed
1285  * by these routines.  The REPLY bit can be used to distinguish whether a
1286  * one-off message is a command or reply.  For example, one-off replies
1287  * will typically just contain status updates.
1288  */
1289 static int
1290 hammer2_state_msgrx(hammer2_iocom_t *iocom, hammer2_msg_t *msg)
1291 {
1292         hammer2_state_t *state;
1293         hammer2_state_t dummy;
1294         int error;
1295
1296         /*
1297          * Lock RB tree and locate existing persistent state, if any.
1298          *
1299          * If received msg is a command state is on staterd_tree.
1300          * If received msg is a reply state is on statewr_tree.
1301          */
1302         /*lockmgr(&pmp->msglk, LK_EXCLUSIVE);*/
1303
1304         dummy.msgid = msg->any.head.msgid;
1305         dummy.spanid = msg->any.head.spanid;
1306 #if 0
1307         iocom_printf(iocom, msg->any.head.cmd,
1308                      "received msg %08x msgid %jx spanid=%jx\n",
1309                       msg->any.head.cmd,
1310                       (intmax_t)msg->any.head.msgid,
1311                       (intmax_t)msg->any.head.spanid);
1312 #endif
1313         if (msg->any.head.cmd & HAMMER2_MSGF_REPLY) {
1314                 state = RB_FIND(hammer2_state_tree,
1315                                 &iocom->statewr_tree, &dummy);
1316         } else {
1317                 state = RB_FIND(hammer2_state_tree,
1318                                 &iocom->staterd_tree, &dummy);
1319         }
1320         msg->state = state;
1321
1322         /*
1323          * Short-cut one-off or mid-stream messages (state may be NULL).
1324          */
1325         if ((msg->any.head.cmd & (HAMMER2_MSGF_CREATE | HAMMER2_MSGF_DELETE |
1326                                   HAMMER2_MSGF_ABORT)) == 0) {
1327                 /*lockmgr(&pmp->msglk, LK_RELEASE);*/
1328                 return(0);
1329         }
1330
1331         /*
1332          * Switch on CREATE, DELETE, REPLY, and also handle ABORT from
1333          * inside the case statements.
1334          */
1335         switch(msg->any.head.cmd & (HAMMER2_MSGF_CREATE | HAMMER2_MSGF_DELETE |
1336                                     HAMMER2_MSGF_REPLY)) {
1337         case HAMMER2_MSGF_CREATE:
1338         case HAMMER2_MSGF_CREATE | HAMMER2_MSGF_DELETE:
1339                 /*
1340                  * New persistant command received.
1341                  */
1342                 if (state) {
1343                         iocom_printf(iocom, msg->any.head.cmd,
1344                                      "hammer2_state_msgrx: "
1345                                      "duplicate transaction\n");
1346                         error = HAMMER2_IOQ_ERROR_TRANS;
1347                         break;
1348                 }
1349                 state = malloc(sizeof(*state));
1350                 bzero(state, sizeof(*state));
1351                 state->iocom = iocom;
1352                 state->flags = HAMMER2_STATE_DYNAMIC;
1353                 state->msg = msg;
1354                 state->rxcmd = msg->any.head.cmd & ~HAMMER2_MSGF_DELETE;
1355                 RB_INSERT(hammer2_state_tree, &iocom->staterd_tree, state);
1356                 state->flags |= HAMMER2_STATE_INSERTED;
1357                 state->msgid = msg->any.head.msgid;
1358                 state->spanid = msg->any.head.spanid;
1359                 msg->state = state;
1360                 error = 0;
1361                 break;
1362         case HAMMER2_MSGF_DELETE:
1363                 /*
1364                  * Persistent state is expected but might not exist if an
1365                  * ABORT+DELETE races the close.
1366                  */
1367                 if (state == NULL) {
1368                         if (msg->any.head.cmd & HAMMER2_MSGF_ABORT) {
1369                                 error = HAMMER2_IOQ_ERROR_EALREADY;
1370                         } else {
1371                                 iocom_printf(iocom, msg->any.head.cmd,
1372                                              "hammer2_state_msgrx: "
1373                                              "no state for DELETE\n");
1374                                 error = HAMMER2_IOQ_ERROR_TRANS;
1375                         }
1376                         break;
1377                 }
1378
1379                 /*
1380                  * Handle another ABORT+DELETE case if the msgid has already
1381                  * been reused.
1382                  */
1383                 if ((state->rxcmd & HAMMER2_MSGF_CREATE) == 0) {
1384                         if (msg->any.head.cmd & HAMMER2_MSGF_ABORT) {
1385                                 error = HAMMER2_IOQ_ERROR_EALREADY;
1386                         } else {
1387                                 iocom_printf(iocom, msg->any.head.cmd,
1388                                              "hammer2_state_msgrx: "
1389                                              "state reused for DELETE\n");
1390                                 error = HAMMER2_IOQ_ERROR_TRANS;
1391                         }
1392                         break;
1393                 }
1394                 error = 0;
1395                 break;
1396         default:
1397                 /*
1398                  * Check for mid-stream ABORT command received, otherwise
1399                  * allow.
1400                  */
1401                 if (msg->any.head.cmd & HAMMER2_MSGF_ABORT) {
1402                         if (state == NULL ||
1403                             (state->rxcmd & HAMMER2_MSGF_CREATE) == 0) {
1404                                 error = HAMMER2_IOQ_ERROR_EALREADY;
1405                                 break;
1406                         }
1407                 }
1408                 error = 0;
1409                 break;
1410         case HAMMER2_MSGF_REPLY | HAMMER2_MSGF_CREATE:
1411         case HAMMER2_MSGF_REPLY | HAMMER2_MSGF_CREATE | HAMMER2_MSGF_DELETE:
1412                 /*
1413                  * When receiving a reply with CREATE set the original
1414                  * persistent state message should already exist.
1415                  */
1416                 if (state == NULL) {
1417                         iocom_printf(iocom, msg->any.head.cmd,
1418                                      "hammer2_state_msgrx: "
1419                                      "no state match for REPLY cmd=%08x\n",
1420                                      msg->any.head.cmd);
1421                         error = HAMMER2_IOQ_ERROR_TRANS;
1422                         break;
1423                 }
1424                 state->rxcmd = msg->any.head.cmd & ~HAMMER2_MSGF_DELETE;
1425                 error = 0;
1426                 break;
1427         case HAMMER2_MSGF_REPLY | HAMMER2_MSGF_DELETE:
1428                 /*
1429                  * Received REPLY+ABORT+DELETE in case where msgid has
1430                  * already been fully closed, ignore the message.
1431                  */
1432                 if (state == NULL) {
1433                         if (msg->any.head.cmd & HAMMER2_MSGF_ABORT) {
1434                                 error = HAMMER2_IOQ_ERROR_EALREADY;
1435                         } else {
1436                                 iocom_printf(iocom, msg->any.head.cmd,
1437                                              "hammer2_state_msgrx: "
1438                                              "no state match for "
1439                                              "REPLY|DELETE\n");
1440                                 error = HAMMER2_IOQ_ERROR_TRANS;
1441                         }
1442                         break;
1443                 }
1444
1445                 /*
1446                  * Received REPLY+ABORT+DELETE in case where msgid has
1447                  * already been reused for an unrelated message,
1448                  * ignore the message.
1449                  */
1450                 if ((state->rxcmd & HAMMER2_MSGF_CREATE) == 0) {
1451                         if (msg->any.head.cmd & HAMMER2_MSGF_ABORT) {
1452                                 error = HAMMER2_IOQ_ERROR_EALREADY;
1453                         } else {
1454                                 iocom_printf(iocom, msg->any.head.cmd,
1455                                              "hammer2_state_msgrx: "
1456                                              "state reused for REPLY|DELETE\n");
1457                                 error = HAMMER2_IOQ_ERROR_TRANS;
1458                         }
1459                         break;
1460                 }
1461                 error = 0;
1462                 break;
1463         case HAMMER2_MSGF_REPLY:
1464                 /*
1465                  * Check for mid-stream ABORT reply received to sent command.
1466                  */
1467                 if (msg->any.head.cmd & HAMMER2_MSGF_ABORT) {
1468                         if (state == NULL ||
1469                             (state->rxcmd & HAMMER2_MSGF_CREATE) == 0) {
1470                                 error = HAMMER2_IOQ_ERROR_EALREADY;
1471                                 break;
1472                         }
1473                 }
1474                 error = 0;
1475                 break;
1476         }
1477         /*lockmgr(&pmp->msglk, LK_RELEASE);*/
1478         return (error);
1479 }
1480
1481 void
1482 hammer2_state_cleanuprx(hammer2_iocom_t *iocom, hammer2_msg_t *msg)
1483 {
1484         hammer2_state_t *state;
1485
1486         if ((state = msg->state) == NULL) {
1487                 /*
1488                  * Free a non-transactional message, there is no state
1489                  * to worry about.
1490                  */
1491                 hammer2_msg_free(iocom, msg);
1492         } else if (msg->any.head.cmd & HAMMER2_MSGF_DELETE) {
1493                 /*
1494                  * Message terminating transaction, destroy the related
1495                  * state, the original message, and this message (if it
1496                  * isn't the original message due to a CREATE|DELETE).
1497                  */
1498                 /*lockmgr(&pmp->msglk, LK_EXCLUSIVE);*/
1499                 state->rxcmd |= HAMMER2_MSGF_DELETE;
1500                 if (state->txcmd & HAMMER2_MSGF_DELETE) {
1501                         if (state->msg == msg)
1502                                 state->msg = NULL;
1503                         assert(state->flags & HAMMER2_STATE_INSERTED);
1504                         if (msg->any.head.cmd & HAMMER2_MSGF_REPLY) {
1505                                 RB_REMOVE(hammer2_state_tree,
1506                                           &iocom->statewr_tree, state);
1507                         } else {
1508                                 RB_REMOVE(hammer2_state_tree,
1509                                           &iocom->staterd_tree, state);
1510                         }
1511                         state->flags &= ~HAMMER2_STATE_INSERTED;
1512                         /*lockmgr(&pmp->msglk, LK_RELEASE);*/
1513                         hammer2_state_free(state);
1514                 } else {
1515                         /*lockmgr(&pmp->msglk, LK_RELEASE);*/
1516                 }
1517                 hammer2_msg_free(iocom, msg);
1518         } else if (state->msg != msg) {
1519                 /*
1520                  * Message not terminating transaction, leave state intact
1521                  * and free message if it isn't the CREATE message.
1522                  */
1523                 hammer2_msg_free(iocom, msg);
1524         }
1525 }
1526
1527 static void
1528 hammer2_state_cleanuptx(hammer2_iocom_t *iocom, hammer2_msg_t *msg)
1529 {
1530         hammer2_state_t *state;
1531
1532         if ((state = msg->state) == NULL) {
1533                 hammer2_msg_free(iocom, msg);
1534         } else if (msg->any.head.cmd & HAMMER2_MSGF_DELETE) {
1535                 /*lockmgr(&pmp->msglk, LK_EXCLUSIVE);*/
1536                 state->txcmd |= HAMMER2_MSGF_DELETE;
1537                 if (state->rxcmd & HAMMER2_MSGF_DELETE) {
1538                         if (state->msg == msg)
1539                                 state->msg = NULL;
1540                         assert(state->flags & HAMMER2_STATE_INSERTED);
1541                         if (msg->any.head.cmd & HAMMER2_MSGF_REPLY) {
1542                                 RB_REMOVE(hammer2_state_tree,
1543                                           &iocom->staterd_tree, state);
1544                         } else {
1545                                 RB_REMOVE(hammer2_state_tree,
1546                                           &iocom->statewr_tree, state);
1547                         }
1548                         state->flags &= ~HAMMER2_STATE_INSERTED;
1549                         /*lockmgr(&pmp->msglk, LK_RELEASE);*/
1550                         hammer2_state_free(state);
1551                 } else {
1552                         /*lockmgr(&pmp->msglk, LK_RELEASE);*/
1553                 }
1554                 hammer2_msg_free(iocom, msg);
1555         } else if (state->msg != msg) {
1556                 hammer2_msg_free(iocom, msg);
1557         }
1558 }
1559
1560 void
1561 hammer2_state_free(hammer2_state_t *state)
1562 {
1563         hammer2_iocom_t *iocom = state->iocom;
1564         hammer2_msg_t *msg;
1565
1566         msg = state->msg;
1567         state->msg = NULL;
1568         if (msg)
1569                 hammer2_msg_free(iocom, msg);
1570         free(state);
1571 }
1572
1573 /*
1574  * Indexed messages are stored in a red-black tree indexed by their
1575  * msgid.  Only persistent messages are indexed.
1576  */
1577 int
1578 hammer2_state_cmp(hammer2_state_t *state1, hammer2_state_t *state2)
1579 {
1580         if (state1->spanid < state2->spanid)
1581                 return(-1);
1582         if (state1->spanid > state2->spanid)
1583                 return(1);
1584         if (state1->msgid < state2->msgid)
1585                 return(-1);
1586         if (state1->msgid > state2->msgid)
1587                 return(1);
1588         return(0);
1589 }