d4e814d26fb6e5d81b091d884c91e8c552588202
[kai/samba.git] / source3 / locking / shmem_sysv.c
1 /* 
2    Unix SMB/Netbios implementation.
3    Version 1.9.
4    Shared memory functions - SYSV IPC implementation
5    Copyright (C) Andrew Tridgell 1997-1998
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 #include "includes.h"
24
25
26 #ifdef HAVE_SYSV_IPC
27
28 extern int DEBUGLEVEL;
29
30 #define SHMEM_KEY ((key_t)0x280267)
31 #define SEMAPHORE_KEY (SHMEM_KEY+2)
32
33 #define SHM_MAGIC 0x53484100
34 #define SHM_VERSION 2
35
36 #define IPC_PERMS ((SHM_R | SHM_W) | (SHM_R>>3) | (SHM_R>>6))
37
38
39 #ifdef SECURE_SEMAPHORES
40 /* secure semaphores are slow because we have to do a become_root()
41    on every call! */
42 #define SEMAPHORE_PERMS IPC_PERMS
43 #else
44 #define SEMAPHORE_PERMS 0666
45 #endif
46
47 #define SHMEM_HASH_SIZE 13
48
49 #define MIN_SHM_SIZE 0x1000
50
51 static int shm_id;
52 static int sem_id;
53 static int shm_size;
54 static int hash_size;
55 static int global_lock_count;
56
57 struct ShmHeader {
58    int shm_magic;
59    int shm_version;
60    int total_size;      /* in bytes */
61    BOOL consistent;
62    int first_free_off;
63    int userdef_off;    /* a userdefined offset. can be used to store
64                           root of tree or list */
65    struct {             /* a cell is a range of bytes of sizeof(struct
66                            ShmBlockDesc) size */
67            int cells_free;
68            int cells_used;
69            int cells_system; /* number of cells used as allocated
70                                 block descriptors */
71    } statistics;
72 };
73
74 #define SHM_NOT_FREE_OFF (-1)
75 struct ShmBlockDesc
76 {
77    int next;    /* offset of next block in the free list or
78                    SHM_NOT_FREE_OFF when block in use */
79    int size;   /* user size in BlockDescSize units */
80 };
81
82 #define EOList_Addr     NULL
83 #define EOList_Off      (0)
84
85 #define CellSize        sizeof(struct ShmBlockDesc)
86
87 /* HeaderSize aligned on a 8 byte boundary */
88 #define AlignedHeaderSize ((sizeof(struct ShmHeader)+7) & ~7)
89
90 static struct ShmHeader *shm_header_p = NULL;
91
92 static int read_only;
93
94 static BOOL sem_change(int i, int op)
95 {
96 #ifdef SECURE_SEMAPHORES
97         extern struct current_user current_user;
98         int became_root=0;
99 #endif
100         struct sembuf sb;
101         int ret;
102
103         if (read_only) return True;
104
105 #ifdef SECURE_SEMAPHORES
106         if (current_user.uid != 0) {
107                 become_root(0);
108                 became_root = 1;
109         }
110 #endif
111
112         sb.sem_num = i;
113         sb.sem_op = op;
114         sb.sem_flg = 0;
115
116         ret = semop(sem_id, &sb, 1);
117
118         if (ret != 0) {
119                 DEBUG(0,("ERROR: sem_change(%d,%d) failed (%s)\n", 
120                          i, op, strerror(errno)));
121         }
122
123 #ifdef SECURE_SEMAPHORES
124         if (became_root) {
125                 unbecome_root(0);
126         }
127 #endif
128
129         return ret == 0;
130 }
131
132 static BOOL global_lock(void)
133 {
134         global_lock_count++;
135         if (global_lock_count == 1)
136                 return sem_change(0, -1);
137         return True;
138 }
139
140 static BOOL global_unlock(void)
141 {
142         global_lock_count--;
143         if (global_lock_count == 0)
144                 return sem_change(0, 1);
145         return True;
146 }
147
148 static void *shm_offset2addr(int offset)
149 {
150    if (offset == 0 )
151       return (void *)(0);
152    
153    if (!shm_header_p)
154       return (void *)(0);
155    
156    return (void *)((char *)shm_header_p + offset);
157 }
158
159 static int shm_addr2offset(void *addr)
160 {
161    if (!addr)
162       return 0;
163    
164    if (!shm_header_p)
165       return 0;
166    
167    return (int)((char *)addr - (char *)shm_header_p);
168 }
169
170
171 static int shm_alloc(int size)
172 {
173         unsigned num_cells ;
174         struct ShmBlockDesc *scanner_p;
175         struct ShmBlockDesc *prev_p;
176         struct ShmBlockDesc *new_p;
177         int result_offset;
178    
179    
180         if (!shm_header_p) {
181                 /* not mapped yet */
182                 DEBUG(0,("ERROR shm_alloc : shmem not mapped\n"));
183                 return 0;
184         }
185         
186         global_lock();
187         
188         if (!shm_header_p->consistent) {
189                 DEBUG(0,("ERROR shm_alloc : shmem not consistent\n"));
190                 global_unlock();
191                 return 0;
192         }
193         
194         /* calculate the number of cells */
195         num_cells = (size + (CellSize-1)) / CellSize;
196         
197         /* set start of scan */
198         prev_p = (struct ShmBlockDesc *)shm_offset2addr(shm_header_p->first_free_off);
199         scanner_p =     prev_p ;
200         
201         /* scan the free list to find a matching free space */
202         while ((scanner_p != EOList_Addr) && (scanner_p->size < num_cells)) {
203                 prev_p = scanner_p;
204                 scanner_p = (struct ShmBlockDesc *)shm_offset2addr(scanner_p->next);
205         }
206    
207         /* at this point scanner point to a block header or to the end of
208            the list */
209         if (scanner_p == EOList_Addr) {
210                 DEBUG(0,("ERROR shm_alloc : alloc of %d bytes failed\n",size));
211                 global_unlock();
212                 return (0);
213         }
214    
215         /* going to modify shared mem */
216         shm_header_p->consistent = False;
217         
218         /* if we found a good one : scanner == the good one */
219         if (scanner_p->size > num_cells + 2) {
220                 /* Make a new one */
221                 new_p = scanner_p + 1 + num_cells;
222                 new_p->size = scanner_p->size - (num_cells + 1);
223                 new_p->next = scanner_p->next;
224                 scanner_p->size = num_cells;
225                 scanner_p->next = shm_addr2offset(new_p);
226
227                 shm_header_p->statistics.cells_free -= 1;
228                 shm_header_p->statistics.cells_system += 1;
229         }
230
231         /* take it from the free list */
232         if (prev_p == scanner_p) {
233                 shm_header_p->first_free_off = scanner_p->next;
234         } else {
235                 prev_p->next = scanner_p->next;
236         }
237         shm_header_p->statistics.cells_free -= scanner_p->size;
238         shm_header_p->statistics.cells_used += scanner_p->size;
239
240         result_offset = shm_addr2offset(&(scanner_p[1]));
241         scanner_p->next = SHM_NOT_FREE_OFF;
242
243         /* end modification of shared mem */
244         shm_header_p->consistent = True;
245
246         global_unlock();
247         
248         DEBUG(6,("shm_alloc : allocated %d bytes at offset %d\n",
249                  size,result_offset));
250
251         return result_offset;
252 }   
253
254 static void shm_solve_neighbors(struct ShmBlockDesc *head_p )
255 {
256         struct ShmBlockDesc *next_p;
257    
258         /* Check if head_p and head_p->next are neighbors and if so
259            join them */
260         if ( head_p == EOList_Addr ) return ;
261         if ( head_p->next == EOList_Off ) return ;
262    
263         next_p = (struct ShmBlockDesc *)shm_offset2addr(head_p->next);
264         if ((head_p + head_p->size + 1) == next_p) {
265                 head_p->size += next_p->size + 1; /* adapt size */
266                 head_p->next = next_p->next; /* link out */
267       
268                 shm_header_p->statistics.cells_free += 1;
269                 shm_header_p->statistics.cells_system -= 1;
270         }
271 }
272
273
274 static BOOL shm_free(int offset)
275 {
276         struct ShmBlockDesc *header_p; /* pointer to header of
277                                           block to free */
278         struct ShmBlockDesc *scanner_p; /* used to scan the list */
279         struct ShmBlockDesc *prev_p; /* holds previous in the
280                                         list */
281    
282         if (!shm_header_p) {
283                 /* not mapped yet */
284                 DEBUG(0,("ERROR shm_free : shmem not mapped\n"));
285                 return False;
286         }
287         
288         global_lock();
289         
290         if (!shm_header_p->consistent) {
291                 DEBUG(0,("ERROR shm_free : shmem not consistent\n"));
292                 global_unlock();
293                 return False;
294         }
295         
296         /* make pointer to header of block */
297         header_p = ((struct ShmBlockDesc *)shm_offset2addr(offset) - 1); 
298         
299         if (header_p->next != SHM_NOT_FREE_OFF) {
300                 DEBUG(0,("ERROR shm_free : bad offset (%d)\n",offset));
301                 global_unlock();
302                 return False;
303         }
304         
305         /* find a place in the free_list to put the header in */
306         
307         /* set scanner and previous pointer to start of list */
308         prev_p = (struct ShmBlockDesc *)
309                 shm_offset2addr(shm_header_p->first_free_off);
310         scanner_p = prev_p ;
311         
312         while ((scanner_p != EOList_Addr) && 
313                (scanner_p < header_p)) { 
314                 /* while we didn't scan past its position */
315                 prev_p = scanner_p ;
316                 scanner_p = (struct ShmBlockDesc *)
317                         shm_offset2addr(scanner_p->next);
318         }
319         
320         shm_header_p->consistent = False;
321         
322         DEBUG(6,("shm_free : freeing %d bytes at offset %d\n",
323                  header_p->size*CellSize,offset));
324
325         /* zero the area being freed - this allows us to find bugs faster */
326         memset(shm_offset2addr(offset), 0, header_p->size*CellSize);
327         
328         if (scanner_p == prev_p) {
329                 shm_header_p->statistics.cells_free += header_p->size;
330                 shm_header_p->statistics.cells_used -= header_p->size;
331                 
332                 /* we must free it at the beginning of the list */
333                 shm_header_p->first_free_off = shm_addr2offset(header_p);
334                 /* set the free_list_pointer to this block_header */
335                 
336                 /* scanner is the one that was first in the list */
337                 header_p->next = shm_addr2offset(scanner_p);
338                 shm_solve_neighbors(header_p); 
339                 
340                 shm_header_p->consistent = True;
341         } else {
342                 shm_header_p->statistics.cells_free += header_p->size;
343                 shm_header_p->statistics.cells_used -= header_p->size;
344                 
345                 prev_p->next = shm_addr2offset(header_p);
346                 header_p->next = shm_addr2offset(scanner_p);
347                 shm_solve_neighbors(header_p) ;
348                 shm_solve_neighbors(prev_p) ;
349            
350                 shm_header_p->consistent = True;
351         }
352
353         global_unlock();
354         return True;
355 }
356
357
358 /* 
359  * Function to create the hash table for the share mode entries. Called
360  * when smb shared memory is global locked.
361  */
362 static BOOL shm_create_hash_table(unsigned int hash_entries)
363 {
364         int size = hash_entries * sizeof(int);
365
366         global_lock();
367         shm_header_p->userdef_off = shm_alloc(size);
368
369         if(shm_header_p->userdef_off == 0) {
370                 DEBUG(0,("shm_create_hash_table: Failed to create hash table of size %d\n",
371                          size));
372                 global_unlock();
373                 return False;
374         }
375
376         /* Clear hash buckets. */
377         memset(shm_offset2addr(shm_header_p->userdef_off), '\0', size);
378         global_unlock();
379         return True;
380 }
381
382
383 static BOOL shm_validate_header(int size)
384 {
385         if(!shm_header_p) {
386                 /* not mapped yet */
387                 DEBUG(0,("ERROR shm_validate_header : shmem not mapped\n"));
388                 return False;
389         }
390    
391         if(shm_header_p->shm_magic != SHM_MAGIC) {
392                 DEBUG(0,("ERROR shm_validate_header : bad magic\n"));
393                 return False;
394         }
395
396         if(shm_header_p->shm_version != SHM_VERSION) {
397                 DEBUG(0,("ERROR shm_validate_header : bad version %X\n",
398                          shm_header_p->shm_version));
399                 return False;
400         }
401    
402         if(shm_header_p->total_size != size) {
403                 DEBUG(0,("ERROR shmem size mismatch (old = %d, new = %d)\n",
404                          shm_header_p->total_size,size));
405                 return False;
406         }
407
408         if(!shm_header_p->consistent) {
409                 DEBUG(0,("ERROR shmem not consistent\n"));
410                 return False;
411         }
412         return True;
413 }
414
415
416 static BOOL shm_initialize(int size)
417 {
418         struct ShmBlockDesc * first_free_block_p;
419         
420         DEBUG(5,("shm_initialize : initializing shmem size %d\n",size));
421    
422         if( !shm_header_p ) {
423                 /* not mapped yet */
424                 DEBUG(0,("ERROR shm_initialize : shmem not mapped\n"));
425                 return False;
426         }
427    
428         shm_header_p->shm_magic = SHM_MAGIC;
429         shm_header_p->shm_version = SHM_VERSION;
430         shm_header_p->total_size = size;
431         shm_header_p->first_free_off = AlignedHeaderSize;
432         shm_header_p->userdef_off = 0;
433         
434         first_free_block_p = (struct ShmBlockDesc *)
435                 shm_offset2addr(shm_header_p->first_free_off);
436         first_free_block_p->next = EOList_Off;
437         first_free_block_p->size = 
438                 (size - (AlignedHeaderSize+CellSize))/CellSize;   
439         shm_header_p->statistics.cells_free = first_free_block_p->size;
440         shm_header_p->statistics.cells_used = 0;
441         shm_header_p->statistics.cells_system = 1;
442    
443         shm_header_p->consistent = True;
444    
445         return True;
446 }
447    
448 static BOOL shm_close( void )
449 {
450         return True;
451 }
452
453
454 static int shm_get_userdef_off(void)
455 {
456    if (!shm_header_p)
457       return 0;
458    else
459       return shm_header_p->userdef_off;
460 }
461
462
463 /*******************************************************************
464   Lock a particular hash bucket entry.
465   ******************************************************************/
466 static BOOL shm_lock_hash_entry(unsigned int entry)
467 {
468         return sem_change(entry+1, -1);
469 }
470
471 /*******************************************************************
472   Unlock a particular hash bucket entry.
473   ******************************************************************/
474 static BOOL shm_unlock_hash_entry(unsigned int entry)
475 {
476         return sem_change(entry+1, 1);
477 }
478
479
480 /*******************************************************************
481   Gather statistics on shared memory usage.
482   ******************************************************************/
483 static BOOL shm_get_usage(int *bytes_free,
484                           int *bytes_used,
485                           int *bytes_overhead)
486 {
487         if(!shm_header_p) {
488                 /* not mapped yet */
489                 DEBUG(0,("ERROR shm_free : shmem not mapped\n"));
490                 return False;
491         }
492
493         *bytes_free = shm_header_p->statistics.cells_free * CellSize;
494         *bytes_used = shm_header_p->statistics.cells_used * CellSize;
495         *bytes_overhead = shm_header_p->statistics.cells_system * CellSize + 
496                 AlignedHeaderSize;
497         
498         return True;
499 }
500
501
502 /*******************************************************************
503 hash a number into a hash_entry
504   ******************************************************************/
505 static unsigned shm_hash_size(void)
506 {
507         return hash_size;
508 }
509
510
511 static struct shmem_ops shmops = {
512         shm_close,
513         shm_alloc,
514         shm_free,
515         shm_get_userdef_off,
516         shm_offset2addr,
517         shm_addr2offset,
518         shm_lock_hash_entry,
519         shm_unlock_hash_entry,
520         shm_get_usage,
521         shm_hash_size,
522 };
523
524 /*******************************************************************
525   open the shared memory
526   ******************************************************************/
527 struct shmem_ops *sysv_shm_open(int ronly)
528 {
529         BOOL other_processes;
530         struct shmid_ds shm_ds;
531         struct semid_ds sem_ds;
532         union semun su;
533         int i;
534         int pid;
535
536         read_only = ronly;
537
538         shm_size = lp_shmem_size();
539
540         DEBUG(4,("Trying sysv shmem open of size %d\n", shm_size));
541
542         /* first the semaphore */
543         sem_id = semget(SEMAPHORE_KEY, 0, 0);
544         if (sem_id == -1) {
545                 if (read_only) return NULL;
546
547                 hash_size = SHMEM_HASH_SIZE;
548
549                 while (hash_size > 1) {
550                         sem_id = semget(SEMAPHORE_KEY, hash_size+1, 
551                                         IPC_CREAT|IPC_EXCL| SEMAPHORE_PERMS);
552                         if (sem_id != -1 || 
553                             (errno != EINVAL && errno != ENOSPC)) break;
554                         hash_size -= 5;
555                 }
556
557                 if (sem_id == -1) {
558                         DEBUG(0,("Can't create or use semaphore [1]. Error was %s\n", 
559                                  strerror(errno)));
560             return NULL;
561                 }   
562
563                 if (sem_id != -1) {
564                         su.val = 1;
565                         for (i=0;i<hash_size+1;i++) {
566                                 if (semctl(sem_id, i, SETVAL, su) != 0) {
567                                         DEBUG(1,("Failed to init semaphore %d. Error was %s\n",
568                           i, strerror(errno)));
569                     return NULL;
570                                 }
571                         }
572                 }
573         }
574         if (shm_id == -1) {
575                 sem_id = semget(SEMAPHORE_KEY, 0, 0);
576         }
577         if (sem_id == -1) {
578                 DEBUG(0,("Can't create or use semaphore [2]. Error was %s\n", 
579                          strerror(errno)));
580                 return NULL;
581         }   
582
583         su.buf = &sem_ds;
584         if (semctl(sem_id, 0, IPC_STAT, su) != 0) {
585                 DEBUG(0,("ERROR semctl: can't IPC_STAT. Error was %s\n",
586               strerror(errno)));
587                 return NULL;
588         }
589         hash_size = sem_ds.sem_nsems-1;
590
591         if (!read_only) {
592                 if (sem_ds.sem_perm.cuid != 0 || sem_ds.sem_perm.cgid != 0) {
593                         DEBUG(0,("ERROR: root did not create the semaphore\n"));
594                         return NULL;
595                 }
596
597                 if (semctl(sem_id, 0, GETVAL, su) == 0 &&
598                     !process_exists((pid=semctl(sem_id, 0, GETPID, su)))) {
599                         DEBUG(0,("WARNING: clearing global IPC lock set by dead process %d\n",
600                                  pid));
601                         su.val = 1;
602                         if (semctl(sem_id, 0, SETVAL, su) != 0) {
603                                 DEBUG(0,("ERROR: Failed to clear global lock. Error was %s\n",
604                       strerror(errno)));
605                 return NULL;
606                         }
607                 }
608
609                 sem_ds.sem_perm.mode = SEMAPHORE_PERMS;
610                 if (semctl(sem_id, 0, IPC_SET, su) != 0) {
611                         DEBUG(0,("ERROR shmctl : can't IPC_SET. Error was %s\n",
612                   strerror(errno)));
613             return NULL;
614                 }
615         }
616
617         if (!global_lock())
618                 return NULL;
619
620
621         for (i=1;i<hash_size+1;i++) {
622                 if (semctl(sem_id, i, GETVAL, su) == 0 && 
623                     !process_exists((pid=semctl(sem_id, i, GETPID, su)))) {
624                         DEBUG(1,("WARNING: clearing IPC lock %d set by dead process %d\n", 
625                                  i, pid));
626                         su.val = 1;
627                         if (semctl(sem_id, i, SETVAL, su) != 0) {
628                                 DEBUG(0,("ERROR: Failed to clear IPC lock %d. Error was %s\n",
629                       i, strerror(errno)));
630                         global_unlock();
631                 return NULL;
632                         }
633                 }
634         }
635         
636         /* 
637      * Try to use an existing key. Note that
638      * in order to use an existing key successfully
639      * size must be zero else shmget returns EINVAL.
640      * Thanks to Veselin Terzic <vterzic@systems.DHL.COM>
641      * for pointing this out.
642      */
643
644         shm_id = shmget(SHMEM_KEY, 0, 0);
645         
646         /* if that failed then create one */
647         if (shm_id == -1) {
648                 if (read_only) return NULL;
649                 while (shm_size > MIN_SHM_SIZE) {
650                         shm_id = shmget(SHMEM_KEY, shm_size, 
651                                         IPC_CREAT | IPC_EXCL | IPC_PERMS);
652                         if (shm_id != -1 || 
653                             (errno != EINVAL && errno != ENOSPC)) break;
654                         shm_size *= 0.8;
655                 }
656         }
657         
658         if (shm_id == -1) {
659                 DEBUG(0,("Can't create or use IPC area. Error was %s\n", strerror(errno)));
660                 global_unlock();
661                 return NULL;
662         }   
663         
664         
665         shm_header_p = (struct ShmHeader *)shmat(shm_id, 0, 
666                                                  read_only?SHM_RDONLY:0);
667         if ((long)shm_header_p == -1) {
668                 DEBUG(0,("Can't attach to IPC area. Error was %s\n", strerror(errno)));
669                 global_unlock();
670                 return NULL;
671         }
672
673         /* to find out if some other process is already mapping the file,
674            we use a registration file containing the processids of the file
675            mapping processes */
676         if (shmctl(shm_id, IPC_STAT, &shm_ds) != 0) {
677                 DEBUG(0,("ERROR shmctl : can't IPC_STAT. Error was %s\n", strerror(errno)));
678         global_unlock();
679         return NULL;
680         }
681
682         if (!read_only) {
683                 if (shm_ds.shm_perm.cuid != 0 || shm_ds.shm_perm.cgid != 0) {
684                         DEBUG(0,("ERROR: root did not create the shmem\n"));
685                         global_unlock();
686                         return NULL;
687                 }
688         }
689
690         shm_size = shm_ds.shm_segsz;
691
692         other_processes = (shm_ds.shm_nattch > 1);
693
694         if (!read_only && !other_processes) {
695                 memset((char *)shm_header_p, 0, shm_size);
696                 shm_initialize(shm_size);
697                 shm_create_hash_table(hash_size);
698                 DEBUG(3,("Initialised IPC area of size %d\n", shm_size));
699         } else if (!shm_validate_header(shm_size)) {
700                 /* existing file is corrupt, samba admin should remove
701                    it by hand */
702                 DEBUG(0,("ERROR shm_open : corrupt IPC area - remove it!\n"));
703                 global_unlock();
704                 return NULL;
705         }
706    
707         global_unlock();
708         return &shmops;
709 }
710
711
712
713 #else 
714  int ipc_dummy_procedure(void)
715 {return 0;}
716 #endif