Add file-level doxygen comment blocks where they were missing.
[ircu2.10.12-pk.git] / ircd / msgq.c
1 /*
2  * IRC - Internet Relay Chat, ircd/msgq.c
3  * Copyright (C) 2000 Kevin L. Mitchell <klmitch@mit.edu>
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 1, or (at your option)
8  * any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18  */
19 /** @file
20  * @brief Outbound message queue implementation.
21  * @version $Id$
22  */
23 #include "config.h"
24
25 #include "msgq.h"
26 #include "ircd.h"
27 #include "ircd_alloc.h"
28 #include "ircd_defs.h"
29 #include "ircd_features.h"
30 #include "ircd_reply.h"
31 #include "ircd_snprintf.h"
32 #include "numeric.h"
33 #include "send.h"
34 #include "s_debug.h"
35 #include "s_stats.h"
36
37 #include <assert.h>
38 #include <stdarg.h>
39 #include <string.h>
40 #include <sys/types.h>
41 #include <sys/uio.h>    /* struct iovec */
42
43 #define MB_BASE_SHIFT   5 /**< Log2 of smallest message body to allocate. */
44 #define MB_MAX_SHIFT    9 /**< Log2 of largest message body to allocate. */
45
46 /** Buffer for a single message. */
47 struct MsgBuf {
48   struct MsgBuf *next;          /**< next msg in global queue */
49   struct MsgBuf **prev_p;       /**< what points to us in linked list */
50   struct MsgBuf *real;          /**< the actual MsgBuf we're attaching */
51   unsigned int ref;             /**< reference count */
52   unsigned int length;          /**< length of message */
53   unsigned int power;           /**< size of buffer (power of 2) */
54   char msg[1];                  /**< the message */
55 };
56
57 /** Return allocated length of the buffer of \a buf. */
58 #define bufsize(buf)    (1 << (buf)->power)
59
60 /** Message body for a particular destination. */
61 struct Msg {
62   struct Msg *next;             /**< next msg */
63   unsigned int sent;            /**< bytes in msg that have already been sent */
64   struct MsgBuf *msg;           /**< actual message in queue */
65 };
66
67 /** Statistics tracking for message sizes. */
68 struct MsgSizes {
69   unsigned int msgs;            /**< total number of messages */
70   unsigned int sizes[BUFSIZE];  /**< histogram of message sizes */
71 };
72
73 /** Global tracking data for message buffers. */
74 static struct {
75   struct MsgBuf *msglist;       /**< list of in-use MsgBuf's */
76   struct {
77     unsigned int alloc;         /**< number of Msg's allocated */
78     unsigned int used;          /**< number of Msg's in use */
79     struct Msg *free;           /**< freelist of Msg's */
80   } msgs;                       /**< tracking info for Msg structs */
81   size_t tot_bufsize;           /**< total amount of memory in buffers */
82   /** Array of MsgBuf information, one entry for each used bucket size. */
83   struct {
84     unsigned int alloc;         /**< total MsgBuf's of this size */
85     unsigned int used;          /**< number of MsgBuf's of this size in use */
86     struct MsgBuf *free;        /**< list of free MsgBuf's */
87   } msgBufs[MB_MAX_SHIFT - MB_BASE_SHIFT + 1];
88   struct MsgSizes sizes;        /**< histogram of message sizes */
89 } MQData;
90
91 /*
92  * This routine is used to remove a certain amount of data from a given
93  * queue and release the Msg (and MsgBuf) structure if needed
94  */
95 /** Remove some data from a list within a message queue.
96  * @param[in,out] mq Message queue to remove from.
97  * @param[in,out] qlist Particular list within queue to remove from.
98  * @param[in,out] length_p Number of bytes left to remove.
99  */
100 static void
101 msgq_delmsg(struct MsgQ *mq, struct MsgQList *qlist, unsigned int *length_p)
102 {
103   struct Msg *m;
104   unsigned int msglen;
105
106   assert(0 != mq);
107   assert(0 != qlist);
108   assert(0 != qlist->head);
109   assert(0 != length_p);
110
111   m = qlist->head; /* find the msg we're deleting from */
112
113   msglen = m->msg->length - m->sent; /* calculate how much is left */
114
115   if (*length_p >= msglen) { /* deleted it all? */
116     mq->length -= msglen; /* decrement length */
117     mq->count--; /* decrement the message count */
118     *length_p -= msglen;
119
120     msgq_clean(m->msg); /* free up the struct MsgBuf */
121     m->msg = 0; /* don't let it point anywhere nasty, please */
122
123     if (qlist->head == qlist->tail) /* figure out if we emptied the queue */
124       qlist->head = qlist->tail = 0;
125     else
126       qlist->head = m->next; /* just shift the list down some */
127
128     MQData.msgs.used--; /* struct Msg is not in use anymore */
129
130     m->next = MQData.msgs.free; /* throw it onto the free list */
131     MQData.msgs.free = m;
132   } else {
133     mq->length -= *length_p; /* decrement queue length */
134     m->sent += *length_p; /* this much of the message has been sent */
135     *length_p = 0; /* we've dealt with it all */
136   }
137 }
138
139 /** Initialize \a mq.
140  * @param[in] mq MsgQ to initialize.
141  */
142 void
143 msgq_init(struct MsgQ *mq)
144 {
145   assert(0 != mq);
146
147   mq->length = 0;
148   mq->count = 0;
149   mq->queue.head = 0;
150   mq->queue.tail = 0;
151   mq->prio.head = 0;
152   mq->prio.tail = 0;
153 }
154
155 /** Delete bytes from the front of a message queue.
156  * @param[in] mq Queue to drop data from.
157  * @param[in] length Number of bytes to drop.
158  */
159 void
160 msgq_delete(struct MsgQ *mq, unsigned int length)
161 {
162   assert(0 != mq);
163
164   while (length > 0) {
165     if (mq->queue.head && mq->queue.head->sent > 0) /* partial msg on norm q */
166       msgq_delmsg(mq, &mq->queue, &length);
167     else if (mq->prio.head) /* message (partial or complete) on prio queue */
168       msgq_delmsg(mq, &mq->prio, &length);
169     else if (mq->queue.head) /* message on normal queue */
170       msgq_delmsg(mq, &mq->queue, &length);
171     else
172       break;
173   }
174 }
175
176 /** Map data from a message queue to an I/O vector.
177  * @param[in] mq Message queue to send from.
178  * @param[out] iov Output vector.
179  * @param[in] count Number of elements in \a iov.
180  * @param[out] len Number of bytes mapped from \a mq to \a iov.
181  * @return Number of elements filled in \a iov.
182  */
183 int
184 msgq_mapiov(const struct MsgQ *mq, struct iovec *iov, int count,
185             unsigned int *len)
186 {
187   struct Msg *queue;
188   struct Msg *prio;
189   int i = 0;
190
191   assert(0 != mq);
192   assert(0 != iov);
193   assert(0 != count);
194   assert(0 != len);
195
196   if (mq->length <= 0) /* no data to map */
197     return 0;
198
199   if (mq->queue.head && mq->queue.head->sent > 0) { /* partial msg on norm q */
200     iov[i].iov_base = mq->queue.head->msg->msg + mq->queue.head->sent;
201     iov[i].iov_len = mq->queue.head->msg->length - mq->queue.head->sent;
202     *len += iov[i].iov_len;
203
204     queue = mq->queue.head->next; /* where we start later... */
205
206     i++; /* filled an iovec... */
207     if (!--count) /* check for space */
208       return i;
209   } else
210     queue = mq->queue.head; /* start at head of queue */
211
212   if (mq->prio.head && mq->prio.head->sent > 0) { /* partial msg on prio q */
213     iov[i].iov_base = mq->prio.head->msg->msg + mq->prio.head->sent;
214     iov[i].iov_len = mq->prio.head->msg->length - mq->prio.head->sent;
215     *len += iov[i].iov_len;
216
217     prio = mq->prio.head->next; /* where we start later... */
218
219     i++; /* filled an iovec... */
220     if (!--count) /* check for space */
221       return i;
222   } else
223     prio = mq->prio.head; /* start at head of prio */
224
225   for (; prio; prio = prio->next) { /* go through prio queue */
226     iov[i].iov_base = prio->msg->msg; /* store message */
227     iov[i].iov_len = prio->msg->length;
228     *len += iov[i].iov_len;
229
230     i++; /* filled an iovec... */
231     if (!--count) /* check for space */
232       return i;
233   }
234
235   for (; queue; queue = queue->next) { /* go through normal queue */
236     iov[i].iov_base = queue->msg->msg;
237     iov[i].iov_len = queue->msg->length;
238     *len += iov[i].iov_len;
239
240     i++; /* filled an iovec... */
241     if (!--count) /* check for space */
242       return i;
243   }
244
245   return i;
246 }
247
248 /** Allocate a message buffer large enough to hold \a length bytes.
249  * TODO: \a in_mb needs better documentation.
250  * @param[in] in_mb Some other message buffer(?).
251  * @param[in] length Number of bytes of space to reserve in output.
252  * @return Pointer to some usable message buffer.
253  */
254 static struct MsgBuf *
255 msgq_alloc(struct MsgBuf *in_mb, int length)
256 {
257   struct MsgBuf *mb;
258   int power;
259
260   /* Find the power of two size that will accomodate the message */
261   for (power = MB_BASE_SHIFT; power < MB_MAX_SHIFT + 1; power++)
262     if ((length - 1) >> power == 0)
263       break;
264   assert((1 << power) >= length);
265   assert((1 << power) <= 512);
266   length = 1 << power; /* reset the length */
267
268   /* If the message needs a buffer of exactly the existing size, just use it */
269   if (in_mb && in_mb->power == power) {
270     in_mb->real = in_mb; /* real buffer is this buffer */
271     return in_mb;
272   }
273
274   /* Try popping one off the freelist first */
275   if ((mb = MQData.msgBufs[power - MB_BASE_SHIFT].free)) {
276     MQData.msgBufs[power - MB_BASE_SHIFT].free = mb->next;
277   } else if (MQData.tot_bufsize < feature_int(FEAT_BUFFERPOOL)) {
278     /* Allocate another if we won't bust the BUFFERPOOL */
279     Debug((DEBUG_MALLOC, "Allocating MsgBuf of length %d (total size %zu)",
280            length, sizeof(struct MsgBuf) + length));
281     mb = (struct MsgBuf *)MyMalloc(sizeof(struct MsgBuf) + length);
282     MQData.msgBufs[power - MB_BASE_SHIFT].alloc++;
283     mb->power = power; /* remember size */
284     MQData.tot_bufsize += length;
285   }
286
287   if (mb) {
288     MQData.msgBufs[power - MB_BASE_SHIFT].used++; /* how many are we using? */
289
290     mb->real = 0; /* essential initializations */
291     mb->ref = 1;
292
293     if (in_mb) /* remember who's the *real* buffer */
294       in_mb->real = mb;
295   } else if (in_mb) /* just use the input buffer */
296     mb = in_mb->real = in_mb;
297
298   return mb; /* return the buffer */
299 }
300
301 /** Deallocate unused message buffers.
302  */
303 static void
304 msgq_clear_freembs(void)
305 {
306   struct MsgBuf *mb;
307   int i;
308
309   /* Walk through the various size classes */
310   for (i = MB_BASE_SHIFT; i < MB_MAX_SHIFT + 1; i++)
311     /* walk down the free list */
312     while ((mb = MQData.msgBufs[i - MB_BASE_SHIFT].free)) {
313       MQData.msgBufs[i - MB_BASE_SHIFT].free = mb->next; /* shift free list */
314       MQData.msgBufs[i - MB_BASE_SHIFT].alloc--; /* reduce allocation count */
315       MQData.tot_bufsize -= 1 << i; /* reduce total buffer allocation count */
316       MyFree(mb); /* and free the buffer */
317     }
318 }
319
320 /** Format a message buffer for a client from a format string.
321  * @param[in] dest %Client that receives the data (may be NULL).
322  * @param[in] format Format string for message.
323  * @param[in] vl Argument list for \a format.
324  * @return Allocated MsgBuf.
325  */
326 struct MsgBuf *
327 msgq_vmake(struct Client *dest, const char *format, va_list vl)
328 {
329   struct MsgBuf *mb;
330
331   assert(0 != format);
332
333   if (!(mb = msgq_alloc(0, BUFSIZE))) {
334     if (feature_bool(FEAT_HAS_FERGUSON_FLUSHER)) {
335       /*
336        * from "Married With Children" episode were Al bought a REAL toilet
337        * on the black market because he was tired of the wimpy water
338        * conserving toilets they make these days --Bleep
339        */
340       /*
341        * Apparently this doesn't work, the server _has_ to
342        * dump a few clients to handle the load. A fully loaded
343        * server cannot handle a net break without dumping some
344        * clients. If we flush the connections here under a full
345        * load we may end up starving the kernel for mbufs and
346        * crash the machine
347        */
348       /*
349        * attempt to recover from buffer starvation before
350        * bailing this may help servers running out of memory
351        */
352       flush_connections(0);
353       mb = msgq_alloc(0, BUFSIZE);
354     }
355     if (!mb) { /* OK, try clearing the buffer free list */
356       msgq_clear_freembs();
357       mb = msgq_alloc(0, BUFSIZE);
358     }
359     if (!mb) { /* OK, try killing a client */
360       kill_highest_sendq(0); /* Don't kill any server connections */
361       mb = msgq_alloc(0, BUFSIZE);
362     }
363     if (!mb) { /* hmmm... */
364       kill_highest_sendq(1); /* Try killing a server connection now */
365       mb = msgq_alloc(0, BUFSIZE);
366     }
367     if (!mb) /* AIEEEE! */
368       server_panic("Unable to allocate buffers!");
369   }
370
371   mb->next = MQData.msglist; /* initialize the msgbuf */
372   mb->prev_p = &MQData.msglist;
373
374   /* fill the buffer */
375   mb->length = ircd_vsnprintf(dest, mb->msg, bufsize(mb) - 1, format, vl);
376
377   if (mb->length > bufsize(mb) - 2)
378     mb->length = bufsize(mb) - 2;
379
380   mb->msg[mb->length++] = '\r'; /* add \r\n to buffer */
381   mb->msg[mb->length++] = '\n';
382   mb->msg[mb->length] = '\0'; /* not strictly necessary */
383
384   assert(mb->length <= bufsize(mb));
385
386   if (MQData.msglist) /* link it into the list */
387     MQData.msglist->prev_p = &mb->next;
388   MQData.msglist = mb;
389
390   return mb;
391 }
392
393 /** Format a message buffer for a client from a format string.
394  * @param[in] dest %Client that receives the data (may be NULL).
395  * @param[in] format Format string for message.
396  * @return Allocated MsgBuf.
397  */
398 struct MsgBuf *
399 msgq_make(struct Client *dest, const char *format, ...)
400 {
401   va_list vl;
402   struct MsgBuf *mb;
403
404   va_start(vl, format);
405   mb = msgq_vmake(dest, format, vl);
406   va_end(vl);
407
408   return mb;
409 }
410
411 /** Append text to an existing message buffer.
412  * @param[in] dest %Client for whom to format the message.
413  * @param[in] mb Message buffer to append to.
414  * @param[in] format Format string of what to append.
415  */
416 void
417 msgq_append(struct Client *dest, struct MsgBuf *mb, const char *format, ...)
418 {
419   va_list vl;
420
421   assert(0 != mb);
422   assert(0 != format);
423   assert(0 == mb->real);
424
425   assert(2 < mb->length);
426   assert(bufsize(mb) >= mb->length);
427
428   mb->length -= 2; /* back up to before \r\n */
429
430   va_start(vl, format); /* append to the buffer */
431   mb->length += ircd_vsnprintf(dest, mb->msg + mb->length,
432                                bufsize(mb) - mb->length - 1, format, vl);
433   va_end(vl);
434
435   if (mb->length > bufsize(mb) - 2)
436     mb->length = bufsize(mb) - 2;
437
438   mb->msg[mb->length++] = '\r'; /* add \r\n to buffer */
439   mb->msg[mb->length++] = '\n';
440   mb->msg[mb->length] = '\0'; /* not strictly necessary */
441
442   assert(mb->length <= bufsize(mb));
443 }
444
445 /** Decrement the reference count on \a mb, freeing it if needed.
446  * @param[in] mb MsgBuf to release.
447  */
448 void
449 msgq_clean(struct MsgBuf *mb)
450 {
451   assert(0 != mb);
452   assert(0 < mb->ref);
453
454   if (!--mb->ref) { /* deallocate the message */
455     if (mb->prev_p) {
456       *mb->prev_p = mb->next; /* clip it out of active MsgBuf's list */
457       if (mb->next)
458         mb->next->prev_p = mb->prev_p;
459     }
460
461     if (mb->real && mb->real != mb) /* clean up the real buffer */
462       msgq_clean(mb->real);
463
464     mb->next = MQData.msgBufs[mb->power - MB_BASE_SHIFT].free;
465     MQData.msgBufs[mb->power - MB_BASE_SHIFT].free = mb;
466     MQData.msgBufs[mb->power - MB_BASE_SHIFT].used--;
467
468     mb->prev_p = 0;
469   }
470 }
471
472 /** Append a message to a peer's message queue.
473  * @param[in] mq Message queue to append to.
474  * @param[in] mb Message to append.
475  * @param[in] prio If non-zero, use the high-priority (lag-busting) message list; else use the normal list.
476  */
477 void
478 msgq_add(struct MsgQ *mq, struct MsgBuf *mb, int prio)
479 {
480   struct MsgQList *qlist;
481   struct Msg *msg;
482
483   assert(0 != mq);
484   assert(0 != mb);
485   assert(0 < mb->ref);
486   assert(0 < mb->length);
487
488   Debug((DEBUG_SEND, "Adding buffer %p [%.*s] length %u to %s queue", mb,
489          mb->length - 2, mb->msg, mb->length, prio ? "priority" : "normal"));
490
491   qlist = prio ? &mq->prio : &mq->queue;
492
493   if (!(msg = MQData.msgs.free)) { /* do I need to allocate one? */
494     msg = (struct Msg *)MyMalloc(sizeof(struct Msg));
495     MQData.msgs.alloc++; /* we allocated another */
496   } else /* shift the free list */
497     MQData.msgs.free = MQData.msgs.free->next;
498
499   MQData.msgs.used++; /* we're using another */
500
501   msg->next = 0; /* initialize the msg */
502   msg->sent = 0;
503
504   /* Get the real buffer, allocating one if necessary */
505   if (!mb->real) {
506     struct MsgBuf *tmp;
507
508     MQData.sizes.msgs++; /* update histogram counts */
509     MQData.sizes.sizes[mb->length - 1]++;
510
511     tmp = msgq_alloc(mb, mb->length); /* allocate a close-fitting buffer */
512
513     if (tmp != mb) { /* OK, prepare the new "real" buffer */
514       Debug((DEBUG_SEND, "Copying old buffer %p [%.*s] length %u into new "
515              "buffer %p size %u", mb, mb->length - 2, mb->msg, mb->length,
516              tmp, bufsize(tmp)));
517       memcpy(tmp->msg, mb->msg, mb->length + 1); /* copy string over */
518       tmp->length = mb->length;
519
520       tmp->next = mb->next; /* replace it in the list, now */
521       if (tmp->next)
522         tmp->next->prev_p = &tmp->next;
523       tmp->prev_p = mb->prev_p;
524       *tmp->prev_p = tmp;
525
526       mb->next = 0; /* this one's no longer in the list */
527       mb->prev_p = 0;
528     }
529   }
530
531   mb = mb->real; /* work with the real buffer */
532   mb->ref++; /* increment the ref count on the buffer */
533
534   msg->msg = mb; /* point at the real message buffer now */
535
536   if (!qlist->head) /* queue list was empty; head and tail point to msg */
537     qlist->head = qlist->tail = msg;
538   else {
539     assert(0 != qlist->tail);
540
541     qlist->tail->next = msg; /* queue had something in it; add to end */
542     qlist->tail = msg;
543   }
544
545   mq->length += mb->length; /* update the queue length */
546   mq->count++; /* and the queue count */
547 }
548
549 /** Report memory statistics for message buffers.
550  * @param[in] cptr Client requesting information.
551  * @param[out] msg_alloc Receives number of bytes allocated in Msg structs.
552  * @param[out] msgbuf_alloc Receives number of bytes allocated in MsgBuf structs.
553  */
554 void
555 msgq_count_memory(struct Client *cptr, size_t *msg_alloc, size_t *msgbuf_alloc)
556 {
557   int i;
558   size_t total = 0, size;
559
560   assert(0 != cptr);
561   assert(0 != msg_alloc);
562   assert(0 != msgbuf_alloc);
563
564   /* Data for Msg's is simple, so just send it */
565   send_reply(cptr, SND_EXPLICIT | RPL_STATSDEBUG,
566              ":Msgs allocated %d(%zu) used %d(%zu)", MQData.msgs.alloc,
567              MQData.msgs.alloc * sizeof(struct Msg), MQData.msgs.used,
568              MQData.msgs.used * sizeof(struct Msg));
569   /* count_memory() wants to know the total */
570   *msg_alloc = MQData.msgs.alloc * sizeof(struct Msg);
571
572   /* Ok, now walk through each size class */
573   for (i = MB_BASE_SHIFT; i < MB_MAX_SHIFT + 1; i++) {
574     size = sizeof(struct MsgBuf) + (1 << i); /* total size of a buffer */
575
576     /* Send information for this buffer size class */
577     send_reply(cptr, SND_EXPLICIT | RPL_STATSDEBUG,
578                ":MsgBufs of size %zu allocated %d(%zu) used %d(%zu)", 1 << i,
579                MQData.msgBufs[i - MB_BASE_SHIFT].alloc,
580                MQData.msgBufs[i - MB_BASE_SHIFT].alloc * size,
581                MQData.msgBufs[i - MB_BASE_SHIFT].used,
582                MQData.msgBufs[i - MB_BASE_SHIFT].used * size);
583
584     /* count_memory() wants to know the total */
585     total += MQData.msgBufs[i - MB_BASE_SHIFT].alloc * size;
586   }
587   *msgbuf_alloc = total;
588 }
589
590 /** Report remaining space in a MsgBuf.
591  * @param[in] mb Message buffer to check.
592  * @return Number of additional bytes that can be appended to the message.
593  */
594 unsigned int
595 msgq_bufleft(struct MsgBuf *mb)
596 {
597   assert(0 != mb);
598
599   return bufsize(mb) - mb->length; /* \r\n counted in mb->length */
600 }
601
602 /** Send histogram of message lengths to a client.
603  * @param[in] cptr Client requesting statistics.
604  * @param[in] sd Stats descriptor for request (ignored).
605  * @param[in] param Extra parameter from user (ignored).
606  */
607 void
608 msgq_histogram(struct Client *cptr, const struct StatDesc *sd, char *param)
609 {
610   struct MsgSizes tmp = MQData.sizes; /* All hail structure copy! */
611   int i;
612
613   send_reply(cptr, SND_EXPLICIT | RPL_STATSDEBUG,
614              ":Histogram of message lengths (%lu messages)", tmp.msgs);
615   for (i = 0; i + 16 <= BUFSIZE; i += 16)
616     send_reply(cptr, SND_EXPLICIT | RPL_STATSDEBUG, ":% 4d: %lu %lu %lu %lu "
617                "%lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu", i + 1,
618                tmp.sizes[i +  0], tmp.sizes[i +  1], tmp.sizes[i +  2],
619                tmp.sizes[i +  3], tmp.sizes[i +  4], tmp.sizes[i +  5],
620                tmp.sizes[i +  6], tmp.sizes[i +  7], tmp.sizes[i +  8],
621                tmp.sizes[i +  9], tmp.sizes[i + 10], tmp.sizes[i + 11],
622                tmp.sizes[i + 12], tmp.sizes[i + 13], tmp.sizes[i + 14],
623                tmp.sizes[i + 15]);
624 }