BUG_ON() Conversion in ipc/sem.c
[safe/jmp/linux-2.6] / 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 <manfred@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 <linux/capability.h>
77 #include <linux/seq_file.h>
78 #include <asm/uaccess.h>
79 #include "util.h"
80
81
82 #define sem_lock(id)    ((struct sem_array*)ipc_lock(&sem_ids,id))
83 #define sem_unlock(sma) ipc_unlock(&(sma)->sem_perm)
84 #define sem_rmid(id)    ((struct sem_array*)ipc_rmid(&sem_ids,id))
85 #define sem_checkid(sma, semid) \
86         ipc_checkid(&sem_ids,&sma->sem_perm,semid)
87 #define sem_buildid(id, seq) \
88         ipc_buildid(&sem_ids, id, seq)
89 static struct ipc_ids sem_ids;
90
91 static int newary (key_t, int, int);
92 static void freeary (struct sem_array *sma, int id);
93 #ifdef CONFIG_PROC_FS
94 static int sysvipc_sem_proc_show(struct seq_file *s, void *it);
95 #endif
96
97 #define SEMMSL_FAST     256 /* 512 bytes on stack */
98 #define SEMOPM_FAST     64  /* ~ 372 bytes on stack */
99
100 /*
101  * linked list protection:
102  *      sem_undo.id_next,
103  *      sem_array.sem_pending{,last},
104  *      sem_array.sem_undo: sem_lock() for read/write
105  *      sem_undo.proc_next: only "current" is allowed to read/write that field.
106  *      
107  */
108
109 int sem_ctls[4] = {SEMMSL, SEMMNS, SEMOPM, SEMMNI};
110 #define sc_semmsl       (sem_ctls[0])
111 #define sc_semmns       (sem_ctls[1])
112 #define sc_semopm       (sem_ctls[2])
113 #define sc_semmni       (sem_ctls[3])
114
115 static int used_sems;
116
117 void __init sem_init (void)
118 {
119         used_sems = 0;
120         ipc_init_ids(&sem_ids,sc_semmni);
121         ipc_init_proc_interface("sysvipc/sem",
122                                 "       key      semid perms      nsems   uid   gid  cuid  cgid      otime      ctime\n",
123                                 &sem_ids,
124                                 sysvipc_sem_proc_show);
125 }
126
127 /*
128  * Lockless wakeup algorithm:
129  * Without the check/retry algorithm a lockless wakeup is possible:
130  * - queue.status is initialized to -EINTR before blocking.
131  * - wakeup is performed by
132  *      * unlinking the queue entry from sma->sem_pending
133  *      * setting queue.status to IN_WAKEUP
134  *        This is the notification for the blocked thread that a
135  *        result value is imminent.
136  *      * call wake_up_process
137  *      * set queue.status to the final value.
138  * - the previously blocked thread checks queue.status:
139  *      * if it's IN_WAKEUP, then it must wait until the value changes
140  *      * if it's not -EINTR, then the operation was completed by
141  *        update_queue. semtimedop can return queue.status without
142  *        performing any operation on the semaphore array.
143  *      * otherwise it must acquire the spinlock and check what's up.
144  *
145  * The two-stage algorithm is necessary to protect against the following
146  * races:
147  * - if queue.status is set after wake_up_process, then the woken up idle
148  *   thread could race forward and try (and fail) to acquire sma->lock
149  *   before update_queue had a chance to set queue.status
150  * - if queue.status is written before wake_up_process and if the
151  *   blocked process is woken up by a signal between writing
152  *   queue.status and the wake_up_process, then the woken up
153  *   process could return from semtimedop and die by calling
154  *   sys_exit before wake_up_process is called. Then wake_up_process
155  *   will oops, because the task structure is already invalid.
156  *   (yes, this happened on s390 with sysv msg).
157  *
158  */
159 #define IN_WAKEUP       1
160
161 static int newary (key_t key, int nsems, int semflg)
162 {
163         int id;
164         int retval;
165         struct sem_array *sma;
166         int size;
167
168         if (!nsems)
169                 return -EINVAL;
170         if (used_sems + nsems > sc_semmns)
171                 return -ENOSPC;
172
173         size = sizeof (*sma) + nsems * sizeof (struct sem);
174         sma = ipc_rcu_alloc(size);
175         if (!sma) {
176                 return -ENOMEM;
177         }
178         memset (sma, 0, size);
179
180         sma->sem_perm.mode = (semflg & S_IRWXUGO);
181         sma->sem_perm.key = key;
182
183         sma->sem_perm.security = NULL;
184         retval = security_sem_alloc(sma);
185         if (retval) {
186                 ipc_rcu_putref(sma);
187                 return retval;
188         }
189
190         id = ipc_addid(&sem_ids, &sma->sem_perm, sc_semmni);
191         if(id == -1) {
192                 security_sem_free(sma);
193                 ipc_rcu_putref(sma);
194                 return -ENOSPC;
195         }
196         used_sems += nsems;
197
198         sma->sem_id = sem_buildid(id, sma->sem_perm.seq);
199         sma->sem_base = (struct sem *) &sma[1];
200         /* sma->sem_pending = NULL; */
201         sma->sem_pending_last = &sma->sem_pending;
202         /* sma->undo = NULL; */
203         sma->sem_nsems = nsems;
204         sma->sem_ctime = get_seconds();
205         sem_unlock(sma);
206
207         return sma->sem_id;
208 }
209
210 asmlinkage long sys_semget (key_t key, int nsems, int semflg)
211 {
212         int id, err = -EINVAL;
213         struct sem_array *sma;
214
215         if (nsems < 0 || nsems > sc_semmsl)
216                 return -EINVAL;
217         down(&sem_ids.sem);
218         
219         if (key == IPC_PRIVATE) {
220                 err = newary(key, nsems, semflg);
221         } else if ((id = ipc_findkey(&sem_ids, key)) == -1) {  /* key not used */
222                 if (!(semflg & IPC_CREAT))
223                         err = -ENOENT;
224                 else
225                         err = newary(key, nsems, semflg);
226         } else if (semflg & IPC_CREAT && semflg & IPC_EXCL) {
227                 err = -EEXIST;
228         } else {
229                 sma = sem_lock(id);
230                 BUG_ON(sma==NULL);
231                 if (nsems > sma->sem_nsems)
232                         err = -EINVAL;
233                 else if (ipcperms(&sma->sem_perm, semflg))
234                         err = -EACCES;
235                 else {
236                         int semid = sem_buildid(id, sma->sem_perm.seq);
237                         err = security_sem_associate(sma, semflg);
238                         if (!err)
239                                 err = semid;
240                 }
241                 sem_unlock(sma);
242         }
243
244         up(&sem_ids.sem);
245         return err;
246 }
247
248 /* Manage the doubly linked list sma->sem_pending as a FIFO:
249  * insert new queue elements at the tail sma->sem_pending_last.
250  */
251 static inline void append_to_queue (struct sem_array * sma,
252                                     struct sem_queue * q)
253 {
254         *(q->prev = sma->sem_pending_last) = q;
255         *(sma->sem_pending_last = &q->next) = NULL;
256 }
257
258 static inline void prepend_to_queue (struct sem_array * sma,
259                                      struct sem_queue * q)
260 {
261         q->next = sma->sem_pending;
262         *(q->prev = &sma->sem_pending) = q;
263         if (q->next)
264                 q->next->prev = &q->next;
265         else /* sma->sem_pending_last == &sma->sem_pending */
266                 sma->sem_pending_last = &q->next;
267 }
268
269 static inline void remove_from_queue (struct sem_array * sma,
270                                       struct sem_queue * q)
271 {
272         *(q->prev) = q->next;
273         if (q->next)
274                 q->next->prev = q->prev;
275         else /* sma->sem_pending_last == &q->next */
276                 sma->sem_pending_last = q->prev;
277         q->prev = NULL; /* mark as removed */
278 }
279
280 /*
281  * Determine whether a sequence of semaphore operations would succeed
282  * all at once. Return 0 if yes, 1 if need to sleep, else return error code.
283  */
284
285 static int try_atomic_semop (struct sem_array * sma, struct sembuf * sops,
286                              int nsops, struct sem_undo *un, int pid)
287 {
288         int result, sem_op;
289         struct sembuf *sop;
290         struct sem * curr;
291
292         for (sop = sops; sop < sops + nsops; sop++) {
293                 curr = sma->sem_base + sop->sem_num;
294                 sem_op = sop->sem_op;
295                 result = curr->semval;
296   
297                 if (!sem_op && result)
298                         goto would_block;
299
300                 result += sem_op;
301                 if (result < 0)
302                         goto would_block;
303                 if (result > SEMVMX)
304                         goto out_of_range;
305                 if (sop->sem_flg & SEM_UNDO) {
306                         int undo = un->semadj[sop->sem_num] - sem_op;
307                         /*
308                          *      Exceeding the undo range is an error.
309                          */
310                         if (undo < (-SEMAEM - 1) || undo > SEMAEM)
311                                 goto out_of_range;
312                 }
313                 curr->semval = result;
314         }
315
316         sop--;
317         while (sop >= sops) {
318                 sma->sem_base[sop->sem_num].sempid = pid;
319                 if (sop->sem_flg & SEM_UNDO)
320                         un->semadj[sop->sem_num] -= sop->sem_op;
321                 sop--;
322         }
323         
324         sma->sem_otime = get_seconds();
325         return 0;
326
327 out_of_range:
328         result = -ERANGE;
329         goto undo;
330
331 would_block:
332         if (sop->sem_flg & IPC_NOWAIT)
333                 result = -EAGAIN;
334         else
335                 result = 1;
336
337 undo:
338         sop--;
339         while (sop >= sops) {
340                 sma->sem_base[sop->sem_num].semval -= sop->sem_op;
341                 sop--;
342         }
343
344         return result;
345 }
346
347 /* Go through the pending queue for the indicated semaphore
348  * looking for tasks that can be completed.
349  */
350 static void update_queue (struct sem_array * sma)
351 {
352         int error;
353         struct sem_queue * q;
354
355         q = sma->sem_pending;
356         while(q) {
357                 error = try_atomic_semop(sma, q->sops, q->nsops,
358                                          q->undo, q->pid);
359
360                 /* Does q->sleeper still need to sleep? */
361                 if (error <= 0) {
362                         struct sem_queue *n;
363                         remove_from_queue(sma,q);
364                         q->status = IN_WAKEUP;
365                         /*
366                          * Continue scanning. The next operation
367                          * that must be checked depends on the type of the
368                          * completed operation:
369                          * - if the operation modified the array, then
370                          *   restart from the head of the queue and
371                          *   check for threads that might be waiting
372                          *   for semaphore values to become 0.
373                          * - if the operation didn't modify the array,
374                          *   then just continue.
375                          */
376                         if (q->alter)
377                                 n = sma->sem_pending;
378                         else
379                                 n = q->next;
380                         wake_up_process(q->sleeper);
381                         /* hands-off: q will disappear immediately after
382                          * writing q->status.
383                          */
384                         smp_wmb();
385                         q->status = error;
386                         q = n;
387                 } else {
388                         q = q->next;
389                 }
390         }
391 }
392
393 /* The following counts are associated to each semaphore:
394  *   semncnt        number of tasks waiting on semval being nonzero
395  *   semzcnt        number of tasks waiting on semval being zero
396  * This model assumes that a task waits on exactly one semaphore.
397  * Since semaphore operations are to be performed atomically, tasks actually
398  * wait on a whole sequence of semaphores simultaneously.
399  * The counts we return here are a rough approximation, but still
400  * warrant that semncnt+semzcnt>0 if the task is on the pending queue.
401  */
402 static int count_semncnt (struct sem_array * sma, ushort semnum)
403 {
404         int semncnt;
405         struct sem_queue * q;
406
407         semncnt = 0;
408         for (q = sma->sem_pending; q; q = q->next) {
409                 struct sembuf * sops = q->sops;
410                 int nsops = q->nsops;
411                 int i;
412                 for (i = 0; i < nsops; i++)
413                         if (sops[i].sem_num == semnum
414                             && (sops[i].sem_op < 0)
415                             && !(sops[i].sem_flg & IPC_NOWAIT))
416                                 semncnt++;
417         }
418         return semncnt;
419 }
420 static int count_semzcnt (struct sem_array * sma, ushort semnum)
421 {
422         int semzcnt;
423         struct sem_queue * q;
424
425         semzcnt = 0;
426         for (q = sma->sem_pending; q; q = q->next) {
427                 struct sembuf * sops = q->sops;
428                 int nsops = q->nsops;
429                 int i;
430                 for (i = 0; i < nsops; i++)
431                         if (sops[i].sem_num == semnum
432                             && (sops[i].sem_op == 0)
433                             && !(sops[i].sem_flg & IPC_NOWAIT))
434                                 semzcnt++;
435         }
436         return semzcnt;
437 }
438
439 /* Free a semaphore set. freeary() is called with sem_ids.sem down and
440  * the spinlock for this semaphore set hold. sem_ids.sem remains locked
441  * on exit.
442  */
443 static void freeary (struct sem_array *sma, int id)
444 {
445         struct sem_undo *un;
446         struct sem_queue *q;
447         int size;
448
449         /* Invalidate the existing undo structures for this semaphore set.
450          * (They will be freed without any further action in exit_sem()
451          * or during the next semop.)
452          */
453         for (un = sma->undo; un; un = un->id_next)
454                 un->semid = -1;
455
456         /* Wake up all pending processes and let them fail with EIDRM. */
457         q = sma->sem_pending;
458         while(q) {
459                 struct sem_queue *n;
460                 /* lazy remove_from_queue: we are killing the whole queue */
461                 q->prev = NULL;
462                 n = q->next;
463                 q->status = IN_WAKEUP;
464                 wake_up_process(q->sleeper); /* doesn't sleep */
465                 smp_wmb();
466                 q->status = -EIDRM;     /* hands-off q */
467                 q = n;
468         }
469
470         /* Remove the semaphore set from the ID array*/
471         sma = sem_rmid(id);
472         sem_unlock(sma);
473
474         used_sems -= sma->sem_nsems;
475         size = sizeof (*sma) + sma->sem_nsems * sizeof (struct sem);
476         security_sem_free(sma);
477         ipc_rcu_putref(sma);
478 }
479
480 static unsigned long copy_semid_to_user(void __user *buf, struct semid64_ds *in, int version)
481 {
482         switch(version) {
483         case IPC_64:
484                 return copy_to_user(buf, in, sizeof(*in));
485         case IPC_OLD:
486             {
487                 struct semid_ds out;
488
489                 ipc64_perm_to_ipc_perm(&in->sem_perm, &out.sem_perm);
490
491                 out.sem_otime   = in->sem_otime;
492                 out.sem_ctime   = in->sem_ctime;
493                 out.sem_nsems   = in->sem_nsems;
494
495                 return copy_to_user(buf, &out, sizeof(out));
496             }
497         default:
498                 return -EINVAL;
499         }
500 }
501
502 static int semctl_nolock(int semid, int semnum, int cmd, int version, union semun arg)
503 {
504         int err = -EINVAL;
505         struct sem_array *sma;
506
507         switch(cmd) {
508         case IPC_INFO:
509         case SEM_INFO:
510         {
511                 struct seminfo seminfo;
512                 int max_id;
513
514                 err = security_sem_semctl(NULL, cmd);
515                 if (err)
516                         return err;
517                 
518                 memset(&seminfo,0,sizeof(seminfo));
519                 seminfo.semmni = sc_semmni;
520                 seminfo.semmns = sc_semmns;
521                 seminfo.semmsl = sc_semmsl;
522                 seminfo.semopm = sc_semopm;
523                 seminfo.semvmx = SEMVMX;
524                 seminfo.semmnu = SEMMNU;
525                 seminfo.semmap = SEMMAP;
526                 seminfo.semume = SEMUME;
527                 down(&sem_ids.sem);
528                 if (cmd == SEM_INFO) {
529                         seminfo.semusz = sem_ids.in_use;
530                         seminfo.semaem = used_sems;
531                 } else {
532                         seminfo.semusz = SEMUSZ;
533                         seminfo.semaem = SEMAEM;
534                 }
535                 max_id = sem_ids.max_id;
536                 up(&sem_ids.sem);
537                 if (copy_to_user (arg.__buf, &seminfo, sizeof(struct seminfo))) 
538                         return -EFAULT;
539                 return (max_id < 0) ? 0: max_id;
540         }
541         case SEM_STAT:
542         {
543                 struct semid64_ds tbuf;
544                 int id;
545
546                 if(semid >= sem_ids.entries->size)
547                         return -EINVAL;
548
549                 memset(&tbuf,0,sizeof(tbuf));
550
551                 sma = sem_lock(semid);
552                 if(sma == NULL)
553                         return -EINVAL;
554
555                 err = -EACCES;
556                 if (ipcperms (&sma->sem_perm, S_IRUGO))
557                         goto out_unlock;
558
559                 err = security_sem_semctl(sma, cmd);
560                 if (err)
561                         goto out_unlock;
562
563                 id = sem_buildid(semid, sma->sem_perm.seq);
564
565                 kernel_to_ipc64_perm(&sma->sem_perm, &tbuf.sem_perm);
566                 tbuf.sem_otime  = sma->sem_otime;
567                 tbuf.sem_ctime  = sma->sem_ctime;
568                 tbuf.sem_nsems  = sma->sem_nsems;
569                 sem_unlock(sma);
570                 if (copy_semid_to_user (arg.buf, &tbuf, version))
571                         return -EFAULT;
572                 return id;
573         }
574         default:
575                 return -EINVAL;
576         }
577         return err;
578 out_unlock:
579         sem_unlock(sma);
580         return err;
581 }
582
583 static int semctl_main(int semid, int semnum, int cmd, int version, union semun arg)
584 {
585         struct sem_array *sma;
586         struct sem* curr;
587         int err;
588         ushort fast_sem_io[SEMMSL_FAST];
589         ushort* sem_io = fast_sem_io;
590         int nsems;
591
592         sma = sem_lock(semid);
593         if(sma==NULL)
594                 return -EINVAL;
595
596         nsems = sma->sem_nsems;
597
598         err=-EIDRM;
599         if (sem_checkid(sma,semid))
600                 goto out_unlock;
601
602         err = -EACCES;
603         if (ipcperms (&sma->sem_perm, (cmd==SETVAL||cmd==SETALL)?S_IWUGO:S_IRUGO))
604                 goto out_unlock;
605
606         err = security_sem_semctl(sma, cmd);
607         if (err)
608                 goto out_unlock;
609
610         err = -EACCES;
611         switch (cmd) {
612         case GETALL:
613         {
614                 ushort __user *array = arg.array;
615                 int i;
616
617                 if(nsems > SEMMSL_FAST) {
618                         ipc_rcu_getref(sma);
619                         sem_unlock(sma);                        
620
621                         sem_io = ipc_alloc(sizeof(ushort)*nsems);
622                         if(sem_io == NULL) {
623                                 ipc_lock_by_ptr(&sma->sem_perm);
624                                 ipc_rcu_putref(sma);
625                                 sem_unlock(sma);
626                                 return -ENOMEM;
627                         }
628
629                         ipc_lock_by_ptr(&sma->sem_perm);
630                         ipc_rcu_putref(sma);
631                         if (sma->sem_perm.deleted) {
632                                 sem_unlock(sma);
633                                 err = -EIDRM;
634                                 goto out_free;
635                         }
636                 }
637
638                 for (i = 0; i < sma->sem_nsems; i++)
639                         sem_io[i] = sma->sem_base[i].semval;
640                 sem_unlock(sma);
641                 err = 0;
642                 if(copy_to_user(array, sem_io, nsems*sizeof(ushort)))
643                         err = -EFAULT;
644                 goto out_free;
645         }
646         case SETALL:
647         {
648                 int i;
649                 struct sem_undo *un;
650
651                 ipc_rcu_getref(sma);
652                 sem_unlock(sma);
653
654                 if(nsems > SEMMSL_FAST) {
655                         sem_io = ipc_alloc(sizeof(ushort)*nsems);
656                         if(sem_io == NULL) {
657                                 ipc_lock_by_ptr(&sma->sem_perm);
658                                 ipc_rcu_putref(sma);
659                                 sem_unlock(sma);
660                                 return -ENOMEM;
661                         }
662                 }
663
664                 if (copy_from_user (sem_io, arg.array, nsems*sizeof(ushort))) {
665                         ipc_lock_by_ptr(&sma->sem_perm);
666                         ipc_rcu_putref(sma);
667                         sem_unlock(sma);
668                         err = -EFAULT;
669                         goto out_free;
670                 }
671
672                 for (i = 0; i < nsems; i++) {
673                         if (sem_io[i] > SEMVMX) {
674                                 ipc_lock_by_ptr(&sma->sem_perm);
675                                 ipc_rcu_putref(sma);
676                                 sem_unlock(sma);
677                                 err = -ERANGE;
678                                 goto out_free;
679                         }
680                 }
681                 ipc_lock_by_ptr(&sma->sem_perm);
682                 ipc_rcu_putref(sma);
683                 if (sma->sem_perm.deleted) {
684                         sem_unlock(sma);
685                         err = -EIDRM;
686                         goto out_free;
687                 }
688
689                 for (i = 0; i < nsems; i++)
690                         sma->sem_base[i].semval = sem_io[i];
691                 for (un = sma->undo; un; un = un->id_next)
692                         for (i = 0; i < nsems; i++)
693                                 un->semadj[i] = 0;
694                 sma->sem_ctime = get_seconds();
695                 /* maybe some queued-up processes were waiting for this */
696                 update_queue(sma);
697                 err = 0;
698                 goto out_unlock;
699         }
700         case IPC_STAT:
701         {
702                 struct semid64_ds tbuf;
703                 memset(&tbuf,0,sizeof(tbuf));
704                 kernel_to_ipc64_perm(&sma->sem_perm, &tbuf.sem_perm);
705                 tbuf.sem_otime  = sma->sem_otime;
706                 tbuf.sem_ctime  = sma->sem_ctime;
707                 tbuf.sem_nsems  = sma->sem_nsems;
708                 sem_unlock(sma);
709                 if (copy_semid_to_user (arg.buf, &tbuf, version))
710                         return -EFAULT;
711                 return 0;
712         }
713         /* GETVAL, GETPID, GETNCTN, GETZCNT, SETVAL: fall-through */
714         }
715         err = -EINVAL;
716         if(semnum < 0 || semnum >= nsems)
717                 goto out_unlock;
718
719         curr = &sma->sem_base[semnum];
720
721         switch (cmd) {
722         case GETVAL:
723                 err = curr->semval;
724                 goto out_unlock;
725         case GETPID:
726                 err = curr->sempid;
727                 goto out_unlock;
728         case GETNCNT:
729                 err = count_semncnt(sma,semnum);
730                 goto out_unlock;
731         case GETZCNT:
732                 err = count_semzcnt(sma,semnum);
733                 goto out_unlock;
734         case SETVAL:
735         {
736                 int val = arg.val;
737                 struct sem_undo *un;
738                 err = -ERANGE;
739                 if (val > SEMVMX || val < 0)
740                         goto out_unlock;
741
742                 for (un = sma->undo; un; un = un->id_next)
743                         un->semadj[semnum] = 0;
744                 curr->semval = val;
745                 curr->sempid = current->tgid;
746                 sma->sem_ctime = get_seconds();
747                 /* maybe some queued-up processes were waiting for this */
748                 update_queue(sma);
749                 err = 0;
750                 goto out_unlock;
751         }
752         }
753 out_unlock:
754         sem_unlock(sma);
755 out_free:
756         if(sem_io != fast_sem_io)
757                 ipc_free(sem_io, sizeof(ushort)*nsems);
758         return err;
759 }
760
761 struct sem_setbuf {
762         uid_t   uid;
763         gid_t   gid;
764         mode_t  mode;
765 };
766
767 static inline unsigned long copy_semid_from_user(struct sem_setbuf *out, void __user *buf, int version)
768 {
769         switch(version) {
770         case IPC_64:
771             {
772                 struct semid64_ds tbuf;
773
774                 if(copy_from_user(&tbuf, buf, sizeof(tbuf)))
775                         return -EFAULT;
776
777                 out->uid        = tbuf.sem_perm.uid;
778                 out->gid        = tbuf.sem_perm.gid;
779                 out->mode       = tbuf.sem_perm.mode;
780
781                 return 0;
782             }
783         case IPC_OLD:
784             {
785                 struct semid_ds tbuf_old;
786
787                 if(copy_from_user(&tbuf_old, buf, sizeof(tbuf_old)))
788                         return -EFAULT;
789
790                 out->uid        = tbuf_old.sem_perm.uid;
791                 out->gid        = tbuf_old.sem_perm.gid;
792                 out->mode       = tbuf_old.sem_perm.mode;
793
794                 return 0;
795             }
796         default:
797                 return -EINVAL;
798         }
799 }
800
801 static int semctl_down(int semid, int semnum, int cmd, int version, union semun arg)
802 {
803         struct sem_array *sma;
804         int err;
805         struct sem_setbuf setbuf;
806         struct kern_ipc_perm *ipcp;
807
808         if(cmd == IPC_SET) {
809                 if(copy_semid_from_user (&setbuf, arg.buf, version))
810                         return -EFAULT;
811         }
812         sma = sem_lock(semid);
813         if(sma==NULL)
814                 return -EINVAL;
815
816         if (sem_checkid(sma,semid)) {
817                 err=-EIDRM;
818                 goto out_unlock;
819         }       
820         ipcp = &sma->sem_perm;
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                 if ((err = audit_ipc_perms(0, setbuf.uid, setbuf.gid, setbuf.mode, ipcp)))
838                         goto out_unlock;
839                 ipcp->uid = setbuf.uid;
840                 ipcp->gid = setbuf.gid;
841                 ipcp->mode = (ipcp->mode & ~S_IRWXUGO)
842                                 | (setbuf.mode & S_IRWXUGO);
843                 sma->sem_ctime = get_seconds();
844                 sem_unlock(sma);
845                 err = 0;
846                 break;
847         default:
848                 sem_unlock(sma);
849                 err = -EINVAL;
850                 break;
851         }
852         return err;
853
854 out_unlock:
855         sem_unlock(sma);
856         return err;
857 }
858
859 asmlinkage long sys_semctl (int semid, int semnum, int cmd, union semun arg)
860 {
861         int err = -EINVAL;
862         int version;
863
864         if (semid < 0)
865                 return -EINVAL;
866
867         version = ipc_parse_version(&cmd);
868
869         switch(cmd) {
870         case IPC_INFO:
871         case SEM_INFO:
872         case SEM_STAT:
873                 err = semctl_nolock(semid,semnum,cmd,version,arg);
874                 return err;
875         case GETALL:
876         case GETVAL:
877         case GETPID:
878         case GETNCNT:
879         case GETZCNT:
880         case IPC_STAT:
881         case SETVAL:
882         case SETALL:
883                 err = semctl_main(semid,semnum,cmd,version,arg);
884                 return err;
885         case IPC_RMID:
886         case IPC_SET:
887                 down(&sem_ids.sem);
888                 err = semctl_down(semid,semnum,cmd,version,arg);
889                 up(&sem_ids.sem);
890                 return err;
891         default:
892                 return -EINVAL;
893         }
894 }
895
896 static inline void lock_semundo(void)
897 {
898         struct sem_undo_list *undo_list;
899
900         undo_list = current->sysvsem.undo_list;
901         if (undo_list)
902                 spin_lock(&undo_list->lock);
903 }
904
905 /* This code has an interaction with copy_semundo().
906  * Consider; two tasks are sharing the undo_list. task1
907  * acquires the undo_list lock in lock_semundo().  If task2 now
908  * exits before task1 releases the lock (by calling
909  * unlock_semundo()), then task1 will never call spin_unlock().
910  * This leave the sem_undo_list in a locked state.  If task1 now creats task3
911  * and once again shares the sem_undo_list, the sem_undo_list will still be
912  * locked, and future SEM_UNDO operations will deadlock.  This case is
913  * dealt with in copy_semundo() by having it reinitialize the spin lock when 
914  * the refcnt goes from 1 to 2.
915  */
916 static inline void unlock_semundo(void)
917 {
918         struct sem_undo_list *undo_list;
919
920         undo_list = current->sysvsem.undo_list;
921         if (undo_list)
922                 spin_unlock(&undo_list->lock);
923 }
924
925
926 /* If the task doesn't already have a undo_list, then allocate one
927  * here.  We guarantee there is only one thread using this undo list,
928  * and current is THE ONE
929  *
930  * If this allocation and assignment succeeds, but later
931  * portions of this code fail, there is no need to free the sem_undo_list.
932  * Just let it stay associated with the task, and it'll be freed later
933  * at exit time.
934  *
935  * This can block, so callers must hold no locks.
936  */
937 static inline int get_undo_list(struct sem_undo_list **undo_listp)
938 {
939         struct sem_undo_list *undo_list;
940         int size;
941
942         undo_list = current->sysvsem.undo_list;
943         if (!undo_list) {
944                 size = sizeof(struct sem_undo_list);
945                 undo_list = (struct sem_undo_list *) kmalloc(size, GFP_KERNEL);
946                 if (undo_list == NULL)
947                         return -ENOMEM;
948                 memset(undo_list, 0, size);
949                 spin_lock_init(&undo_list->lock);
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, 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 = 1;
1094                 if (sop->sem_op != 0)
1095                         alter = 1;
1096         }
1097
1098 retry_undos:
1099         if (undos) {
1100                 un = find_undo(semid);
1101                 if (IS_ERR(un)) {
1102                         error = PTR_ERR(un);
1103                         goto out_free;
1104                 }
1105         } else
1106                 un = NULL;
1107
1108         sma = sem_lock(semid);
1109         error=-EINVAL;
1110         if(sma==NULL)
1111                 goto out_free;
1112         error = -EIDRM;
1113         if (sem_checkid(sma,semid))
1114                 goto out_unlock_free;
1115         /*
1116          * semid identifies are not unique - find_undo may have
1117          * allocated an undo structure, it was invalidated by an RMID
1118          * and now a new array with received the same id. Check and retry.
1119          */
1120         if (un && un->semid == -1) {
1121                 sem_unlock(sma);
1122                 goto retry_undos;
1123         }
1124         error = -EFBIG;
1125         if (max >= sma->sem_nsems)
1126                 goto out_unlock_free;
1127
1128         error = -EACCES;
1129         if (ipcperms(&sma->sem_perm, alter ? S_IWUGO : S_IRUGO))
1130                 goto out_unlock_free;
1131
1132         error = security_sem_semop(sma, sops, nsops, alter);
1133         if (error)
1134                 goto out_unlock_free;
1135
1136         error = try_atomic_semop (sma, sops, nsops, un, current->tgid);
1137         if (error <= 0) {
1138                 if (alter && error == 0)
1139                         update_queue (sma);
1140                 goto out_unlock_free;
1141         }
1142
1143         /* We need to sleep on this operation, so we put the current
1144          * task into the pending queue and go to sleep.
1145          */
1146                 
1147         queue.sma = sma;
1148         queue.sops = sops;
1149         queue.nsops = nsops;
1150         queue.undo = un;
1151         queue.pid = current->tgid;
1152         queue.id = semid;
1153         queue.alter = alter;
1154         if (alter)
1155                 append_to_queue(sma ,&queue);
1156         else
1157                 prepend_to_queue(sma ,&queue);
1158
1159         queue.status = -EINTR;
1160         queue.sleeper = current;
1161         current->state = TASK_INTERRUPTIBLE;
1162         sem_unlock(sma);
1163
1164         if (timeout)
1165                 jiffies_left = schedule_timeout(jiffies_left);
1166         else
1167                 schedule();
1168
1169         error = queue.status;
1170         while(unlikely(error == IN_WAKEUP)) {
1171                 cpu_relax();
1172                 error = queue.status;
1173         }
1174
1175         if (error != -EINTR) {
1176                 /* fast path: update_queue already obtained all requested
1177                  * resources */
1178                 goto out_free;
1179         }
1180
1181         sma = sem_lock(semid);
1182         if(sma==NULL) {
1183                 BUG_ON(queue.prev != NULL);
1184                 error = -EIDRM;
1185                 goto out_free;
1186         }
1187
1188         /*
1189          * If queue.status != -EINTR we are woken up by another process
1190          */
1191         error = queue.status;
1192         if (error != -EINTR) {
1193                 goto out_unlock_free;
1194         }
1195
1196         /*
1197          * If an interrupt occurred we have to clean up the queue
1198          */
1199         if (timeout && jiffies_left == 0)
1200                 error = -EAGAIN;
1201         remove_from_queue(sma,&queue);
1202         goto out_unlock_free;
1203
1204 out_unlock_free:
1205         sem_unlock(sma);
1206 out_free:
1207         if(sops != fast_sops)
1208                 kfree(sops);
1209         return error;
1210 }
1211
1212 asmlinkage long sys_semop (int semid, struct sembuf __user *tsops, unsigned nsops)
1213 {
1214         return sys_semtimedop(semid, tsops, nsops, NULL);
1215 }
1216
1217 /* If CLONE_SYSVSEM is set, establish sharing of SEM_UNDO state between
1218  * parent and child tasks.
1219  *
1220  * See the notes above unlock_semundo() regarding the spin_lock_init()
1221  * in this code.  Initialize the undo_list->lock here instead of get_undo_list()
1222  * because of the reasoning in the comment above unlock_semundo.
1223  */
1224
1225 int copy_semundo(unsigned long clone_flags, struct task_struct *tsk)
1226 {
1227         struct sem_undo_list *undo_list;
1228         int error;
1229
1230         if (clone_flags & CLONE_SYSVSEM) {
1231                 error = get_undo_list(&undo_list);
1232                 if (error)
1233                         return error;
1234                 atomic_inc(&undo_list->refcnt);
1235                 tsk->sysvsem.undo_list = undo_list;
1236         } else 
1237                 tsk->sysvsem.undo_list = NULL;
1238
1239         return 0;
1240 }
1241
1242 /*
1243  * add semadj values to semaphores, free undo structures.
1244  * undo structures are not freed when semaphore arrays are destroyed
1245  * so some of them may be out of date.
1246  * IMPLEMENTATION NOTE: There is some confusion over whether the
1247  * set of adjustments that needs to be done should be done in an atomic
1248  * manner or not. That is, if we are attempting to decrement the semval
1249  * should we queue up and wait until we can do so legally?
1250  * The original implementation attempted to do this (queue and wait).
1251  * The current implementation does not do so. The POSIX standard
1252  * and SVID should be consulted to determine what behavior is mandated.
1253  */
1254 void exit_sem(struct task_struct *tsk)
1255 {
1256         struct sem_undo_list *undo_list;
1257         struct sem_undo *u, **up;
1258
1259         undo_list = tsk->sysvsem.undo_list;
1260         if (!undo_list)
1261                 return;
1262
1263         if (!atomic_dec_and_test(&undo_list->refcnt))
1264                 return;
1265
1266         /* There's no need to hold the semundo list lock, as current
1267          * is the last task exiting for this undo list.
1268          */
1269         for (up = &undo_list->proc_list; (u = *up); *up = u->proc_next, kfree(u)) {
1270                 struct sem_array *sma;
1271                 int nsems, i;
1272                 struct sem_undo *un, **unp;
1273                 int semid;
1274                
1275                 semid = u->semid;
1276
1277                 if(semid == -1)
1278                         continue;
1279                 sma = sem_lock(semid);
1280                 if (sma == NULL)
1281                         continue;
1282
1283                 if (u->semid == -1)
1284                         goto next_entry;
1285
1286                 BUG_ON(sem_checkid(sma,u->semid));
1287
1288                 /* remove u from the sma->undo list */
1289                 for (unp = &sma->undo; (un = *unp); unp = &un->id_next) {
1290                         if (u == un)
1291                                 goto found;
1292                 }
1293                 printk ("exit_sem undo list error id=%d\n", u->semid);
1294                 goto next_entry;
1295 found:
1296                 *unp = un->id_next;
1297                 /* perform adjustments registered in u */
1298                 nsems = sma->sem_nsems;
1299                 for (i = 0; i < nsems; i++) {
1300                         struct sem * sem = &sma->sem_base[i];
1301                         if (u->semadj[i]) {
1302                                 sem->semval += u->semadj[i];
1303                                 /*
1304                                  * Range checks of the new semaphore value,
1305                                  * not defined by sus:
1306                                  * - Some unices ignore the undo entirely
1307                                  *   (e.g. HP UX 11i 11.22, Tru64 V5.1)
1308                                  * - some cap the value (e.g. FreeBSD caps
1309                                  *   at 0, but doesn't enforce SEMVMX)
1310                                  *
1311                                  * Linux caps the semaphore value, both at 0
1312                                  * and at SEMVMX.
1313                                  *
1314                                  *      Manfred <manfred@colorfullife.com>
1315                                  */
1316                                 if (sem->semval < 0)
1317                                         sem->semval = 0;
1318                                 if (sem->semval > SEMVMX)
1319                                         sem->semval = SEMVMX;
1320                                 sem->sempid = current->tgid;
1321                         }
1322                 }
1323                 sma->sem_otime = get_seconds();
1324                 /* maybe some queued-up processes were waiting for this */
1325                 update_queue(sma);
1326 next_entry:
1327                 sem_unlock(sma);
1328         }
1329         kfree(undo_list);
1330 }
1331
1332 #ifdef CONFIG_PROC_FS
1333 static int sysvipc_sem_proc_show(struct seq_file *s, void *it)
1334 {
1335         struct sem_array *sma = it;
1336
1337         return seq_printf(s,
1338                           "%10d %10d  %4o %10lu %5u %5u %5u %5u %10lu %10lu\n",
1339                           sma->sem_perm.key,
1340                           sma->sem_id,
1341                           sma->sem_perm.mode,
1342                           sma->sem_nsems,
1343                           sma->sem_perm.uid,
1344                           sma->sem_perm.gid,
1345                           sma->sem_perm.cuid,
1346                           sma->sem_perm.cgid,
1347                           sma->sem_otime,
1348                           sma->sem_ctime);
1349 }
1350 #endif