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