Merge to Fedora kernel-2.6.18-1.2224_FC5 patched with stable patch-2.6.18.1-vs2.0...
[linux-2.6.git] / ipc / util.c
1 /*
2  * linux/ipc/util.c
3  * Copyright (C) 1992 Krishna Balasubramanian
4  *
5  * Sep 1997 - Call suser() last after "normal" permission checks so we
6  *            get BSD style process accounting right.
7  *            Occurs in several places in the IPC code.
8  *            Chris Evans, <chris@ferret.lmh.ox.ac.uk>
9  * Nov 1999 - ipc helper functions, unified SMP locking
10  *            Manfred Spraul <manfred@colorfullife.com>
11  * Oct 2002 - One lock per IPC id. RCU ipc_free for lock-free grow_ary().
12  *            Mingming Cao <cmm@us.ibm.com>
13  * Mar 2006 - support for audit of ipc object properties
14  *            Dustin Kirkland <dustin.kirkland@us.ibm.com>
15  */
16
17 #include <linux/mm.h>
18 #include <linux/shm.h>
19 #include <linux/init.h>
20 #include <linux/msg.h>
21 #include <linux/smp_lock.h>
22 #include <linux/vmalloc.h>
23 #include <linux/slab.h>
24 #include <linux/capability.h>
25 #include <linux/highuid.h>
26 #include <linux/security.h>
27 #include <linux/rcupdate.h>
28 #include <linux/workqueue.h>
29 #include <linux/seq_file.h>
30 #include <linux/proc_fs.h>
31 #include <linux/audit.h>
32
33 #include <asm/unistd.h>
34
35 #include "util.h"
36
37 struct ipc_proc_iface {
38         const char *path;
39         const char *header;
40         struct ipc_ids *ids;
41         int (*show)(struct seq_file *, void *);
42 };
43
44 /**
45  *      ipc_init        -       initialise IPC subsystem
46  *
47  *      The various system5 IPC resources (semaphores, messages and shared
48  *      memory are initialised
49  */
50  
51 static int __init ipc_init(void)
52 {
53         sem_init();
54         msg_init();
55         shm_init();
56         return 0;
57 }
58 __initcall(ipc_init);
59
60 /**
61  *      ipc_init_ids            -       initialise IPC identifiers
62  *      @ids: Identifier set
63  *      @size: Number of identifiers
64  *
65  *      Given a size for the ipc identifier range (limited below IPCMNI)
66  *      set up the sequence range to use then allocate and initialise the
67  *      array itself. 
68  */
69  
70 void __init ipc_init_ids(struct ipc_ids* ids, int size)
71 {
72         int i;
73
74         mutex_init(&ids->mutex);
75
76         if(size > IPCMNI)
77                 size = IPCMNI;
78         ids->in_use = 0;
79         ids->max_id = -1;
80         ids->seq = 0;
81         {
82                 int seq_limit = INT_MAX/SEQ_MULTIPLIER;
83                 if(seq_limit > USHRT_MAX)
84                         ids->seq_max = USHRT_MAX;
85                  else
86                         ids->seq_max = seq_limit;
87         }
88
89         ids->entries = ipc_rcu_alloc(sizeof(struct kern_ipc_perm *)*size +
90                                      sizeof(struct ipc_id_ary));
91
92         if(ids->entries == NULL) {
93                 printk(KERN_ERR "ipc_init_ids() failed, ipc service disabled.\n");
94                 size = 0;
95                 ids->entries = &ids->nullentry;
96         }
97         ids->entries->size = size;
98         for(i=0;i<size;i++)
99                 ids->entries->p[i] = NULL;
100 }
101
102 #ifdef CONFIG_PROC_FS
103 static struct file_operations sysvipc_proc_fops;
104 /**
105  *      ipc_init_proc_interface -  Create a proc interface for sysipc types
106  *                                 using a seq_file interface.
107  *      @path: Path in procfs
108  *      @header: Banner to be printed at the beginning of the file.
109  *      @ids: ipc id table to iterate.
110  *      @show: show routine.
111  */
112 void __init ipc_init_proc_interface(const char *path, const char *header,
113                                     struct ipc_ids *ids,
114                                     int (*show)(struct seq_file *, void *))
115 {
116         struct proc_dir_entry *pde;
117         struct ipc_proc_iface *iface;
118
119         iface = kmalloc(sizeof(*iface), GFP_KERNEL);
120         if (!iface)
121                 return;
122         iface->path     = path;
123         iface->header   = header;
124         iface->ids      = ids;
125         iface->show     = show;
126
127         pde = create_proc_entry(path,
128                                 S_IRUGO,        /* world readable */
129                                 NULL            /* parent dir */);
130         if (pde) {
131                 pde->data = iface;
132                 pde->proc_fops = &sysvipc_proc_fops;
133         } else {
134                 kfree(iface);
135         }
136 }
137 #endif
138
139 /**
140  *      ipc_findkey     -       find a key in an ipc identifier set     
141  *      @ids: Identifier set
142  *      @key: The key to find
143  *      
144  *      Requires ipc_ids.mutex locked.
145  *      Returns the identifier if found or -1 if not.
146  */
147  
148 int ipc_findkey(struct ipc_ids* ids, key_t key)
149 {
150         int id;
151         struct kern_ipc_perm* p;
152         int max_id = ids->max_id;
153
154         /*
155          * rcu_dereference() is not needed here
156          * since ipc_ids.mutex is held
157          */
158         for (id = 0; id <= max_id; id++) {
159                 p = ids->entries->p[id];
160                 if (p==NULL)
161                         continue;
162                 if (!vx_check(p->xid, VX_IDENT))
163                         continue;
164                 if (key == p->key)
165                         return id;
166         }
167         return -1;
168 }
169
170 /*
171  * Requires ipc_ids.mutex locked
172  */
173 static int grow_ary(struct ipc_ids* ids, int newsize)
174 {
175         struct ipc_id_ary* new;
176         struct ipc_id_ary* old;
177         int i;
178         int size = ids->entries->size;
179
180         if(newsize > IPCMNI)
181                 newsize = IPCMNI;
182         if(newsize <= size)
183                 return newsize;
184
185         new = ipc_rcu_alloc(sizeof(struct kern_ipc_perm *)*newsize +
186                             sizeof(struct ipc_id_ary));
187         if(new == NULL)
188                 return size;
189         new->size = newsize;
190         memcpy(new->p, ids->entries->p, sizeof(struct kern_ipc_perm *)*size);
191         for(i=size;i<newsize;i++) {
192                 new->p[i] = NULL;
193         }
194         old = ids->entries;
195
196         /*
197          * Use rcu_assign_pointer() to make sure the memcpyed contents
198          * of the new array are visible before the new array becomes visible.
199          */
200         rcu_assign_pointer(ids->entries, new);
201
202         ipc_rcu_putref(old);
203         return newsize;
204 }
205
206 /**
207  *      ipc_addid       -       add an IPC identifier
208  *      @ids: IPC identifier set
209  *      @new: new IPC permission set
210  *      @size: new size limit for the id array
211  *
212  *      Add an entry 'new' to the IPC arrays. The permissions object is
213  *      initialised and the first free entry is set up and the id assigned
214  *      is returned. The list is returned in a locked state on success.
215  *      On failure the list is not locked and -1 is returned.
216  *
217  *      Called with ipc_ids.mutex held.
218  */
219  
220 int ipc_addid(struct ipc_ids* ids, struct kern_ipc_perm* new, int size)
221 {
222         int id;
223
224         size = grow_ary(ids,size);
225
226         /*
227          * rcu_dereference()() is not needed here since
228          * ipc_ids.mutex is held
229          */
230         for (id = 0; id < size; id++) {
231                 if(ids->entries->p[id] == NULL)
232                         goto found;
233         }
234         return -1;
235 found:
236         ids->in_use++;
237         if (id > ids->max_id)
238                 ids->max_id = id;
239
240         new->cuid = new->uid = current->euid;
241         new->gid = new->cgid = current->egid;
242
243         new->seq = ids->seq++;
244         if(ids->seq > ids->seq_max)
245                 ids->seq = 0;
246
247         spin_lock_init(&new->lock);
248         new->deleted = 0;
249         rcu_read_lock();
250         spin_lock(&new->lock);
251         ids->entries->p[id] = new;
252         return id;
253 }
254
255 /**
256  *      ipc_rmid        -       remove an IPC identifier
257  *      @ids: identifier set
258  *      @id: Identifier to remove
259  *
260  *      The identifier must be valid, and in use. The kernel will panic if
261  *      fed an invalid identifier. The entry is removed and internal
262  *      variables recomputed. The object associated with the identifier
263  *      is returned.
264  *      ipc_ids.mutex and the spinlock for this ID is hold before this function
265  *      is called, and remain locked on the exit.
266  */
267  
268 struct kern_ipc_perm* ipc_rmid(struct ipc_ids* ids, int id)
269 {
270         struct kern_ipc_perm* p;
271         int lid = id % SEQ_MULTIPLIER;
272         BUG_ON(lid >= ids->entries->size);
273
274         /* 
275          * do not need a rcu_dereference()() here to force ordering
276          * on Alpha, since the ipc_ids.mutex is held.
277          */     
278         p = ids->entries->p[lid];
279         ids->entries->p[lid] = NULL;
280         BUG_ON(p==NULL);
281         ids->in_use--;
282
283         if (lid == ids->max_id) {
284                 do {
285                         lid--;
286                         if(lid == -1)
287                                 break;
288                 } while (ids->entries->p[lid] == NULL);
289                 ids->max_id = lid;
290         }
291         p->deleted = 1;
292         return p;
293 }
294
295 /**
296  *      ipc_alloc       -       allocate ipc space
297  *      @size: size desired
298  *
299  *      Allocate memory from the appropriate pools and return a pointer to it.
300  *      NULL is returned if the allocation fails
301  */
302  
303 void* ipc_alloc(int size)
304 {
305         void* out;
306         if(size > PAGE_SIZE)
307                 out = vmalloc(size);
308         else
309                 out = kmalloc(size, GFP_KERNEL);
310         return out;
311 }
312
313 /**
314  *      ipc_free        -       free ipc space
315  *      @ptr: pointer returned by ipc_alloc
316  *      @size: size of block
317  *
318  *      Free a block created with ipc_alloc. The caller must know the size
319  *      used in the allocation call.
320  */
321
322 void ipc_free(void* ptr, int size)
323 {
324         if(size > PAGE_SIZE)
325                 vfree(ptr);
326         else
327                 kfree(ptr);
328 }
329
330 /*
331  * rcu allocations:
332  * There are three headers that are prepended to the actual allocation:
333  * - during use: ipc_rcu_hdr.
334  * - during the rcu grace period: ipc_rcu_grace.
335  * - [only if vmalloc]: ipc_rcu_sched.
336  * Their lifetime doesn't overlap, thus the headers share the same memory.
337  * Unlike a normal union, they are right-aligned, thus some container_of
338  * forward/backward casting is necessary:
339  */
340 struct ipc_rcu_hdr
341 {
342         int refcount;
343         int is_vmalloc;
344         void *data[0];
345 };
346
347
348 struct ipc_rcu_grace
349 {
350         struct rcu_head rcu;
351         /* "void *" makes sure alignment of following data is sane. */
352         void *data[0];
353 };
354
355 struct ipc_rcu_sched
356 {
357         struct work_struct work;
358         /* "void *" makes sure alignment of following data is sane. */
359         void *data[0];
360 };
361
362 #define HDRLEN_KMALLOC          (sizeof(struct ipc_rcu_grace) > sizeof(struct ipc_rcu_hdr) ? \
363                                         sizeof(struct ipc_rcu_grace) : sizeof(struct ipc_rcu_hdr))
364 #define HDRLEN_VMALLOC          (sizeof(struct ipc_rcu_sched) > HDRLEN_KMALLOC ? \
365                                         sizeof(struct ipc_rcu_sched) : HDRLEN_KMALLOC)
366
367 static inline int rcu_use_vmalloc(int size)
368 {
369         /* Too big for a single page? */
370         if (HDRLEN_KMALLOC + size > PAGE_SIZE)
371                 return 1;
372         return 0;
373 }
374
375 /**
376  *      ipc_rcu_alloc   -       allocate ipc and rcu space 
377  *      @size: size desired
378  *
379  *      Allocate memory for the rcu header structure +  the object.
380  *      Returns the pointer to the object.
381  *      NULL is returned if the allocation fails. 
382  */
383  
384 void* ipc_rcu_alloc(int size)
385 {
386         void* out;
387         /* 
388          * We prepend the allocation with the rcu struct, and
389          * workqueue if necessary (for vmalloc). 
390          */
391         if (rcu_use_vmalloc(size)) {
392                 out = vmalloc(HDRLEN_VMALLOC + size);
393                 if (out) {
394                         out += HDRLEN_VMALLOC;
395                         container_of(out, struct ipc_rcu_hdr, data)->is_vmalloc = 1;
396                         container_of(out, struct ipc_rcu_hdr, data)->refcount = 1;
397                 }
398         } else {
399                 out = kmalloc(HDRLEN_KMALLOC + size, GFP_KERNEL);
400                 if (out) {
401                         out += HDRLEN_KMALLOC;
402                         container_of(out, struct ipc_rcu_hdr, data)->is_vmalloc = 0;
403                         container_of(out, struct ipc_rcu_hdr, data)->refcount = 1;
404                 }
405         }
406
407         return out;
408 }
409
410 void ipc_rcu_getref(void *ptr)
411 {
412         container_of(ptr, struct ipc_rcu_hdr, data)->refcount++;
413 }
414
415 /**
416  * ipc_schedule_free - free ipc + rcu space
417  * @head: RCU callback structure for queued work
418  * 
419  * Since RCU callback function is called in bh,
420  * we need to defer the vfree to schedule_work
421  */
422 static void ipc_schedule_free(struct rcu_head *head)
423 {
424         struct ipc_rcu_grace *grace =
425                 container_of(head, struct ipc_rcu_grace, rcu);
426         struct ipc_rcu_sched *sched =
427                         container_of(&(grace->data[0]), struct ipc_rcu_sched, data[0]);
428
429         INIT_WORK(&sched->work, vfree, sched);
430         schedule_work(&sched->work);
431 }
432
433 /**
434  * ipc_immediate_free - free ipc + rcu space
435  * @head: RCU callback structure that contains pointer to be freed
436  *
437  * Free from the RCU callback context
438  */
439 static void ipc_immediate_free(struct rcu_head *head)
440 {
441         struct ipc_rcu_grace *free =
442                 container_of(head, struct ipc_rcu_grace, rcu);
443         kfree(free);
444 }
445
446 void ipc_rcu_putref(void *ptr)
447 {
448         if (--container_of(ptr, struct ipc_rcu_hdr, data)->refcount > 0)
449                 return;
450
451         if (container_of(ptr, struct ipc_rcu_hdr, data)->is_vmalloc) {
452                 call_rcu(&container_of(ptr, struct ipc_rcu_grace, data)->rcu,
453                                 ipc_schedule_free);
454         } else {
455                 call_rcu(&container_of(ptr, struct ipc_rcu_grace, data)->rcu,
456                                 ipc_immediate_free);
457         }
458 }
459
460 /**
461  *      ipcperms        -       check IPC permissions
462  *      @ipcp: IPC permission set
463  *      @flag: desired permission set.
464  *
465  *      Check user, group, other permissions for access
466  *      to ipc resources. return 0 if allowed
467  */
468  
469 int ipcperms (struct kern_ipc_perm *ipcp, short flag)
470 {       /* flag will most probably be 0 or S_...UGO from <linux/stat.h> */
471         int requested_mode, granted_mode, err;
472
473         if (unlikely((err = audit_ipc_obj(ipcp))))
474                 return err;
475
476         if (!vx_check(ipcp->xid, VX_ADMIN|VX_IDENT)) /* maybe just VX_IDENT? */
477                 return -1;
478         requested_mode = (flag >> 6) | (flag >> 3) | flag;
479         granted_mode = ipcp->mode;
480         if (current->euid == ipcp->cuid || current->euid == ipcp->uid)
481                 granted_mode >>= 6;
482         else if (in_group_p(ipcp->cgid) || in_group_p(ipcp->gid))
483                 granted_mode >>= 3;
484         /* is there some bit set in requested_mode but not in granted_mode? */
485         if ((requested_mode & ~granted_mode & 0007) && 
486             !capable(CAP_IPC_OWNER))
487                 return -1;
488
489         return security_ipc_permission(ipcp, flag);
490 }
491
492 /*
493  * Functions to convert between the kern_ipc_perm structure and the
494  * old/new ipc_perm structures
495  */
496
497 /**
498  *      kernel_to_ipc64_perm    -       convert kernel ipc permissions to user
499  *      @in: kernel permissions
500  *      @out: new style IPC permissions
501  *
502  *      Turn the kernel object 'in' into a set of permissions descriptions
503  *      for returning to userspace (out).
504  */
505  
506
507 void kernel_to_ipc64_perm (struct kern_ipc_perm *in, struct ipc64_perm *out)
508 {
509         out->key        = in->key;
510         out->uid        = in->uid;
511         out->gid        = in->gid;
512         out->cuid       = in->cuid;
513         out->cgid       = in->cgid;
514         out->mode       = in->mode;
515         out->seq        = in->seq;
516 }
517
518 /**
519  *      ipc64_perm_to_ipc_perm  -       convert old ipc permissions to new
520  *      @in: new style IPC permissions
521  *      @out: old style IPC permissions
522  *
523  *      Turn the new style permissions object in into a compatibility
524  *      object and store it into the 'out' pointer.
525  */
526  
527 void ipc64_perm_to_ipc_perm (struct ipc64_perm *in, struct ipc_perm *out)
528 {
529         out->key        = in->key;
530         SET_UID(out->uid, in->uid);
531         SET_GID(out->gid, in->gid);
532         SET_UID(out->cuid, in->cuid);
533         SET_GID(out->cgid, in->cgid);
534         out->mode       = in->mode;
535         out->seq        = in->seq;
536 }
537
538 /*
539  * So far only shm_get_stat() calls ipc_get() via shm_get(), so ipc_get()
540  * is called with shm_ids.mutex locked.  Since grow_ary() is also called with
541  * shm_ids.mutex down(for Shared Memory), there is no need to add read
542  * barriers here to gurantee the writes in grow_ary() are seen in order 
543  * here (for Alpha).
544  *
545  * However ipc_get() itself does not necessary require ipc_ids.mutex down. So
546  * if in the future ipc_get() is used by other places without ipc_ids.mutex
547  * down, then ipc_get() needs read memery barriers as ipc_lock() does.
548  */
549 struct kern_ipc_perm* ipc_get(struct ipc_ids* ids, int id)
550 {
551         struct kern_ipc_perm* out;
552         int lid = id % SEQ_MULTIPLIER;
553         if(lid >= ids->entries->size)
554                 return NULL;
555         out = ids->entries->p[lid];
556         return out;
557 }
558
559 struct kern_ipc_perm* ipc_lock(struct ipc_ids* ids, int id)
560 {
561         struct kern_ipc_perm* out;
562         int lid = id % SEQ_MULTIPLIER;
563         struct ipc_id_ary* entries;
564
565         rcu_read_lock();
566         entries = rcu_dereference(ids->entries);
567         if(lid >= entries->size) {
568                 rcu_read_unlock();
569                 return NULL;
570         }
571         out = entries->p[lid];
572         if(out == NULL) {
573                 rcu_read_unlock();
574                 return NULL;
575         }
576         spin_lock(&out->lock);
577         
578         /* ipc_rmid() may have already freed the ID while ipc_lock
579          * was spinning: here verify that the structure is still valid
580          */
581         if (out->deleted) {
582                 spin_unlock(&out->lock);
583                 rcu_read_unlock();
584                 return NULL;
585         }
586         return out;
587 }
588
589 void ipc_lock_by_ptr(struct kern_ipc_perm *perm)
590 {
591         rcu_read_lock();
592         spin_lock(&perm->lock);
593 }
594
595 void ipc_unlock(struct kern_ipc_perm* perm)
596 {
597         spin_unlock(&perm->lock);
598         rcu_read_unlock();
599 }
600
601 int ipc_buildid(struct ipc_ids* ids, int id, int seq)
602 {
603         return SEQ_MULTIPLIER*seq + id;
604 }
605
606 int ipc_checkid(struct ipc_ids* ids, struct kern_ipc_perm* ipcp, int uid)
607 {
608         if(uid/SEQ_MULTIPLIER != ipcp->seq)
609                 return 1;
610         return 0;
611 }
612
613 #ifdef __ARCH_WANT_IPC_PARSE_VERSION
614
615
616 /**
617  *      ipc_parse_version       -       IPC call version
618  *      @cmd: pointer to command
619  *
620  *      Return IPC_64 for new style IPC and IPC_OLD for old style IPC. 
621  *      The cmd value is turned from an encoding command and version into
622  *      just the command code.
623  */
624  
625 int ipc_parse_version (int *cmd)
626 {
627         if (*cmd & IPC_64) {
628                 *cmd ^= IPC_64;
629                 return IPC_64;
630         } else {
631                 return IPC_OLD;
632         }
633 }
634
635 #endif /* __ARCH_WANT_IPC_PARSE_VERSION */
636
637 #ifdef CONFIG_PROC_FS
638 static void *sysvipc_proc_next(struct seq_file *s, void *it, loff_t *pos)
639 {
640         struct ipc_proc_iface *iface = s->private;
641         struct kern_ipc_perm *ipc = it;
642         loff_t p;
643
644         /* If we had an ipc id locked before, unlock it */
645         if (ipc && ipc != SEQ_START_TOKEN)
646                 ipc_unlock(ipc);
647
648         /*
649          * p = *pos - 1 (because id 0 starts at position 1)
650          *          + 1 (because we increment the position by one)
651          */
652         for (p = *pos; p <= iface->ids->max_id; p++) {
653                 if ((ipc = ipc_lock(iface->ids, p)) != NULL) {
654                         *pos = p + 1;
655                         return ipc;
656                 }
657         }
658
659         /* Out of range - return NULL to terminate iteration */
660         return NULL;
661 }
662
663 /*
664  * File positions: pos 0 -> header, pos n -> ipc id + 1.
665  * SeqFile iterator: iterator value locked shp or SEQ_TOKEN_START.
666  */
667 static void *sysvipc_proc_start(struct seq_file *s, loff_t *pos)
668 {
669         struct ipc_proc_iface *iface = s->private;
670         struct kern_ipc_perm *ipc;
671         loff_t p;
672
673         /*
674          * Take the lock - this will be released by the corresponding
675          * call to stop().
676          */
677         mutex_lock(&iface->ids->mutex);
678
679         /* pos < 0 is invalid */
680         if (*pos < 0)
681                 return NULL;
682
683         /* pos == 0 means header */
684         if (*pos == 0)
685                 return SEQ_START_TOKEN;
686
687         /* Find the (pos-1)th ipc */
688         for (p = *pos - 1; p <= iface->ids->max_id; p++) {
689                 if ((ipc = ipc_lock(iface->ids, p)) != NULL) {
690                         *pos = p + 1;
691                         return ipc;
692                 }
693         }
694         return NULL;
695 }
696
697 static void sysvipc_proc_stop(struct seq_file *s, void *it)
698 {
699         struct kern_ipc_perm *ipc = it;
700         struct ipc_proc_iface *iface = s->private;
701
702         /* If we had a locked segment, release it */
703         if (ipc && ipc != SEQ_START_TOKEN)
704                 ipc_unlock(ipc);
705
706         /* Release the lock we took in start() */
707         mutex_unlock(&iface->ids->mutex);
708 }
709
710 static int sysvipc_proc_show(struct seq_file *s, void *it)
711 {
712         struct ipc_proc_iface *iface = s->private;
713
714         if (it == SEQ_START_TOKEN)
715                 return seq_puts(s, iface->header);
716
717         return iface->show(s, it);
718 }
719
720 static struct seq_operations sysvipc_proc_seqops = {
721         .start = sysvipc_proc_start,
722         .stop  = sysvipc_proc_stop,
723         .next  = sysvipc_proc_next,
724         .show  = sysvipc_proc_show,
725 };
726
727 static int sysvipc_proc_open(struct inode *inode, struct file *file) {
728         int ret;
729         struct seq_file *seq;
730
731         ret = seq_open(file, &sysvipc_proc_seqops);
732         if (!ret) {
733                 seq = file->private_data;
734                 seq->private = PDE(inode)->data;
735         }
736         return ret;
737 }
738
739 static struct file_operations sysvipc_proc_fops = {
740         .open    = sysvipc_proc_open,
741         .read    = seq_read,
742         .llseek  = seq_lseek,
743         .release = seq_release,
744 };
745 #endif /* CONFIG_PROC_FS */