f74c5eef57d0d7e98561d4cc580264693e2d1561
[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 <manfreds@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  */
14
15 #include <linux/config.h>
16 #include <linux/mm.h>
17 #include <linux/shm.h>
18 #include <linux/init.h>
19 #include <linux/msg.h>
20 #include <linux/smp_lock.h>
21 #include <linux/vmalloc.h>
22 #include <linux/slab.h>
23 #include <linux/highuid.h>
24 #include <linux/security.h>
25 #include <linux/rcupdate.h>
26 #include <linux/workqueue.h>
27
28 #include "util.h"
29
30 /**
31  *      ipc_init        -       initialise IPC subsystem
32  *
33  *      The various system5 IPC resources (semaphores, messages and shared
34  *      memory are initialised
35  */
36  
37 static int __init ipc_init(void)
38 {
39         sem_init();
40         msg_init();
41         shm_init();
42         return 0;
43 }
44 __initcall(ipc_init);
45
46 /**
47  *      ipc_init_ids            -       initialise IPC identifiers
48  *      @ids: Identifier set
49  *      @size: Number of identifiers
50  *
51  *      Given a size for the ipc identifier range (limited below IPCMNI)
52  *      set up the sequence range to use then allocate and initialise the
53  *      array itself. 
54  */
55  
56 void __init ipc_init_ids(struct ipc_ids* ids, int size)
57 {
58         int i;
59         sema_init(&ids->sem,1);
60
61         if(size > IPCMNI)
62                 size = IPCMNI;
63         ids->size = size;
64         ids->in_use = 0;
65         ids->max_id = -1;
66         ids->seq = 0;
67         {
68                 int seq_limit = INT_MAX/SEQ_MULTIPLIER;
69                 if(seq_limit > USHRT_MAX)
70                         ids->seq_max = USHRT_MAX;
71                  else
72                         ids->seq_max = seq_limit;
73         }
74
75         ids->entries = ipc_rcu_alloc(sizeof(struct ipc_id)*size);
76
77         if(ids->entries == NULL) {
78                 printk(KERN_ERR "ipc_init_ids() failed, ipc service disabled.\n");
79                 ids->size = 0;
80         }
81         for(i=0;i<ids->size;i++)
82                 ids->entries[i].p = NULL;
83 }
84
85 /**
86  *      ipc_findkey     -       find a key in an ipc identifier set     
87  *      @ids: Identifier set
88  *      @key: The key to find
89  *      
90  *      Requires ipc_ids.sem locked.
91  *      Returns the identifier if found or -1 if not.
92  */
93  
94 int ipc_findkey(struct ipc_ids* ids, key_t key)
95 {
96         int id;
97         struct kern_ipc_perm* p;
98         int max_id = ids->max_id;
99
100         /*
101          * read_barrier_depends is not needed here
102          * since ipc_ids.sem is held
103          */
104         for (id = 0; id <= max_id; id++) {
105                 p = ids->entries[id].p;
106                 if(p==NULL)
107                         continue;
108                 if (key == p->key)
109                         return id;
110         }
111         return -1;
112 }
113
114 /*
115  * Requires ipc_ids.sem locked
116  */
117 static int grow_ary(struct ipc_ids* ids, int newsize)
118 {
119         struct ipc_id* new;
120         struct ipc_id* old;
121         int i;
122
123         if(newsize > IPCMNI)
124                 newsize = IPCMNI;
125         if(newsize <= ids->size)
126                 return newsize;
127
128         new = ipc_rcu_alloc(sizeof(struct ipc_id)*newsize);
129         if(new == NULL)
130                 return ids->size;
131         memcpy(new, ids->entries, sizeof(struct ipc_id)*ids->size);
132         for(i=ids->size;i<newsize;i++) {
133                 new[i].p = NULL;
134         }
135         old = ids->entries;
136         i = ids->size;
137
138         /*
139          * before setting the ids->entries to the new array, there must be a
140          * smp_wmb() to make sure the memcpyed contents of the new array are
141          * visible before the new array becomes visible.
142          */
143         smp_wmb();      /* prevent seeing new array uninitialized. */
144         ids->entries = new;
145         smp_wmb();      /* prevent indexing into old array based on new size. */
146         ids->size = newsize;
147
148         ipc_rcu_free(old, sizeof(struct ipc_id)*i);
149         return ids->size;
150 }
151
152 /**
153  *      ipc_addid       -       add an IPC identifier
154  *      @ids: IPC identifier set
155  *      @new: new IPC permission set
156  *      @size: new size limit for the id array
157  *
158  *      Add an entry 'new' to the IPC arrays. The permissions object is
159  *      initialised and the first free entry is set up and the id assigned
160  *      is returned. The list is returned in a locked state on success.
161  *      On failure the list is not locked and -1 is returned.
162  *
163  *      Called with ipc_ids.sem held.
164  */
165  
166 int ipc_addid(struct ipc_ids* ids, struct kern_ipc_perm* new, int size)
167 {
168         int id;
169
170         size = grow_ary(ids,size);
171
172         /*
173          * read_barrier_depends() is not needed here since
174          * ipc_ids.sem is held
175          */
176         for (id = 0; id < size; id++) {
177                 if(ids->entries[id].p == NULL)
178                         goto found;
179         }
180         return -1;
181 found:
182         ids->in_use++;
183         if (id > ids->max_id)
184                 ids->max_id = id;
185
186         new->cuid = new->uid = current->euid;
187         new->gid = new->cgid = current->egid;
188
189         new->seq = ids->seq++;
190         if(ids->seq > ids->seq_max)
191                 ids->seq = 0;
192
193         new->lock = SPIN_LOCK_UNLOCKED;
194         new->deleted = 0;
195         rcu_read_lock();
196         spin_lock(&new->lock);
197         ids->entries[id].p = new;
198         return id;
199 }
200
201 /**
202  *      ipc_rmid        -       remove an IPC identifier
203  *      @ids: identifier set
204  *      @id: Identifier to remove
205  *
206  *      The identifier must be valid, and in use. The kernel will panic if
207  *      fed an invalid identifier. The entry is removed and internal
208  *      variables recomputed. The object associated with the identifier
209  *      is returned.
210  *      ipc_ids.sem and the spinlock for this ID is hold before this function
211  *      is called, and remain locked on the exit.
212  */
213  
214 struct kern_ipc_perm* ipc_rmid(struct ipc_ids* ids, int id)
215 {
216         struct kern_ipc_perm* p;
217         int lid = id % SEQ_MULTIPLIER;
218         if(lid >= ids->size)
219                 BUG();
220
221         /* 
222          * do not need a read_barrier_depends() here to force ordering
223          * on Alpha, since the ipc_ids.sem is held.
224          */     
225         p = ids->entries[lid].p;
226         ids->entries[lid].p = NULL;
227         if(p==NULL)
228                 BUG();
229         ids->in_use--;
230
231         if (lid == ids->max_id) {
232                 do {
233                         lid--;
234                         if(lid == -1)
235                                 break;
236                 } while (ids->entries[lid].p == NULL);
237                 ids->max_id = lid;
238         }
239         p->deleted = 1;
240         return p;
241 }
242
243 /**
244  *      ipc_alloc       -       allocate ipc space
245  *      @size: size desired
246  *
247  *      Allocate memory from the appropriate pools and return a pointer to it.
248  *      NULL is returned if the allocation fails
249  */
250  
251 void* ipc_alloc(int size)
252 {
253         void* out;
254         if(size > PAGE_SIZE)
255                 out = vmalloc(size);
256         else
257                 out = kmalloc(size, GFP_KERNEL);
258         return out;
259 }
260
261 /**
262  *      ipc_free        -       free ipc space
263  *      @ptr: pointer returned by ipc_alloc
264  *      @size: size of block
265  *
266  *      Free a block created with ipc_alloc. The caller must know the size
267  *      used in the allocation call.
268  */
269
270 void ipc_free(void* ptr, int size)
271 {
272         if(size > PAGE_SIZE)
273                 vfree(ptr);
274         else
275                 kfree(ptr);
276 }
277
278 struct ipc_rcu_kmalloc
279 {
280         struct rcu_head rcu;
281         /* "void *" makes sure alignment of following data is sane. */
282         void *data[0];
283 };
284
285 struct ipc_rcu_vmalloc
286 {
287         struct rcu_head rcu;
288         struct work_struct work;
289         /* "void *" makes sure alignment of following data is sane. */
290         void *data[0];
291 };
292
293 static inline int rcu_use_vmalloc(int size)
294 {
295         /* Too big for a single page? */
296         if (sizeof(struct ipc_rcu_kmalloc) + size > PAGE_SIZE)
297                 return 1;
298         return 0;
299 }
300
301 /**
302  *      ipc_rcu_alloc   -       allocate ipc and rcu space 
303  *      @size: size desired
304  *
305  *      Allocate memory for the rcu header structure +  the object.
306  *      Returns the pointer to the object.
307  *      NULL is returned if the allocation fails. 
308  */
309  
310 void* ipc_rcu_alloc(int size)
311 {
312         void* out;
313         /* 
314          * We prepend the allocation with the rcu struct, and
315          * workqueue if necessary (for vmalloc). 
316          */
317         if (rcu_use_vmalloc(size)) {
318                 out = vmalloc(sizeof(struct ipc_rcu_vmalloc) + size);
319                 if (out) out += sizeof(struct ipc_rcu_vmalloc);
320         } else {
321                 out = kmalloc(sizeof(struct ipc_rcu_kmalloc)+size, GFP_KERNEL);
322                 if (out) out += sizeof(struct ipc_rcu_kmalloc);
323         }
324
325         return out;
326 }
327
328 /**
329  *      ipc_schedule_free       - free ipc + rcu space
330  * 
331  * Since RCU callback function is called in bh,
332  * we need to defer the vfree to schedule_work
333  */
334 static void ipc_schedule_free(void* arg)
335 {
336         struct ipc_rcu_vmalloc *free = arg;
337
338         INIT_WORK(&free->work, vfree, free);
339         schedule_work(&free->work);
340 }
341
342 void ipc_rcu_free(void* ptr, int size)
343 {
344         if (rcu_use_vmalloc(size)) {
345                 struct ipc_rcu_vmalloc *free;
346                 free = ptr - sizeof(*free);
347                 call_rcu(&free->rcu, ipc_schedule_free, free);
348         } else {
349                 struct ipc_rcu_kmalloc *free;
350                 free = ptr - sizeof(*free);
351                 /* kfree takes a "const void *" so gcc warns.  So we cast. */
352                 call_rcu(&free->rcu, (void (*)(void *))kfree, free);
353         }
354
355 }
356
357 /**
358  *      ipcperms        -       check IPC permissions
359  *      @ipcp: IPC permission set
360  *      @flag: desired permission set.
361  *
362  *      Check user, group, other permissions for access
363  *      to ipc resources. return 0 if allowed
364  */
365  
366 int ipcperms (struct kern_ipc_perm *ipcp, short flag)
367 {       /* flag will most probably be 0 or S_...UGO from <linux/stat.h> */
368         int requested_mode, granted_mode;
369
370         requested_mode = (flag >> 6) | (flag >> 3) | flag;
371         granted_mode = ipcp->mode;
372         if (current->euid == ipcp->cuid || current->euid == ipcp->uid)
373                 granted_mode >>= 6;
374         else if (in_group_p(ipcp->cgid) || in_group_p(ipcp->gid))
375                 granted_mode >>= 3;
376         /* is there some bit set in requested_mode but not in granted_mode? */
377         if ((requested_mode & ~granted_mode & 0007) && 
378             !capable(CAP_IPC_OWNER))
379                 return -1;
380
381         return security_ipc_permission(ipcp, flag);
382 }
383
384 /*
385  * Functions to convert between the kern_ipc_perm structure and the
386  * old/new ipc_perm structures
387  */
388
389 /**
390  *      kernel_to_ipc64_perm    -       convert kernel ipc permissions to user
391  *      @in: kernel permissions
392  *      @out: new style IPC permissions
393  *
394  *      Turn the kernel object 'in' into a set of permissions descriptions
395  *      for returning to userspace (out).
396  */
397  
398
399 void kernel_to_ipc64_perm (struct kern_ipc_perm *in, struct ipc64_perm *out)
400 {
401         out->key        = in->key;
402         out->uid        = in->uid;
403         out->gid        = in->gid;
404         out->cuid       = in->cuid;
405         out->cgid       = in->cgid;
406         out->mode       = in->mode;
407         out->seq        = in->seq;
408 }
409
410 /**
411  *      ipc64_perm_to_ipc_perm  -       convert old ipc permissions to new
412  *      @in: new style IPC permissions
413  *      @out: old style IPC permissions
414  *
415  *      Turn the new style permissions object in into a compatibility
416  *      object and store it into the 'out' pointer.
417  */
418  
419 void ipc64_perm_to_ipc_perm (struct ipc64_perm *in, struct ipc_perm *out)
420 {
421         out->key        = in->key;
422         SET_UID(out->uid, in->uid);
423         SET_GID(out->gid, in->gid);
424         SET_UID(out->cuid, in->cuid);
425         SET_GID(out->cgid, in->cgid);
426         out->mode       = in->mode;
427         out->seq        = in->seq;
428 }
429
430 /*
431  * So far only shm_get_stat() calls ipc_get() via shm_get(), so ipc_get()
432  * is called with shm_ids.sem locked.  Since grow_ary() is also called with
433  * shm_ids.sem down(for Shared Memory), there is no need to add read 
434  * barriers here to gurantee the writes in grow_ary() are seen in order 
435  * here (for Alpha).
436  *
437  * However ipc_get() itself does not necessary require ipc_ids.sem down. So
438  * if in the future ipc_get() is used by other places without ipc_ids.sem
439  * down, then ipc_get() needs read memery barriers as ipc_lock() does.
440  */
441 struct kern_ipc_perm* ipc_get(struct ipc_ids* ids, int id)
442 {
443         struct kern_ipc_perm* out;
444         int lid = id % SEQ_MULTIPLIER;
445         if(lid >= ids->size)
446                 return NULL;
447         out = ids->entries[lid].p;
448         return out;
449 }
450
451 struct kern_ipc_perm* ipc_lock(struct ipc_ids* ids, int id)
452 {
453         struct kern_ipc_perm* out;
454         int lid = id % SEQ_MULTIPLIER;
455         struct ipc_id* entries;
456
457         rcu_read_lock();
458         if(lid >= ids->size) {
459                 rcu_read_unlock();
460                 return NULL;
461         }
462
463         /* 
464          * Note: The following two read barriers are corresponding
465          * to the two write barriers in grow_ary(). They guarantee 
466          * the writes are seen in the same order on the read side. 
467          * smp_rmb() has effect on all CPUs.  read_barrier_depends() 
468          * is used if there are data dependency between two reads, and 
469          * has effect only on Alpha.
470          */
471         smp_rmb(); /* prevent indexing old array with new size */
472         entries = ids->entries;
473         read_barrier_depends(); /*prevent seeing new array unitialized */
474         out = entries[lid].p;
475         if(out == NULL) {
476                 rcu_read_unlock();
477                 return NULL;
478         }
479         spin_lock(&out->lock);
480         
481         /* ipc_rmid() may have already freed the ID while ipc_lock
482          * was spinning: here verify that the structure is still valid
483          */
484         if (out->deleted) {
485                 spin_unlock(&out->lock);
486                 rcu_read_unlock();
487                 return NULL;
488         }
489         return out;
490 }
491
492 void ipc_unlock(struct kern_ipc_perm* perm)
493 {
494         spin_unlock(&perm->lock);
495         rcu_read_unlock();
496 }
497
498 int ipc_buildid(struct ipc_ids* ids, int id, int seq)
499 {
500         return SEQ_MULTIPLIER*seq + id;
501 }
502
503 int ipc_checkid(struct ipc_ids* ids, struct kern_ipc_perm* ipcp, int uid)
504 {
505         if(uid/SEQ_MULTIPLIER != ipcp->seq)
506                 return 1;
507         return 0;
508 }
509
510 #if !defined(__ia64__) && !defined(__x86_64__) && !defined(__hppa__)
511
512 /**
513  *      ipc_parse_version       -       IPC call version
514  *      @cmd: pointer to command
515  *
516  *      Return IPC_64 for new style IPC and IPC_OLD for old style IPC. 
517  *      The cmd value is turned from an encoding command and version into
518  *      just the command code.
519  */
520  
521 int ipc_parse_version (int *cmd)
522 {
523         if (*cmd & IPC_64) {
524                 *cmd ^= IPC_64;
525                 return IPC_64;
526         } else {
527                 return IPC_OLD;
528         }
529 }
530
531 #endif /* __ia64__ */