- added FAST_SHARE_MODES code
[kai/samba.git] / source3 / locking / shmem.c
1 /* 
2    Unix SMB/Netbios implementation.
3    Version 1.9.
4    Shared memory functions
5    Copyright (C) Erik Devriendt 1996
6    
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 2 of the License, or
10    (at your option) any later version.
11    
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16    
17    You should have received a copy of the GNU General Public License
18    along with this program; if not, write to the Free Software
19    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
20
21 */
22
23 #ifdef FAST_SHARE_MODES
24
25
26 #include "includes.h"
27
28 extern int DEBUGLEVEL;
29
30
31 #define SHM_MAGIC 0x53484100
32 /* = "SHM" in hex */
33
34 #define SHM_VERSION 1
35
36 /* WARNING : offsets are used because mmap() does not guarantee that all processes have the 
37    shared memory mapped to the same address */
38
39 struct ShmHeader
40 {
41    int shm_magic;
42    int shm_version;
43    int total_size;      /* in bytes */
44    BOOL consistent;
45    shm_offset_t first_free_off;
46    shm_offset_t userdef_off;    /* a userdefined offset. can be used to store root of tree or list */
47    struct {             /* a cell is a range of bytes of sizeof(struct ShmBlockDesc) size */
48       int cells_free;
49       int cells_used;
50       int cells_system; /* number of cells used as allocated block descriptors */
51    } statistics;
52 };
53
54 #define SHM_NOT_FREE_OFF (-1)
55 struct ShmBlockDesc
56 {
57    shm_offset_t next;   /* offset of next block in the free list or SHM_NOT_FREE_OFF when block in use  */
58    int          size;   /* user size in BlockDescSize units */
59 };
60
61 #define EOList_Addr     (struct ShmBlockDesc *)( 0 )
62 #define EOList_Off      (NULL_OFFSET)
63
64 #define CellSize        sizeof(struct ShmBlockDesc)
65
66 /* HeaderSize aligned on 8 byte boundary */
67 #define AlignedHeaderSize       ((sizeof(struct ShmHeader)+7) & ~7)
68
69 static int  shm_fd = -1;
70 static pstring shm_processreg_name = "";
71
72 static struct ShmHeader *shm_header_p = (struct ShmHeader *)0;
73 static int shm_times_locked = 0;
74
75 static BOOL shm_register_process(char *processreg_file, pid_t pid, BOOL *other_processes)
76 {
77    int old_umask;
78    int shm_processes_fd = -1;
79    int nb_read;
80    pid_t other_pid;
81    int free_slot = -1;
82    int erased_slot;
83    
84    
85    old_umask = umask(0);
86    shm_processes_fd = open(processreg_file, O_RDWR | O_CREAT, 0666);
87    umask(old_umask);
88    if ( shm_processes_fd < 0 )
89    {
90       DEBUG(0,("ERROR shm_register_process : processreg_file open failed with code %d\n",errno));
91       return False;
92    }
93    
94    *other_processes = False;
95    
96    while ((nb_read = read(shm_processes_fd, &other_pid, sizeof(other_pid))) > 0)
97    {
98       if(other_pid)
99       {
100          if(process_exists(other_pid))
101             *other_processes = True;
102          else
103          {
104             /* erase old pid */
105             DEBUG(2,("shm_register_process : erasing stale record for pid %d\n",other_pid));
106             other_pid = (pid_t)0;
107             erased_slot = lseek(shm_processes_fd, -sizeof(other_pid), SEEK_CUR);
108             write(shm_processes_fd, &other_pid, sizeof(other_pid));
109             if(free_slot < 0)
110                free_slot = erased_slot;
111          }
112       }
113       else 
114          if(free_slot < 0)
115             free_slot = lseek(shm_processes_fd, -sizeof(other_pid), SEEK_CUR);
116    }
117    if (nb_read < 0)
118    {
119       DEBUG(0,("ERROR shm_register_process : processreg_file read failed with code %d\n",errno));
120       close(shm_processes_fd);
121       return False;
122    }
123    
124    if(free_slot < 0)
125       free_slot = lseek(shm_processes_fd, 0, SEEK_END);
126
127    DEBUG(2,("shm_register_process : writing record for pid %d at offset %d\n",pid,free_slot));
128    lseek(shm_processes_fd, free_slot, SEEK_SET);
129    if(write(shm_processes_fd, &pid, sizeof(pid)) < 0)
130    {
131       DEBUG(0,("ERROR shm_register_process : processreg_file write failed with code %d\n",errno));
132       close(shm_processes_fd);
133       return False;
134    }
135
136    close(shm_processes_fd);
137
138    return True;
139 }
140
141 static BOOL shm_unregister_process(char *processreg_file, pid_t pid)
142 {
143    int old_umask;
144    int shm_processes_fd = -1;
145    int nb_read;
146    pid_t other_pid;
147    int erased_slot;
148    BOOL found = False;
149    
150    
151    old_umask = umask(0);
152    shm_processes_fd = open(processreg_file, O_RDWR);
153    umask(old_umask);
154    if ( shm_processes_fd < 0 )
155    {
156       DEBUG(0,("ERROR shm_unregister_process : processreg_file open failed with code %d\n",errno));
157       return False;
158    }
159    
160    while ((nb_read = read(shm_processes_fd, &other_pid, sizeof(other_pid))) > 0)
161    {
162       if(other_pid == pid)
163       {
164          /* erase pid */
165          DEBUG(2,("shm_unregister_process : erasing record for pid %d\n",other_pid));
166          other_pid = (pid_t)0;
167          erased_slot = lseek(shm_processes_fd, -sizeof(other_pid), SEEK_CUR);
168          if(write(shm_processes_fd, &other_pid, sizeof(other_pid)) < 0)
169          {
170             DEBUG(0,("ERROR shm_unregister_process : processreg_file write failed with code %d\n",errno));
171             close(shm_processes_fd);
172             return False;
173          }
174          
175          found = True;
176          break;
177       }
178    }
179    if (nb_read < 0)
180    {
181       DEBUG(0,("ERROR shm_unregister_process : processreg_file read failed with code %d\n",errno));
182       close(shm_processes_fd);
183       return False;
184    }
185    
186    if(!found)
187    {
188       DEBUG(0,("ERROR shm_unregister_process : couldn't find pid %d in file %s\n",pid,processreg_file));
189       close(shm_processes_fd);
190       return False;
191    }
192       
193    
194    close(shm_processes_fd);
195
196    return True;
197 }
198
199
200 static BOOL shm_validate_header(int size)
201 {
202    if( !shm_header_p )
203    {
204       /* not mapped yet */
205       DEBUG(0,("ERROR shm_validate_header : shmem not mapped\n"));
206       return False;
207    }
208    
209    if(shm_header_p->shm_magic != SHM_MAGIC)
210    {
211       DEBUG(0,("ERROR shm_validate_header : bad magic\n"));
212       return False;
213    }
214    if(shm_header_p->shm_version != SHM_VERSION)
215    {
216       DEBUG(0,("ERROR shm_validate_header : bad version %X\n",shm_header_p->shm_version));
217       return False;
218    }
219    
220    if(shm_header_p->total_size != size)
221    {
222       DEBUG(0,("ERROR shm_validate_header : shmem size mismatch (old = %d, new = %d)\n",shm_header_p->total_size,size));
223       return False;
224    }
225
226    if(!shm_header_p->consistent)
227    {
228       DEBUG(0,("ERROR shm_validate_header : shmem not consistent\n"));
229       return False;
230    }
231    return True;
232 }
233
234 static BOOL shm_initialize(int size)
235 {
236    struct ShmBlockDesc * first_free_block_p;
237    
238    DEBUG(2,("shm_initialize : initializing shmem file of size %d\n",size));
239    
240    if( !shm_header_p )
241    {
242       /* not mapped yet */
243       DEBUG(0,("ERROR shm_initialize : shmem not mapped\n"));
244       return False;
245    }
246    
247    shm_header_p->shm_magic = SHM_MAGIC;
248    shm_header_p->shm_version = SHM_VERSION;
249    shm_header_p->total_size = size;
250    shm_header_p->first_free_off = AlignedHeaderSize;
251    shm_header_p->userdef_off = NULL_OFFSET;
252    
253    first_free_block_p = (struct ShmBlockDesc *)shm_offset2addr(shm_header_p->first_free_off);
254    first_free_block_p->next = EOList_Off;
255    first_free_block_p->size = ( size - AlignedHeaderSize - CellSize ) / CellSize ;
256    
257    shm_header_p->statistics.cells_free = first_free_block_p->size;
258    shm_header_p->statistics.cells_used = 0;
259    shm_header_p->statistics.cells_system = 1;
260    
261    shm_header_p->consistent = True;
262    
263    return True;
264 }
265    
266 static void shm_solve_neighbors(struct ShmBlockDesc *head_p )
267 {
268    struct ShmBlockDesc *next_p;
269    
270    /* Check if head_p and head_p->next are neighbors and if so join them */
271    if ( head_p == EOList_Addr ) return ;
272    if ( head_p->next == EOList_Off ) return ;
273    
274    next_p = (struct ShmBlockDesc *)shm_offset2addr(head_p->next);
275    if ( ( head_p + head_p->size + 1 ) == next_p)
276    {
277       head_p->size += next_p->size +1 ; /* adapt size */
278       head_p->next = next_p->next         ; /* link out */
279       
280       shm_header_p->statistics.cells_free += 1;
281       shm_header_p->statistics.cells_system -= 1;
282    }
283 }
284
285
286
287 BOOL shm_open( char *file_name, int size)
288 {
289    int filesize;
290    BOOL created_new = False;
291    BOOL other_processes = True;
292    int old_umask;
293    
294    DEBUG(2,("shm_open : using shmem file %s to be of size %d\n",file_name,size));
295
296    old_umask = umask(0);
297    shm_fd = open(file_name, O_RDWR | O_CREAT, 0666);
298    umask(old_umask);
299    if ( shm_fd < 0 )
300    {
301       DEBUG(0,("ERROR shm_open : open failed with code %d\n",errno));
302       return False;
303    }
304    
305    if (!shm_lock())
306    {
307       DEBUG(0,("ERROR shm_open : can't do shm_lock\n"));
308       return False;
309    }
310    
311    if( (filesize = lseek(shm_fd, 0, SEEK_END)) < 0)
312    {
313       DEBUG(0,("ERROR shm_open : lseek failed with code %d\n",errno));
314       shm_unlock();
315       close(shm_fd);
316       return False;
317    }
318
319    /* return the file offset to 0 to save on later seeks */
320    lseek(shm_fd,0,SEEK_SET);
321
322    if (filesize == 0)
323    {
324       /* we just created a new one */
325       created_new = True;
326    }
327    
328    /* to find out if some other process is already mapping the file,
329       we use a registration file containing the processids of the file mapping processes
330       */
331
332    /* construct processreg file name */
333    strcpy(shm_processreg_name, file_name);
334    strcat(shm_processreg_name, ".processes");
335
336    if (! shm_register_process(shm_processreg_name, getpid(), &other_processes))
337    {
338       shm_unlock();
339       close(shm_fd);
340       return False;
341    }
342
343    if (created_new || !other_processes)
344    {
345       /* we just created a new one, or are the first opener, lets set it size */
346       if( ftruncate(shm_fd, size) <0)
347       {
348          DEBUG(0,("ERROR shm_open : ftruncate failed with code %d\n",errno));
349          shm_unregister_process(shm_processreg_name, getpid());
350          shm_unlock();
351          close(shm_fd);
352          return False;
353       }
354
355       /* paranoia */
356       lseek(shm_fd,0,SEEK_SET);
357
358       filesize = size;
359    }
360    
361    if (size != filesize )
362    {
363       /* the existing file has a different size and we are not the first opener.
364          Since another process is still using it, we will use the file size */
365       DEBUG(0,("WARNING shm_open : filesize (%d) != expected size (%d), using filesize\n",filesize,size));
366       size = filesize;
367    }
368    
369    shm_header_p = (struct ShmHeader *)mmap( NULL, size, PROT_READ | PROT_WRITE, MAP_FILE | MAP_SHARED, shm_fd, 0);
370    /* WARNING, shm_header_p can be different for different processes mapping the same file ! */
371    if (shm_header_p  == (struct ShmHeader *)(-1))
372    {
373       DEBUG(0,("ERROR shm_open : mmap failed with code %d\n",errno));
374       shm_unregister_process(shm_processreg_name, getpid());
375       shm_unlock();
376       close(shm_fd);
377       return False;
378    }      
379    
380       
381    if (created_new || !other_processes)
382    {
383       shm_initialize(size);
384    }
385    else if (!shm_validate_header(size) )
386    {
387       /* existing file is corrupt, samba admin should remove it by hand */
388       DEBUG(0,("ERROR shm_open : corrupt shared mem file, remove it manually\n"));
389       munmap((caddr_t)shm_header_p, size);
390       shm_unregister_process(shm_processreg_name, getpid());
391       shm_unlock();
392       close(shm_fd);
393       return False;
394    }
395    
396    shm_unlock();
397    return True;
398       
399 }
400
401
402 BOOL shm_close( void )
403 {
404    
405    DEBUG(2,("shm_close\n"));
406    if(shm_times_locked > 0)
407       DEBUG(0,("WARNING shm_close : shmem was still locked %d times\n",shm_times_locked));;
408    if ( munmap((caddr_t)shm_header_p, shm_header_p->total_size) < 0)
409    {
410       DEBUG(0,("ERROR shm_close : munmap failed with code %d\n",errno));
411    }
412
413    shm_lock();
414    shm_unregister_process(shm_processreg_name, getpid());
415    shm_unlock();
416    
417    close(shm_fd);
418    
419    shm_fd = -1;
420    shm_processreg_name[0] = '\0';
421
422    shm_header_p = (struct ShmHeader *)0;
423    shm_times_locked = 0;
424    
425    return True;
426 }
427
428 shm_offset_t shm_alloc(int size)
429 {
430    unsigned num_cells ;
431    struct ShmBlockDesc *scanner_p;
432    struct ShmBlockDesc *prev_p;
433    struct ShmBlockDesc *new_p;
434    shm_offset_t result_offset;
435    
436    
437    if( !shm_header_p )
438    {
439       /* not mapped yet */
440       DEBUG(0,("ERROR shm_alloc : shmem not mapped\n"));
441       return NULL_OFFSET;
442    }
443    
444    if( !shm_header_p->consistent)
445    {
446       DEBUG(0,("ERROR shm_alloc : shmem not consistent\n"));
447       return NULL_OFFSET;
448    }
449    
450    
451    /* calculate the number of cells */
452    num_cells = (size + CellSize -1) / CellSize;
453
454    /* set start of scan */
455    prev_p = (struct ShmBlockDesc *)shm_offset2addr(shm_header_p->first_free_off);
456    scanner_p =  prev_p ;
457    
458    /* scan the free list to find a matching free space */
459    while ( ( scanner_p != EOList_Addr ) && ( scanner_p->size < num_cells ) )
460    {
461       prev_p = scanner_p;
462       scanner_p = (struct ShmBlockDesc *)shm_offset2addr(scanner_p->next);
463    }
464    
465    /* at this point scanner point to a block header or to the end of the list */
466    if ( scanner_p == EOList_Addr )      
467    {
468       DEBUG(0,("ERROR shm_alloc : alloc of %d bytes failed, no free space found\n",size));
469       return (NULL_OFFSET);
470    }
471    
472    /* going to modify shared mem */
473    shm_header_p->consistent = False;
474    
475    /* if we found a good one : scanner == the good one */
476    if ( scanner_p->size <= num_cells + 2 )
477    {
478       /* there is no use in making a new one, it will be too small anyway 
479       *  we will link out scanner
480       */
481       if ( prev_p == scanner_p )
482       {
483          shm_header_p->first_free_off = scanner_p->next ;
484       }
485       else
486       {
487          prev_p->next = scanner_p->next ;
488       }
489       shm_header_p->statistics.cells_free -= scanner_p->size;
490       shm_header_p->statistics.cells_used += scanner_p->size;
491    }
492    else
493    {
494       /* Make a new one */
495       new_p = scanner_p + 1 + num_cells;
496       new_p->size = scanner_p->size - num_cells - 1;
497       new_p->next = scanner_p->next;
498       scanner_p->size = num_cells;
499       scanner_p->next = shm_addr2offset(new_p);
500       
501       if ( prev_p       != scanner_p )
502       {
503          prev_p->next      = shm_addr2offset(new_p)  ;
504       }
505       else
506       {
507          shm_header_p->first_free_off = shm_addr2offset(new_p)  ;
508       }
509       shm_header_p->statistics.cells_free -= num_cells+1;
510       shm_header_p->statistics.cells_used += num_cells;
511       shm_header_p->statistics.cells_system += 1;
512    }
513
514    result_offset = shm_addr2offset( &(scanner_p[1]) );
515    scanner_p->next =    SHM_NOT_FREE_OFF ;
516
517    /* end modification of shared mem */
518    shm_header_p->consistent = True;
519
520    DEBUG(2,("shm_alloc : request for %d bytes, allocated %d bytes at offset %d\n",size,scanner_p->size*CellSize,result_offset ));
521
522    return ( result_offset );
523 }   
524
525
526
527 BOOL shm_free(shm_offset_t offset)
528 {
529    struct ShmBlockDesc *header_p  ; /*  pointer to header of block to free */
530    struct ShmBlockDesc *scanner_p ; /*  used to scan the list                      */
531    struct ShmBlockDesc *prev_p     ; /* holds previous in the list                 */
532    
533    if( !shm_header_p )
534    {
535       /* not mapped yet */
536       DEBUG(0,("ERROR shm_free : shmem not mapped\n"));
537       return False;
538    }
539    
540    if( !shm_header_p->consistent)
541    {
542       DEBUG(0,("ERROR shm_free : shmem not consistent\n"));
543       return False;
544    }
545    
546    header_p = ( (struct ShmBlockDesc *)shm_offset2addr(offset) - 1); /* make pointer to header of block */
547
548    if (header_p->next != SHM_NOT_FREE_OFF)
549    {
550       DEBUG(0,("ERROR shm_free : bad offset (%d)\n",offset));
551       return False;
552    }
553    
554    /* find a place in the free_list to put the header in */
555    
556    /* set scanner and previous pointer to start of list */
557    prev_p = (struct ShmBlockDesc *)shm_offset2addr(shm_header_p->first_free_off);
558    scanner_p = prev_p ;
559    
560    while ( ( scanner_p != EOList_Addr) && (scanner_p < header_p) ) /* while we didn't scan past its position */
561    {
562       prev_p = scanner_p ;
563       scanner_p = (struct ShmBlockDesc *)shm_offset2addr(scanner_p->next);
564    }
565    
566    shm_header_p->consistent = False;
567    
568    DEBUG(2,("shm_free : freeing %d bytes at offset %d\n",header_p->size*CellSize,offset));
569
570    if ( scanner_p == prev_p )
571    {
572       shm_header_p->statistics.cells_free += header_p->size;
573       shm_header_p->statistics.cells_used -= header_p->size;
574
575       /* we must free it at the beginning of the list */
576       shm_header_p->first_free_off = shm_addr2offset(header_p);                                          /*     set     the free_list_pointer to this block_header */
577
578       /* scanner is the one that was first in the list */
579       header_p->next = shm_addr2offset(scanner_p);
580       shm_solve_neighbors( header_p ); /* if neighbors then link them */
581       
582       shm_header_p->consistent = True;
583       return True;
584    } 
585    else
586    {
587       shm_header_p->statistics.cells_free += header_p->size;
588       shm_header_p->statistics.cells_used -= header_p->size;
589
590       prev_p->next = shm_addr2offset(header_p);
591       header_p->next = shm_addr2offset(scanner_p);
592       shm_solve_neighbors(header_p) ;
593       shm_solve_neighbors(prev_p) ;
594
595       shm_header_p->consistent = True;
596       return True;
597    }
598 }
599
600 shm_offset_t shm_get_userdef_off(void)
601 {
602    if (!shm_header_p)
603       return NULL_OFFSET;
604    else
605       return shm_header_p->userdef_off;
606 }
607
608 BOOL shm_set_userdef_off(shm_offset_t userdef_off)
609 {
610    if (!shm_header_p)
611       return False;
612    else
613       shm_header_p->userdef_off = userdef_off;
614    return True;
615 }
616
617 void * shm_offset2addr(shm_offset_t offset)
618 {
619    if (offset == NULL_OFFSET )
620       return (void *)(0);
621    
622    if (!shm_header_p)
623       return (void *)(0);
624    
625    return (void *)((char *)shm_header_p + offset );
626 }
627
628 shm_offset_t shm_addr2offset(void *addr)
629 {
630    if (!addr)
631       return NULL_OFFSET;
632    
633    if (!shm_header_p)
634       return NULL_OFFSET;
635    
636    return (shm_offset_t)((char *)addr - (char *)shm_header_p);
637 }
638
639 BOOL shm_lock(void)
640 {
641    if (shm_fd < 0)
642    {
643       DEBUG(0,("ERROR shm_lock : bad shm_fd (%d)\n",shm_fd));
644       return False;
645    }
646    
647    shm_times_locked++;
648    
649    if(shm_times_locked > 1)
650    {
651       DEBUG(2,("shm_lock : locked %d times\n",shm_times_locked));
652       return True;
653    }
654    
655    if (lockf(shm_fd, F_LOCK, 0) < 0)
656    {
657       DEBUG(0,("ERROR shm_lock : lockf failed with code %d\n",errno));
658       shm_times_locked--;
659       return False;
660    }
661    
662    return True;
663    
664 }
665
666
667
668 BOOL shm_unlock(void)
669 {
670    if (shm_fd < 0)
671    {
672       DEBUG(0,("ERROR shm_unlock : bad shm_fd (%d)\n",shm_fd));
673       return False;
674    }
675    
676    if(shm_times_locked == 0)
677    {
678       DEBUG(0,("ERROR shm_unlock : shmem not locked\n",shm_fd));
679       return False;
680    }
681    
682    shm_times_locked--;
683    
684    if(shm_times_locked > 0)
685    {
686       DEBUG(2,("shm_unlock : still locked %d times\n",shm_times_locked));
687       return True;
688    }
689    
690    if (lockf(shm_fd, F_ULOCK, 0) < 0)
691    {
692       DEBUG(0,("ERROR shm_unlock : lockf failed with code %d\n",errno));
693       shm_times_locked++;
694       return False;
695    }
696    
697    return True;
698    
699 }
700
701
702 BOOL shm_get_usage(int *bytes_free,
703                    int *bytes_used,
704                    int *bytes_overhead)
705 {
706    if( !shm_header_p )
707    {
708       /* not mapped yet */
709       DEBUG(0,("ERROR shm_free : shmem not mapped\n"));
710       return False;
711    }
712    *bytes_free = shm_header_p->statistics.cells_free * CellSize;
713    *bytes_used = shm_header_p->statistics.cells_used * CellSize;
714    *bytes_overhead = shm_header_p->statistics.cells_system * CellSize + AlignedHeaderSize;
715    
716    return True;
717 }
718
719 #else /* FAST_SHARE_MODES */
720  int shmem_dummy_procedure(void)
721 {return 0;}
722 #endif