2c7e202a8c903d62740c77074cae35606959b04d
[yaz-moved-to-github.git] / src / nmem.c
1 /*
2  * Copyright (C) 1995-2006, Index Data ApS
3  * See the file LICENSE for details.
4  *
5  * $Id: nmem.c,v 1.24 2006-08-11 12:50:23 adam Exp $
6  */
7
8 /**
9  * \file nmem.c
10  * \brief Implements Nibble Memory
11  *
12  * This is a simple and fairly wasteful little module for nibble memory
13  * allocation. Evemtually we'll put in something better.
14  *
15  * FIXME - it also has some semaphore stuff, and stuff to handle errno.
16  *         These should be moved to some other place!
17  */
18 #if HAVE_CONFIG_H
19 #include <config.h>
20 #endif
21
22 #include <assert.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <errno.h>
26 #include <stddef.h>
27 #include <yaz/xmalloc.h>
28 #include <yaz/nmem.h>
29 #include <yaz/log.h>
30 #include <yaz/oid.h>
31
32 #ifdef WIN32
33 #include <windows.h>
34 #endif
35
36 #if YAZ_POSIX_THREADS
37 #include <pthread.h>
38 #endif
39
40 #if YAZ_GNU_THREADS
41 #include <pth.h>
42 #endif
43
44 #define NMEM_CHUNK (4*1024)
45
46 struct nmem_block
47 {
48     char *buf;              /* memory allocated in this block */
49     size_t size;            /* size of buf */
50     size_t top;             /* top of buffer */
51     struct nmem_block *next;
52 };
53
54 struct nmem_control
55 {
56     int total;
57     struct nmem_block *blocks;
58     struct nmem_control *next;
59 };
60
61 struct align {
62     char x;
63     union {
64         char c;
65         short s;
66         int i;
67         long l;
68 #if HAVE_LONG_LONG
69         long long ll;
70 #endif
71         float f;
72         double d;
73     } u;
74 };
75
76 #define NMEM_ALIGN (offsetof(struct align, u))
77
78 static int log_level = 0;
79 static int log_level_initialized = 0;
80
81 #ifdef WIN32
82 static CRITICAL_SECTION critical_section;
83 #define NMEM_ENTER EnterCriticalSection(&critical_section)
84 #define NMEM_LEAVE LeaveCriticalSection(&critical_section)
85 struct nmem_mutex {
86     CRITICAL_SECTION m_handle;
87 };
88 #elif YAZ_POSIX_THREADS
89 static pthread_mutex_t nmem_mutex = PTHREAD_MUTEX_INITIALIZER;
90 #define NMEM_ENTER pthread_mutex_lock(&nmem_mutex);
91 #define NMEM_LEAVE pthread_mutex_unlock(&nmem_mutex);
92 struct nmem_mutex {
93     pthread_mutex_t m_handle;
94 };
95 #elif YAZ_GNU_THREADS
96 static pth_mutex_t nmem_mutex = PTH_MUTEX_INIT;
97 #define NMEM_ENTER pth_mutex_acquire(&nmem_mutex, 0, 0)
98 #define NMEM_LEAVE pth_mutex_release(&nmem_mutex)
99 struct nmem_mutex {
100     pth_mutex_t m_handle;
101 };
102 #else
103 #define NMEM_ENTER
104 #define NMEM_LEAVE
105 struct nmem_mutex {
106     int dummy;
107 };
108 #endif
109
110 size_t nmem_memory_in_use = 0;
111 size_t nmem_memory_free = 0;
112
113 YAZ_EXPORT void nmem_mutex_create(NMEM_MUTEX *p)
114 {
115     NMEM_ENTER;
116     if (!*p)
117     {
118         *p = (NMEM_MUTEX) malloc(sizeof(**p));
119 #ifdef WIN32
120         InitializeCriticalSection(&(*p)->m_handle);
121 #elif YAZ_POSIX_THREADS
122         pthread_mutex_init(&(*p)->m_handle, 0);
123 #elif YAZ_GNU_THREADS
124         pth_mutex_init(&(*p)->m_handle);
125 #endif
126     }
127     NMEM_LEAVE;
128     if (!log_level_initialized)
129     {
130         log_level_initialized = 1;
131         log_level = yaz_log_module_level("nmem");
132     }
133
134 }
135
136 YAZ_EXPORT void nmem_mutex_enter(NMEM_MUTEX p)
137 {
138     if (p)
139     {
140 #ifdef WIN32
141         EnterCriticalSection(&p->m_handle);
142 #elif YAZ_POSIX_THREADS
143         pthread_mutex_lock(&p->m_handle);
144 #endif
145     }
146 }
147
148 YAZ_EXPORT void nmem_mutex_leave(NMEM_MUTEX p)
149 {
150     if (p)
151     {
152 #ifdef WIN32
153         LeaveCriticalSection(&p->m_handle);
154 #elif YAZ_POSIX_THREADS
155         pthread_mutex_unlock(&p->m_handle);
156 #endif
157     }
158 }
159
160 YAZ_EXPORT void nmem_mutex_destroy(NMEM_MUTEX *p)
161 {
162     if (*p)
163     {
164 #ifdef WIN32
165         DeleteCriticalSection(&(*p)->m_handle);
166 #endif
167         free(*p);
168         *p = 0;
169     }
170 }
171
172 /** \brief free NMEM memory blocks . Reused in get_block */
173 static struct nmem_block *freelist = NULL;
174
175 /** \brief free NMEM control blocks. Reused in nmem_create */
176 static struct nmem_control *cfreelist = NULL;
177
178 /** \brief number NMEM's in use (number of nmem_controls not in free list) */
179 static int nmem_active_no = 0;
180
181 /** \brief NMEM usage counter */
182 static int nmem_init_flag = 0;
183
184 /** \brief whether nmem blocks should be reassigned to heap */
185 static int nmem_release_in_heap = 0;
186
187 #if NMEM_DEBUG
188 struct nmem_debug_info {
189     void *p;
190     char file[40];
191     int line;
192     struct nmem_debug_info *next;
193 };
194   
195 struct nmem_debug_info *nmem_debug_list = 0;  
196 #endif
197
198 static void free_block(struct nmem_block *p)
199 {  
200     nmem_memory_in_use -= p->size;
201     if (nmem_release_in_heap)
202     {
203         xfree(p->buf);
204         xfree(p);
205     }
206     else
207     {
208         memset(p->buf, 'Y', p->size);
209         p->next = freelist;
210         freelist = p;
211         nmem_memory_free += p->size;
212     }
213     if (log_level)
214         yaz_log (log_level, "nmem free_block p=%p", p);
215 }
216
217 #if NMEM_DEBUG
218 void nmem_print_list (void)
219 {
220     if (log_level)
221         nmem_print_list_l(log_level);
222 }
223
224 void nmem_print_list_l (int level)
225 {
226     struct nmem_debug_info *p;
227
228     yaz_log (level, "nmem print list");
229     NMEM_ENTER;
230     for (p = nmem_debug_list; p; p = p->next)
231         yaz_log (level, " %s:%d p=%p size=%d", p->file, p->line, p->p,
232                  nmem_total(p->p));
233     NMEM_LEAVE;
234 }
235 #endif
236 /*
237  * acquire a block with a minimum of size free bytes.
238  */
239 static struct nmem_block *get_block(size_t size)
240 {
241     struct nmem_block *r, *l;
242
243     if (log_level)
244         yaz_log (log_level, "nmem get_block size=%ld", (long) size);
245
246     for (r = freelist, l = 0; r; l = r, r = r->next)
247         if (r->size >= size)
248             break;
249     if (r)
250     {
251         if (log_level)
252             yaz_log (log_level, "nmem get_block found free block p=%p", r);
253         if (l)
254             l->next = r->next;
255         else
256             freelist = r->next;
257     }
258     else
259     {
260         size_t get = NMEM_CHUNK;
261
262         if (get < size)
263             get = size;
264         if(log_level)
265             yaz_log (log_level, "nmem get_block alloc new block size=%ld",
266                      (long) get);
267
268         r = (struct nmem_block *) xmalloc(sizeof(*r));
269         r->buf = (char *)xmalloc(r->size = get);
270         nmem_memory_in_use += r->size;
271     }
272     r->top = 0;
273     return r;
274 }
275
276 void nmem_reset(NMEM n)
277 {
278     struct nmem_block *t;
279     
280     yaz_log (log_level, "nmem_reset p=%p", n);
281     if (!n)
282         return;
283     NMEM_ENTER;
284     while (n->blocks)
285     {
286         t = n->blocks;
287         n->blocks = n->blocks->next;
288         free_block(t);
289     }
290     n->total = 0;
291     NMEM_LEAVE;
292 }
293
294 #if NMEM_DEBUG
295 void *nmem_malloc_f (const char *file, int line, NMEM n, int size)
296 #else
297 void *nmem_malloc(NMEM n, int size)
298 #endif
299 {
300     struct nmem_block *p;
301     char *r;
302
303 #if NMEM_DEBUG
304     if (log_level)
305         yaz_log (log_level, "%s:%d: nmem_malloc p=%p size=%d", 
306                 file, line, n, size);
307 #endif
308     if (!n)
309     {
310         yaz_log (YLOG_FATAL, "calling nmem_malloc with an null pointer");
311         abort ();
312     }
313 #ifdef WIN32
314     assert (nmem_init_flag);
315 #endif
316     NMEM_ENTER;
317     p = n->blocks;
318     if (!p || p->size < size + p->top)
319     {
320         p = get_block(size);
321         p->next = n->blocks;
322         n->blocks = p;
323     }
324     r = p->buf + p->top;
325     /* align size */
326     p->top += (size + (NMEM_ALIGN - 1)) & ~(NMEM_ALIGN - 1);
327     n->total += size;
328     NMEM_LEAVE;
329     return r;
330 }
331
332 int nmem_total(NMEM n)
333 {
334     return n->total;
335 }
336
337 #if NMEM_DEBUG
338 NMEM nmem_create_f(const char *file, int line)
339 #else
340 NMEM nmem_create(void)
341 #endif
342 {
343     NMEM r;
344 #if NMEM_DEBUG
345     struct nmem_debug_info *debug_p;
346 #endif
347     if (!log_level_initialized)
348     {
349         log_level = yaz_log_module_level("nmem");
350         log_level_initialized = 1;
351     }
352     
353     NMEM_ENTER;
354     nmem_active_no++;
355     r = cfreelist;
356     if (r)
357         cfreelist = cfreelist->next;
358     else
359         r = (struct nmem_control *)xmalloc(sizeof(*r));
360     NMEM_LEAVE;
361
362 #if NMEM_DEBUG
363     yaz_log (YLOG_DEBUG, "%s:%d: nmem_create %d p=%p", file, line,
364                      nmem_active_no, r);
365 #endif
366     r->blocks = 0;
367     r->total = 0;
368     r->next = 0;
369
370 #if NMEM_DEBUG
371     for (debug_p = nmem_debug_list; debug_p; debug_p = debug_p->next)
372         if (debug_p->p == r)
373         {
374             yaz_log (YLOG_FATAL, "multi used block in nmem");
375             abort ();
376         }
377     debug_p = xmalloc (sizeof(*debug_p));
378     strncpy (debug_p->file, file, sizeof(debug_p->file)-1);
379     debug_p->file[sizeof(debug_p->file)-1] = '\0';
380     debug_p->line = line;
381     debug_p->p = r;
382     debug_p->next = nmem_debug_list;
383     nmem_debug_list = debug_p;
384
385     nmem_print_list();
386 #endif
387     return r;
388 }
389
390 #if NMEM_DEBUG
391 void nmem_destroy_f(const char *file, int line, NMEM n)
392 #else
393 void nmem_destroy(NMEM n)
394 #endif
395 {
396 #if NMEM_DEBUG
397     struct nmem_debug_info **debug_p;
398     int ok = 0;
399 #endif
400     if (!n)
401         return;
402     
403 #if NMEM_DEBUG
404     yaz_log (log_level, "%s:%d: nmem_destroy %d p=%p", file, line,
405                      nmem_active_no-1, n);
406     NMEM_ENTER;
407     for (debug_p = &nmem_debug_list; *debug_p; debug_p = &(*debug_p)->next)
408         if ((*debug_p)->p == n)
409         {
410             struct nmem_debug_info *debug_save = *debug_p;
411             *debug_p = (*debug_p)->next;
412             xfree (debug_save);
413             ok = 1;
414             break;
415         }
416     NMEM_LEAVE;
417     nmem_print_list();
418     if (!ok)
419     {
420         yaz_log (YLOG_WARN, "%s:%d destroying unallocated nmem block p=%p",
421                  file, line, n);
422         return;
423     }
424 #endif
425     nmem_reset(n);
426     NMEM_ENTER;
427     nmem_active_no--;
428     if (nmem_release_in_heap)
429     {
430         xfree(n);
431     }
432     else
433     {
434         n->next = cfreelist;
435         cfreelist = n;
436     }
437     NMEM_LEAVE;
438 }
439
440 void nmem_transfer (NMEM dst, NMEM src)
441 {
442     struct nmem_block *t;
443     while ((t = src->blocks))
444     {
445         src->blocks = t->next;
446         t->next = dst->blocks;
447         dst->blocks = t;
448     }
449     dst->total += src->total;
450     src->total = 0;
451 }
452
453 void nmem_get_memory_in_use(size_t *p)
454 {
455     NMEM_ENTER;
456     *p = nmem_memory_in_use;
457     NMEM_LEAVE;
458 }
459
460 void nmem_get_memory_free(size_t *p)
461 {
462     NMEM_ENTER;
463     *p = nmem_memory_free;
464     NMEM_LEAVE;
465 }
466
467 void nmem_critical_enter (void)
468 {
469     NMEM_ENTER;
470 }
471
472 void nmem_critical_leave (void)
473 {
474     NMEM_LEAVE;
475 }
476
477 void nmem_init (void)
478 {
479     if (++nmem_init_flag == 1)
480     {
481 #ifdef WIN32
482         InitializeCriticalSection(&critical_section);
483 #elif YAZ_GNU_THREADS
484         pth_init ();
485 #endif
486         nmem_active_no = 0;
487         freelist = NULL;
488         cfreelist = NULL;
489     }
490     if (!log_level_initialized)
491     {
492         log_level = yaz_log_module_level("nmem");
493         log_level_initialized = 1;
494     }
495 }
496
497 void nmem_exit (void)
498 {
499     if (--nmem_init_flag == 0)
500     {
501         oid_exit();
502         while (freelist)
503         {
504             struct nmem_block *fl = freelist;
505             nmem_memory_free -= fl->size;
506             freelist = freelist->next;
507             xfree (fl->buf);
508             xfree (fl);
509         }
510         while (cfreelist)
511         {
512             struct nmem_control *cfl = cfreelist;
513             cfreelist = cfreelist->next;
514             xfree (cfl);
515         }
516 #ifdef WIN32
517         DeleteCriticalSection(&critical_section);
518 #endif
519     }
520 }
521
522
523 #ifdef WIN32
524 BOOL WINAPI DllMain (HINSTANCE hinstDLL,
525                      DWORD reason,
526                      LPVOID reserved)
527 {
528     switch (reason)
529     {
530     case DLL_PROCESS_ATTACH:
531         nmem_init ();
532         break;
533     case DLL_PROCESS_DETACH:
534         nmem_exit ();
535     }
536     return TRUE;
537 }
538 #endif
539
540 int yaz_errno(void)
541 {
542     return errno;
543 }
544
545 void yaz_set_errno(int v)
546 {
547     errno = v;
548 }
549
550 void yaz_strerror(char *buf, int max)
551 {
552 #ifdef WIN32
553     DWORD err;
554 #endif
555     char *cp;
556     if (!log_level_initialized)
557     {
558         log_level = yaz_log_module_level("nmem");
559         log_level_initialized = 1;
560     }
561     
562 #ifdef WIN32
563     err = GetLastError();
564     if (err)
565     {
566         FormatMessage(
567                 FORMAT_MESSAGE_FROM_SYSTEM,
568                 NULL,
569                 err,
570                 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), /* Default lang */
571                 (LPTSTR) buf,
572                 max-1,
573                 NULL);
574     }
575     else
576         *buf = '\0';
577 #else
578 /* UNIX */
579 #if HAVE_STRERROR_R
580 #if YAZ_POSIX_THREADS
581     *buf = '\0';
582     strerror_r(errno, buf, max);
583     /* if buffer is unset - use strerror anyway (GLIBC bug) */
584     if (*buf == '\0')
585         strcpy(buf, strerror(yaz_errno()));
586 #else
587     strcpy(buf, strerror(yaz_errno()));
588 #endif
589 #else
590     strcpy(buf, strerror(yaz_errno()));
591 #endif
592 /* UNIX */
593 #endif
594     if ((cp = strrchr(buf, '\n')))
595         *cp = '\0';
596     if ((cp = strrchr(buf, '\r')))
597         *cp = '\0';
598 }
599 /*
600  * Local variables:
601  * c-basic-offset: 4
602  * indent-tabs-mode: nil
603  * End:
604  * vim: shiftwidth=4 tabstop=8 expandtab
605  */
606