233abcc6bebbed33783914113eab787432b5ce49
[yaz-moved-to-github.git] / src / nmem.c
1 /*
2  * Copyright (C) 1995-2005, Index Data ApS
3  * See the file LICENSE for details.
4  *
5  * $Id: nmem.c,v 1.23 2006-08-09 14:00:18 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     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 YAZ_EXPORT void nmem_mutex_create(NMEM_MUTEX *p)
111 {
112     NMEM_ENTER;
113     if (!*p)
114     {
115         *p = (NMEM_MUTEX) malloc(sizeof(**p));
116 #ifdef WIN32
117         InitializeCriticalSection(&(*p)->m_handle);
118 #elif YAZ_POSIX_THREADS
119         pthread_mutex_init(&(*p)->m_handle, 0);
120 #elif YAZ_GNU_THREADS
121         pth_mutex_init(&(*p)->m_handle);
122 #endif
123     }
124     NMEM_LEAVE;
125     if (!log_level_initialized)
126     {
127         log_level_initialized = 1;
128         log_level = yaz_log_module_level("nmem");
129     }
130
131 }
132
133 YAZ_EXPORT void nmem_mutex_enter(NMEM_MUTEX p)
134 {
135     if (p)
136     {
137 #ifdef WIN32
138         EnterCriticalSection(&p->m_handle);
139 #elif YAZ_POSIX_THREADS
140         pthread_mutex_lock(&p->m_handle);
141 #endif
142     }
143 }
144
145 YAZ_EXPORT void nmem_mutex_leave(NMEM_MUTEX p)
146 {
147     if (p)
148     {
149 #ifdef WIN32
150         LeaveCriticalSection(&p->m_handle);
151 #elif YAZ_POSIX_THREADS
152         pthread_mutex_unlock(&p->m_handle);
153 #endif
154     }
155 }
156
157 YAZ_EXPORT void nmem_mutex_destroy(NMEM_MUTEX *p)
158 {
159     if (*p)
160     {
161 #ifdef WIN32
162         DeleteCriticalSection(&(*p)->m_handle);
163 #endif
164         free(*p);
165         *p = 0;
166     }
167 }
168
169 static nmem_block *freelist = NULL;       /* "global" freelists */
170 static nmem_control *cfreelist = NULL;
171 static int nmem_active_no = 0;
172 static int nmem_init_flag = 0;
173
174 /** \brief whether nmem blocks should be reassigned to heap */
175 static int nmem_release_in_heap = 0;
176
177 #if NMEM_DEBUG
178 struct nmem_debug_info {
179     void *p;
180     char file[40];
181     int line;
182     struct nmem_debug_info *next;
183 };
184   
185 struct nmem_debug_info *nmem_debug_list = 0;  
186 #endif
187
188 static void free_block(nmem_block *p)
189 {  
190     if (nmem_release_in_heap)
191     {
192         xfree(p->buf);
193         xfree(p);
194     }
195     else
196     {
197         memset(p->buf, 'Y', p->size);
198         p->next = freelist;
199         freelist = p;
200     }
201     if (log_level)
202         yaz_log (log_level, "nmem free_block p=%p", p);
203 }
204
205 #if NMEM_DEBUG
206 void nmem_print_list (void)
207 {
208     if (log_level)
209         nmem_print_list_l(log_level);
210 }
211
212 void nmem_print_list_l (int level)
213 {
214     struct nmem_debug_info *p;
215
216     yaz_log (level, "nmem print list");
217     NMEM_ENTER;
218     for (p = nmem_debug_list; p; p = p->next)
219         yaz_log (level, " %s:%d p=%p size=%d", p->file, p->line, p->p,
220                  nmem_total(p->p));
221     NMEM_LEAVE;
222 }
223 #endif
224 /*
225  * acquire a block with a minimum of size free bytes.
226  */
227 static nmem_block *get_block(size_t size)
228 {
229     nmem_block *r, *l;
230
231     if (log_level)
232         yaz_log (log_level, "nmem get_block size=%ld", (long) size);
233
234     for (r = freelist, l = 0; r; l = r, r = r->next)
235         if (r->size >= size)
236             break;
237     if (r)
238     {
239         if (log_level)
240             yaz_log (log_level, "nmem get_block found free block p=%p", r);
241         if (l)
242             l->next = r->next;
243         else
244             freelist = r->next;
245     }
246     else
247     {
248         size_t get = NMEM_CHUNK;
249
250         if (get < size)
251             get = size;
252         if(log_level)
253             yaz_log (log_level, "nmem get_block alloc new block size=%ld",
254                      (long) get);
255
256         r = (nmem_block *)xmalloc(sizeof(*r));
257         r->buf = (char *)xmalloc(r->size = get);
258     }
259     r->top = 0;
260     return r;
261 }
262
263 void nmem_reset(NMEM n)
264 {
265     nmem_block *t;
266     
267     yaz_log (log_level, "nmem_reset p=%p", n);
268     if (!n)
269         return;
270     NMEM_ENTER;
271     while (n->blocks)
272     {
273         t = n->blocks;
274         n->blocks = n->blocks->next;
275         free_block(t);
276     }
277     n->total = 0;
278     NMEM_LEAVE;
279 }
280
281 #if NMEM_DEBUG
282 void *nmem_malloc_f (const char *file, int line, NMEM n, int size)
283 #else
284 void *nmem_malloc(NMEM n, int size)
285 #endif
286 {
287     struct nmem_block *p;
288     char *r;
289
290 #if NMEM_DEBUG
291     if (log_level)
292         yaz_log (log_level, "%s:%d: nmem_malloc p=%p size=%d", 
293                 file, line, n, size);
294 #endif
295     if (!n)
296     {
297         yaz_log (YLOG_FATAL, "calling nmem_malloc with an null pointer");
298         abort ();
299     }
300 #ifdef WIN32
301     assert (nmem_init_flag);
302 #endif
303     NMEM_ENTER;
304     p = n->blocks;
305     if (!p || p->size < size + p->top)
306     {
307         p = get_block(size);
308         p->next = n->blocks;
309         n->blocks = p;
310     }
311     r = p->buf + p->top;
312     /* align size */
313     p->top += (size + (NMEM_ALIGN - 1)) & ~(NMEM_ALIGN - 1);
314     n->total += size;
315     NMEM_LEAVE;
316     return r;
317 }
318
319 int nmem_total(NMEM n)
320 {
321     return n->total;
322 }
323
324 #if NMEM_DEBUG
325 NMEM nmem_create_f(const char *file, int line)
326 #else
327 NMEM nmem_create(void)
328 #endif
329 {
330     NMEM r;
331 #if NMEM_DEBUG
332     struct nmem_debug_info *debug_p;
333 #endif
334     if (!log_level_initialized)
335     {
336         log_level = yaz_log_module_level("nmem");
337         log_level_initialized = 1;
338     }
339     
340     NMEM_ENTER;
341     nmem_active_no++;
342     r = cfreelist;
343     if (r)
344         cfreelist = cfreelist->next;
345     else
346         r = (nmem_control *)xmalloc(sizeof(*r));
347     NMEM_LEAVE;
348
349 #if NMEM_DEBUG
350     yaz_log (YLOG_DEBUG, "%s:%d: nmem_create %d p=%p", file, line,
351                      nmem_active_no, r);
352 #endif
353     r->blocks = 0;
354     r->total = 0;
355     r->next = 0;
356
357 #if NMEM_DEBUG
358     for (debug_p = nmem_debug_list; debug_p; debug_p = debug_p->next)
359         if (debug_p->p == r)
360         {
361             yaz_log (YLOG_FATAL, "multi used block in nmem");
362             abort ();
363         }
364     debug_p = xmalloc (sizeof(*debug_p));
365     strncpy (debug_p->file, file, sizeof(debug_p->file)-1);
366     debug_p->file[sizeof(debug_p->file)-1] = '\0';
367     debug_p->line = line;
368     debug_p->p = r;
369     debug_p->next = nmem_debug_list;
370     nmem_debug_list = debug_p;
371
372     nmem_print_list();
373 #endif
374     return r;
375 }
376
377 #if NMEM_DEBUG
378 void nmem_destroy_f(const char *file, int line, NMEM n)
379 #else
380 void nmem_destroy(NMEM n)
381 #endif
382 {
383 #if NMEM_DEBUG
384     struct nmem_debug_info **debug_p;
385     int ok = 0;
386 #endif
387     if (!n)
388         return;
389     
390 #if NMEM_DEBUG
391     yaz_log (log_level, "%s:%d: nmem_destroy %d p=%p", file, line,
392                      nmem_active_no-1, n);
393     NMEM_ENTER;
394     for (debug_p = &nmem_debug_list; *debug_p; debug_p = &(*debug_p)->next)
395         if ((*debug_p)->p == n)
396         {
397             struct nmem_debug_info *debug_save = *debug_p;
398             *debug_p = (*debug_p)->next;
399             xfree (debug_save);
400             ok = 1;
401             break;
402         }
403     NMEM_LEAVE;
404     nmem_print_list();
405     if (!ok)
406     {
407         yaz_log (YLOG_WARN, "%s:%d destroying unallocated nmem block p=%p",
408                  file, line, n);
409         return;
410     }
411 #endif
412     nmem_reset(n);
413     NMEM_ENTER;
414     nmem_active_no--;
415     if (nmem_release_in_heap)
416     {
417         xfree(n);
418     }
419     else
420     {
421         n->next = cfreelist;
422         cfreelist = n;
423     }
424     NMEM_LEAVE;
425 }
426
427 void nmem_transfer (NMEM dst, NMEM src)
428 {
429     nmem_block *t;
430     while ((t = src->blocks))
431     {
432         src->blocks = t->next;
433         t->next = dst->blocks;
434         dst->blocks = t;
435     }
436     dst->total += src->total;
437     src->total = 0;
438 }
439
440 void nmem_critical_enter (void)
441 {
442     NMEM_ENTER;
443 }
444
445 void nmem_critical_leave (void)
446 {
447     NMEM_LEAVE;
448 }
449
450 void nmem_init (void)
451 {
452     
453     if (++nmem_init_flag == 1)
454     {
455 #ifdef WIN32
456         InitializeCriticalSection(&critical_section);
457 #elif YAZ_GNU_THREADS
458         pth_init ();
459 #endif
460         nmem_active_no = 0;
461         freelist = NULL;
462         cfreelist = NULL;
463     }
464     if (!log_level_initialized)
465     {
466         log_level = yaz_log_module_level("nmem");
467         log_level_initialized = 1;
468     }
469 }
470
471 void nmem_exit (void)
472 {
473     if (--nmem_init_flag == 0)
474     {
475         oid_exit();
476         while (freelist)
477         {
478             struct nmem_block *fl = freelist;
479             freelist = freelist->next;
480             xfree (fl->buf);
481             xfree (fl);
482         }
483         while (cfreelist)
484         {
485             struct nmem_control *cfl = cfreelist;
486             cfreelist = cfreelist->next;
487             xfree (cfl);
488         }
489 #ifdef WIN32
490         DeleteCriticalSection(&critical_section);
491 #endif
492     }
493 }
494
495
496 #ifdef WIN32
497 BOOL WINAPI DllMain (HINSTANCE hinstDLL,
498                      DWORD reason,
499                      LPVOID reserved)
500 {
501     switch (reason)
502     {
503     case DLL_PROCESS_ATTACH:
504         nmem_init ();
505         break;
506     case DLL_PROCESS_DETACH:
507         nmem_exit ();
508     }
509     return TRUE;
510 }
511 #endif
512
513 int yaz_errno(void)
514 {
515     return errno;
516 }
517
518 void yaz_set_errno(int v)
519 {
520     errno = v;
521 }
522
523 void yaz_strerror(char *buf, int max)
524 {
525 #ifdef WIN32
526     DWORD err;
527 #endif
528     char *cp;
529     if (!log_level_initialized)
530     {
531         log_level = yaz_log_module_level("nmem");
532         log_level_initialized = 1;
533     }
534     
535 #ifdef WIN32
536     err = GetLastError();
537     if (err)
538     {
539         FormatMessage(
540                 FORMAT_MESSAGE_FROM_SYSTEM,
541                 NULL,
542                 err,
543                 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), /* Default lang */
544                 (LPTSTR) buf,
545                 max-1,
546                 NULL);
547     }
548     else
549         *buf = '\0';
550 #else
551 /* UNIX */
552 #if HAVE_STRERROR_R
553 #if YAZ_POSIX_THREADS
554     *buf = '\0';
555     strerror_r(errno, buf, max);
556     /* if buffer is unset - use strerror anyway (GLIBC bug) */
557     if (*buf == '\0')
558         strcpy(buf, strerror(yaz_errno()));
559 #else
560     strcpy(buf, strerror(yaz_errno()));
561 #endif
562 #else
563     strcpy(buf, strerror(yaz_errno()));
564 #endif
565 /* UNIX */
566 #endif
567     if ((cp = strrchr(buf, '\n')))
568         *cp = '\0';
569     if ((cp = strrchr(buf, '\r')))
570         *cp = '\0';
571 }
572 /*
573  * Local variables:
574  * c-basic-offset: 4
575  * indent-tabs-mode: nil
576  * End:
577  * vim: shiftwidth=4 tabstop=8 expandtab
578  */
579