vserver 2.0 rc7
[linux-2.6.git] / ipc / sem.c
1 /*
2  * linux/ipc/sem.c
3  * Copyright (C) 1992 Krishna Balasubramanian
4  * Copyright (C) 1995 Eric Schenk, Bruno Haible
5  *
6  * IMPLEMENTATION NOTES ON CODE REWRITE (Eric Schenk, January 1995):
7  * This code underwent a massive rewrite in order to solve some problems
8  * with the original code. In particular the original code failed to
9  * wake up processes that were waiting for semval to go to 0 if the
10  * value went to 0 and was then incremented rapidly enough. In solving
11  * this problem I have also modified the implementation so that it
12  * processes pending operations in a FIFO manner, thus give a guarantee
13  * that processes waiting for a lock on the semaphore won't starve
14  * unless another locking process fails to unlock.
15  * In addition the following two changes in behavior have been introduced:
16  * - The original implementation of semop returned the value
17  *   last semaphore element examined on success. This does not
18  *   match the manual page specifications, and effectively
19  *   allows the user to read the semaphore even if they do not
20  *   have read permissions. The implementation now returns 0
21  *   on success as stated in the manual page.
22  * - There is some confusion over whether the set of undo adjustments
23  *   to be performed at exit should be done in an atomic manner.
24  *   That is, if we are attempting to decrement the semval should we queue
25  *   up and wait until we can do so legally?
26  *   The original implementation attempted to do this.
27  *   The current implementation does not do so. This is because I don't
28  *   think it is the right thing (TM) to do, and because I couldn't
29  *   see a clean way to get the old behavior with the new design.
30  *   The POSIX standard and SVID should be consulted to determine
31  *   what behavior is mandated.
32  *
33  * Further notes on refinement (Christoph Rohland, December 1998):
34  * - The POSIX standard says, that the undo adjustments simply should
35  *   redo. So the current implementation is o.K.
36  * - The previous code had two flaws:
37  *   1) It actively gave the semaphore to the next waiting process
38  *      sleeping on the semaphore. Since this process did not have the
39  *      cpu this led to many unnecessary context switches and bad
40  *      performance. Now we only check which process should be able to
41  *      get the semaphore and if this process wants to reduce some
42  *      semaphore value we simply wake it up without doing the
43  *      operation. So it has to try to get it later. Thus e.g. the
44  *      running process may reacquire the semaphore during the current
45  *      time slice. If it only waits for zero or increases the semaphore,
46  *      we do the operation in advance and wake it up.
47  *   2) It did not wake up all zero waiting processes. We try to do
48  *      better but only get the semops right which only wait for zero or
49  *      increase. If there are decrement operations in the operations
50  *      array we do the same as before.
51  *
52  * With the incarnation of O(1) scheduler, it becomes unnecessary to perform
53  * check/retry algorithm for waking up blocked processes as the new scheduler
54  * is better at handling thread switch than the old one.
55  *
56  * /proc/sysvipc/sem support (c) 1999 Dragos Acostachioaie <dragos@iname.com>
57  *
58  * SMP-threaded, sysctl's added
59  * (c) 1999 Manfred Spraul <manfreds@colorfullife.com>
60  * Enforced range limit on SEM_UNDO
61  * (c) 2001 Red Hat Inc <alan@redhat.com>
62  * Lockless wakeup
63  * (c) 2003 Manfred Spraul <manfred@colorfullife.com>
64  */
65
66 #include <linux/config.h>
67 #include <linux/slab.h>
68 #include <linux/spinlock.h>
69 #include <linux/init.h>
70 #include <linux/proc_fs.h>
71 #include <linux/time.h>
72 #include <linux/smp_lock.h>
73 #include <linux/security.h>
74 #include <linux/syscalls.h>
75 #include <linux/audit.h>
76 #include <asm/uaccess.h>
77 #include "util.h"
78
79
80 #define sem_lock(id)    ((struct sem_array*)ipc_lock(&sem_ids,id))
81 #define sem_unlock(sma) ipc_unlock(&(sma)->sem_perm)
82 #define sem_rmid(id)    ((struct sem_array*)ipc_rmid(&sem_ids,id))
83 #define sem_checkid(sma, semid) \
84         ipc_checkid(&sem_ids,&sma->sem_perm,semid)
85 #define sem_buildid(id, seq) \
86         ipc_buildid(&sem_ids, id, seq)
87 static struct ipc_ids sem_ids;
88
89 static int newary (key_t, int, int);
90 static void freeary (struct sem_array *sma, int id);
91 #ifdef CONFIG_PROC_FS
92 static int sysvipc_sem_read_proc(char *buffer, char **start, off_t offset, int length, int *eof, void *data);
93 #endif
94
95 #define SEMMSL_FAST     256 /* 512 bytes on stack */
96 #define SEMOPM_FAST     64  /* ~ 372 bytes on stack */
97
98 /*
99  * linked list protection:
100  *      sem_undo.id_next,
101  *      sem_array.sem_pending{,last},
102  *      sem_array.sem_undo: sem_lock() for read/write
103  *      sem_undo.proc_next: only "current" is allowed to read/write that field.
104  *      
105  */
106
107 int sem_ctls[4] = {SEMMSL, SEMMNS, SEMOPM, SEMMNI};
108 #define sc_semmsl       (sem_ctls[0])
109 #define sc_semmns       (sem_ctls[1])
110 #define sc_semopm       (sem_ctls[2])
111 #define sc_semmni       (sem_ctls[3])
112
113 static int used_sems;
114
115 void __init sem_init (void)
116 {
117         used_sems = 0;
118         ipc_init_ids(&sem_ids,sc_semmni);
119
120 #ifdef CONFIG_PROC_FS
121         create_proc_read_entry("sysvipc/sem", 0, NULL, sysvipc_sem_read_proc, NULL);
122 #endif
123 }
124
125 /*
126  * Lockless wakeup algorithm:
127  * Without the check/retry algorithm a lockless wakeup is possible:
128  * - queue.status is initialized to -EINTR before blocking.
129  * - wakeup is performed by
130  *      * unlinking the queue entry from sma->sem_pending
131  *      * setting queue.status to IN_WAKEUP
132  *        This is the notification for the blocked thread that a
133  *        result value is imminent.
134  *      * call wake_up_process
135  *      * set queue.status to the final value.
136  * - the previously blocked thread checks queue.status:
137  *      * if it's IN_WAKEUP, then it must wait until the value changes
138  *      * if it's not -EINTR, then the operation was completed by
139  *        update_queue. semtimedop can return queue.status without
140  *        performing any operation on the semaphore array.
141  *      * otherwise it must acquire the spinlock and check what's up.
142  *
143  * The two-stage algorithm is necessary to protect against the following
144  * races:
145  * - if queue.status is set after wake_up_process, then the woken up idle
146  *   thread could race forward and try (and fail) to acquire sma->lock
147  *   before update_queue had a chance to set queue.status
148  * - if queue.status is written before wake_up_process and if the
149  *   blocked process is woken up by a signal between writing
150  *   queue.status and the wake_up_process, then the woken up
151  *   process could return from semtimedop and die by calling
152  *   sys_exit before wake_up_process is called. Then wake_up_process
153  *   will oops, because the task structure is already invalid.
154  *   (yes, this happened on s390 with sysv msg).
155  *
156  */
157 #define IN_WAKEUP       1
158
159 static int newary (key_t key, int nsems, int semflg)
160 {
161         int id;
162         int retval;
163         struct sem_array *sma;
164         int size;
165
166         if (!nsems)
167                 return -EINVAL;
168         if (used_sems + nsems > sc_semmns)
169                 return -ENOSPC;
170
171         size = sizeof (*sma) + nsems * sizeof (struct sem);
172         sma = ipc_rcu_alloc(size);
173         if (!sma) {
174                 return -ENOMEM;
175         }
176         memset (sma, 0, size);
177
178         sma->sem_perm.mode = (semflg & S_IRWXUGO);
179         sma->sem_perm.key = key;
180         sma->sem_perm.xid = vx_current_xid();
181
182         sma->sem_perm.security = NULL;
183         retval = security_sem_alloc(sma);
184         if (retval) {
185                 ipc_rcu_putref(sma);
186                 return retval;
187         }
188
189         id = ipc_addid(&sem_ids, &sma->sem_perm, sc_semmni);
190         if(id == -1) {
191                 security_sem_free(sma);
192                 ipc_rcu_putref(sma);
193                 return -ENOSPC;
194         }
195         used_sems += nsems;
196
197         sma->sem_base = (struct sem *) &sma[1];
198         /* sma->sem_pending = NULL; */
199         sma->sem_pending_last = &sma->sem_pending;
200         /* sma->undo = NULL; */
201         sma->sem_nsems = nsems;
202         sma->sem_ctime = get_seconds();
203         sem_unlock(sma);
204
205         return sem_buildid(id, sma->sem_perm.seq);
206 }
207
208 asmlinkage long sys_semget (key_t key, int nsems, int semflg)
209 {
210         int id, err = -EINVAL;
211         struct sem_array *sma;
212
213         if (nsems < 0 || nsems > sc_semmsl)
214                 return -EINVAL;
215         down(&sem_ids.sem);
216         
217         if (key == IPC_PRIVATE) {
218                 err = newary(key, nsems, semflg);
219         } else if ((id = ipc_findkey(&sem_ids, key)) == -1) {  /* key not used */
220                 if (!(semflg & IPC_CREAT))
221                         err = -ENOENT;
222                 else
223                         err = newary(key, nsems, semflg);
224         } else if (semflg & IPC_CREAT && semflg & IPC_EXCL) {
225                 err = -EEXIST;
226         } else {
227                 sma = sem_lock(id);
228                 if(sma==NULL)
229                         BUG();
230                 if (nsems > sma->sem_nsems)
231                         err = -EINVAL;
232                 else if (ipcperms(&sma->sem_perm, semflg))
233                         err = -EACCES;
234                 else {
235                         int semid = sem_buildid(id, sma->sem_perm.seq);
236                         err = security_sem_associate(sma, semflg);
237                         if (!err)
238                                 err = semid;
239                 }
240                 sem_unlock(sma);
241         }
242
243         up(&sem_ids.sem);
244         return err;
245 }
246
247 /* Manage the doubly linked list sma->sem_pending as a FIFO:
248  * insert new queue elements at the tail sma->sem_pending_last.
249  */
250 static inline void append_to_queue (struct sem_array * sma,
251                                     struct sem_queue * q)
252 {
253         *(q->prev = sma->sem_pending_last) = q;
254         *(sma->sem_pending_last = &q->next) = NULL;
255 }
256
257 static inline void prepend_to_queue (struct sem_array * sma,
258                                      struct sem_queue * q)
259 {
260         q->next = sma->sem_pending;
261         *(q->prev = &sma->sem_pending) = q;
262         if (q->next)
263                 q->next->prev = &q->next;
264         else /* sma->sem_pending_last == &sma->sem_pending */
265                 sma->sem_pending_last = &q->next;
266 }
267
268 static inline void remove_from_queue (struct sem_array * sma,
269                                       struct sem_queue * q)
270 {
271         *(q->prev) = q->next;
272         if (q->next)
273                 q->next->prev = q->prev;
274         else /* sma->sem_pending_last == &q->next */
275                 sma->sem_pending_last = q->prev;
276         q->prev = NULL; /* mark as removed */
277 }
278
279 /*
280  * Determine whether a sequence of semaphore operations would succeed
281  * all at once. Return 0 if yes, 1 if need to sleep, else return error code.
282  */
283
284 static int try_atomic_semop (struct sem_array * sma, struct sembuf * sops,
285                              int nsops, struct sem_undo *un, int pid)
286 {
287         int result, sem_op;
288         struct sembuf *sop;
289         struct sem * curr;
290
291         for (sop = sops; sop < sops + nsops; sop++) {
292                 curr = sma->sem_base + sop->sem_num;
293                 sem_op = sop->sem_op;
294                 result = curr->semval;
295   
296                 if (!sem_op && result)
297                         goto would_block;
298
299                 result += sem_op;
300                 if (result < 0)
301                         goto would_block;
302                 if (result > SEMVMX)
303                         goto out_of_range;
304                 if (sop->sem_flg & SEM_UNDO) {
305                         int undo = un->semadj[sop->sem_num] - sem_op;
306                         /*
307                          *      Exceeding the undo range is an error.
308                          */
309                         if (undo < (-SEMAEM - 1) || undo > SEMAEM)
310                                 goto out_of_range;
311                 }
312                 curr->semval = result;
313         }
314
315         sop--;
316         while (sop >= sops) {
317                 sma->sem_base[sop->sem_num].sempid = pid;
318                 if (sop->sem_flg & SEM_UNDO)
319                         un->semadj[sop->sem_num] -= sop->sem_op;
320                 sop--;
321         }
322         
323         sma->sem_otime = get_seconds();
324         return 0;
325
326 out_of_range:
327         result = -ERANGE;
328         goto undo;
329
330 would_block:
331         if (sop->sem_flg & IPC_NOWAIT)
332                 result = -EAGAIN;
333         else
334                 result = 1;
335
336 undo:
337         sop--;
338         while (sop >= sops) {
339                 sma->sem_base[sop->sem_num].semval -= sop->sem_op;
340                 sop--;
341         }
342
343         return result;
344 }
345
346 /* Go through the pending queue for the indicated semaphore
347  * looking for tasks that can be completed.
348  */
349 static void update_queue (struct sem_array * sma)
350 {
351         int error;
352         struct sem_queue * q;
353
354         q = sma->sem_pending;
355         while(q) {
356                 error = try_atomic_semop(sma, q->sops, q->nsops,
357                                          q->undo, q->pid);
358
359                 /* Does q->sleeper still need to sleep? */
360                 if (error <= 0) {
361                         struct sem_queue *n;
362                         remove_from_queue(sma,q);
363                         q->status = IN_WAKEUP;
364                         /*
365                          * Continue scanning. The next operation
366                          * that must be checked depends on the type of the
367                          * completed operation:
368                          * - if the operation modified the array, then
369                          *   restart from the head of the queue and
370                          *   check for threads that might be waiting
371                          *   for semaphore values to become 0.
372                          * - if the operation didn't modify the array,
373                          *   then just continue.
374                          */
375                         if (q->alter)
376                                 n = sma->sem_pending;
377                         else
378                                 n = q->next;
379                         wake_up_process(q->sleeper);
380                         /* hands-off: q will disappear immediately after
381                          * writing q->status.
382                          */
383                         q->status = error;
384                         q = n;
385                 } else {
386                         q = q->next;
387                 }
388         }
389 }
390
391 /* The following counts are associated to each semaphore:
392  *   semncnt        number of tasks waiting on semval being nonzero
393  *   semzcnt        number of tasks waiting on semval being zero
394  * This model assumes that a task waits on exactly one semaphore.
395  * Since semaphore operations are to be performed atomically, tasks actually
396  * wait on a whole sequence of semaphores simultaneously.
397  * The counts we return here are a rough approximation, but still
398  * warrant that semncnt+semzcnt>0 if the task is on the pending queue.
399  */
400 static int count_semncnt (struct sem_array * sma, ushort semnum)
401 {
402         int semncnt;
403         struct sem_queue * q;
404
405         semncnt = 0;
406         for (q = sma->sem_pending; q; q = q->next) {
407                 struct sembuf * sops = q->sops;
408                 int nsops = q->nsops;
409                 int i;
410                 for (i = 0; i < nsops; i++)
411                         if (sops[i].sem_num == semnum
412                             && (sops[i].sem_op < 0)
413                             && !(sops[i].sem_flg & IPC_NOWAIT))
414                                 semncnt++;
415         }
416         return semncnt;
417 }
418 static int count_semzcnt (struct sem_array * sma, ushort semnum)
419 {
420         int semzcnt;
421         struct sem_queue * q;
422
423         semzcnt = 0;
424         for (q = sma->sem_pending; q; q = q->next) {
425                 struct sembuf * sops = q->sops;
426                 int nsops = q->nsops;
427                 int i;
428                 for (i = 0; i < nsops; i++)
429                         if (sops[i].sem_num == semnum
430                             && (sops[i].sem_op == 0)
431                             && !(sops[i].sem_flg & IPC_NOWAIT))
432                                 semzcnt++;
433         }
434         return semzcnt;
435 }
436
437 /* Free a semaphore set. freeary() is called with sem_ids.sem down and
438  * the spinlock for this semaphore set hold. sem_ids.sem remains locked
439  * on exit.
440  */
441 static void freeary (struct sem_array *sma, int id)
442 {
443         struct sem_undo *un;
444         struct sem_queue *q;
445         int size;
446
447         /* Invalidate the existing undo structures for this semaphore set.
448          * (They will be freed without any further action in exit_sem()
449          * or during the next semop.)
450          */
451         for (un = sma->undo; un; un = un->id_next)
452                 un->semid = -1;
453
454         /* Wake up all pending processes and let them fail with EIDRM. */
455         q = sma->sem_pending;
456         while(q) {
457                 struct sem_queue *n;
458                 /* lazy remove_from_queue: we are killing the whole queue */
459                 q->prev = NULL;
460                 n = q->next;
461                 q->status = IN_WAKEUP;
462                 wake_up_process(q->sleeper); /* doesn't sleep */
463                 q->status = -EIDRM;     /* hands-off q */
464                 q = n;
465         }
466
467         /* Remove the semaphore set from the ID array*/
468         sma = sem_rmid(id);
469         sem_unlock(sma);
470
471         used_sems -= sma->sem_nsems;
472         size = sizeof (*sma) + sma->sem_nsems * sizeof (struct sem);
473         security_sem_free(sma);
474         ipc_rcu_putref(sma);
475 }
476
477 static unsigned long copy_semid_to_user(void __user *buf, struct semid64_ds *in, int version)
478 {
479         switch(version) {
480         case IPC_64:
481                 return copy_to_user(buf, in, sizeof(*in));
482         case IPC_OLD:
483             {
484                 struct semid_ds out;
485
486                 ipc64_perm_to_ipc_perm(&in->sem_perm, &out.sem_perm);
487
488                 out.sem_otime   = in->sem_otime;
489                 out.sem_ctime   = in->sem_ctime;
490                 out.sem_nsems   = in->sem_nsems;
491
492                 return copy_to_user(buf, &out, sizeof(out));
493             }
494         default:
495                 return -EINVAL;
496         }
497 }
498
499 static int semctl_nolock(int semid, int semnum, int cmd, int version, union semun arg)
500 {
501         int err = -EINVAL;
502         struct sem_array *sma;
503
504         switch(cmd) {
505         case IPC_INFO:
506         case SEM_INFO:
507         {
508                 struct seminfo seminfo;
509                 int max_id;
510
511                 err = security_sem_semctl(NULL, cmd);
512                 if (err)
513                         return err;
514                 
515                 memset(&seminfo,0,sizeof(seminfo));
516                 seminfo.semmni = sc_semmni;
517                 seminfo.semmns = sc_semmns;
518                 seminfo.semmsl = sc_semmsl;
519                 seminfo.semopm = sc_semopm;
520                 seminfo.semvmx = SEMVMX;
521                 seminfo.semmnu = SEMMNU;
522                 seminfo.semmap = SEMMAP;
523                 seminfo.semume = SEMUME;
524                 down(&sem_ids.sem);
525                 if (cmd == SEM_INFO) {
526                         seminfo.semusz = sem_ids.in_use;
527                         seminfo.semaem = used_sems;
528                 } else {
529                         seminfo.semusz = SEMUSZ;
530                         seminfo.semaem = SEMAEM;
531                 }
532                 max_id = sem_ids.max_id;
533                 up(&sem_ids.sem);
534                 if (copy_to_user (arg.__buf, &seminfo, sizeof(struct seminfo))) 
535                         return -EFAULT;
536                 return (max_id < 0) ? 0: max_id;
537         }
538         case SEM_STAT:
539         {
540                 struct semid64_ds tbuf;
541                 int id;
542
543                 if(semid >= sem_ids.entries->size)
544                         return -EINVAL;
545
546                 memset(&tbuf,0,sizeof(tbuf));
547
548                 sma = sem_lock(semid);
549                 if(sma == NULL)
550                         return -EINVAL;
551
552                 err = -EACCES;
553                 if (ipcperms (&sma->sem_perm, S_IRUGO))
554                         goto out_unlock;
555
556                 err = security_sem_semctl(sma, cmd);
557                 if (err)
558                         goto out_unlock;
559
560                 id = sem_buildid(semid, sma->sem_perm.seq);
561
562                 kernel_to_ipc64_perm(&sma->sem_perm, &tbuf.sem_perm);
563                 tbuf.sem_otime  = sma->sem_otime;
564                 tbuf.sem_ctime  = sma->sem_ctime;
565                 tbuf.sem_nsems  = sma->sem_nsems;
566                 sem_unlock(sma);
567                 if (copy_semid_to_user (arg.buf, &tbuf, version))
568                         return -EFAULT;
569                 return id;
570         }
571         default:
572                 return -EINVAL;
573         }
574         return err;
575 out_unlock:
576         sem_unlock(sma);
577         return err;
578 }
579
580 static int semctl_main(int semid, int semnum, int cmd, int version, union semun arg)
581 {
582         struct sem_array *sma;
583         struct sem* curr;
584         int err;
585         ushort fast_sem_io[SEMMSL_FAST];
586         ushort* sem_io = fast_sem_io;
587         int nsems;
588
589         sma = sem_lock(semid);
590         if(sma==NULL)
591                 return -EINVAL;
592
593         nsems = sma->sem_nsems;
594
595         err=-EIDRM;
596         if (sem_checkid(sma,semid))
597                 goto out_unlock;
598
599         err = -EACCES;
600         if (ipcperms (&sma->sem_perm, (cmd==SETVAL||cmd==SETALL)?S_IWUGO:S_IRUGO))
601                 goto out_unlock;
602
603         err = security_sem_semctl(sma, cmd);
604         if (err)
605                 goto out_unlock;
606
607         err = -EACCES;
608         switch (cmd) {
609         case GETALL:
610         {
611                 ushort __user *array = arg.array;
612                 int i;
613
614                 if(nsems > SEMMSL_FAST) {
615                         ipc_rcu_getref(sma);
616                         sem_unlock(sma);                        
617
618                         sem_io = ipc_alloc(sizeof(ushort)*nsems);
619                         if(sem_io == NULL) {
620                                 ipc_lock_by_ptr(&sma->sem_perm);
621                                 ipc_rcu_putref(sma);
622                                 sem_unlock(sma);
623                                 return -ENOMEM;
624                         }
625
626                         ipc_lock_by_ptr(&sma->sem_perm);
627                         ipc_rcu_putref(sma);
628                         if (sma->sem_perm.deleted) {
629                                 sem_unlock(sma);
630                                 err = -EIDRM;
631                                 goto out_free;
632                         }
633                 }
634
635                 for (i = 0; i < sma->sem_nsems; i++)
636                         sem_io[i] = sma->sem_base[i].semval;
637                 sem_unlock(sma);
638                 err = 0;
639                 if(copy_to_user(array, sem_io, nsems*sizeof(ushort)))
640                         err = -EFAULT;
641                 goto out_free;
642         }
643         case SETALL:
644         {
645                 int i;
646                 struct sem_undo *un;
647
648                 ipc_rcu_getref(sma);
649                 sem_unlock(sma);
650
651                 if(nsems > SEMMSL_FAST) {
652                         sem_io = ipc_alloc(sizeof(ushort)*nsems);
653                         if(sem_io == NULL) {
654                                 ipc_lock_by_ptr(&sma->sem_perm);
655                                 ipc_rcu_putref(sma);
656                                 sem_unlock(sma);
657                                 return -ENOMEM;
658                         }
659                 }
660
661                 if (copy_from_user (sem_io, arg.array, nsems*sizeof(ushort))) {
662                         ipc_lock_by_ptr(&sma->sem_perm);
663                         ipc_rcu_putref(sma);
664                         sem_unlock(sma);
665                         err = -EFAULT;
666                         goto out_free;
667                 }
668
669                 for (i = 0; i < nsems; i++) {
670                         if (sem_io[i] > SEMVMX) {
671                                 ipc_lock_by_ptr(&sma->sem_perm);
672                                 ipc_rcu_putref(sma);
673                                 sem_unlock(sma);
674                                 err = -ERANGE;
675                                 goto out_free;
676                         }
677                 }
678                 ipc_lock_by_ptr(&sma->sem_perm);
679                 ipc_rcu_putref(sma);
680                 if (sma->sem_perm.deleted) {
681                         sem_unlock(sma);
682                         err = -EIDRM;
683                         goto out_free;
684                 }
685
686                 for (i = 0; i < nsems; i++)
687                         sma->sem_base[i].semval = sem_io[i];
688                 for (un = sma->undo; un; un = un->id_next)
689                         for (i = 0; i < nsems; i++)
690                                 un->semadj[i] = 0;
691                 sma->sem_ctime = get_seconds();
692                 /* maybe some queued-up processes were waiting for this */
693                 update_queue(sma);
694                 err = 0;
695                 goto out_unlock;
696         }
697         case IPC_STAT:
698         {
699                 struct semid64_ds tbuf;
700                 memset(&tbuf,0,sizeof(tbuf));
701                 kernel_to_ipc64_perm(&sma->sem_perm, &tbuf.sem_perm);
702                 tbuf.sem_otime  = sma->sem_otime;
703                 tbuf.sem_ctime  = sma->sem_ctime;
704                 tbuf.sem_nsems  = sma->sem_nsems;
705                 sem_unlock(sma);
706                 if (copy_semid_to_user (arg.buf, &tbuf, version))
707                         return -EFAULT;
708                 return 0;
709         }
710         /* GETVAL, GETPID, GETNCTN, GETZCNT, SETVAL: fall-through */
711         }
712         err = -EINVAL;
713         if(semnum < 0 || semnum >= nsems)
714                 goto out_unlock;
715
716         curr = &sma->sem_base[semnum];
717
718         switch (cmd) {
719         case GETVAL:
720                 err = curr->semval;
721                 goto out_unlock;
722         case GETPID:
723                 err = curr->sempid;
724                 goto out_unlock;
725         case GETNCNT:
726                 err = count_semncnt(sma,semnum);
727                 goto out_unlock;
728         case GETZCNT:
729                 err = count_semzcnt(sma,semnum);
730                 goto out_unlock;
731         case SETVAL:
732         {
733                 int val = arg.val;
734                 struct sem_undo *un;
735                 err = -ERANGE;
736                 if (val > SEMVMX || val < 0)
737                         goto out_unlock;
738
739                 for (un = sma->undo; un; un = un->id_next)
740                         un->semadj[semnum] = 0;
741                 curr->semval = val;
742                 curr->sempid = current->tgid;
743                 sma->sem_ctime = get_seconds();
744                 /* maybe some queued-up processes were waiting for this */
745                 update_queue(sma);
746                 err = 0;
747                 goto out_unlock;
748         }
749         }
750 out_unlock:
751         sem_unlock(sma);
752 out_free:
753         if(sem_io != fast_sem_io)
754                 ipc_free(sem_io, sizeof(ushort)*nsems);
755         return err;
756 }
757
758 struct sem_setbuf {
759         uid_t   uid;
760         gid_t   gid;
761         mode_t  mode;
762 };
763
764 static inline unsigned long copy_semid_from_user(struct sem_setbuf *out, void __user *buf, int version)
765 {
766         switch(version) {
767         case IPC_64:
768             {
769                 struct semid64_ds tbuf;
770
771                 if(copy_from_user(&tbuf, buf, sizeof(tbuf)))
772                         return -EFAULT;
773
774                 out->uid        = tbuf.sem_perm.uid;
775                 out->gid        = tbuf.sem_perm.gid;
776                 out->mode       = tbuf.sem_perm.mode;
777
778                 return 0;
779             }
780         case IPC_OLD:
781             {
782                 struct semid_ds tbuf_old;
783
784                 if(copy_from_user(&tbuf_old, buf, sizeof(tbuf_old)))
785                         return -EFAULT;
786
787                 out->uid        = tbuf_old.sem_perm.uid;
788                 out->gid        = tbuf_old.sem_perm.gid;
789                 out->mode       = tbuf_old.sem_perm.mode;
790
791                 return 0;
792             }
793         default:
794                 return -EINVAL;
795         }
796 }
797
798 static int semctl_down(int semid, int semnum, int cmd, int version, union semun arg)
799 {
800         struct sem_array *sma;
801         int err;
802         struct sem_setbuf setbuf;
803         struct kern_ipc_perm *ipcp;
804
805         if(cmd == IPC_SET) {
806                 if(copy_semid_from_user (&setbuf, arg.buf, version))
807                         return -EFAULT;
808                 if ((err = audit_ipc_perms(0, setbuf.uid, setbuf.gid, setbuf.mode)))
809                         return err;
810         }
811         sma = sem_lock(semid);
812         if(sma==NULL)
813                 return -EINVAL;
814
815         if (sem_checkid(sma,semid)) {
816                 err=-EIDRM;
817                 goto out_unlock;
818         }       
819         ipcp = &sma->sem_perm;
820         
821         if (current->euid != ipcp->cuid && 
822             current->euid != ipcp->uid && !capable(CAP_SYS_ADMIN)) {
823                 err=-EPERM;
824                 goto out_unlock;
825         }
826
827         err = security_sem_semctl(sma, cmd);
828         if (err)
829                 goto out_unlock;
830
831         switch(cmd){
832         case IPC_RMID:
833                 freeary(sma, semid);
834                 err = 0;
835                 break;
836         case IPC_SET:
837                 ipcp->uid = setbuf.uid;
838                 ipcp->gid = setbuf.gid;
839                 ipcp->mode = (ipcp->mode & ~S_IRWXUGO)
840                                 | (setbuf.mode & S_IRWXUGO);
841                 sma->sem_ctime = get_seconds();
842                 sem_unlock(sma);
843                 err = 0;
844                 break;
845         default:
846                 sem_unlock(sma);
847                 err = -EINVAL;
848                 break;
849         }
850         return err;
851
852 out_unlock:
853         sem_unlock(sma);
854         return err;
855 }
856
857 asmlinkage long sys_semctl (int semid, int semnum, int cmd, union semun arg)
858 {
859         int err = -EINVAL;
860         int version;
861
862         if (semid < 0)
863                 return -EINVAL;
864
865         version = ipc_parse_version(&cmd);
866
867         switch(cmd) {
868         case IPC_INFO:
869         case SEM_INFO:
870         case SEM_STAT:
871                 err = semctl_nolock(semid,semnum,cmd,version,arg);
872                 return err;
873         case GETALL:
874         case GETVAL:
875         case GETPID:
876         case GETNCNT:
877         case GETZCNT:
878         case IPC_STAT:
879         case SETVAL:
880         case SETALL:
881                 err = semctl_main(semid,semnum,cmd,version,arg);
882                 return err;
883         case IPC_RMID:
884         case IPC_SET:
885                 down(&sem_ids.sem);
886                 err = semctl_down(semid,semnum,cmd,version,arg);
887                 up(&sem_ids.sem);
888                 return err;
889         default:
890                 return -EINVAL;
891         }
892 }
893
894 static inline void lock_semundo(void)
895 {
896         struct sem_undo_list *undo_list;
897
898         undo_list = current->sysvsem.undo_list;
899         if ((undo_list != NULL) && (atomic_read(&undo_list->refcnt) != 1))
900                 spin_lock(&undo_list->lock);
901 }
902
903 /* This code has an interaction with copy_semundo().
904  * Consider; two tasks are sharing the undo_list. task1
905  * acquires the undo_list lock in lock_semundo().  If task2 now
906  * exits before task1 releases the lock (by calling
907  * unlock_semundo()), then task1 will never call spin_unlock().
908  * This leave the sem_undo_list in a locked state.  If task1 now creats task3
909  * and once again shares the sem_undo_list, the sem_undo_list will still be
910  * locked, and future SEM_UNDO operations will deadlock.  This case is
911  * dealt with in copy_semundo() by having it reinitialize the spin lock when 
912  * the refcnt goes from 1 to 2.
913  */
914 static inline void unlock_semundo(void)
915 {
916         struct sem_undo_list *undo_list;
917
918         undo_list = current->sysvsem.undo_list;
919         if ((undo_list != NULL) && (atomic_read(&undo_list->refcnt) != 1))
920                 spin_unlock(&undo_list->lock);
921 }
922
923
924 /* If the task doesn't already have a undo_list, then allocate one
925  * here.  We guarantee there is only one thread using this undo list,
926  * and current is THE ONE
927  *
928  * If this allocation and assignment succeeds, but later
929  * portions of this code fail, there is no need to free the sem_undo_list.
930  * Just let it stay associated with the task, and it'll be freed later
931  * at exit time.
932  *
933  * This can block, so callers must hold no locks.
934  */
935 static inline int get_undo_list(struct sem_undo_list **undo_listp)
936 {
937         struct sem_undo_list *undo_list;
938         int size;
939
940         undo_list = current->sysvsem.undo_list;
941         if (!undo_list) {
942                 size = sizeof(struct sem_undo_list);
943                 undo_list = (struct sem_undo_list *) kmalloc(size, GFP_KERNEL);
944                 if (undo_list == NULL)
945                         return -ENOMEM;
946                 memset(undo_list, 0, size);
947                 /* don't initialize unodhd->lock here.  It's done
948                  * in copy_semundo() instead.
949                  */
950                 atomic_set(&undo_list->refcnt, 1);
951                 current->sysvsem.undo_list = undo_list;
952         }
953         *undo_listp = undo_list;
954         return 0;
955 }
956
957 static struct sem_undo *lookup_undo(struct sem_undo_list *ulp, int semid)
958 {
959         struct sem_undo **last, *un;
960
961         last = &ulp->proc_list;
962         un = *last;
963         while(un != NULL) {
964                 if(un->semid==semid)
965                         break;
966                 if(un->semid==-1) {
967                         *last=un->proc_next;
968                         kfree(un);
969                 } else {
970                         last=&un->proc_next;
971                 }
972                 un=*last;
973         }
974         return un;
975 }
976
977 static struct sem_undo *find_undo(int semid)
978 {
979         struct sem_array *sma;
980         struct sem_undo_list *ulp;
981         struct sem_undo *un, *new;
982         int nsems;
983         int error;
984
985         error = get_undo_list(&ulp);
986         if (error)
987                 return ERR_PTR(error);
988
989         lock_semundo();
990         un = lookup_undo(ulp, semid);
991         unlock_semundo();
992         if (likely(un!=NULL))
993                 goto out;
994
995         /* no undo structure around - allocate one. */
996         sma = sem_lock(semid);
997         un = ERR_PTR(-EINVAL);
998         if(sma==NULL)
999                 goto out;
1000         un = ERR_PTR(-EIDRM);
1001         if (sem_checkid(sma,semid)) {
1002                 sem_unlock(sma);
1003                 goto out;
1004         }
1005         nsems = sma->sem_nsems;
1006         ipc_rcu_getref(sma);
1007         sem_unlock(sma);
1008
1009         new = (struct sem_undo *) kmalloc(sizeof(struct sem_undo) + sizeof(short)*nsems, GFP_KERNEL);
1010         if (!new) {
1011                 ipc_lock_by_ptr(&sma->sem_perm);
1012                 ipc_rcu_putref(sma);
1013                 sem_unlock(sma);
1014                 return ERR_PTR(-ENOMEM);
1015         }
1016         memset(new, 0, sizeof(struct sem_undo) + sizeof(short)*nsems);
1017         new->semadj = (short *) &new[1];
1018         new->semid = semid;
1019
1020         lock_semundo();
1021         un = lookup_undo(ulp, semid);
1022         if (un) {
1023                 unlock_semundo();
1024                 kfree(new);
1025                 ipc_lock_by_ptr(&sma->sem_perm);
1026                 ipc_rcu_putref(sma);
1027                 sem_unlock(sma);
1028                 goto out;
1029         }
1030         ipc_lock_by_ptr(&sma->sem_perm);
1031         ipc_rcu_putref(sma);
1032         if (sma->sem_perm.deleted) {
1033                 sem_unlock(sma);
1034                 unlock_semundo();
1035                 kfree(new);
1036                 un = ERR_PTR(-EIDRM);
1037                 goto out;
1038         }
1039         new->proc_next = ulp->proc_list;
1040         ulp->proc_list = new;
1041         new->id_next = sma->undo;
1042         sma->undo = new;
1043         sem_unlock(sma);
1044         un = new;
1045         unlock_semundo();
1046 out:
1047         return un;
1048 }
1049
1050 asmlinkage long sys_semtimedop(int semid, struct sembuf __user *tsops,
1051                         unsigned nsops, const struct timespec __user *timeout)
1052 {
1053         int error = -EINVAL;
1054         struct sem_array *sma;
1055         struct sembuf fast_sops[SEMOPM_FAST];
1056         struct sembuf* sops = fast_sops, *sop;
1057         struct sem_undo *un;
1058         int undos = 0, decrease = 0, alter = 0, max;
1059         struct sem_queue queue;
1060         unsigned long jiffies_left = 0;
1061
1062         if (nsops < 1 || semid < 0)
1063                 return -EINVAL;
1064         if (nsops > sc_semopm)
1065                 return -E2BIG;
1066         if(nsops > SEMOPM_FAST) {
1067                 sops = kmalloc(sizeof(*sops)*nsops,GFP_KERNEL);
1068                 if(sops==NULL)
1069                         return -ENOMEM;
1070         }
1071         if (copy_from_user (sops, tsops, nsops * sizeof(*tsops))) {
1072                 error=-EFAULT;
1073                 goto out_free;
1074         }
1075         if (timeout) {
1076                 struct timespec _timeout;
1077                 if (copy_from_user(&_timeout, timeout, sizeof(*timeout))) {
1078                         error = -EFAULT;
1079                         goto out_free;
1080                 }
1081                 if (_timeout.tv_sec < 0 || _timeout.tv_nsec < 0 ||
1082                         _timeout.tv_nsec >= 1000000000L) {
1083                         error = -EINVAL;
1084                         goto out_free;
1085                 }
1086                 jiffies_left = timespec_to_jiffies(&_timeout);
1087         }
1088         max = 0;
1089         for (sop = sops; sop < sops + nsops; sop++) {
1090                 if (sop->sem_num >= max)
1091                         max = sop->sem_num;
1092                 if (sop->sem_flg & SEM_UNDO)
1093                         undos++;
1094                 if (sop->sem_op < 0)
1095                         decrease = 1;
1096                 if (sop->sem_op > 0)
1097                         alter = 1;
1098         }
1099         alter |= decrease;
1100
1101 retry_undos:
1102         if (undos) {
1103                 un = find_undo(semid);
1104                 if (IS_ERR(un)) {
1105                         error = PTR_ERR(un);
1106                         goto out_free;
1107                 }
1108         } else
1109                 un = NULL;
1110
1111         sma = sem_lock(semid);
1112         error=-EINVAL;
1113         if(sma==NULL)
1114                 goto out_free;
1115         error = -EIDRM;
1116         if (sem_checkid(sma,semid))
1117                 goto out_unlock_free;
1118         /*
1119          * semid identifies are not unique - find_undo may have
1120          * allocated an undo structure, it was invalidated by an RMID
1121          * and now a new array with received the same id. Check and retry.
1122          */
1123         if (un && un->semid == -1) {
1124                 sem_unlock(sma);
1125                 goto retry_undos;
1126         }
1127         error = -EFBIG;
1128         if (max >= sma->sem_nsems)
1129                 goto out_unlock_free;
1130
1131         error = -EACCES;
1132         if (ipcperms(&sma->sem_perm, alter ? S_IWUGO : S_IRUGO))
1133                 goto out_unlock_free;
1134
1135         error = security_sem_semop(sma, sops, nsops, alter);
1136         if (error)
1137                 goto out_unlock_free;
1138
1139         error = try_atomic_semop (sma, sops, nsops, un, current->tgid);
1140         if (error <= 0) {
1141                 if (alter && error == 0)
1142                         update_queue (sma);
1143                 goto out_unlock_free;
1144         }
1145
1146         /* We need to sleep on this operation, so we put the current
1147          * task into the pending queue and go to sleep.
1148          */
1149                 
1150         queue.sma = sma;
1151         queue.sops = sops;
1152         queue.nsops = nsops;
1153         queue.undo = un;
1154         queue.pid = current->tgid;
1155         queue.id = semid;
1156         queue.alter = alter;
1157         if (alter)
1158                 append_to_queue(sma ,&queue);
1159         else
1160                 prepend_to_queue(sma ,&queue);
1161
1162         queue.status = -EINTR;
1163         queue.sleeper = current;
1164         current->state = TASK_INTERRUPTIBLE;
1165         sem_unlock(sma);
1166
1167         if (timeout)
1168                 jiffies_left = schedule_timeout(jiffies_left);
1169         else
1170                 schedule();
1171
1172         error = queue.status;
1173         while(unlikely(error == IN_WAKEUP)) {
1174                 cpu_relax();
1175                 error = queue.status;
1176         }
1177
1178         if (error != -EINTR) {
1179                 /* fast path: update_queue already obtained all requested
1180                  * resources */
1181                 goto out_free;
1182         }
1183
1184         sma = sem_lock(semid);
1185         if(sma==NULL) {
1186                 if(queue.prev != NULL)
1187                         BUG();
1188                 error = -EIDRM;
1189                 goto out_free;
1190         }
1191
1192         /*
1193          * If queue.status != -EINTR we are woken up by another process
1194          */
1195         error = queue.status;
1196         if (error != -EINTR) {
1197                 goto out_unlock_free;
1198         }
1199
1200         /*
1201          * If an interrupt occurred we have to clean up the queue
1202          */
1203         if (timeout && jiffies_left == 0)
1204                 error = -EAGAIN;
1205         remove_from_queue(sma,&queue);
1206         goto out_unlock_free;
1207
1208 out_unlock_free:
1209         sem_unlock(sma);
1210 out_free:
1211         if(sops != fast_sops)
1212                 kfree(sops);
1213         return error;
1214 }
1215
1216 asmlinkage long sys_semop (int semid, struct sembuf __user *tsops, unsigned nsops)
1217 {
1218         return sys_semtimedop(semid, tsops, nsops, NULL);
1219 }
1220
1221 /* If CLONE_SYSVSEM is set, establish sharing of SEM_UNDO state between
1222  * parent and child tasks.
1223  *
1224  * See the notes above unlock_semundo() regarding the spin_lock_init()
1225  * in this code.  Initialize the undo_list->lock here instead of get_undo_list()
1226  * because of the reasoning in the comment above unlock_semundo.
1227  */
1228
1229 int copy_semundo(unsigned long clone_flags, struct task_struct *tsk)
1230 {
1231         struct sem_undo_list *undo_list;
1232         int error;
1233
1234         if (clone_flags & CLONE_SYSVSEM) {
1235                 error = get_undo_list(&undo_list);
1236                 if (error)
1237                         return error;
1238                 if (atomic_read(&undo_list->refcnt) == 1)
1239                         spin_lock_init(&undo_list->lock);
1240                 atomic_inc(&undo_list->refcnt);
1241                 tsk->sysvsem.undo_list = undo_list;
1242         } else 
1243                 tsk->sysvsem.undo_list = NULL;
1244
1245         return 0;
1246 }
1247
1248 /*
1249  * add semadj values to semaphores, free undo structures.
1250  * undo structures are not freed when semaphore arrays are destroyed
1251  * so some of them may be out of date.
1252  * IMPLEMENTATION NOTE: There is some confusion over whether the
1253  * set of adjustments that needs to be done should be done in an atomic
1254  * manner or not. That is, if we are attempting to decrement the semval
1255  * should we queue up and wait until we can do so legally?
1256  * The original implementation attempted to do this (queue and wait).
1257  * The current implementation does not do so. The POSIX standard
1258  * and SVID should be consulted to determine what behavior is mandated.
1259  */
1260 void exit_sem(struct task_struct *tsk)
1261 {
1262         struct sem_undo_list *undo_list;
1263         struct sem_undo *u, **up;
1264
1265         undo_list = tsk->sysvsem.undo_list;
1266         if (!undo_list)
1267                 return;
1268
1269         if (!atomic_dec_and_test(&undo_list->refcnt))
1270                 return;
1271
1272         /* There's no need to hold the semundo list lock, as current
1273          * is the last task exiting for this undo list.
1274          */
1275         for (up = &undo_list->proc_list; (u = *up); *up = u->proc_next, kfree(u)) {
1276                 struct sem_array *sma;
1277                 int nsems, i;
1278                 struct sem_undo *un, **unp;
1279                 int semid;
1280                
1281                 semid = u->semid;
1282
1283                 if(semid == -1)
1284                         continue;
1285                 sma = sem_lock(semid);
1286                 if (sma == NULL)
1287                         continue;
1288
1289                 if (u->semid == -1)
1290                         goto next_entry;
1291
1292                 BUG_ON(sem_checkid(sma,u->semid));
1293
1294                 /* remove u from the sma->undo list */
1295                 for (unp = &sma->undo; (un = *unp); unp = &un->id_next) {
1296                         if (u == un)
1297                                 goto found;
1298                 }
1299                 printk ("exit_sem undo list error id=%d\n", u->semid);
1300                 goto next_entry;
1301 found:
1302                 *unp = un->id_next;
1303                 /* perform adjustments registered in u */
1304                 nsems = sma->sem_nsems;
1305                 for (i = 0; i < nsems; i++) {
1306                         struct sem * sem = &sma->sem_base[i];
1307                         if (u->semadj[i]) {
1308                                 sem->semval += u->semadj[i];
1309                                 /*
1310                                  * Range checks of the new semaphore value,
1311                                  * not defined by sus:
1312                                  * - Some unices ignore the undo entirely
1313                                  *   (e.g. HP UX 11i 11.22, Tru64 V5.1)
1314                                  * - some cap the value (e.g. FreeBSD caps
1315                                  *   at 0, but doesn't enforce SEMVMX)
1316                                  *
1317                                  * Linux caps the semaphore value, both at 0
1318                                  * and at SEMVMX.
1319                                  *
1320                                  *      Manfred <manfred@colorfullife.com>
1321                                  */
1322                                 if (sem->semval < 0)
1323                                         sem->semval = 0;
1324                                 if (sem->semval > SEMVMX)
1325                                         sem->semval = SEMVMX;
1326                                 sem->sempid = current->tgid;
1327                         }
1328                 }
1329                 sma->sem_otime = get_seconds();
1330                 /* maybe some queued-up processes were waiting for this */
1331                 update_queue(sma);
1332 next_entry:
1333                 sem_unlock(sma);
1334         }
1335         kfree(undo_list);
1336 }
1337
1338 #ifdef CONFIG_PROC_FS
1339 static int sysvipc_sem_read_proc(char *buffer, char **start, off_t offset, int length, int *eof, void *data)
1340 {
1341         off_t pos = 0;
1342         off_t begin = 0;
1343         int i, len = 0;
1344
1345         len += sprintf(buffer, "       key      semid perms      nsems   uid   gid  cuid  cgid      otime      ctime\n");
1346         down(&sem_ids.sem);
1347
1348         for(i = 0; i <= sem_ids.max_id; i++) {
1349                 struct sem_array *sma;
1350                 sma = sem_lock(i);
1351                 if (sma) {
1352                         if (!vx_check(sma->sem_perm.xid, VX_IDENT)) {
1353                                 sem_unlock(sma);
1354                                 continue;
1355                         }
1356                         len += sprintf(buffer + len, "%10d %10d  %4o %10lu %5u %5u %5u %5u %10lu %10lu\n",
1357                                 sma->sem_perm.key,
1358                                 sem_buildid(i,sma->sem_perm.seq),
1359                                 sma->sem_perm.mode,
1360                                 sma->sem_nsems,
1361                                 sma->sem_perm.uid,
1362                                 sma->sem_perm.gid,
1363                                 sma->sem_perm.cuid,
1364                                 sma->sem_perm.cgid,
1365                                 sma->sem_otime,
1366                                 sma->sem_ctime);
1367                         sem_unlock(sma);
1368
1369                         pos += len;
1370                         if(pos < offset) {
1371                                 len = 0;
1372                                 begin = pos;
1373                         }
1374                         if(pos > offset + length)
1375                                 goto done;
1376                 }
1377         }
1378         *eof = 1;
1379 done:
1380         up(&sem_ids.sem);
1381         *start = buffer + (offset - begin);
1382         len -= (offset - begin);
1383         if(len > length)
1384                 len = length;
1385         if(len < 0)
1386                 len = 0;
1387         return len;
1388 }
1389 #endif