Optimized locking.
[silc.git] / lib / silcutil / silcstack.c
1 /*
2
3   silcstack.c
4
5   Author: Pekka Riikonen <priikone@silcnet.org>
6
7   Copyright (C) 2003 - 2007 Pekka Riikonen
8
9   This program is free software; you can redistribute it and/or modify
10   it under the terms of the GNU General Public License as published by
11   the Free Software Foundation; version 2 of the License.
12
13   This program is distributed in the hope that it will be useful,
14   but WITHOUT ANY WARRANTY; without even the implied warranty of
15   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16   GNU General Public License for more details.
17
18 */
19
20 #include "silc.h"
21
22 /************************** Types and definitions ***************************/
23
24 /* The SilcStack context */
25 struct SilcStackStruct {
26   SilcStack parent;                           /* Parent stack */
27   SilcMutex lock;                             /* Stack lock */
28   SilcList stacks;                            /* List of stacks for childs */
29   SilcStackDataEntry stack;                   /* The allocated stack */
30   SilcStackFrame *frames;                     /* Allocated stack frames */
31   SilcStackFrame *frame;                      /* Current stack frame */
32   SilcStackOomHandler oom_handler;            /* OOM handler */
33   void *oom_context;                          /* OOM handler context */
34   SilcUInt32 stack_size;                      /* Default stack size */
35   SilcUInt32 alignment;                       /* Memory alignment */
36 #ifdef SILC_DIST_INPLACE
37   /* Statistics */
38   SilcUInt32 snum_malloc;
39   SilcUInt32 sbytes_malloc;
40   SilcUInt32 snum_errors;
41 #endif /* SILC_DIST_INPLACE */
42 };
43
44 /************************ Static utility functions **************************/
45
46 /* Compute stack block index for the `size'. */
47
48 static SilcUInt32 silc_stack_get_index(SilcUInt32 size, SilcUInt32 *ret_bsize)
49 {
50   SilcUInt32 bsize, si;
51
52   if (size < SILC_STACK_DEFAULT_SIZE)
53     size = SILC_STACK_DEFAULT_SIZE;
54   si = 0;
55   bsize = SILC_STACK_DEFAULT_SIZE;
56   while (bsize < size) {
57     bsize <<= 1;
58     si++;
59   }
60
61   *ret_bsize = bsize;
62
63   return si;
64 }
65
66 /* Get stack from `stack' or allocate new one. */
67
68 static SilcStackDataEntry silc_stack_ref_stack(SilcStack stack,
69                                                SilcUInt32 size,
70                                                SilcUInt32 *ret_si,
71                                                SilcUInt32 *ret_bsize)
72 {
73   SilcStackDataEntry e;
74   SilcUInt32 si, bsize;
75
76   /* Get stack block index and block size for requested size */
77   si = silc_stack_get_index(size, &bsize);
78   *ret_si = si;
79   *ret_bsize = bsize;
80
81   SILC_ST_DEBUG(("Get stack block, si %d, size %lu, stack %p",
82                  si, bsize, stack));
83
84   silc_mutex_lock(stack->lock);
85
86   /* Get stack that has block that can house our size requirement. */
87   silc_list_start(stack->stacks);
88   while ((e = silc_list_get(stack->stacks))) {
89     if (!e->data[si])
90       continue;
91
92     silc_list_del(stack->stacks, e);
93     SILC_ST_DEBUG(("Got stack blocks %p from stack %p", e->data, stack));
94     silc_mutex_unlock(stack->lock);
95     return e;
96   }
97
98   silc_mutex_unlock(stack->lock);
99
100   /* If we are child, get block from parent */
101   if (stack->parent)
102     return silc_stack_ref_stack(stack->parent, size, ret_si, ret_bsize);
103
104   SILC_ST_DEBUG(("Allocate new stack blocks"));
105
106   /* Allocate new stack blocks */
107   e = silc_calloc(1, sizeof(*e));
108   if (!e)
109     return NULL;
110   e->data[si] = silc_malloc(bsize + SILC_STACK_ALIGN(sizeof(*e->data[0]),
111                                                      stack->alignment));
112   if (!e->data[si]) {
113     silc_free(e);
114     return NULL;
115   }
116   e->data[si]->bytes_left = bsize;
117   e->si = si;
118   e->bsize = bsize;
119
120   SILC_ST_DEBUG(("Got stack blocks %p from stack %p", e->data, stack));
121
122   return e;
123 }
124
125 /* Return the `data' back to the `stack'. */
126
127 static void silc_stack_unref_stack(SilcStack stack, SilcStackDataEntry e)
128 {
129   int i;
130
131   SILC_LOG_DEBUG(("Release stack blocks %p to stack %p, si %d",
132                   e->data, stack, e->si));
133
134   /* Release all blocks from allocations */
135   for (i = e->si; i < SILC_STACK_BLOCK_NUM; i++) {
136     if (!e->data[i])
137       continue;
138     if (!i)
139       e->data[i]->bytes_left = e->bsize;
140     else
141       e->data[i]->bytes_left = SILC_STACK_BLOCK_SIZE(stack, i);
142   }
143
144   silc_mutex_lock(stack->lock);
145   silc_list_add(stack->stacks, e);
146   silc_mutex_unlock(stack->lock);
147 }
148
149 /* Allocate memory from a specific stack block */
150
151 static void *silc_stack_alloc_block(SilcStack stack, SilcStackDataEntry e,
152                                     SilcUInt32 items, SilcUInt32 size)
153 {
154   SilcUInt32 asize;
155   void *ptr;
156
157   /* Get pointer and consume the stack block */
158   asize = SILC_STACK_ALIGN(items * size, stack->alignment);
159   ptr = SILC_STACK_DATA_EXT(e->data, e->si, e->bsize, stack->alignment);
160   e->data[e->si]->bytes_left -= asize;
161   memset(ptr, 0, items * size);
162
163   return ptr;
164 }
165
166 /***************************** SilcStack API ********************************/
167
168 /* Allocate the stack */
169
170 SilcStack silc_stack_alloc(SilcUInt32 stack_size, SilcStack parent)
171 {
172   SilcStack stack;
173   SilcStackDataEntry e;
174   SilcUInt32 si = 0, bsize = 0;
175
176   stack_size = stack_size ? stack_size : SILC_STACK_DEFAULT_SIZE;
177   if (stack_size < SILC_STACK_DEFAULT_SIZE)
178     stack_size = SILC_STACK_DEFAULT_SIZE;
179
180   if (parent) {
181     /* Get stack from parent.  The stack itself is allocated from the
182        parent. */
183     e = silc_stack_ref_stack(parent, stack_size, &si, &bsize);
184     if (!e)
185       return NULL;
186
187     /* Allocate stack from the parent */
188     stack = silc_stack_alloc_block(parent, e, 1, sizeof(*stack));
189     if (!stack) {
190       silc_stack_unref_stack(parent, e);
191       return NULL;
192     }
193
194     stack->parent = parent;
195     stack->stack_size = stack_size;
196     stack->alignment = SILC_STACK_DEFAULT_ALIGN;
197     stack->oom_handler = parent->oom_handler;
198     stack->oom_context = parent->oom_context;
199     stack->lock = parent->lock;
200     silc_list_init(stack->stacks, struct SilcStackDataEntryStruct, next);
201
202     /* Allocate stack frames from the parent */
203     stack->frames = silc_stack_alloc_block(parent, e, SILC_STACK_BLOCK_NUM,
204                                            sizeof(*stack->frames));
205     if (!stack->frames) {
206       silc_stack_unref_stack(parent, e);
207       return NULL;
208     }
209
210     /* Set the initial stack */
211     stack->stack = e;
212   } else {
213     /* Dynamically allocate new stack */
214     stack = silc_calloc(1, sizeof(*stack));
215     if (!stack)
216       return NULL;
217
218     stack->stack_size = stack_size;
219     stack->alignment = SILC_STACK_DEFAULT_ALIGN;
220     silc_list_init(stack->stacks, struct SilcStackDataEntryStruct, next);
221
222     /* Create initial stack */
223     stack->stack = silc_calloc(1, sizeof(*stack->stack));
224     if (!stack->stack) {
225       silc_free(stack);
226       return NULL;
227     }
228     stack->stack->data[0] =
229       silc_malloc(stack->stack_size +
230                   SILC_STACK_ALIGN(sizeof(*stack->stack->data[0]),
231                                    stack->alignment));
232     if (!stack->stack->data[0]) {
233       silc_free(stack->stack);
234       silc_free(stack);
235       return NULL;
236     }
237     stack->stack->data[0]->bytes_left = stack->stack_size;
238     stack->stack->si = 0;
239     stack->stack->bsize = stack->stack_size;
240
241     /* Allocate stack frames from the stack itself */
242     stack->frames = silc_stack_alloc_block(stack, stack->stack,
243                                            SILC_STACK_DEFAULT_NUM,
244                                            sizeof(*stack->frames));
245     if (!stack->frames) {
246       silc_free(stack->stack->data[0]);
247       silc_free(stack->stack);
248       silc_free(stack);
249       return NULL;
250     }
251
252     /* Allocate lock */
253     silc_mutex_alloc(&stack->lock);
254   }
255
256   /* Use the allocated stack in first stack frame */
257   stack->frame = &stack->frames[0];
258   stack->frame->prev = NULL;
259   stack->frame->bytes_used = stack->stack_size;
260   stack->frame->sp = 1;
261   stack->frame->si = si;
262
263   SILC_LOG_DEBUG(("New stack %p, size %d bytes", stack, stack->stack_size));
264
265   return stack;
266 }
267
268 /* Frees the stack and all allocated memory */
269
270 void silc_stack_free(SilcStack stack)
271 {
272   SilcStackDataEntry e;
273   int i;
274
275   if (!stack)
276     return;
277
278   SILC_LOG_DEBUG(("Free stack %p", stack));
279
280   if (!stack->parent) {
281     silc_list_start(stack->stacks);
282     while ((e = silc_list_get(stack->stacks))) {
283       for (i = 0; i < SILC_STACK_BLOCK_NUM; i++)
284         silc_free(e->data[i]);
285       silc_free(e);
286     }
287
288     for (i = 0; i < SILC_STACK_BLOCK_NUM; i++)
289       silc_free(stack->stack->data[i]);
290     silc_free(stack->stack);
291
292     if (stack->lock)
293       silc_mutex_free(stack->lock);
294
295     silc_free(stack);
296   } else {
297     /* Return all stack blocks to the parent */
298     silc_list_start(stack->stacks);
299     while ((e = silc_list_get(stack->stacks)))
300       silc_stack_unref_stack(stack->parent, e);
301
302     silc_stack_unref_stack(stack->parent, stack->stack);
303   }
304 }
305
306 /* Push to next stack frame */
307
308 SilcUInt32 silc_stack_push(SilcStack stack, SilcStackFrame *frame)
309 {
310   if (!stack)
311     return 0;
312
313   if (!frame) {
314     if (stack->frame->sp >= SILC_STACK_ALIGN(stack->frame->sp,
315                                              SILC_STACK_DEFAULT_NUM)) {
316       SILC_LOG_DEBUG(("SilcStack %p running out of frames, cannot push",
317                       stack));
318       return stack->frame->sp;
319     }
320
321     frame = &stack->frames[stack->frame->sp];
322   }
323
324   /* Push */
325   frame->prev = stack->frame;
326   frame->sp = stack->frame->sp + 1;
327   frame->si = stack->frame->si;
328   frame->bytes_used = stack->stack->data[frame->si]->bytes_left;
329   stack->frame = frame;
330
331   SILC_ST_DEBUG(("Push %p: sp %d -> %d, si %d", stack, frame->prev->sp,
332                  frame->sp, frame->si));
333
334   return stack->frame->sp;
335 }
336
337 /* Pop to previous stack frame */
338
339 SilcUInt32 silc_stack_pop(SilcStack stack)
340 {
341   SilcUInt32 si;
342
343   if (!stack || !stack->frame->prev)
344     return 0;
345
346   /* Pop */
347   si = stack->frame->si;
348   while (si > stack->frame->prev->si) {
349     if (stack->stack->data[si])
350       stack->stack->data[si]->bytes_left = SILC_STACK_BLOCK_SIZE(stack, si);
351     si--;
352   }
353   stack->stack->data[si]->bytes_left = stack->frame->bytes_used;
354   stack->frame = stack->frame->prev;
355
356   SILC_ST_DEBUG(("Pop %p: sp %d -> %d, si %d", stack, stack->frame->sp + 1,
357                  stack->frame->sp, stack->frame->si));
358
359   return stack->frame->sp + 1;
360 }
361
362 /* Allocate memory.  Returns pointer to the memory or NULL on error. */
363
364 void *silc_stack_malloc(SilcStack stack, SilcUInt32 size)
365 {
366   void *ptr;
367   SilcUInt32 bsize, bsize2;
368   SilcUInt32 si = stack->frame->si;
369
370   SILC_STACK_STAT(stack, num_malloc, 1);
371   SILC_ST_DEBUG(("Allocating %d bytes from %p", size, stack));
372
373   if (silc_unlikely(!size)) {
374     SILC_LOG_ERROR(("Allocation by zero (0)"));
375     SILC_STACK_STAT(stack, num_errors, 1);
376     return NULL;
377   }
378
379   if (silc_unlikely(size > SILC_STACK_MAX_ALLOC)) {
380     SILC_LOG_ERROR(("Allocating too much"));
381     SILC_STACK_STAT(stack, num_errors, 1);
382     if (stack->oom_handler)
383       stack->oom_handler(stack, stack->oom_context);
384     return NULL;
385   }
386
387   /* Align properly  */
388   size = SILC_STACK_ALIGN(size, stack->alignment);
389
390   /* Compute the size of current stack block */
391   bsize = SILC_STACK_BLOCK_SIZE(stack, si);
392
393   /* See if there is space in the current stack block */
394   if (stack->stack->data[si]->bytes_left >= size) {
395     /* Get pointer to the memory */
396     ptr = SILC_STACK_DATA(stack, si, bsize);
397     stack->stack->data[si]->bytes_left -= size;
398     SILC_STACK_STAT(stack, bytes_malloc, size);
399     return ptr;
400   }
401
402   /* There is not enough space in this block.  Find the spot to stack
403      block that can handle this size memory. */
404   if (bsize < SILC_STACK_DEFAULT_SIZE)
405     bsize = SILC_STACK_DEFAULT_SIZE;
406   bsize += size;
407   bsize2 = SILC_STACK_DEFAULT_SIZE;
408   si = 0;
409   while (bsize2 < bsize) {
410     bsize2 <<= 1;
411     si++;
412   }
413   if (silc_unlikely(si >= SILC_STACK_BLOCK_NUM)) {
414     SILC_LOG_ERROR(("Allocating too large block"));
415     SILC_STACK_STAT(stack, num_errors, 1);
416     if (stack->oom_handler)
417       stack->oom_handler(stack, stack->oom_context);
418     return NULL;
419   }
420
421   /* Allocate the block if it doesn't exist yet */
422   if (!stack->stack->data[si]) {
423     SILC_ST_DEBUG(("Allocating new stack block, %d bytes", bsize2));
424     stack->stack->data[si] =
425       silc_malloc(bsize2 +
426                   SILC_STACK_ALIGN(sizeof(**stack->stack->data),
427                                    stack->alignment));
428     if (silc_unlikely(!stack->stack->data[si])) {
429       SILC_STACK_STAT(stack, num_errors, 1);
430       if (stack->oom_handler)
431         stack->oom_handler(stack, stack->oom_context);
432       return NULL;
433     }
434     stack->stack->data[si]->bytes_left = bsize2;
435   }
436
437   /* Now return memory from this new block.  It is guaranteed that in this
438      block there is enough space for this memory. */
439   assert(stack->stack->data[si]->bytes_left >= size);
440   ptr = SILC_STACK_DATA(stack, si, bsize2);
441   stack->stack->data[si]->bytes_left -= size;
442   stack->frame->si = si;
443   SILC_STACK_STAT(stack, bytes_malloc, size);
444
445   return ptr;
446 }
447
448 /* Attempts to reallocate memory by changing the size of the `ptr' into
449    `size'.  This routine works only if the previous allocation to `stack'
450    was `ptr'.  If there is another memory allocation between allocating
451    `ptr' and this call this routine will return NULL.  NULL is also returned
452    if the `size' does not fit into the current block.  If NULL is returned
453    the old memory remains intact. */
454
455 void *silc_stack_realloc(SilcStack stack, SilcUInt32 old_size,
456                          void *ptr, SilcUInt32 size)
457 {
458   SilcUInt32 si = stack->frame->si;
459   SilcUInt32 bsize;
460   void *sptr;
461
462   if (!ptr)
463     return silc_stack_malloc(stack, size);
464
465   SILC_STACK_STAT(stack, num_malloc, 1);
466   SILC_ST_DEBUG(("Reallocating %d bytes (%d) from %p", size, old_size, stack));
467
468   if (silc_unlikely(!size || !old_size)) {
469     SILC_LOG_ERROR(("Allocation by zero (0)"));
470     SILC_STACK_STAT(stack, num_errors, 1);
471     return NULL;
472   }
473
474   if (silc_unlikely(size > SILC_STACK_MAX_ALLOC)) {
475     SILC_LOG_ERROR(("Allocating too much"));
476     SILC_STACK_STAT(stack, num_errors, 1);
477     if (stack->oom_handler)
478       stack->oom_handler(stack, stack->oom_context);
479     return NULL;
480   }
481
482   /* Align properly */
483   old_size = SILC_STACK_ALIGN(old_size, stack->alignment);
484
485   /* Compute the size of current stack block */
486   bsize = SILC_STACK_BLOCK_SIZE(stack, si);
487
488   /* Check that `ptr' is last allocation */
489   sptr = (unsigned char *)stack->stack->data[si] +
490     SILC_STACK_ALIGN(sizeof(**stack->stack->data), stack->alignment);
491   if (stack->stack->data[si]->bytes_left + old_size +
492       ((unsigned char *)ptr - (unsigned char *)sptr) != bsize) {
493     SILC_LOG_DEBUG(("Cannot reallocate"));
494     SILC_STACK_STAT(stack, num_errors, 1);
495     return NULL;
496   }
497
498   /* Now check that the new size fits to this block */
499   if (stack->stack->data[si]->bytes_left >= size) {
500     /* It fits, so simply return the old pointer */
501     size = SILC_STACK_ALIGN(size, stack->alignment);
502     stack->stack->data[si]->bytes_left -= (size - old_size);
503     SILC_STACK_STAT(stack, bytes_malloc, (size - old_size));
504     return ptr;
505   }
506
507   SILC_LOG_DEBUG(("Cannot reallocate in this block"));
508   SILC_STACK_STAT(stack, num_errors, 1);
509   return NULL;
510 }
511
512 /* Set OOM handler */
513
514 void silc_stack_set_oom_handler(SilcStack stack,
515                                 SilcStackOomHandler oom_handler,
516                                 void *context)
517 {
518   stack->oom_handler = oom_handler;
519   stack->oom_context = context;
520 }
521
522 /* Set default alignment */
523
524 void silc_stack_set_alignment(SilcStack stack, SilcUInt32 alignment)
525 {
526   SILC_LOG_DEBUG(("Set stack %p alignment to %d bytes", stack, alignment));
527   stack->alignment = alignment;
528 }
529
530 /* Get default alignment */
531
532 SilcUInt32 silc_stack_get_alignment(SilcStack stack)
533 {
534   return stack->alignment;
535 }
536
537 /* Purge stack */
538
539 SilcBool silc_stack_purge(SilcStack stack)
540 {
541   SilcStackDataEntry e;
542   SilcBool ret = FALSE;
543   int i;
544
545   SILC_LOG_DEBUG(("Purge stack %p", stack));
546
547   /* Go through the default stack */
548   for (i = SILC_STACK_BLOCK_NUM - 1; i > 3; i--) {
549     if (stack->stack->data[i] &&
550         stack->stack->data[i]->bytes_left == SILC_STACK_BLOCK_SIZE(stack, i)) {
551       SILC_LOG_DEBUG(("Purge %d bytes",
552                       SILC_STACK_BLOCK_SIZE(stack, i)));
553       silc_free(stack->stack->data[i]);
554       stack->stack->data[i] = NULL;
555       ret = TRUE;
556     }
557   }
558
559   silc_mutex_lock(stack->lock);
560
561   /* Remove one child stack */
562   if (silc_list_count(stack->stacks) > 2) {
563     silc_list_start(stack->stacks);
564     e = silc_list_get(stack->stacks);
565
566     SILC_LOG_DEBUG(("Remove stack blocks %p", e->data));
567     silc_list_del(stack->stacks, e);
568     ret = TRUE;
569
570     for (i = 0; i < SILC_STACK_BLOCK_NUM; i++)
571       silc_free(e->data[i]);
572     silc_free(e);
573   }
574
575   /* Go through the child stacks */
576   silc_list_start(stack->stacks);
577   while ((e = silc_list_get(stack->stacks))) {
578     for (i = SILC_STACK_BLOCK_NUM - 1; i > 3; i--) {
579       if (e->data[i]) {
580         SILC_LOG_DEBUG(("Purge %d bytes",
581                         SILC_STACK_BLOCK_SIZE(stack, i)));
582         silc_free(e->data[i]);
583         e->data[i] = NULL;
584         ret = TRUE;
585       }
586     }
587   }
588
589   silc_mutex_unlock(stack->lock);
590
591   return ret;
592 }
593
594 #ifdef SILC_DIST_INPLACE
595 /* Statistics dumping. */
596
597 void silc_stack_stats(SilcStack stack)
598 {
599   SilcStackDataEntry e;
600   SilcUInt32 stack_size = 0;
601   int i, c = 0;
602
603   for (i = 0; i < SILC_STACK_BLOCK_NUM; i++) {
604     if (!stack->stack->data[i])
605       continue;
606     stack_size += SILC_STACK_BLOCK_SIZE(stack, i);
607     c++;
608   }
609
610   fprintf(stdout, "\nSilcStack %p statistics :\n\n", stack);
611   fprintf(stdout, "  Size of stack           : %u\n",
612           (unsigned int)stack_size);
613   fprintf(stdout, "  Stack alignment         : %d\n",
614           (int)stack->alignment);
615   fprintf(stdout, "  Number of allocs        : %u\n",
616           (unsigned int)stack->snum_malloc);
617   fprintf(stdout, "  Bytes allocated         : %u\n",
618           (unsigned int)stack->sbytes_malloc);
619   fprintf(stdout, "  Average alloc size      : %.2f\n",
620           (double)((double)stack->sbytes_malloc / (double)stack->snum_malloc));
621   fprintf(stdout, "  Number of alloc errors  : %u\n",
622           (unsigned int)stack->snum_errors);
623   fprintf(stdout, "  Number of frames        : %u\n",
624           (unsigned int)SILC_STACK_ALIGN(stack->frame->sp,
625                                          SILC_STACK_DEFAULT_NUM));
626   fprintf(stdout, "  Number of blocks        : %u\n", c);
627   fprintf(stdout, "  Number of stacks        : %d\n",
628           silc_list_count(stack->stacks));
629
630   silc_list_start(stack->stacks);
631   while ((e = silc_list_get(stack->stacks))) {
632     stack_size = 0;
633     c = 0;
634     for (i = 0; i < SILC_STACK_BLOCK_NUM; i++) {
635       if (!e->data[i])
636         continue;
637       stack_size += e->data[i]->bytes_left;
638       c++;
639     }
640     fprintf(stdout, "\n  Size of stack           : %u\n",
641             (unsigned int)stack_size);
642     fprintf(stdout, "  Number of blocks        : %u\n", c);
643   }
644 }
645 #endif /* SILC_DIST_INPLACE */