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