Linux kernel & device driver programming

Cross-Referenced Linux and Device Driver Code

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