SILC_ERR_INVALID_ARGUMENT is return by silc_stack_realloc if
[crypto.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 (but does not consume parent's own stack). */
183     e = silc_stack_ref_stack(parent, stack_size, &si, &bsize);
184     if (!e)
185       return NULL;
186
187     /* Allocate stack from the returned stack.  We allocate ourselves from
188        our own stack. */
189     stack = silc_stack_alloc_block(parent, e, 1, sizeof(*stack));
190     if (!stack) {
191       silc_stack_unref_stack(parent, e);
192       return NULL;
193     }
194
195     stack->parent = parent;
196     stack->stack_size = stack_size;
197     stack->alignment = SILC_STACK_DEFAULT_ALIGN;
198     stack->oom_handler = parent->oom_handler;
199     stack->oom_context = parent->oom_context;
200     stack->lock = parent->lock;
201     silc_list_init(stack->stacks, struct SilcStackDataEntryStruct, next);
202
203     /* Allocate stack frames from the stack itself */
204     stack->frames = silc_stack_alloc_block(stack, e, SILC_STACK_BLOCK_NUM,
205                                            sizeof(*stack->frames));
206     if (!stack->frames) {
207       silc_stack_unref_stack(parent, e);
208       return NULL;
209     }
210
211     /* Set the initial stack */
212     stack->stack = e;
213   } else {
214     /* Dynamically allocate new stack */
215     stack = silc_calloc(1, sizeof(*stack));
216     if (!stack)
217       return NULL;
218
219     stack->stack_size = stack_size;
220     stack->alignment = SILC_STACK_DEFAULT_ALIGN;
221     silc_list_init(stack->stacks, struct SilcStackDataEntryStruct, next);
222
223     /* Create initial stack */
224     stack->stack = silc_calloc(1, sizeof(*stack->stack));
225     if (!stack->stack) {
226       silc_free(stack);
227       return NULL;
228     }
229     stack->stack->data[0] =
230       silc_malloc(stack->stack_size +
231                   SILC_STACK_ALIGN(sizeof(*stack->stack->data[0]),
232                                    stack->alignment));
233     if (!stack->stack->data[0]) {
234       silc_free(stack->stack);
235       silc_free(stack);
236       return NULL;
237     }
238     stack->stack->data[0]->bytes_left = stack->stack_size;
239     stack->stack->si = 0;
240     stack->stack->bsize = stack->stack_size;
241
242     /* Allocate stack frames from the stack itself */
243     stack->frames = silc_stack_alloc_block(stack, stack->stack,
244                                            SILC_STACK_DEFAULT_NUM,
245                                            sizeof(*stack->frames));
246     if (!stack->frames) {
247       silc_free(stack->stack->data[0]);
248       silc_free(stack->stack);
249       silc_free(stack);
250       return NULL;
251     }
252
253     /* Allocate lock */
254     silc_mutex_alloc(&stack->lock);
255   }
256
257   /* Use the allocated stack in first stack frame */
258   stack->frame = &stack->frames[0];
259   stack->frame->prev = NULL;
260   stack->frame->bytes_used = stack->stack_size;
261   stack->frame->sp = 1;
262   stack->frame->si = si;
263
264   SILC_LOG_DEBUG(("New stack %p, size %d bytes", stack, stack->stack_size));
265
266   return stack;
267 }
268
269 /* Frees the stack and all allocated memory */
270
271 void silc_stack_free(SilcStack stack)
272 {
273   SilcStackDataEntry e;
274   int i;
275
276   if (!stack)
277     return;
278
279   SILC_LOG_DEBUG(("Free stack %p", stack));
280
281   if (!stack->parent) {
282     silc_list_start(stack->stacks);
283     while ((e = silc_list_get(stack->stacks))) {
284       for (i = 0; i < SILC_STACK_BLOCK_NUM; i++)
285         silc_free(e->data[i]);
286       silc_free(e);
287     }
288
289     for (i = 0; i < SILC_STACK_BLOCK_NUM; i++)
290       silc_free(stack->stack->data[i]);
291     silc_free(stack->stack);
292
293     if (stack->lock)
294       silc_mutex_free(stack->lock);
295
296     silc_free(stack);
297   } else {
298     /* Return all stack blocks to the parent */
299     silc_list_start(stack->stacks);
300     while ((e = silc_list_get(stack->stacks)))
301       silc_stack_unref_stack(stack->parent, e);
302
303     silc_stack_unref_stack(stack->parent, stack->stack);
304   }
305 }
306
307 /* Push to next stack frame */
308
309 SilcUInt32 silc_stack_push(SilcStack stack, SilcStackFrame *frame)
310 {
311   if (!stack)
312     return 0;
313
314   if (!frame) {
315     if (stack->frame->sp >= SILC_STACK_ALIGN(stack->frame->sp,
316                                              SILC_STACK_DEFAULT_NUM)) {
317       SILC_LOG_DEBUG(("SilcStack %p running out of frames, cannot push",
318                       stack));
319       return stack->frame->sp;
320     }
321
322     frame = &stack->frames[stack->frame->sp];
323   }
324
325   /* Push */
326   frame->prev = stack->frame;
327   frame->sp = stack->frame->sp + 1;
328   frame->si = stack->frame->si;
329   frame->bytes_used = stack->stack->data[frame->si]->bytes_left;
330   stack->frame = frame;
331
332   SILC_ST_DEBUG(("Push %p: sp %d -> %d, si %d", stack, frame->prev->sp,
333                  frame->sp, frame->si));
334
335   return stack->frame->sp;
336 }
337
338 /* Pop to previous stack frame */
339
340 SilcUInt32 silc_stack_pop(SilcStack stack)
341 {
342   SilcUInt32 si;
343
344   if (!stack || !stack->frame->prev)
345     return 0;
346
347   /* Pop */
348   si = stack->frame->si;
349   while (si > stack->frame->prev->si) {
350     if (stack->stack->data[si])
351       stack->stack->data[si]->bytes_left = SILC_STACK_BLOCK_SIZE(stack, si);
352     si--;
353   }
354   stack->stack->data[si]->bytes_left = stack->frame->bytes_used;
355   stack->frame = stack->frame->prev;
356
357   SILC_ST_DEBUG(("Pop %p: sp %d -> %d, si %d", stack, stack->frame->sp + 1,
358                  stack->frame->sp, stack->frame->si));
359
360   return stack->frame->sp + 1;
361 }
362
363 /* Allocate memory.  Returns pointer to the memory or NULL on error. */
364
365 void *silc_stack_malloc(SilcStack stack, SilcUInt32 size)
366 {
367   void *ptr;
368   SilcUInt32 bsize, bsize2;
369   SilcUInt32 si = stack->frame->si;
370
371   SILC_STACK_STAT(stack, num_malloc, 1);
372   SILC_ST_DEBUG(("Allocating %d bytes from %p", size, stack));
373
374   if (silc_unlikely(!size)) {
375     SILC_LOG_DEBUG(("Allocation by zero (0)"));
376     silc_set_errno_nofail(SILC_ERR_ZERO_ALLOCATION);
377     SILC_STACK_STAT(stack, num_errors, 1);
378     return NULL;
379   }
380
381   if (silc_unlikely(size > SILC_STACK_MAX_ALLOC)) {
382     SILC_LOG_DEBUG(("Allocating too much"));
383     silc_set_errno_nofail(SILC_ERR_TOO_LARGE_ALLOCATION);
384     SILC_STACK_STAT(stack, num_errors, 1);
385     if (stack->oom_handler)
386       stack->oom_handler(stack, stack->oom_context);
387     return NULL;
388   }
389
390   /* Align properly  */
391   size = SILC_STACK_ALIGN(size, stack->alignment);
392
393   /* Compute the size of current stack block */
394   bsize = SILC_STACK_BLOCK_SIZE(stack, si);
395
396   /* See if there is space in the current stack block */
397   if (stack->stack->data[si]->bytes_left >= size) {
398     /* Get pointer to the memory */
399     ptr = SILC_STACK_DATA(stack, si, bsize);
400     stack->stack->data[si]->bytes_left -= size;
401     SILC_STACK_STAT(stack, bytes_malloc, size);
402     return ptr;
403   }
404
405   /* There is not enough space in this block.  Find the spot to stack
406      block that can handle this size memory. */
407   if (bsize < SILC_STACK_DEFAULT_SIZE)
408     bsize = SILC_STACK_DEFAULT_SIZE;
409   bsize += size;
410   bsize2 = SILC_STACK_DEFAULT_SIZE;
411   si = 0;
412   while (bsize2 < bsize) {
413     bsize2 <<= 1;
414     si++;
415   }
416   if (silc_unlikely(si >= SILC_STACK_BLOCK_NUM)) {
417     SILC_LOG_DEBUG(("Allocating too large block"));
418     silc_set_errno_nofail(SILC_ERR_TOO_LARGE_ALLOCATION);
419     SILC_STACK_STAT(stack, num_errors, 1);
420     if (stack->oom_handler)
421       stack->oom_handler(stack, stack->oom_context);
422     return NULL;
423   }
424
425   /* Allocate the block if it doesn't exist yet */
426   if (!stack->stack->data[si]) {
427     SILC_ST_DEBUG(("Allocating new stack block, %d bytes", bsize2));
428     stack->stack->data[si] =
429       silc_malloc(bsize2 +
430                   SILC_STACK_ALIGN(sizeof(**stack->stack->data),
431                                    stack->alignment));
432     if (silc_unlikely(!stack->stack->data[si])) {
433       SILC_STACK_STAT(stack, num_errors, 1);
434       if (stack->oom_handler)
435         stack->oom_handler(stack, stack->oom_context);
436       return NULL;
437     }
438     stack->stack->data[si]->bytes_left = bsize2;
439   }
440
441   /* Now return memory from this new block.  It is guaranteed that in this
442      block there is enough space for this memory. */
443   assert(stack->stack->data[si]->bytes_left >= size);
444   ptr = SILC_STACK_DATA(stack, si, bsize2);
445   stack->stack->data[si]->bytes_left -= size;
446   stack->frame->si = si;
447   SILC_STACK_STAT(stack, bytes_malloc, size);
448
449   return ptr;
450 }
451
452 /* Attempts to reallocate memory by changing the size of the `ptr' into
453    `size'.  This routine works only if the previous allocation to `stack'
454    was `ptr'.  If there is another memory allocation between allocating
455    `ptr' and this call this routine will return NULL.  NULL is also returned
456    if the `size' does not fit into the current block.  If NULL is returned
457    the old memory remains intact. */
458
459 void *silc_stack_realloc(SilcStack stack, SilcUInt32 old_size,
460                          void *ptr, SilcUInt32 size)
461 {
462   SilcUInt32 si = stack->frame->si;
463   SilcUInt32 bsize;
464   void *sptr;
465
466   if (!ptr)
467     return silc_stack_malloc(stack, size);
468
469   SILC_STACK_STAT(stack, num_malloc, 1);
470   SILC_ST_DEBUG(("Reallocating %d bytes (%d) from %p", size, old_size, stack));
471
472   if (silc_unlikely(!size || !old_size)) {
473     SILC_LOG_DEBUG(("Allocation by zero (0)"));
474     silc_set_errno_nofail(SILC_ERR_ZERO_ALLOCATION);
475     SILC_STACK_STAT(stack, num_errors, 1);
476     return NULL;
477   }
478
479   if (silc_unlikely(size > SILC_STACK_MAX_ALLOC)) {
480     SILC_LOG_DEBUG(("Allocating too much"));
481     silc_set_errno_nofail(SILC_ERR_TOO_LARGE_ALLOCATION);
482     SILC_STACK_STAT(stack, num_errors, 1);
483     if (stack->oom_handler)
484       stack->oom_handler(stack, stack->oom_context);
485     return NULL;
486   }
487
488   /* Align properly */
489   old_size = SILC_STACK_ALIGN(old_size, stack->alignment);
490
491   /* Compute the size of current stack block */
492   bsize = SILC_STACK_BLOCK_SIZE(stack, si);
493
494   /* Check that `ptr' is last allocation */
495   sptr = (unsigned char *)stack->stack->data[si] +
496     SILC_STACK_ALIGN(sizeof(**stack->stack->data), stack->alignment);
497   if (stack->stack->data[si]->bytes_left + old_size +
498       ((unsigned char *)ptr - (unsigned char *)sptr) != bsize) {
499     SILC_LOG_DEBUG(("Cannot reallocate"));
500     silc_set_errno_nofail(SILC_ERR_INVALID_ARGUMENT);
501     SILC_STACK_STAT(stack, num_errors, 1);
502     return NULL;
503   }
504
505   /* Now check that the new size fits to this block */
506   if (stack->stack->data[si]->bytes_left >= size) {
507     /* It fits, so simply return the old pointer */
508     size = SILC_STACK_ALIGN(size, stack->alignment);
509     stack->stack->data[si]->bytes_left -= (size - old_size);
510     SILC_STACK_STAT(stack, bytes_malloc, (size - old_size));
511     return ptr;
512   }
513
514   SILC_LOG_DEBUG(("Cannot reallocate in this block"));
515   silc_set_errno_reason_nofail(SILC_ERR_TOO_LARGE_ALLOCATION,
516                                "Cannot reallocate in this memory block");
517   SILC_STACK_STAT(stack, num_errors, 1);
518   return NULL;
519 }
520
521 /* Set OOM handler */
522
523 void silc_stack_set_oom_handler(SilcStack stack,
524                                 SilcStackOomHandler oom_handler,
525                                 void *context)
526 {
527   stack->oom_handler = oom_handler;
528   stack->oom_context = context;
529 }
530
531 /* Set default alignment */
532
533 void silc_stack_set_alignment(SilcStack stack, SilcUInt32 alignment)
534 {
535   SILC_LOG_DEBUG(("Set stack %p alignment to %d bytes", stack, alignment));
536   stack->alignment = alignment;
537 }
538
539 /* Get default alignment */
540
541 SilcUInt32 silc_stack_get_alignment(SilcStack stack)
542 {
543   return stack->alignment;
544 }
545
546 /* Purge stack */
547
548 SilcBool silc_stack_purge(SilcStack stack)
549 {
550   SilcStackDataEntry e;
551   SilcBool ret = FALSE;
552   int i;
553
554   SILC_LOG_DEBUG(("Purge stack %p", stack));
555
556   /* Go through the default stack */
557   for (i = SILC_STACK_BLOCK_NUM - 1; i > 3; i--) {
558     if (stack->stack->data[i] &&
559         stack->stack->data[i]->bytes_left == SILC_STACK_BLOCK_SIZE(stack, i)) {
560       SILC_LOG_DEBUG(("Purge %d bytes",
561                       SILC_STACK_BLOCK_SIZE(stack, i)));
562       silc_free(stack->stack->data[i]);
563       stack->stack->data[i] = NULL;
564       ret = TRUE;
565     }
566   }
567
568   silc_mutex_lock(stack->lock);
569
570   /* Remove one child stack */
571   if (silc_list_count(stack->stacks) > 2) {
572     silc_list_start(stack->stacks);
573     e = silc_list_get(stack->stacks);
574
575     SILC_LOG_DEBUG(("Remove stack blocks %p", e->data));
576     silc_list_del(stack->stacks, e);
577     ret = TRUE;
578
579     for (i = 0; i < SILC_STACK_BLOCK_NUM; i++)
580       silc_free(e->data[i]);
581     silc_free(e);
582   }
583
584   /* Go through the child stacks */
585   silc_list_start(stack->stacks);
586   while ((e = silc_list_get(stack->stacks))) {
587     for (i = SILC_STACK_BLOCK_NUM - 1; i > 3; i--) {
588       if (e->data[i]) {
589         SILC_LOG_DEBUG(("Purge %d bytes",
590                         SILC_STACK_BLOCK_SIZE(stack, i)));
591         silc_free(e->data[i]);
592         e->data[i] = NULL;
593         ret = TRUE;
594       }
595     }
596   }
597
598   silc_mutex_unlock(stack->lock);
599
600   return ret;
601 }
602
603 #ifdef SILC_DIST_INPLACE
604 /* Statistics dumping. */
605
606 void silc_stack_stats(SilcStack stack)
607 {
608   SilcStackDataEntry e;
609   SilcUInt32 stack_size = 0;
610   int i, c = 0;
611
612   for (i = 0; i < SILC_STACK_BLOCK_NUM; i++) {
613     if (!stack->stack->data[i])
614       continue;
615     stack_size += SILC_STACK_BLOCK_SIZE(stack, i);
616     c++;
617   }
618
619   fprintf(stdout, "\nSilcStack %p statistics :\n\n", stack);
620   fprintf(stdout, "  Size of stack           : %u\n",
621           (unsigned int)stack_size);
622   fprintf(stdout, "  Stack alignment         : %d\n",
623           (int)stack->alignment);
624   fprintf(stdout, "  Number of allocs        : %u\n",
625           (unsigned int)stack->snum_malloc);
626   fprintf(stdout, "  Bytes allocated         : %u\n",
627           (unsigned int)stack->sbytes_malloc);
628   fprintf(stdout, "  Average alloc size      : %.2f\n",
629           (double)((double)stack->sbytes_malloc / (double)stack->snum_malloc));
630   fprintf(stdout, "  Number of alloc errors  : %u\n",
631           (unsigned int)stack->snum_errors);
632   fprintf(stdout, "  Number of frames        : %u\n",
633           (unsigned int)SILC_STACK_ALIGN(stack->frame->sp,
634                                          SILC_STACK_DEFAULT_NUM));
635   fprintf(stdout, "  Number of blocks        : %u\n", c);
636   fprintf(stdout, "  Number of stacks        : %d\n",
637           silc_list_count(stack->stacks));
638
639   silc_list_start(stack->stacks);
640   while ((e = silc_list_get(stack->stacks))) {
641     stack_size = 0;
642     c = 0;
643     for (i = 0; i < SILC_STACK_BLOCK_NUM; i++) {
644       if (!e->data[i])
645         continue;
646       stack_size += e->data[i]->bytes_left;
647       c++;
648     }
649     fprintf(stdout, "\n  Size of stack           : %u\n",
650             (unsigned int)stack_size);
651     fprintf(stdout, "  Number of blocks        : %u\n", c);
652   }
653 }
654 #endif /* SILC_DIST_INPLACE */