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