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