3 * Copyright (C) 1992 Krishna Balasubramanian
4 * Copyright (C) 1995 Eric Schenk, Bruno Haible
6 * /proc/sysvipc/sem support (c) 1999 Dragos Acostachioaie <dragos@iname.com>
8 * SMP-threaded, sysctl's added
9 * (c) 1999 Manfred Spraul <manfred@colorfullife.com>
10 * Enforced range limit on SEM_UNDO
11 * (c) 2001 Red Hat Inc
13 * (c) 2003 Manfred Spraul <manfred@colorfullife.com>
14 * Further wakeup optimizations, documentation
15 * (c) 2010 Manfred Spraul <manfred@colorfullife.com>
17 * support for audit of ipc object properties and permission changes
18 * Dustin Kirkland <dustin.kirkland@us.ibm.com>
22 * Pavel Emelianov <xemul@openvz.org>
24 * Implementation notes: (May 2010)
25 * This file implements System V semaphores.
27 * User space visible behavior:
28 * - FIFO ordering for semop() operations (just FIFO, not starvation
30 * - multiple semaphore operations that alter the same semaphore in
31 * one semop() are handled.
32 * - sem_ctime (time of last semctl()) is updated in the IPC_SET, SETVAL and
34 * - two Linux specific semctl() commands: SEM_STAT, SEM_INFO.
35 * - undo adjustments at process exit are limited to 0..SEMVMX.
36 * - namespace are supported.
37 * - SEMMSL, SEMMNS, SEMOPM and SEMMNI can be configured at runtine by writing
38 * to /proc/sys/kernel/sem.
39 * - statistics about the usage are reported in /proc/sysvipc/sem.
43 * - all global variables are read-mostly.
44 * - semop() calls and semctl(RMID) are synchronized by RCU.
45 * - most operations do write operations (actually: spin_lock calls) to
46 * the per-semaphore array structure.
47 * Thus: Perfect SMP scaling between independent semaphore arrays.
48 * If multiple semaphores in one array are used, then cache line
49 * trashing on the semaphore array spinlock will limit the scaling.
50 * - semncnt and semzcnt are calculated on demand in count_semcnt()
51 * - the task that performs a successful semop() scans the list of all
52 * sleeping tasks and completes any pending operations that can be fulfilled.
53 * Semaphores are actively given to waiting tasks (necessary for FIFO).
54 * (see update_queue())
55 * - To improve the scalability, the actual wake-up calls are performed after
56 * dropping all locks. (see wake_up_sem_queue_prepare(),
57 * wake_up_sem_queue_do())
58 * - All work is done by the waker, the woken up task does not have to do
59 * anything - not even acquiring a lock or dropping a refcount.
60 * - A woken up task may not even touch the semaphore array anymore, it may
61 * have been destroyed already by a semctl(RMID).
62 * - The synchronizations between wake-ups due to a timeout/signal and a
63 * wake-up due to a completed semaphore operation is achieved by using an
64 * intermediate state (IN_WAKEUP).
65 * - UNDO values are stored in an array (one per process and per
66 * semaphore array, lazily allocated). For backwards compatibility, multiple
67 * modes for the UNDO variables are supported (per process, per thread)
68 * (see copy_semundo, CLONE_SYSVSEM)
69 * - There are two lists of the pending operations: a per-array list
70 * and per-semaphore list (stored in the array). This allows to achieve FIFO
71 * ordering without always scanning all pending operations.
72 * The worst-case behavior is nevertheless O(N^2) for N wakeups.
75 #include <linux/slab.h>
76 #include <linux/spinlock.h>
77 #include <linux/init.h>
78 #include <linux/proc_fs.h>
79 #include <linux/time.h>
80 #include <linux/security.h>
81 #include <linux/syscalls.h>
82 #include <linux/audit.h>
83 #include <linux/capability.h>
84 #include <linux/seq_file.h>
85 #include <linux/rwsem.h>
86 #include <linux/nsproxy.h>
87 #include <linux/ipc_namespace.h>
89 #include <linux/uaccess.h>
92 /* One semaphore structure for each semaphore in the system. */
94 int semval; /* current value */
95 int sempid; /* pid of last operation */
96 spinlock_t lock; /* spinlock for fine-grained semtimedop */
97 struct list_head pending_alter; /* pending single-sop operations */
98 /* that alter the semaphore */
99 struct list_head pending_const; /* pending single-sop operations */
100 /* that do not alter the semaphore*/
101 time_t sem_otime; /* candidate for sem_otime */
102 } ____cacheline_aligned_in_smp;
104 /* One queue for each sleeping process in the system. */
106 struct list_head list; /* queue of pending operations */
107 struct task_struct *sleeper; /* this process */
108 struct sem_undo *undo; /* undo structure */
109 int pid; /* process id of requesting process */
110 int status; /* completion status of operation */
111 struct sembuf *sops; /* array of pending operations */
112 int nsops; /* number of operations */
113 int alter; /* does *sops alter the array? */
116 /* Each task has a list of undo requests. They are executed automatically
117 * when the process exits.
120 struct list_head list_proc; /* per-process list: *
121 * all undos from one process
123 struct rcu_head rcu; /* rcu struct for sem_undo */
124 struct sem_undo_list *ulp; /* back ptr to sem_undo_list */
125 struct list_head list_id; /* per semaphore array list:
126 * all undos for one array */
127 int semid; /* semaphore set identifier */
128 short *semadj; /* array of adjustments */
129 /* one per semaphore */
132 /* sem_undo_list controls shared access to the list of sem_undo structures
133 * that may be shared among all a CLONE_SYSVSEM task group.
135 struct sem_undo_list {
138 struct list_head list_proc;
142 #define sem_ids(ns) ((ns)->ids[IPC_SEM_IDS])
144 #define sem_checkid(sma, semid) ipc_checkid(&sma->sem_perm, semid)
146 static int newary(struct ipc_namespace *, struct ipc_params *);
147 static void freeary(struct ipc_namespace *, struct kern_ipc_perm *);
148 #ifdef CONFIG_PROC_FS
149 static int sysvipc_sem_proc_show(struct seq_file *s, void *it);
152 #define SEMMSL_FAST 256 /* 512 bytes on stack */
153 #define SEMOPM_FAST 64 /* ~ 372 bytes on stack */
158 * sem_array.complex_count,
159 * sem_array.pending{_alter,_cont},
160 * sem_array.sem_undo: global sem_lock() for read/write
161 * sem_undo.proc_next: only "current" is allowed to read/write that field.
163 * sem_array.sem_base[i].pending_{const,alter}:
164 * global or semaphore sem_lock() for read/write
167 #define sc_semmsl sem_ctls[0]
168 #define sc_semmns sem_ctls[1]
169 #define sc_semopm sem_ctls[2]
170 #define sc_semmni sem_ctls[3]
172 void sem_init_ns(struct ipc_namespace *ns)
174 ns->sc_semmsl = SEMMSL;
175 ns->sc_semmns = SEMMNS;
176 ns->sc_semopm = SEMOPM;
177 ns->sc_semmni = SEMMNI;
179 ipc_init_ids(&ns->ids[IPC_SEM_IDS]);
183 void sem_exit_ns(struct ipc_namespace *ns)
185 free_ipcs(ns, &sem_ids(ns), freeary);
186 idr_destroy(&ns->ids[IPC_SEM_IDS].ipcs_idr);
190 void __init sem_init(void)
192 sem_init_ns(&init_ipc_ns);
193 ipc_init_proc_interface("sysvipc/sem",
194 " key semid perms nsems uid gid cuid cgid otime ctime\n",
195 IPC_SEM_IDS, sysvipc_sem_proc_show);
199 * unmerge_queues - unmerge queues, if possible.
200 * @sma: semaphore array
202 * The function unmerges the wait queues if complex_count is 0.
203 * It must be called prior to dropping the global semaphore array lock.
205 static void unmerge_queues(struct sem_array *sma)
207 struct sem_queue *q, *tq;
209 /* complex operations still around? */
210 if (sma->complex_count)
213 * We will switch back to simple mode.
214 * Move all pending operation back into the per-semaphore
217 list_for_each_entry_safe(q, tq, &sma->pending_alter, list) {
219 curr = &sma->sem_base[q->sops[0].sem_num];
221 list_add_tail(&q->list, &curr->pending_alter);
223 INIT_LIST_HEAD(&sma->pending_alter);
227 * merge_queues - merge single semop queues into global queue
228 * @sma: semaphore array
230 * This function merges all per-semaphore queues into the global queue.
231 * It is necessary to achieve FIFO ordering for the pending single-sop
232 * operations when a multi-semop operation must sleep.
233 * Only the alter operations must be moved, the const operations can stay.
235 static void merge_queues(struct sem_array *sma)
238 for (i = 0; i < sma->sem_nsems; i++) {
239 struct sem *sem = sma->sem_base + i;
241 list_splice_init(&sem->pending_alter, &sma->pending_alter);
245 static void sem_rcu_free(struct rcu_head *head)
247 struct ipc_rcu *p = container_of(head, struct ipc_rcu, rcu);
248 struct sem_array *sma = ipc_rcu_to_struct(p);
250 security_sem_free(sma);
255 * Wait until all currently ongoing simple ops have completed.
256 * Caller must own sem_perm.lock.
257 * New simple ops cannot start, because simple ops first check
258 * that sem_perm.lock is free.
259 * that a) sem_perm.lock is free and b) complex_count is 0.
261 static void sem_wait_array(struct sem_array *sma)
266 if (sma->complex_count) {
267 /* The thread that increased sma->complex_count waited on
268 * all sem->lock locks. Thus we don't need to wait again.
273 for (i = 0; i < sma->sem_nsems; i++) {
274 sem = sma->sem_base + i;
275 spin_unlock_wait(&sem->lock);
280 * If the request contains only one semaphore operation, and there are
281 * no complex transactions pending, lock only the semaphore involved.
282 * Otherwise, lock the entire semaphore array, since we either have
283 * multiple semaphores in our own semops, or we need to look at
284 * semaphores from other pending complex operations.
286 static inline int sem_lock(struct sem_array *sma, struct sembuf *sops,
292 /* Complex operation - acquire a full lock */
293 ipc_lock_object(&sma->sem_perm);
295 /* And wait until all simple ops that are processed
296 * right now have dropped their locks.
303 * Only one semaphore affected - try to optimize locking.
305 * - optimized locking is possible if no complex operation
306 * is either enqueued or processed right now.
307 * - The test for enqueued complex ops is simple:
308 * sma->complex_count != 0
309 * - Testing for complex ops that are processed right now is
310 * a bit more difficult. Complex ops acquire the full lock
311 * and first wait that the running simple ops have completed.
313 * Thus: If we own a simple lock and the global lock is free
314 * and complex_count is now 0, then it will stay 0 and
315 * thus just locking sem->lock is sufficient.
317 sem = sma->sem_base + sops->sem_num;
319 if (sma->complex_count == 0) {
321 * It appears that no complex operation is around.
322 * Acquire the per-semaphore lock.
324 spin_lock(&sem->lock);
326 /* Then check that the global lock is free */
327 if (!spin_is_locked(&sma->sem_perm.lock)) {
328 /* spin_is_locked() is not a memory barrier */
331 /* Now repeat the test of complex_count:
332 * It can't change anymore until we drop sem->lock.
333 * Thus: if is now 0, then it will stay 0.
335 if (sma->complex_count == 0) {
336 /* fast path successful! */
337 return sops->sem_num;
340 spin_unlock(&sem->lock);
343 /* slow path: acquire the full lock */
344 ipc_lock_object(&sma->sem_perm);
346 if (sma->complex_count == 0) {
348 * There is no complex operation, thus we can switch
349 * back to the fast path.
351 spin_lock(&sem->lock);
352 ipc_unlock_object(&sma->sem_perm);
353 return sops->sem_num;
355 /* Not a false alarm, thus complete the sequence for a
363 static inline void sem_unlock(struct sem_array *sma, int locknum)
367 ipc_unlock_object(&sma->sem_perm);
369 struct sem *sem = sma->sem_base + locknum;
370 spin_unlock(&sem->lock);
375 * sem_lock_(check_) routines are called in the paths where the rwsem
378 * The caller holds the RCU read lock.
380 static inline struct sem_array *sem_obtain_lock(struct ipc_namespace *ns,
381 int id, struct sembuf *sops, int nsops, int *locknum)
383 struct kern_ipc_perm *ipcp;
384 struct sem_array *sma;
386 ipcp = ipc_obtain_object(&sem_ids(ns), id);
388 return ERR_CAST(ipcp);
390 sma = container_of(ipcp, struct sem_array, sem_perm);
391 *locknum = sem_lock(sma, sops, nsops);
393 /* ipc_rmid() may have already freed the ID while sem_lock
394 * was spinning: verify that the structure is still valid
396 if (ipc_valid_object(ipcp))
397 return container_of(ipcp, struct sem_array, sem_perm);
399 sem_unlock(sma, *locknum);
400 return ERR_PTR(-EINVAL);
403 static inline struct sem_array *sem_obtain_object(struct ipc_namespace *ns, int id)
405 struct kern_ipc_perm *ipcp = ipc_obtain_object(&sem_ids(ns), id);
408 return ERR_CAST(ipcp);
410 return container_of(ipcp, struct sem_array, sem_perm);
413 static inline struct sem_array *sem_obtain_object_check(struct ipc_namespace *ns,
416 struct kern_ipc_perm *ipcp = ipc_obtain_object_check(&sem_ids(ns), id);
419 return ERR_CAST(ipcp);
421 return container_of(ipcp, struct sem_array, sem_perm);
424 static inline void sem_lock_and_putref(struct sem_array *sma)
426 sem_lock(sma, NULL, -1);
427 ipc_rcu_putref(sma, ipc_rcu_free);
430 static inline void sem_rmid(struct ipc_namespace *ns, struct sem_array *s)
432 ipc_rmid(&sem_ids(ns), &s->sem_perm);
436 * Lockless wakeup algorithm:
437 * Without the check/retry algorithm a lockless wakeup is possible:
438 * - queue.status is initialized to -EINTR before blocking.
439 * - wakeup is performed by
440 * * unlinking the queue entry from the pending list
441 * * setting queue.status to IN_WAKEUP
442 * This is the notification for the blocked thread that a
443 * result value is imminent.
444 * * call wake_up_process
445 * * set queue.status to the final value.
446 * - the previously blocked thread checks queue.status:
447 * * if it's IN_WAKEUP, then it must wait until the value changes
448 * * if it's not -EINTR, then the operation was completed by
449 * update_queue. semtimedop can return queue.status without
450 * performing any operation on the sem array.
451 * * otherwise it must acquire the spinlock and check what's up.
453 * The two-stage algorithm is necessary to protect against the following
455 * - if queue.status is set after wake_up_process, then the woken up idle
456 * thread could race forward and try (and fail) to acquire sma->lock
457 * before update_queue had a chance to set queue.status
458 * - if queue.status is written before wake_up_process and if the
459 * blocked process is woken up by a signal between writing
460 * queue.status and the wake_up_process, then the woken up
461 * process could return from semtimedop and die by calling
462 * sys_exit before wake_up_process is called. Then wake_up_process
463 * will oops, because the task structure is already invalid.
464 * (yes, this happened on s390 with sysv msg).
470 * newary - Create a new semaphore set
472 * @params: ptr to the structure that contains key, semflg and nsems
474 * Called with sem_ids.rwsem held (as a writer)
476 static int newary(struct ipc_namespace *ns, struct ipc_params *params)
480 struct sem_array *sma;
482 key_t key = params->key;
483 int nsems = params->u.nsems;
484 int semflg = params->flg;
489 if (ns->used_sems + nsems > ns->sc_semmns)
492 size = sizeof(*sma) + nsems * sizeof(struct sem);
493 sma = ipc_rcu_alloc(size);
497 memset(sma, 0, size);
499 sma->sem_perm.mode = (semflg & S_IRWXUGO);
500 sma->sem_perm.key = key;
502 sma->sem_perm.security = NULL;
503 retval = security_sem_alloc(sma);
505 ipc_rcu_putref(sma, ipc_rcu_free);
509 id = ipc_addid(&sem_ids(ns), &sma->sem_perm, ns->sc_semmni);
511 ipc_rcu_putref(sma, sem_rcu_free);
514 ns->used_sems += nsems;
516 sma->sem_base = (struct sem *) &sma[1];
518 for (i = 0; i < nsems; i++) {
519 INIT_LIST_HEAD(&sma->sem_base[i].pending_alter);
520 INIT_LIST_HEAD(&sma->sem_base[i].pending_const);
521 spin_lock_init(&sma->sem_base[i].lock);
524 sma->complex_count = 0;
525 INIT_LIST_HEAD(&sma->pending_alter);
526 INIT_LIST_HEAD(&sma->pending_const);
527 INIT_LIST_HEAD(&sma->list_id);
528 sma->sem_nsems = nsems;
529 sma->sem_ctime = get_seconds();
533 return sma->sem_perm.id;
538 * Called with sem_ids.rwsem and ipcp locked.
540 static inline int sem_security(struct kern_ipc_perm *ipcp, int semflg)
542 struct sem_array *sma;
544 sma = container_of(ipcp, struct sem_array, sem_perm);
545 return security_sem_associate(sma, semflg);
549 * Called with sem_ids.rwsem and ipcp locked.
551 static inline int sem_more_checks(struct kern_ipc_perm *ipcp,
552 struct ipc_params *params)
554 struct sem_array *sma;
556 sma = container_of(ipcp, struct sem_array, sem_perm);
557 if (params->u.nsems > sma->sem_nsems)
563 SYSCALL_DEFINE3(semget, key_t, key, int, nsems, int, semflg)
565 struct ipc_namespace *ns;
566 static const struct ipc_ops sem_ops = {
568 .associate = sem_security,
569 .more_checks = sem_more_checks,
571 struct ipc_params sem_params;
573 ns = current->nsproxy->ipc_ns;
575 if (nsems < 0 || nsems > ns->sc_semmsl)
578 sem_params.key = key;
579 sem_params.flg = semflg;
580 sem_params.u.nsems = nsems;
582 return ipcget(ns, &sem_ids(ns), &sem_ops, &sem_params);
586 * perform_atomic_semop - Perform (if possible) a semaphore operation
587 * @sma: semaphore array
588 * @q: struct sem_queue that describes the operation
590 * Returns 0 if the operation was possible.
591 * Returns 1 if the operation is impossible, the caller must sleep.
592 * Negative values are error codes.
594 static int perform_atomic_semop(struct sem_array *sma, struct sem_queue *q)
596 int result, sem_op, nsops, pid;
606 for (sop = sops; sop < sops + nsops; sop++) {
607 curr = sma->sem_base + sop->sem_num;
608 sem_op = sop->sem_op;
609 result = curr->semval;
611 if (!sem_op && result)
620 if (sop->sem_flg & SEM_UNDO) {
621 int undo = un->semadj[sop->sem_num] - sem_op;
622 /* Exceeding the undo range is an error. */
623 if (undo < (-SEMAEM - 1) || undo > SEMAEM)
625 un->semadj[sop->sem_num] = undo;
628 curr->semval = result;
633 while (sop >= sops) {
634 sma->sem_base[sop->sem_num].sempid = pid;
645 if (sop->sem_flg & IPC_NOWAIT)
652 while (sop >= sops) {
653 sem_op = sop->sem_op;
654 sma->sem_base[sop->sem_num].semval -= sem_op;
655 if (sop->sem_flg & SEM_UNDO)
656 un->semadj[sop->sem_num] += sem_op;
663 /** wake_up_sem_queue_prepare(q, error): Prepare wake-up
664 * @q: queue entry that must be signaled
665 * @error: Error value for the signal
667 * Prepare the wake-up of the queue entry q.
669 static void wake_up_sem_queue_prepare(struct list_head *pt,
670 struct sem_queue *q, int error)
672 if (list_empty(pt)) {
674 * Hold preempt off so that we don't get preempted and have the
675 * wakee busy-wait until we're scheduled back on.
679 q->status = IN_WAKEUP;
682 list_add_tail(&q->list, pt);
686 * wake_up_sem_queue_do - do the actual wake-up
687 * @pt: list of tasks to be woken up
689 * Do the actual wake-up.
690 * The function is called without any locks held, thus the semaphore array
691 * could be destroyed already and the tasks can disappear as soon as the
692 * status is set to the actual return code.
694 static void wake_up_sem_queue_do(struct list_head *pt)
696 struct sem_queue *q, *t;
699 did_something = !list_empty(pt);
700 list_for_each_entry_safe(q, t, pt, list) {
701 wake_up_process(q->sleeper);
702 /* q can disappear immediately after writing q->status. */
710 static void unlink_queue(struct sem_array *sma, struct sem_queue *q)
714 sma->complex_count--;
717 /** check_restart(sma, q)
718 * @sma: semaphore array
719 * @q: the operation that just completed
721 * update_queue is O(N^2) when it restarts scanning the whole queue of
722 * waiting operations. Therefore this function checks if the restart is
723 * really necessary. It is called after a previously waiting operation
724 * modified the array.
725 * Note that wait-for-zero operations are handled without restart.
727 static int check_restart(struct sem_array *sma, struct sem_queue *q)
729 /* pending complex alter operations are too difficult to analyse */
730 if (!list_empty(&sma->pending_alter))
733 /* we were a sleeping complex operation. Too difficult */
737 /* It is impossible that someone waits for the new value:
738 * - complex operations always restart.
739 * - wait-for-zero are handled seperately.
740 * - q is a previously sleeping simple operation that
741 * altered the array. It must be a decrement, because
742 * simple increments never sleep.
743 * - If there are older (higher priority) decrements
744 * in the queue, then they have observed the original
745 * semval value and couldn't proceed. The operation
746 * decremented to value - thus they won't proceed either.
752 * wake_const_ops - wake up non-alter tasks
753 * @sma: semaphore array.
754 * @semnum: semaphore that was modified.
755 * @pt: list head for the tasks that must be woken up.
757 * wake_const_ops must be called after a semaphore in a semaphore array
758 * was set to 0. If complex const operations are pending, wake_const_ops must
759 * be called with semnum = -1, as well as with the number of each modified
761 * The tasks that must be woken up are added to @pt. The return code
762 * is stored in q->pid.
763 * The function returns 1 if at least one operation was completed successfully.
765 static int wake_const_ops(struct sem_array *sma, int semnum,
766 struct list_head *pt)
769 struct list_head *walk;
770 struct list_head *pending_list;
771 int semop_completed = 0;
774 pending_list = &sma->pending_const;
776 pending_list = &sma->sem_base[semnum].pending_const;
778 walk = pending_list->next;
779 while (walk != pending_list) {
782 q = container_of(walk, struct sem_queue, list);
785 error = perform_atomic_semop(sma, q);
788 /* operation completed, remove from queue & wakeup */
790 unlink_queue(sma, q);
792 wake_up_sem_queue_prepare(pt, q, error);
797 return semop_completed;
801 * do_smart_wakeup_zero - wakeup all wait for zero tasks
802 * @sma: semaphore array
803 * @sops: operations that were performed
804 * @nsops: number of operations
805 * @pt: list head of the tasks that must be woken up.
807 * Checks all required queue for wait-for-zero operations, based
808 * on the actual changes that were performed on the semaphore array.
809 * The function returns 1 if at least one operation was completed successfully.
811 static int do_smart_wakeup_zero(struct sem_array *sma, struct sembuf *sops,
812 int nsops, struct list_head *pt)
815 int semop_completed = 0;
818 /* first: the per-semaphore queues, if known */
820 for (i = 0; i < nsops; i++) {
821 int num = sops[i].sem_num;
823 if (sma->sem_base[num].semval == 0) {
825 semop_completed |= wake_const_ops(sma, num, pt);
830 * No sops means modified semaphores not known.
831 * Assume all were changed.
833 for (i = 0; i < sma->sem_nsems; i++) {
834 if (sma->sem_base[i].semval == 0) {
836 semop_completed |= wake_const_ops(sma, i, pt);
841 * If one of the modified semaphores got 0,
842 * then check the global queue, too.
845 semop_completed |= wake_const_ops(sma, -1, pt);
847 return semop_completed;
852 * update_queue - look for tasks that can be completed.
853 * @sma: semaphore array.
854 * @semnum: semaphore that was modified.
855 * @pt: list head for the tasks that must be woken up.
857 * update_queue must be called after a semaphore in a semaphore array
858 * was modified. If multiple semaphores were modified, update_queue must
859 * be called with semnum = -1, as well as with the number of each modified
861 * The tasks that must be woken up are added to @pt. The return code
862 * is stored in q->pid.
863 * The function internally checks if const operations can now succeed.
865 * The function return 1 if at least one semop was completed successfully.
867 static int update_queue(struct sem_array *sma, int semnum, struct list_head *pt)
870 struct list_head *walk;
871 struct list_head *pending_list;
872 int semop_completed = 0;
875 pending_list = &sma->pending_alter;
877 pending_list = &sma->sem_base[semnum].pending_alter;
880 walk = pending_list->next;
881 while (walk != pending_list) {
884 q = container_of(walk, struct sem_queue, list);
887 /* If we are scanning the single sop, per-semaphore list of
888 * one semaphore and that semaphore is 0, then it is not
889 * necessary to scan further: simple increments
890 * that affect only one entry succeed immediately and cannot
891 * be in the per semaphore pending queue, and decrements
892 * cannot be successful if the value is already 0.
894 if (semnum != -1 && sma->sem_base[semnum].semval == 0)
897 error = perform_atomic_semop(sma, q);
899 /* Does q->sleeper still need to sleep? */
903 unlink_queue(sma, q);
909 do_smart_wakeup_zero(sma, q->sops, q->nsops, pt);
910 restart = check_restart(sma, q);
913 wake_up_sem_queue_prepare(pt, q, error);
917 return semop_completed;
921 * set_semotime - set sem_otime
922 * @sma: semaphore array
923 * @sops: operations that modified the array, may be NULL
925 * sem_otime is replicated to avoid cache line trashing.
926 * This function sets one instance to the current time.
928 static void set_semotime(struct sem_array *sma, struct sembuf *sops)
931 sma->sem_base[0].sem_otime = get_seconds();
933 sma->sem_base[sops[0].sem_num].sem_otime =
939 * do_smart_update - optimized update_queue
940 * @sma: semaphore array
941 * @sops: operations that were performed
942 * @nsops: number of operations
943 * @otime: force setting otime
944 * @pt: list head of the tasks that must be woken up.
946 * do_smart_update() does the required calls to update_queue and wakeup_zero,
947 * based on the actual changes that were performed on the semaphore array.
948 * Note that the function does not do the actual wake-up: the caller is
949 * responsible for calling wake_up_sem_queue_do(@pt).
950 * It is safe to perform this call after dropping all locks.
952 static void do_smart_update(struct sem_array *sma, struct sembuf *sops, int nsops,
953 int otime, struct list_head *pt)
957 otime |= do_smart_wakeup_zero(sma, sops, nsops, pt);
959 if (!list_empty(&sma->pending_alter)) {
960 /* semaphore array uses the global queue - just process it. */
961 otime |= update_queue(sma, -1, pt);
965 * No sops, thus the modified semaphores are not
968 for (i = 0; i < sma->sem_nsems; i++)
969 otime |= update_queue(sma, i, pt);
972 * Check the semaphores that were increased:
973 * - No complex ops, thus all sleeping ops are
975 * - if we decreased the value, then any sleeping
976 * semaphore ops wont be able to run: If the
977 * previous value was too small, then the new
978 * value will be too small, too.
980 for (i = 0; i < nsops; i++) {
981 if (sops[i].sem_op > 0) {
982 otime |= update_queue(sma,
983 sops[i].sem_num, pt);
989 set_semotime(sma, sops);
993 * check_qop: Test how often a queued operation sleeps on the semaphore semnum
995 static int check_qop(struct sem_array *sma, int semnum, struct sem_queue *q,
998 struct sembuf *sops = q->sops;
999 int nsops = q->nsops;
1004 for (i = 0; i < nsops; i++) {
1005 if (sops[i].sem_num != semnum)
1007 if (sops[i].sem_flg & IPC_NOWAIT)
1009 if (count_zero && sops[i].sem_op == 0)
1011 if (!count_zero && sops[i].sem_op < 0)
1017 /* The following counts are associated to each semaphore:
1018 * semncnt number of tasks waiting on semval being nonzero
1019 * semzcnt number of tasks waiting on semval being zero
1020 * This model assumes that a task waits on exactly one semaphore.
1021 * Since semaphore operations are to be performed atomically, tasks actually
1022 * wait on a whole sequence of semaphores simultaneously.
1023 * The counts we return here are a rough approximation, but still
1024 * warrant that semncnt+semzcnt>0 if the task is on the pending queue.
1026 static int count_semcnt(struct sem_array *sma, ushort semnum,
1029 struct list_head *l;
1030 struct sem_queue *q;
1034 /* First: check the simple operations. They are easy to evaluate */
1036 l = &sma->sem_base[semnum].pending_const;
1038 l = &sma->sem_base[semnum].pending_alter;
1040 list_for_each_entry(q, l, list) {
1041 /* all task on a per-semaphore list sleep on exactly
1047 /* Then: check the complex operations. */
1048 list_for_each_entry(q, &sma->pending_alter, list) {
1049 semcnt += check_qop(sma, semnum, q, count_zero);
1052 list_for_each_entry(q, &sma->pending_const, list) {
1053 semcnt += check_qop(sma, semnum, q, count_zero);
1059 /* Free a semaphore set. freeary() is called with sem_ids.rwsem locked
1060 * as a writer and the spinlock for this semaphore set hold. sem_ids.rwsem
1061 * remains locked on exit.
1063 static void freeary(struct ipc_namespace *ns, struct kern_ipc_perm *ipcp)
1065 struct sem_undo *un, *tu;
1066 struct sem_queue *q, *tq;
1067 struct sem_array *sma = container_of(ipcp, struct sem_array, sem_perm);
1068 struct list_head tasks;
1071 /* Free the existing undo structures for this semaphore set. */
1072 ipc_assert_locked_object(&sma->sem_perm);
1073 list_for_each_entry_safe(un, tu, &sma->list_id, list_id) {
1074 list_del(&un->list_id);
1075 spin_lock(&un->ulp->lock);
1077 list_del_rcu(&un->list_proc);
1078 spin_unlock(&un->ulp->lock);
1082 /* Wake up all pending processes and let them fail with EIDRM. */
1083 INIT_LIST_HEAD(&tasks);
1084 list_for_each_entry_safe(q, tq, &sma->pending_const, list) {
1085 unlink_queue(sma, q);
1086 wake_up_sem_queue_prepare(&tasks, q, -EIDRM);
1089 list_for_each_entry_safe(q, tq, &sma->pending_alter, list) {
1090 unlink_queue(sma, q);
1091 wake_up_sem_queue_prepare(&tasks, q, -EIDRM);
1093 for (i = 0; i < sma->sem_nsems; i++) {
1094 struct sem *sem = sma->sem_base + i;
1095 list_for_each_entry_safe(q, tq, &sem->pending_const, list) {
1096 unlink_queue(sma, q);
1097 wake_up_sem_queue_prepare(&tasks, q, -EIDRM);
1099 list_for_each_entry_safe(q, tq, &sem->pending_alter, list) {
1100 unlink_queue(sma, q);
1101 wake_up_sem_queue_prepare(&tasks, q, -EIDRM);
1105 /* Remove the semaphore set from the IDR */
1107 sem_unlock(sma, -1);
1110 wake_up_sem_queue_do(&tasks);
1111 ns->used_sems -= sma->sem_nsems;
1112 ipc_rcu_putref(sma, sem_rcu_free);
1115 static unsigned long copy_semid_to_user(void __user *buf, struct semid64_ds *in, int version)
1119 return copy_to_user(buf, in, sizeof(*in));
1122 struct semid_ds out;
1124 memset(&out, 0, sizeof(out));
1126 ipc64_perm_to_ipc_perm(&in->sem_perm, &out.sem_perm);
1128 out.sem_otime = in->sem_otime;
1129 out.sem_ctime = in->sem_ctime;
1130 out.sem_nsems = in->sem_nsems;
1132 return copy_to_user(buf, &out, sizeof(out));
1139 static time_t get_semotime(struct sem_array *sma)
1144 res = sma->sem_base[0].sem_otime;
1145 for (i = 1; i < sma->sem_nsems; i++) {
1146 time_t to = sma->sem_base[i].sem_otime;
1154 static int semctl_nolock(struct ipc_namespace *ns, int semid,
1155 int cmd, int version, void __user *p)
1158 struct sem_array *sma;
1164 struct seminfo seminfo;
1167 err = security_sem_semctl(NULL, cmd);
1171 memset(&seminfo, 0, sizeof(seminfo));
1172 seminfo.semmni = ns->sc_semmni;
1173 seminfo.semmns = ns->sc_semmns;
1174 seminfo.semmsl = ns->sc_semmsl;
1175 seminfo.semopm = ns->sc_semopm;
1176 seminfo.semvmx = SEMVMX;
1177 seminfo.semmnu = SEMMNU;
1178 seminfo.semmap = SEMMAP;
1179 seminfo.semume = SEMUME;
1180 down_read(&sem_ids(ns).rwsem);
1181 if (cmd == SEM_INFO) {
1182 seminfo.semusz = sem_ids(ns).in_use;
1183 seminfo.semaem = ns->used_sems;
1185 seminfo.semusz = SEMUSZ;
1186 seminfo.semaem = SEMAEM;
1188 max_id = ipc_get_maxid(&sem_ids(ns));
1189 up_read(&sem_ids(ns).rwsem);
1190 if (copy_to_user(p, &seminfo, sizeof(struct seminfo)))
1192 return (max_id < 0) ? 0 : max_id;
1197 struct semid64_ds tbuf;
1200 memset(&tbuf, 0, sizeof(tbuf));
1203 if (cmd == SEM_STAT) {
1204 sma = sem_obtain_object(ns, semid);
1209 id = sma->sem_perm.id;
1211 sma = sem_obtain_object_check(ns, semid);
1219 if (ipcperms(ns, &sma->sem_perm, S_IRUGO))
1222 err = security_sem_semctl(sma, cmd);
1226 kernel_to_ipc64_perm(&sma->sem_perm, &tbuf.sem_perm);
1227 tbuf.sem_otime = get_semotime(sma);
1228 tbuf.sem_ctime = sma->sem_ctime;
1229 tbuf.sem_nsems = sma->sem_nsems;
1231 if (copy_semid_to_user(p, &tbuf, version))
1243 static int semctl_setval(struct ipc_namespace *ns, int semid, int semnum,
1246 struct sem_undo *un;
1247 struct sem_array *sma;
1250 struct list_head tasks;
1252 #if defined(CONFIG_64BIT) && defined(__BIG_ENDIAN)
1253 /* big-endian 64bit */
1256 /* 32bit or little-endian 64bit */
1260 if (val > SEMVMX || val < 0)
1263 INIT_LIST_HEAD(&tasks);
1266 sma = sem_obtain_object_check(ns, semid);
1269 return PTR_ERR(sma);
1272 if (semnum < 0 || semnum >= sma->sem_nsems) {
1278 if (ipcperms(ns, &sma->sem_perm, S_IWUGO)) {
1283 err = security_sem_semctl(sma, SETVAL);
1289 sem_lock(sma, NULL, -1);
1291 if (!ipc_valid_object(&sma->sem_perm)) {
1292 sem_unlock(sma, -1);
1297 curr = &sma->sem_base[semnum];
1299 ipc_assert_locked_object(&sma->sem_perm);
1300 list_for_each_entry(un, &sma->list_id, list_id)
1301 un->semadj[semnum] = 0;
1304 curr->sempid = task_tgid_vnr(current);
1305 sma->sem_ctime = get_seconds();
1306 /* maybe some queued-up processes were waiting for this */
1307 do_smart_update(sma, NULL, 0, 0, &tasks);
1308 sem_unlock(sma, -1);
1310 wake_up_sem_queue_do(&tasks);
1314 static int semctl_main(struct ipc_namespace *ns, int semid, int semnum,
1315 int cmd, void __user *p)
1317 struct sem_array *sma;
1320 ushort fast_sem_io[SEMMSL_FAST];
1321 ushort *sem_io = fast_sem_io;
1322 struct list_head tasks;
1324 INIT_LIST_HEAD(&tasks);
1327 sma = sem_obtain_object_check(ns, semid);
1330 return PTR_ERR(sma);
1333 nsems = sma->sem_nsems;
1336 if (ipcperms(ns, &sma->sem_perm, cmd == SETALL ? S_IWUGO : S_IRUGO))
1337 goto out_rcu_wakeup;
1339 err = security_sem_semctl(sma, cmd);
1341 goto out_rcu_wakeup;
1347 ushort __user *array = p;
1350 sem_lock(sma, NULL, -1);
1351 if (!ipc_valid_object(&sma->sem_perm)) {
1355 if (nsems > SEMMSL_FAST) {
1356 if (!ipc_rcu_getref(sma)) {
1360 sem_unlock(sma, -1);
1362 sem_io = ipc_alloc(sizeof(ushort)*nsems);
1363 if (sem_io == NULL) {
1364 ipc_rcu_putref(sma, ipc_rcu_free);
1369 sem_lock_and_putref(sma);
1370 if (!ipc_valid_object(&sma->sem_perm)) {
1375 for (i = 0; i < sma->sem_nsems; i++)
1376 sem_io[i] = sma->sem_base[i].semval;
1377 sem_unlock(sma, -1);
1380 if (copy_to_user(array, sem_io, nsems*sizeof(ushort)))
1387 struct sem_undo *un;
1389 if (!ipc_rcu_getref(sma)) {
1391 goto out_rcu_wakeup;
1395 if (nsems > SEMMSL_FAST) {
1396 sem_io = ipc_alloc(sizeof(ushort)*nsems);
1397 if (sem_io == NULL) {
1398 ipc_rcu_putref(sma, ipc_rcu_free);
1403 if (copy_from_user(sem_io, p, nsems*sizeof(ushort))) {
1404 ipc_rcu_putref(sma, ipc_rcu_free);
1409 for (i = 0; i < nsems; i++) {
1410 if (sem_io[i] > SEMVMX) {
1411 ipc_rcu_putref(sma, ipc_rcu_free);
1417 sem_lock_and_putref(sma);
1418 if (!ipc_valid_object(&sma->sem_perm)) {
1423 for (i = 0; i < nsems; i++)
1424 sma->sem_base[i].semval = sem_io[i];
1426 ipc_assert_locked_object(&sma->sem_perm);
1427 list_for_each_entry(un, &sma->list_id, list_id) {
1428 for (i = 0; i < nsems; i++)
1431 sma->sem_ctime = get_seconds();
1432 /* maybe some queued-up processes were waiting for this */
1433 do_smart_update(sma, NULL, 0, 0, &tasks);
1437 /* GETVAL, GETPID, GETNCTN, GETZCNT: fall-through */
1440 if (semnum < 0 || semnum >= nsems)
1441 goto out_rcu_wakeup;
1443 sem_lock(sma, NULL, -1);
1444 if (!ipc_valid_object(&sma->sem_perm)) {
1448 curr = &sma->sem_base[semnum];
1458 err = count_semcnt(sma, semnum, 0);
1461 err = count_semcnt(sma, semnum, 1);
1466 sem_unlock(sma, -1);
1469 wake_up_sem_queue_do(&tasks);
1471 if (sem_io != fast_sem_io)
1472 ipc_free(sem_io, sizeof(ushort)*nsems);
1476 static inline unsigned long
1477 copy_semid_from_user(struct semid64_ds *out, void __user *buf, int version)
1481 if (copy_from_user(out, buf, sizeof(*out)))
1486 struct semid_ds tbuf_old;
1488 if (copy_from_user(&tbuf_old, buf, sizeof(tbuf_old)))
1491 out->sem_perm.uid = tbuf_old.sem_perm.uid;
1492 out->sem_perm.gid = tbuf_old.sem_perm.gid;
1493 out->sem_perm.mode = tbuf_old.sem_perm.mode;
1503 * This function handles some semctl commands which require the rwsem
1504 * to be held in write mode.
1505 * NOTE: no locks must be held, the rwsem is taken inside this function.
1507 static int semctl_down(struct ipc_namespace *ns, int semid,
1508 int cmd, int version, void __user *p)
1510 struct sem_array *sma;
1512 struct semid64_ds semid64;
1513 struct kern_ipc_perm *ipcp;
1515 if (cmd == IPC_SET) {
1516 if (copy_semid_from_user(&semid64, p, version))
1520 down_write(&sem_ids(ns).rwsem);
1523 ipcp = ipcctl_pre_down_nolock(ns, &sem_ids(ns), semid, cmd,
1524 &semid64.sem_perm, 0);
1526 err = PTR_ERR(ipcp);
1530 sma = container_of(ipcp, struct sem_array, sem_perm);
1532 err = security_sem_semctl(sma, cmd);
1538 sem_lock(sma, NULL, -1);
1539 /* freeary unlocks the ipc object and rcu */
1543 sem_lock(sma, NULL, -1);
1544 err = ipc_update_perm(&semid64.sem_perm, ipcp);
1547 sma->sem_ctime = get_seconds();
1555 sem_unlock(sma, -1);
1559 up_write(&sem_ids(ns).rwsem);
1563 SYSCALL_DEFINE4(semctl, int, semid, int, semnum, int, cmd, unsigned long, arg)
1566 struct ipc_namespace *ns;
1567 void __user *p = (void __user *)arg;
1572 version = ipc_parse_version(&cmd);
1573 ns = current->nsproxy->ipc_ns;
1580 return semctl_nolock(ns, semid, cmd, version, p);
1587 return semctl_main(ns, semid, semnum, cmd, p);
1589 return semctl_setval(ns, semid, semnum, arg);
1592 return semctl_down(ns, semid, cmd, version, p);
1598 /* If the task doesn't already have a undo_list, then allocate one
1599 * here. We guarantee there is only one thread using this undo list,
1600 * and current is THE ONE
1602 * If this allocation and assignment succeeds, but later
1603 * portions of this code fail, there is no need to free the sem_undo_list.
1604 * Just let it stay associated with the task, and it'll be freed later
1607 * This can block, so callers must hold no locks.
1609 static inline int get_undo_list(struct sem_undo_list **undo_listp)
1611 struct sem_undo_list *undo_list;
1613 undo_list = current->sysvsem.undo_list;
1615 undo_list = kzalloc(sizeof(*undo_list), GFP_KERNEL);
1616 if (undo_list == NULL)
1618 spin_lock_init(&undo_list->lock);
1619 atomic_set(&undo_list->refcnt, 1);
1620 INIT_LIST_HEAD(&undo_list->list_proc);
1622 current->sysvsem.undo_list = undo_list;
1624 *undo_listp = undo_list;
1628 static struct sem_undo *__lookup_undo(struct sem_undo_list *ulp, int semid)
1630 struct sem_undo *un;
1632 list_for_each_entry_rcu(un, &ulp->list_proc, list_proc) {
1633 if (un->semid == semid)
1639 static struct sem_undo *lookup_undo(struct sem_undo_list *ulp, int semid)
1641 struct sem_undo *un;
1643 assert_spin_locked(&ulp->lock);
1645 un = __lookup_undo(ulp, semid);
1647 list_del_rcu(&un->list_proc);
1648 list_add_rcu(&un->list_proc, &ulp->list_proc);
1654 * find_alloc_undo - lookup (and if not present create) undo array
1656 * @semid: semaphore array id
1658 * The function looks up (and if not present creates) the undo structure.
1659 * The size of the undo structure depends on the size of the semaphore
1660 * array, thus the alloc path is not that straightforward.
1661 * Lifetime-rules: sem_undo is rcu-protected, on success, the function
1662 * performs a rcu_read_lock().
1664 static struct sem_undo *find_alloc_undo(struct ipc_namespace *ns, int semid)
1666 struct sem_array *sma;
1667 struct sem_undo_list *ulp;
1668 struct sem_undo *un, *new;
1671 error = get_undo_list(&ulp);
1673 return ERR_PTR(error);
1676 spin_lock(&ulp->lock);
1677 un = lookup_undo(ulp, semid);
1678 spin_unlock(&ulp->lock);
1679 if (likely(un != NULL))
1682 /* no undo structure around - allocate one. */
1683 /* step 1: figure out the size of the semaphore array */
1684 sma = sem_obtain_object_check(ns, semid);
1687 return ERR_CAST(sma);
1690 nsems = sma->sem_nsems;
1691 if (!ipc_rcu_getref(sma)) {
1693 un = ERR_PTR(-EIDRM);
1698 /* step 2: allocate new undo structure */
1699 new = kzalloc(sizeof(struct sem_undo) + sizeof(short)*nsems, GFP_KERNEL);
1701 ipc_rcu_putref(sma, ipc_rcu_free);
1702 return ERR_PTR(-ENOMEM);
1705 /* step 3: Acquire the lock on semaphore array */
1707 sem_lock_and_putref(sma);
1708 if (!ipc_valid_object(&sma->sem_perm)) {
1709 sem_unlock(sma, -1);
1712 un = ERR_PTR(-EIDRM);
1715 spin_lock(&ulp->lock);
1718 * step 4: check for races: did someone else allocate the undo struct?
1720 un = lookup_undo(ulp, semid);
1725 /* step 5: initialize & link new undo structure */
1726 new->semadj = (short *) &new[1];
1729 assert_spin_locked(&ulp->lock);
1730 list_add_rcu(&new->list_proc, &ulp->list_proc);
1731 ipc_assert_locked_object(&sma->sem_perm);
1732 list_add(&new->list_id, &sma->list_id);
1736 spin_unlock(&ulp->lock);
1737 sem_unlock(sma, -1);
1744 * get_queue_result - retrieve the result code from sem_queue
1745 * @q: Pointer to queue structure
1747 * Retrieve the return code from the pending queue. If IN_WAKEUP is found in
1748 * q->status, then we must loop until the value is replaced with the final
1749 * value: This may happen if a task is woken up by an unrelated event (e.g.
1750 * signal) and in parallel the task is woken up by another task because it got
1751 * the requested semaphores.
1753 * The function can be called with or without holding the semaphore spinlock.
1755 static int get_queue_result(struct sem_queue *q)
1760 while (unlikely(error == IN_WAKEUP)) {
1768 SYSCALL_DEFINE4(semtimedop, int, semid, struct sembuf __user *, tsops,
1769 unsigned, nsops, const struct timespec __user *, timeout)
1771 int error = -EINVAL;
1772 struct sem_array *sma;
1773 struct sembuf fast_sops[SEMOPM_FAST];
1774 struct sembuf *sops = fast_sops, *sop;
1775 struct sem_undo *un;
1776 int undos = 0, alter = 0, max, locknum;
1777 struct sem_queue queue;
1778 unsigned long jiffies_left = 0;
1779 struct ipc_namespace *ns;
1780 struct list_head tasks;
1782 ns = current->nsproxy->ipc_ns;
1784 if (nsops < 1 || semid < 0)
1786 if (nsops > ns->sc_semopm)
1788 if (nsops > SEMOPM_FAST) {
1789 sops = kmalloc(sizeof(*sops)*nsops, GFP_KERNEL);
1793 if (copy_from_user(sops, tsops, nsops * sizeof(*tsops))) {
1798 struct timespec _timeout;
1799 if (copy_from_user(&_timeout, timeout, sizeof(*timeout))) {
1803 if (_timeout.tv_sec < 0 || _timeout.tv_nsec < 0 ||
1804 _timeout.tv_nsec >= 1000000000L) {
1808 jiffies_left = timespec_to_jiffies(&_timeout);
1811 for (sop = sops; sop < sops + nsops; sop++) {
1812 if (sop->sem_num >= max)
1814 if (sop->sem_flg & SEM_UNDO)
1816 if (sop->sem_op != 0)
1820 INIT_LIST_HEAD(&tasks);
1823 /* On success, find_alloc_undo takes the rcu_read_lock */
1824 un = find_alloc_undo(ns, semid);
1826 error = PTR_ERR(un);
1834 sma = sem_obtain_object_check(ns, semid);
1837 error = PTR_ERR(sma);
1842 if (max >= sma->sem_nsems)
1843 goto out_rcu_wakeup;
1846 if (ipcperms(ns, &sma->sem_perm, alter ? S_IWUGO : S_IRUGO))
1847 goto out_rcu_wakeup;
1849 error = security_sem_semop(sma, sops, nsops, alter);
1851 goto out_rcu_wakeup;
1854 locknum = sem_lock(sma, sops, nsops);
1856 * We eventually might perform the following check in a lockless
1857 * fashion, considering ipc_valid_object() locking constraints.
1858 * If nsops == 1 and there is no contention for sem_perm.lock, then
1859 * only a per-semaphore lock is held and it's OK to proceed with the
1860 * check below. More details on the fine grained locking scheme
1861 * entangled here and why it's RMID race safe on comments at sem_lock()
1863 if (!ipc_valid_object(&sma->sem_perm))
1864 goto out_unlock_free;
1866 * semid identifiers are not unique - find_alloc_undo may have
1867 * allocated an undo structure, it was invalidated by an RMID
1868 * and now a new array with received the same id. Check and fail.
1869 * This case can be detected checking un->semid. The existence of
1870 * "un" itself is guaranteed by rcu.
1872 if (un && un->semid == -1)
1873 goto out_unlock_free;
1876 queue.nsops = nsops;
1878 queue.pid = task_tgid_vnr(current);
1879 queue.alter = alter;
1881 error = perform_atomic_semop(sma, &queue);
1883 /* If the operation was successful, then do
1884 * the required updates.
1887 do_smart_update(sma, sops, nsops, 1, &tasks);
1889 set_semotime(sma, sops);
1892 goto out_unlock_free;
1894 /* We need to sleep on this operation, so we put the current
1895 * task into the pending queue and go to sleep.
1900 curr = &sma->sem_base[sops->sem_num];
1903 if (sma->complex_count) {
1904 list_add_tail(&queue.list,
1905 &sma->pending_alter);
1908 list_add_tail(&queue.list,
1909 &curr->pending_alter);
1912 list_add_tail(&queue.list, &curr->pending_const);
1915 if (!sma->complex_count)
1919 list_add_tail(&queue.list, &sma->pending_alter);
1921 list_add_tail(&queue.list, &sma->pending_const);
1923 sma->complex_count++;
1926 queue.status = -EINTR;
1927 queue.sleeper = current;
1930 current->state = TASK_INTERRUPTIBLE;
1931 sem_unlock(sma, locknum);
1935 jiffies_left = schedule_timeout(jiffies_left);
1939 error = get_queue_result(&queue);
1941 if (error != -EINTR) {
1942 /* fast path: update_queue already obtained all requested
1944 * Perform a smp_mb(): User space could assume that semop()
1945 * is a memory barrier: Without the mb(), the cpu could
1946 * speculatively read in user space stale data that was
1947 * overwritten by the previous owner of the semaphore.
1955 sma = sem_obtain_lock(ns, semid, sops, nsops, &locknum);
1958 * Wait until it's guaranteed that no wakeup_sem_queue_do() is ongoing.
1960 error = get_queue_result(&queue);
1963 * Array removed? If yes, leave without sem_unlock().
1972 * If queue.status != -EINTR we are woken up by another process.
1973 * Leave without unlink_queue(), but with sem_unlock().
1975 if (error != -EINTR)
1976 goto out_unlock_free;
1979 * If an interrupt occurred we have to clean up the queue
1981 if (timeout && jiffies_left == 0)
1985 * If the wakeup was spurious, just retry
1987 if (error == -EINTR && !signal_pending(current))
1990 unlink_queue(sma, &queue);
1993 sem_unlock(sma, locknum);
1996 wake_up_sem_queue_do(&tasks);
1998 if (sops != fast_sops)
2003 SYSCALL_DEFINE3(semop, int, semid, struct sembuf __user *, tsops,
2006 return sys_semtimedop(semid, tsops, nsops, NULL);
2009 /* If CLONE_SYSVSEM is set, establish sharing of SEM_UNDO state between
2010 * parent and child tasks.
2013 int copy_semundo(unsigned long clone_flags, struct task_struct *tsk)
2015 struct sem_undo_list *undo_list;
2018 if (clone_flags & CLONE_SYSVSEM) {
2019 error = get_undo_list(&undo_list);
2022 atomic_inc(&undo_list->refcnt);
2023 tsk->sysvsem.undo_list = undo_list;
2025 tsk->sysvsem.undo_list = NULL;
2031 * add semadj values to semaphores, free undo structures.
2032 * undo structures are not freed when semaphore arrays are destroyed
2033 * so some of them may be out of date.
2034 * IMPLEMENTATION NOTE: There is some confusion over whether the
2035 * set of adjustments that needs to be done should be done in an atomic
2036 * manner or not. That is, if we are attempting to decrement the semval
2037 * should we queue up and wait until we can do so legally?
2038 * The original implementation attempted to do this (queue and wait).
2039 * The current implementation does not do so. The POSIX standard
2040 * and SVID should be consulted to determine what behavior is mandated.
2042 void exit_sem(struct task_struct *tsk)
2044 struct sem_undo_list *ulp;
2046 ulp = tsk->sysvsem.undo_list;
2049 tsk->sysvsem.undo_list = NULL;
2051 if (!atomic_dec_and_test(&ulp->refcnt))
2055 struct sem_array *sma;
2056 struct sem_undo *un;
2057 struct list_head tasks;
2061 un = list_entry_rcu(ulp->list_proc.next,
2062 struct sem_undo, list_proc);
2063 if (&un->list_proc == &ulp->list_proc)
2073 sma = sem_obtain_object_check(tsk->nsproxy->ipc_ns, un->semid);
2074 /* exit_sem raced with IPC_RMID, nothing to do */
2080 sem_lock(sma, NULL, -1);
2081 /* exit_sem raced with IPC_RMID, nothing to do */
2082 if (!ipc_valid_object(&sma->sem_perm)) {
2083 sem_unlock(sma, -1);
2087 un = __lookup_undo(ulp, semid);
2089 /* exit_sem raced with IPC_RMID+semget() that created
2090 * exactly the same semid. Nothing to do.
2092 sem_unlock(sma, -1);
2097 /* remove un from the linked lists */
2098 ipc_assert_locked_object(&sma->sem_perm);
2099 list_del(&un->list_id);
2101 spin_lock(&ulp->lock);
2102 list_del_rcu(&un->list_proc);
2103 spin_unlock(&ulp->lock);
2105 /* perform adjustments registered in un */
2106 for (i = 0; i < sma->sem_nsems; i++) {
2107 struct sem *semaphore = &sma->sem_base[i];
2108 if (un->semadj[i]) {
2109 semaphore->semval += un->semadj[i];
2111 * Range checks of the new semaphore value,
2112 * not defined by sus:
2113 * - Some unices ignore the undo entirely
2114 * (e.g. HP UX 11i 11.22, Tru64 V5.1)
2115 * - some cap the value (e.g. FreeBSD caps
2116 * at 0, but doesn't enforce SEMVMX)
2118 * Linux caps the semaphore value, both at 0
2121 * Manfred <manfred@colorfullife.com>
2123 if (semaphore->semval < 0)
2124 semaphore->semval = 0;
2125 if (semaphore->semval > SEMVMX)
2126 semaphore->semval = SEMVMX;
2127 semaphore->sempid = task_tgid_vnr(current);
2130 /* maybe some queued-up processes were waiting for this */
2131 INIT_LIST_HEAD(&tasks);
2132 do_smart_update(sma, NULL, 0, 1, &tasks);
2133 sem_unlock(sma, -1);
2135 wake_up_sem_queue_do(&tasks);
2142 #ifdef CONFIG_PROC_FS
2143 static int sysvipc_sem_proc_show(struct seq_file *s, void *it)
2145 struct user_namespace *user_ns = seq_user_ns(s);
2146 struct sem_array *sma = it;
2150 * The proc interface isn't aware of sem_lock(), it calls
2151 * ipc_lock_object() directly (in sysvipc_find_ipc).
2152 * In order to stay compatible with sem_lock(), we must wait until
2153 * all simple semop() calls have left their critical regions.
2155 sem_wait_array(sma);
2157 sem_otime = get_semotime(sma);
2159 return seq_printf(s,
2160 "%10d %10d %4o %10u %5u %5u %5u %5u %10lu %10lu\n",
2165 from_kuid_munged(user_ns, sma->sem_perm.uid),
2166 from_kgid_munged(user_ns, sma->sem_perm.gid),
2167 from_kuid_munged(user_ns, sma->sem_perm.cuid),
2168 from_kgid_munged(user_ns, sma->sem_perm.cgid),