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 */
96 * PID of the process that last modified the semaphore. For
97 * Linux, specifically these are:
99 * - semctl, via SETVAL and SETALL.
100 * - at task exit when performing undo adjustments (see exit_sem).
103 spinlock_t lock; /* spinlock for fine-grained semtimedop */
104 struct list_head pending_alter; /* pending single-sop operations */
105 /* that alter the semaphore */
106 struct list_head pending_const; /* pending single-sop operations */
107 /* that do not alter the semaphore*/
108 time_t sem_otime; /* candidate for sem_otime */
109 } ____cacheline_aligned_in_smp;
111 /* One queue for each sleeping process in the system. */
113 struct list_head list; /* queue of pending operations */
114 struct task_struct *sleeper; /* this process */
115 struct sem_undo *undo; /* undo structure */
116 struct pid *pid; /* process id of requesting process */
118 int status; /* completion status of operation */
119 struct sembuf *sops; /* array of pending operations */
120 struct sembuf *blocking; /* the operation that blocked */
121 int nsops; /* number of operations */
122 int alter; /* does *sops alter the array? */
125 /* Each task has a list of undo requests. They are executed automatically
126 * when the process exits.
129 struct list_head list_proc; /* per-process list: *
130 * all undos from one process
132 struct rcu_head rcu; /* rcu struct for sem_undo */
133 struct sem_undo_list *ulp; /* back ptr to sem_undo_list */
134 struct list_head list_id; /* per semaphore array list:
135 * all undos for one array */
136 int semid; /* semaphore set identifier */
137 short *semadj; /* array of adjustments */
138 /* one per semaphore */
141 /* sem_undo_list controls shared access to the list of sem_undo structures
142 * that may be shared among all a CLONE_SYSVSEM task group.
144 struct sem_undo_list {
147 struct list_head list_proc;
151 #define sem_ids(ns) ((ns)->ids[IPC_SEM_IDS])
153 #define sem_checkid(sma, semid) ipc_checkid(&sma->sem_perm, semid)
155 static int newary(struct ipc_namespace *, struct ipc_params *);
156 static void freeary(struct ipc_namespace *, struct kern_ipc_perm *);
157 #ifdef CONFIG_PROC_FS
158 static int sysvipc_sem_proc_show(struct seq_file *s, void *it);
161 #define SEMMSL_FAST 256 /* 512 bytes on stack */
162 #define SEMOPM_FAST 64 /* ~ 372 bytes on stack */
166 * a) global sem_lock() for read/write
168 * sem_array.complex_count,
169 * sem_array.complex_mode
170 * sem_array.pending{_alter,_const},
173 * b) global or semaphore sem_lock() for read/write:
174 * sem_array.sem_base[i].pending_{const,alter}:
175 * sem_array.complex_mode (for read)
178 * sem_undo_list.list_proc:
179 * * undo_list->lock for write
183 #define sc_semmsl sem_ctls[0]
184 #define sc_semmns sem_ctls[1]
185 #define sc_semopm sem_ctls[2]
186 #define sc_semmni sem_ctls[3]
188 void sem_init_ns(struct ipc_namespace *ns)
190 ns->sc_semmsl = SEMMSL;
191 ns->sc_semmns = SEMMNS;
192 ns->sc_semopm = SEMOPM;
193 ns->sc_semmni = SEMMNI;
195 ipc_init_ids(&ns->ids[IPC_SEM_IDS]);
199 void sem_exit_ns(struct ipc_namespace *ns)
201 free_ipcs(ns, &sem_ids(ns), freeary);
202 idr_destroy(&ns->ids[IPC_SEM_IDS].ipcs_idr);
206 void __init sem_init(void)
208 sem_init_ns(&init_ipc_ns);
209 ipc_init_proc_interface("sysvipc/sem",
210 " key semid perms nsems uid gid cuid cgid otime ctime\n",
211 IPC_SEM_IDS, sysvipc_sem_proc_show);
215 * unmerge_queues - unmerge queues, if possible.
216 * @sma: semaphore array
218 * The function unmerges the wait queues if complex_count is 0.
219 * It must be called prior to dropping the global semaphore array lock.
221 static void unmerge_queues(struct sem_array *sma)
223 struct sem_queue *q, *tq;
225 /* complex operations still around? */
226 if (sma->complex_count)
229 * We will switch back to simple mode.
230 * Move all pending operation back into the per-semaphore
233 list_for_each_entry_safe(q, tq, &sma->pending_alter, list) {
235 curr = &sma->sem_base[q->sops[0].sem_num];
237 list_add_tail(&q->list, &curr->pending_alter);
239 INIT_LIST_HEAD(&sma->pending_alter);
243 * merge_queues - merge single semop queues into global queue
244 * @sma: semaphore array
246 * This function merges all per-semaphore queues into the global queue.
247 * It is necessary to achieve FIFO ordering for the pending single-sop
248 * operations when a multi-semop operation must sleep.
249 * Only the alter operations must be moved, the const operations can stay.
251 static void merge_queues(struct sem_array *sma)
254 for (i = 0; i < sma->sem_nsems; i++) {
255 struct sem *sem = sma->sem_base + i;
257 list_splice_init(&sem->pending_alter, &sma->pending_alter);
261 static void sem_rcu_free(struct rcu_head *head)
263 struct ipc_rcu *p = container_of(head, struct ipc_rcu, rcu);
264 struct sem_array *sma = ipc_rcu_to_struct(p);
266 security_sem_free(sma);
271 * spin_unlock_wait() and !spin_is_locked() are not memory barriers, they
272 * are only control barriers.
273 * The code must pair with spin_unlock(&sem->lock) or
274 * spin_unlock(&sem_perm.lock), thus just the control barrier is insufficient.
276 * smp_rmb() is sufficient, as writes cannot pass the control barrier.
278 #define ipc_smp_acquire__after_spin_is_unlocked() smp_rmb()
281 * Enter the mode suitable for non-simple operations:
282 * Caller must own sem_perm.lock.
284 static void complexmode_enter(struct sem_array *sma)
289 if (sma->complex_mode) {
290 /* We are already in complex_mode. Nothing to do */
294 /* We need a full barrier after seting complex_mode:
295 * The write to complex_mode must be visible
296 * before we read the first sem->lock spinlock state.
298 set_mb(sma->complex_mode, true);
300 for (i = 0; i < sma->sem_nsems; i++) {
301 sem = sma->sem_base + i;
302 spin_unlock_wait(&sem->lock);
305 * spin_unlock_wait() is not a memory barriers, it is only a
306 * control barrier. The code must pair with spin_unlock(&sem->lock),
307 * thus just the control barrier is insufficient.
309 * smp_rmb() is sufficient, as writes cannot pass the control barrier.
315 * Try to leave the mode that disallows simple operations:
316 * Caller must own sem_perm.lock.
318 static void complexmode_tryleave(struct sem_array *sma)
320 if (sma->complex_count) {
321 /* Complex ops are sleeping.
322 * We must stay in complex mode
327 * Immediately after setting complex_mode to false,
328 * a simple op can start. Thus: all memory writes
329 * performed by the current operation must be visible
330 * before we set complex_mode to false.
332 smp_store_release(&sma->complex_mode, false);
335 #define SEM_GLOBAL_LOCK (-1)
337 * If the request contains only one semaphore operation, and there are
338 * no complex transactions pending, lock only the semaphore involved.
339 * Otherwise, lock the entire semaphore array, since we either have
340 * multiple semaphores in our own semops, or we need to look at
341 * semaphores from other pending complex operations.
343 static inline int sem_lock(struct sem_array *sma, struct sembuf *sops,
349 /* Complex operation - acquire a full lock */
350 ipc_lock_object(&sma->sem_perm);
352 /* Prevent parallel simple ops */
353 complexmode_enter(sma);
354 return SEM_GLOBAL_LOCK;
358 * Only one semaphore affected - try to optimize locking.
359 * Optimized locking is possible if no complex operation
360 * is either enqueued or processed right now.
362 * Both facts are tracked by complex_mode.
364 sem = sma->sem_base + sops->sem_num;
367 * Initial check for complex_mode. Just an optimization,
368 * no locking, no memory barrier.
370 if (!sma->complex_mode) {
372 * It appears that no complex operation is around.
373 * Acquire the per-semaphore lock.
375 spin_lock(&sem->lock);
379 * ("powerpc: Add smp_mb() to arch_spin_is_locked()"):
380 * A full barrier is required: the write of sem->lock
381 * must be visible before the read is executed
385 if (!smp_load_acquire(&sma->complex_mode)) {
386 /* fast path successful! */
387 return sops->sem_num;
389 spin_unlock(&sem->lock);
392 /* slow path: acquire the full lock */
393 ipc_lock_object(&sma->sem_perm);
395 if (sma->complex_count == 0) {
397 * There is no complex operation, thus we can switch
398 * back to the fast path.
400 spin_lock(&sem->lock);
401 ipc_unlock_object(&sma->sem_perm);
402 return sops->sem_num;
404 /* Not a false alarm, thus complete the sequence for a
407 complexmode_enter(sma);
408 return SEM_GLOBAL_LOCK;
412 static inline void sem_unlock(struct sem_array *sma, int locknum)
414 if (locknum == SEM_GLOBAL_LOCK) {
416 complexmode_tryleave(sma);
417 ipc_unlock_object(&sma->sem_perm);
419 struct sem *sem = sma->sem_base + locknum;
420 spin_unlock(&sem->lock);
425 * sem_lock_(check_) routines are called in the paths where the rwsem
428 * The caller holds the RCU read lock.
430 static inline struct sem_array *sem_obtain_lock(struct ipc_namespace *ns,
431 int id, struct sembuf *sops, int nsops, int *locknum)
433 struct kern_ipc_perm *ipcp;
434 struct sem_array *sma;
436 ipcp = ipc_obtain_object(&sem_ids(ns), id);
438 return ERR_CAST(ipcp);
440 sma = container_of(ipcp, struct sem_array, sem_perm);
441 *locknum = sem_lock(sma, sops, nsops);
443 /* ipc_rmid() may have already freed the ID while sem_lock
444 * was spinning: verify that the structure is still valid
446 if (ipc_valid_object(ipcp))
447 return container_of(ipcp, struct sem_array, sem_perm);
449 sem_unlock(sma, *locknum);
450 return ERR_PTR(-EINVAL);
453 static inline struct sem_array *sem_obtain_object(struct ipc_namespace *ns, int id)
455 struct kern_ipc_perm *ipcp = ipc_obtain_object(&sem_ids(ns), id);
458 return ERR_CAST(ipcp);
460 return container_of(ipcp, struct sem_array, sem_perm);
463 static inline struct sem_array *sem_obtain_object_check(struct ipc_namespace *ns,
466 struct kern_ipc_perm *ipcp = ipc_obtain_object_check(&sem_ids(ns), id);
469 return ERR_CAST(ipcp);
471 return container_of(ipcp, struct sem_array, sem_perm);
474 static inline void sem_lock_and_putref(struct sem_array *sma)
476 sem_lock(sma, NULL, -1);
477 ipc_rcu_putref(sma, sem_rcu_free);
480 static inline void sem_rmid(struct ipc_namespace *ns, struct sem_array *s)
482 ipc_rmid(&sem_ids(ns), &s->sem_perm);
486 * Lockless wakeup algorithm:
487 * Without the check/retry algorithm a lockless wakeup is possible:
488 * - queue.status is initialized to -EINTR before blocking.
489 * - wakeup is performed by
490 * * unlinking the queue entry from the pending list
491 * * setting queue.status to IN_WAKEUP
492 * This is the notification for the blocked thread that a
493 * result value is imminent.
494 * * call wake_up_process
495 * * set queue.status to the final value.
496 * - the previously blocked thread checks queue.status:
497 * * if it's IN_WAKEUP, then it must wait until the value changes
498 * * if it's not -EINTR, then the operation was completed by
499 * update_queue. semtimedop can return queue.status without
500 * performing any operation on the sem array.
501 * * otherwise it must acquire the spinlock and check what's up.
503 * The two-stage algorithm is necessary to protect against the following
505 * - if queue.status is set after wake_up_process, then the woken up idle
506 * thread could race forward and try (and fail) to acquire sma->lock
507 * before update_queue had a chance to set queue.status
508 * - if queue.status is written before wake_up_process and if the
509 * blocked process is woken up by a signal between writing
510 * queue.status and the wake_up_process, then the woken up
511 * process could return from semtimedop and die by calling
512 * sys_exit before wake_up_process is called. Then wake_up_process
513 * will oops, because the task structure is already invalid.
514 * (yes, this happened on s390 with sysv msg).
520 * newary - Create a new semaphore set
522 * @params: ptr to the structure that contains key, semflg and nsems
524 * Called with sem_ids.rwsem held (as a writer)
526 static int newary(struct ipc_namespace *ns, struct ipc_params *params)
530 struct sem_array *sma;
532 key_t key = params->key;
533 int nsems = params->u.nsems;
534 int semflg = params->flg;
539 if (ns->used_sems + nsems > ns->sc_semmns)
542 size = sizeof(*sma) + nsems * sizeof(struct sem);
543 sma = ipc_rcu_alloc(size);
547 memset(sma, 0, size);
549 sma->sem_perm.mode = (semflg & S_IRWXUGO);
550 sma->sem_perm.key = key;
552 sma->sem_perm.security = NULL;
553 retval = security_sem_alloc(sma);
555 ipc_rcu_putref(sma, ipc_rcu_free);
559 sma->sem_base = (struct sem *) &sma[1];
561 for (i = 0; i < nsems; i++) {
562 INIT_LIST_HEAD(&sma->sem_base[i].pending_alter);
563 INIT_LIST_HEAD(&sma->sem_base[i].pending_const);
564 spin_lock_init(&sma->sem_base[i].lock);
567 sma->complex_count = 0;
568 sma->complex_mode = true; /* dropped by sem_unlock below */
569 INIT_LIST_HEAD(&sma->pending_alter);
570 INIT_LIST_HEAD(&sma->pending_const);
571 INIT_LIST_HEAD(&sma->list_id);
572 sma->sem_nsems = nsems;
573 sma->sem_ctime = get_seconds();
575 id = ipc_addid(&sem_ids(ns), &sma->sem_perm, ns->sc_semmni);
577 ipc_rcu_putref(sma, sem_rcu_free);
580 ns->used_sems += nsems;
585 return sma->sem_perm.id;
590 * Called with sem_ids.rwsem and ipcp locked.
592 static inline int sem_security(struct kern_ipc_perm *ipcp, int semflg)
594 struct sem_array *sma;
596 sma = container_of(ipcp, struct sem_array, sem_perm);
597 return security_sem_associate(sma, semflg);
601 * Called with sem_ids.rwsem and ipcp locked.
603 static inline int sem_more_checks(struct kern_ipc_perm *ipcp,
604 struct ipc_params *params)
606 struct sem_array *sma;
608 sma = container_of(ipcp, struct sem_array, sem_perm);
609 if (params->u.nsems > sma->sem_nsems)
615 SYSCALL_DEFINE3(semget, key_t, key, int, nsems, int, semflg)
617 struct ipc_namespace *ns;
618 static const struct ipc_ops sem_ops = {
620 .associate = sem_security,
621 .more_checks = sem_more_checks,
623 struct ipc_params sem_params;
625 ns = current->nsproxy->ipc_ns;
627 if (nsems < 0 || nsems > ns->sc_semmsl)
630 sem_params.key = key;
631 sem_params.flg = semflg;
632 sem_params.u.nsems = nsems;
634 return ipcget(ns, &sem_ids(ns), &sem_ops, &sem_params);
638 * perform_atomic_semop - Perform (if possible) a semaphore operation
639 * @sma: semaphore array
640 * @q: struct sem_queue that describes the operation
642 * Returns 0 if the operation was possible.
643 * Returns 1 if the operation is impossible, the caller must sleep.
644 * Negative values are error codes.
646 static int perform_atomic_semop(struct sem_array *sma, struct sem_queue *q)
648 int result, sem_op, nsops;
659 for (sop = sops; sop < sops + nsops; sop++) {
660 curr = sma->sem_base + sop->sem_num;
661 sem_op = sop->sem_op;
662 result = curr->semval;
664 if (!sem_op && result)
673 if (sop->sem_flg & SEM_UNDO) {
674 int undo = un->semadj[sop->sem_num] - sem_op;
675 /* Exceeding the undo range is an error. */
676 if (undo < (-SEMAEM - 1) || undo > SEMAEM)
678 un->semadj[sop->sem_num] = undo;
681 curr->semval = result;
686 while (sop >= sops) {
687 ipc_update_pid(&sma->sem_base[sop->sem_num].sempid, pid);
700 if (sop->sem_flg & IPC_NOWAIT)
707 while (sop >= sops) {
708 sem_op = sop->sem_op;
709 sma->sem_base[sop->sem_num].semval -= sem_op;
710 if (sop->sem_flg & SEM_UNDO)
711 un->semadj[sop->sem_num] += sem_op;
718 /** wake_up_sem_queue_prepare(q, error): Prepare wake-up
719 * @q: queue entry that must be signaled
720 * @error: Error value for the signal
722 * Prepare the wake-up of the queue entry q.
724 static void wake_up_sem_queue_prepare(struct list_head *pt,
725 struct sem_queue *q, int error)
727 if (list_empty(pt)) {
729 * Hold preempt off so that we don't get preempted and have the
730 * wakee busy-wait until we're scheduled back on.
734 q->status = IN_WAKEUP;
735 q->wake_error = error;
737 list_add_tail(&q->list, pt);
741 * wake_up_sem_queue_do - do the actual wake-up
742 * @pt: list of tasks to be woken up
744 * Do the actual wake-up.
745 * The function is called without any locks held, thus the semaphore array
746 * could be destroyed already and the tasks can disappear as soon as the
747 * status is set to the actual return code.
749 static void wake_up_sem_queue_do(struct list_head *pt)
751 struct sem_queue *q, *t;
754 did_something = !list_empty(pt);
755 list_for_each_entry_safe(q, t, pt, list) {
756 wake_up_process(q->sleeper);
757 /* q can disappear immediately after writing q->status. */
759 q->status = q->wake_error;
765 static void unlink_queue(struct sem_array *sma, struct sem_queue *q)
769 sma->complex_count--;
772 /** check_restart(sma, q)
773 * @sma: semaphore array
774 * @q: the operation that just completed
776 * update_queue is O(N^2) when it restarts scanning the whole queue of
777 * waiting operations. Therefore this function checks if the restart is
778 * really necessary. It is called after a previously waiting operation
779 * modified the array.
780 * Note that wait-for-zero operations are handled without restart.
782 static int check_restart(struct sem_array *sma, struct sem_queue *q)
784 /* pending complex alter operations are too difficult to analyse */
785 if (!list_empty(&sma->pending_alter))
788 /* we were a sleeping complex operation. Too difficult */
792 /* It is impossible that someone waits for the new value:
793 * - complex operations always restart.
794 * - wait-for-zero are handled seperately.
795 * - q is a previously sleeping simple operation that
796 * altered the array. It must be a decrement, because
797 * simple increments never sleep.
798 * - If there are older (higher priority) decrements
799 * in the queue, then they have observed the original
800 * semval value and couldn't proceed. The operation
801 * decremented to value - thus they won't proceed either.
807 * wake_const_ops - wake up non-alter tasks
808 * @sma: semaphore array.
809 * @semnum: semaphore that was modified.
810 * @pt: list head for the tasks that must be woken up.
812 * wake_const_ops must be called after a semaphore in a semaphore array
813 * was set to 0. If complex const operations are pending, wake_const_ops must
814 * be called with semnum = -1, as well as with the number of each modified
816 * The tasks that must be woken up are added to @pt. The return code
817 * is stored in q->wake_error.
818 * The function returns 1 if at least one operation was completed successfully.
820 static int wake_const_ops(struct sem_array *sma, int semnum,
821 struct list_head *pt)
824 struct list_head *walk;
825 struct list_head *pending_list;
826 int semop_completed = 0;
829 pending_list = &sma->pending_const;
831 pending_list = &sma->sem_base[semnum].pending_const;
833 walk = pending_list->next;
834 while (walk != pending_list) {
837 q = container_of(walk, struct sem_queue, list);
840 error = perform_atomic_semop(sma, q);
843 /* operation completed, remove from queue & wakeup */
845 unlink_queue(sma, q);
847 wake_up_sem_queue_prepare(pt, q, error);
852 return semop_completed;
856 * do_smart_wakeup_zero - wakeup all wait for zero tasks
857 * @sma: semaphore array
858 * @sops: operations that were performed
859 * @nsops: number of operations
860 * @pt: list head of the tasks that must be woken up.
862 * Checks all required queue for wait-for-zero operations, based
863 * on the actual changes that were performed on the semaphore array.
864 * The function returns 1 if at least one operation was completed successfully.
866 static int do_smart_wakeup_zero(struct sem_array *sma, struct sembuf *sops,
867 int nsops, struct list_head *pt)
870 int semop_completed = 0;
873 /* first: the per-semaphore queues, if known */
875 for (i = 0; i < nsops; i++) {
876 int num = sops[i].sem_num;
878 if (sma->sem_base[num].semval == 0) {
880 semop_completed |= wake_const_ops(sma, num, pt);
885 * No sops means modified semaphores not known.
886 * Assume all were changed.
888 for (i = 0; i < sma->sem_nsems; i++) {
889 if (sma->sem_base[i].semval == 0) {
891 semop_completed |= wake_const_ops(sma, i, pt);
896 * If one of the modified semaphores got 0,
897 * then check the global queue, too.
900 semop_completed |= wake_const_ops(sma, -1, pt);
902 return semop_completed;
907 * update_queue - look for tasks that can be completed.
908 * @sma: semaphore array.
909 * @semnum: semaphore that was modified.
910 * @pt: list head for the tasks that must be woken up.
912 * update_queue must be called after a semaphore in a semaphore array
913 * was modified. If multiple semaphores were modified, update_queue must
914 * be called with semnum = -1, as well as with the number of each modified
916 * The tasks that must be woken up are added to @pt. The return code
917 * is stored in q->wake_error.
918 * The function internally checks if const operations can now succeed.
920 * The function return 1 if at least one semop was completed successfully.
922 static int update_queue(struct sem_array *sma, int semnum, struct list_head *pt)
925 struct list_head *walk;
926 struct list_head *pending_list;
927 int semop_completed = 0;
930 pending_list = &sma->pending_alter;
932 pending_list = &sma->sem_base[semnum].pending_alter;
935 walk = pending_list->next;
936 while (walk != pending_list) {
939 q = container_of(walk, struct sem_queue, list);
942 /* If we are scanning the single sop, per-semaphore list of
943 * one semaphore and that semaphore is 0, then it is not
944 * necessary to scan further: simple increments
945 * that affect only one entry succeed immediately and cannot
946 * be in the per semaphore pending queue, and decrements
947 * cannot be successful if the value is already 0.
949 if (semnum != -1 && sma->sem_base[semnum].semval == 0)
952 error = perform_atomic_semop(sma, q);
954 /* Does q->sleeper still need to sleep? */
958 unlink_queue(sma, q);
964 do_smart_wakeup_zero(sma, q->sops, q->nsops, pt);
965 restart = check_restart(sma, q);
968 wake_up_sem_queue_prepare(pt, q, error);
972 return semop_completed;
976 * set_semotime - set sem_otime
977 * @sma: semaphore array
978 * @sops: operations that modified the array, may be NULL
980 * sem_otime is replicated to avoid cache line trashing.
981 * This function sets one instance to the current time.
983 static void set_semotime(struct sem_array *sma, struct sembuf *sops)
986 sma->sem_base[0].sem_otime = get_seconds();
988 sma->sem_base[sops[0].sem_num].sem_otime =
994 * do_smart_update - optimized update_queue
995 * @sma: semaphore array
996 * @sops: operations that were performed
997 * @nsops: number of operations
998 * @otime: force setting otime
999 * @pt: list head of the tasks that must be woken up.
1001 * do_smart_update() does the required calls to update_queue and wakeup_zero,
1002 * based on the actual changes that were performed on the semaphore array.
1003 * Note that the function does not do the actual wake-up: the caller is
1004 * responsible for calling wake_up_sem_queue_do(@pt).
1005 * It is safe to perform this call after dropping all locks.
1007 static void do_smart_update(struct sem_array *sma, struct sembuf *sops, int nsops,
1008 int otime, struct list_head *pt)
1012 otime |= do_smart_wakeup_zero(sma, sops, nsops, pt);
1014 if (!list_empty(&sma->pending_alter)) {
1015 /* semaphore array uses the global queue - just process it. */
1016 otime |= update_queue(sma, -1, pt);
1020 * No sops, thus the modified semaphores are not
1023 for (i = 0; i < sma->sem_nsems; i++)
1024 otime |= update_queue(sma, i, pt);
1027 * Check the semaphores that were increased:
1028 * - No complex ops, thus all sleeping ops are
1030 * - if we decreased the value, then any sleeping
1031 * semaphore ops wont be able to run: If the
1032 * previous value was too small, then the new
1033 * value will be too small, too.
1035 for (i = 0; i < nsops; i++) {
1036 if (sops[i].sem_op > 0) {
1037 otime |= update_queue(sma,
1038 sops[i].sem_num, pt);
1044 set_semotime(sma, sops);
1048 * check_qop: Test if a queued operation sleeps on the semaphore semnum
1050 static int check_qop(struct sem_array *sma, int semnum, struct sem_queue *q,
1053 struct sembuf *sop = q->blocking;
1056 * Linux always (since 0.99.10) reported a task as sleeping on all
1057 * semaphores. This violates SUS, therefore it was changed to the
1058 * standard compliant behavior.
1059 * Give the administrators a chance to notice that an application
1060 * might misbehave because it relies on the Linux behavior.
1062 pr_info_once("semctl(GETNCNT/GETZCNT) is since 3.16 Single Unix Specification compliant.\n"
1063 "The task %s (%d) triggered the difference, watch for misbehavior.\n",
1064 current->comm, task_pid_nr(current));
1066 if (sop->sem_num != semnum)
1069 if (count_zero && sop->sem_op == 0)
1071 if (!count_zero && sop->sem_op < 0)
1077 /* The following counts are associated to each semaphore:
1078 * semncnt number of tasks waiting on semval being nonzero
1079 * semzcnt number of tasks waiting on semval being zero
1081 * Per definition, a task waits only on the semaphore of the first semop
1082 * that cannot proceed, even if additional operation would block, too.
1084 static int count_semcnt(struct sem_array *sma, ushort semnum,
1087 struct list_head *l;
1088 struct sem_queue *q;
1092 /* First: check the simple operations. They are easy to evaluate */
1094 l = &sma->sem_base[semnum].pending_const;
1096 l = &sma->sem_base[semnum].pending_alter;
1098 list_for_each_entry(q, l, list) {
1099 /* all task on a per-semaphore list sleep on exactly
1105 /* Then: check the complex operations. */
1106 list_for_each_entry(q, &sma->pending_alter, list) {
1107 semcnt += check_qop(sma, semnum, q, count_zero);
1110 list_for_each_entry(q, &sma->pending_const, list) {
1111 semcnt += check_qop(sma, semnum, q, count_zero);
1117 /* Free a semaphore set. freeary() is called with sem_ids.rwsem locked
1118 * as a writer and the spinlock for this semaphore set hold. sem_ids.rwsem
1119 * remains locked on exit.
1121 static void freeary(struct ipc_namespace *ns, struct kern_ipc_perm *ipcp)
1123 struct sem_undo *un, *tu;
1124 struct sem_queue *q, *tq;
1125 struct sem_array *sma = container_of(ipcp, struct sem_array, sem_perm);
1126 struct list_head tasks;
1129 /* Free the existing undo structures for this semaphore set. */
1130 ipc_assert_locked_object(&sma->sem_perm);
1131 list_for_each_entry_safe(un, tu, &sma->list_id, list_id) {
1132 list_del(&un->list_id);
1133 spin_lock(&un->ulp->lock);
1135 list_del_rcu(&un->list_proc);
1136 spin_unlock(&un->ulp->lock);
1140 /* Wake up all pending processes and let them fail with EIDRM. */
1141 INIT_LIST_HEAD(&tasks);
1142 list_for_each_entry_safe(q, tq, &sma->pending_const, list) {
1143 unlink_queue(sma, q);
1144 wake_up_sem_queue_prepare(&tasks, q, -EIDRM);
1147 list_for_each_entry_safe(q, tq, &sma->pending_alter, list) {
1148 unlink_queue(sma, q);
1149 wake_up_sem_queue_prepare(&tasks, q, -EIDRM);
1151 for (i = 0; i < sma->sem_nsems; i++) {
1152 struct sem *sem = sma->sem_base + i;
1153 list_for_each_entry_safe(q, tq, &sem->pending_const, list) {
1154 unlink_queue(sma, q);
1155 wake_up_sem_queue_prepare(&tasks, q, -EIDRM);
1157 list_for_each_entry_safe(q, tq, &sem->pending_alter, list) {
1158 unlink_queue(sma, q);
1159 wake_up_sem_queue_prepare(&tasks, q, -EIDRM);
1161 ipc_update_pid(&sem->sempid, NULL);
1164 /* Remove the semaphore set from the IDR */
1166 sem_unlock(sma, -1);
1169 wake_up_sem_queue_do(&tasks);
1170 ns->used_sems -= sma->sem_nsems;
1171 ipc_rcu_putref(sma, sem_rcu_free);
1174 static unsigned long copy_semid_to_user(void __user *buf, struct semid64_ds *in, int version)
1178 return copy_to_user(buf, in, sizeof(*in));
1181 struct semid_ds out;
1183 memset(&out, 0, sizeof(out));
1185 ipc64_perm_to_ipc_perm(&in->sem_perm, &out.sem_perm);
1187 out.sem_otime = in->sem_otime;
1188 out.sem_ctime = in->sem_ctime;
1189 out.sem_nsems = in->sem_nsems;
1191 return copy_to_user(buf, &out, sizeof(out));
1198 static time_t get_semotime(struct sem_array *sma)
1203 res = sma->sem_base[0].sem_otime;
1204 for (i = 1; i < sma->sem_nsems; i++) {
1205 time_t to = sma->sem_base[i].sem_otime;
1213 static int semctl_nolock(struct ipc_namespace *ns, int semid,
1214 int cmd, int version, void __user *p)
1217 struct sem_array *sma;
1223 struct seminfo seminfo;
1226 err = security_sem_semctl(NULL, cmd);
1230 memset(&seminfo, 0, sizeof(seminfo));
1231 seminfo.semmni = ns->sc_semmni;
1232 seminfo.semmns = ns->sc_semmns;
1233 seminfo.semmsl = ns->sc_semmsl;
1234 seminfo.semopm = ns->sc_semopm;
1235 seminfo.semvmx = SEMVMX;
1236 seminfo.semmnu = SEMMNU;
1237 seminfo.semmap = SEMMAP;
1238 seminfo.semume = SEMUME;
1239 down_read(&sem_ids(ns).rwsem);
1240 if (cmd == SEM_INFO) {
1241 seminfo.semusz = sem_ids(ns).in_use;
1242 seminfo.semaem = ns->used_sems;
1244 seminfo.semusz = SEMUSZ;
1245 seminfo.semaem = SEMAEM;
1247 max_id = ipc_get_maxid(&sem_ids(ns));
1248 up_read(&sem_ids(ns).rwsem);
1249 if (copy_to_user(p, &seminfo, sizeof(struct seminfo)))
1251 return (max_id < 0) ? 0 : max_id;
1256 struct semid64_ds tbuf;
1259 memset(&tbuf, 0, sizeof(tbuf));
1262 if (cmd == SEM_STAT) {
1263 sma = sem_obtain_object(ns, semid);
1268 id = sma->sem_perm.id;
1270 sma = sem_obtain_object_check(ns, semid);
1278 if (ipcperms(ns, &sma->sem_perm, S_IRUGO))
1281 err = security_sem_semctl(sma, cmd);
1285 kernel_to_ipc64_perm(&sma->sem_perm, &tbuf.sem_perm);
1286 tbuf.sem_otime = get_semotime(sma);
1287 tbuf.sem_ctime = sma->sem_ctime;
1288 tbuf.sem_nsems = sma->sem_nsems;
1290 if (copy_semid_to_user(p, &tbuf, version))
1302 static int semctl_setval(struct ipc_namespace *ns, int semid, int semnum,
1305 struct sem_undo *un;
1306 struct sem_array *sma;
1309 struct list_head tasks;
1311 #if defined(CONFIG_64BIT) && defined(__BIG_ENDIAN)
1312 /* big-endian 64bit */
1315 /* 32bit or little-endian 64bit */
1319 if (val > SEMVMX || val < 0)
1322 INIT_LIST_HEAD(&tasks);
1325 sma = sem_obtain_object_check(ns, semid);
1328 return PTR_ERR(sma);
1331 if (semnum < 0 || semnum >= sma->sem_nsems) {
1337 if (ipcperms(ns, &sma->sem_perm, S_IWUGO)) {
1342 err = security_sem_semctl(sma, SETVAL);
1348 sem_lock(sma, NULL, -1);
1350 if (!ipc_valid_object(&sma->sem_perm)) {
1351 sem_unlock(sma, -1);
1356 curr = &sma->sem_base[semnum];
1358 ipc_assert_locked_object(&sma->sem_perm);
1359 list_for_each_entry(un, &sma->list_id, list_id)
1360 un->semadj[semnum] = 0;
1363 ipc_update_pid(&curr->sempid, task_tgid(current));
1364 sma->sem_ctime = get_seconds();
1365 /* maybe some queued-up processes were waiting for this */
1366 do_smart_update(sma, NULL, 0, 0, &tasks);
1367 sem_unlock(sma, -1);
1369 wake_up_sem_queue_do(&tasks);
1373 static int semctl_main(struct ipc_namespace *ns, int semid, int semnum,
1374 int cmd, void __user *p)
1376 struct sem_array *sma;
1379 ushort fast_sem_io[SEMMSL_FAST];
1380 ushort *sem_io = fast_sem_io;
1381 struct list_head tasks;
1383 INIT_LIST_HEAD(&tasks);
1386 sma = sem_obtain_object_check(ns, semid);
1389 return PTR_ERR(sma);
1392 nsems = sma->sem_nsems;
1395 if (ipcperms(ns, &sma->sem_perm, cmd == SETALL ? S_IWUGO : S_IRUGO))
1396 goto out_rcu_wakeup;
1398 err = security_sem_semctl(sma, cmd);
1400 goto out_rcu_wakeup;
1406 ushort __user *array = p;
1409 sem_lock(sma, NULL, -1);
1410 if (!ipc_valid_object(&sma->sem_perm)) {
1414 if (nsems > SEMMSL_FAST) {
1415 if (!ipc_rcu_getref(sma)) {
1419 sem_unlock(sma, -1);
1421 sem_io = ipc_alloc(sizeof(ushort)*nsems);
1422 if (sem_io == NULL) {
1423 ipc_rcu_putref(sma, sem_rcu_free);
1428 sem_lock_and_putref(sma);
1429 if (!ipc_valid_object(&sma->sem_perm)) {
1434 for (i = 0; i < sma->sem_nsems; i++)
1435 sem_io[i] = sma->sem_base[i].semval;
1436 sem_unlock(sma, -1);
1439 if (copy_to_user(array, sem_io, nsems*sizeof(ushort)))
1446 struct sem_undo *un;
1448 if (!ipc_rcu_getref(sma)) {
1450 goto out_rcu_wakeup;
1454 if (nsems > SEMMSL_FAST) {
1455 sem_io = ipc_alloc(sizeof(ushort)*nsems);
1456 if (sem_io == NULL) {
1457 ipc_rcu_putref(sma, sem_rcu_free);
1462 if (copy_from_user(sem_io, p, nsems*sizeof(ushort))) {
1463 ipc_rcu_putref(sma, sem_rcu_free);
1468 for (i = 0; i < nsems; i++) {
1469 if (sem_io[i] > SEMVMX) {
1470 ipc_rcu_putref(sma, sem_rcu_free);
1476 sem_lock_and_putref(sma);
1477 if (!ipc_valid_object(&sma->sem_perm)) {
1482 for (i = 0; i < nsems; i++) {
1483 sma->sem_base[i].semval = sem_io[i];
1484 ipc_update_pid(&sma->sem_base[i].sempid, task_tgid(current));
1487 ipc_assert_locked_object(&sma->sem_perm);
1488 list_for_each_entry(un, &sma->list_id, list_id) {
1489 for (i = 0; i < nsems; i++)
1492 sma->sem_ctime = get_seconds();
1493 /* maybe some queued-up processes were waiting for this */
1494 do_smart_update(sma, NULL, 0, 0, &tasks);
1498 /* GETVAL, GETPID, GETNCTN, GETZCNT: fall-through */
1501 if (semnum < 0 || semnum >= nsems)
1502 goto out_rcu_wakeup;
1504 sem_lock(sma, NULL, -1);
1505 if (!ipc_valid_object(&sma->sem_perm)) {
1509 curr = &sma->sem_base[semnum];
1516 err = pid_vnr(curr->sempid);
1519 err = count_semcnt(sma, semnum, 0);
1522 err = count_semcnt(sma, semnum, 1);
1527 sem_unlock(sma, -1);
1530 wake_up_sem_queue_do(&tasks);
1532 if (sem_io != fast_sem_io)
1533 ipc_free(sem_io, sizeof(ushort)*nsems);
1537 static inline unsigned long
1538 copy_semid_from_user(struct semid64_ds *out, void __user *buf, int version)
1542 if (copy_from_user(out, buf, sizeof(*out)))
1547 struct semid_ds tbuf_old;
1549 if (copy_from_user(&tbuf_old, buf, sizeof(tbuf_old)))
1552 out->sem_perm.uid = tbuf_old.sem_perm.uid;
1553 out->sem_perm.gid = tbuf_old.sem_perm.gid;
1554 out->sem_perm.mode = tbuf_old.sem_perm.mode;
1564 * This function handles some semctl commands which require the rwsem
1565 * to be held in write mode.
1566 * NOTE: no locks must be held, the rwsem is taken inside this function.
1568 static int semctl_down(struct ipc_namespace *ns, int semid,
1569 int cmd, int version, void __user *p)
1571 struct sem_array *sma;
1573 struct semid64_ds semid64;
1574 struct kern_ipc_perm *ipcp;
1576 if (cmd == IPC_SET) {
1577 if (copy_semid_from_user(&semid64, p, version))
1581 down_write(&sem_ids(ns).rwsem);
1584 ipcp = ipcctl_pre_down_nolock(ns, &sem_ids(ns), semid, cmd,
1585 &semid64.sem_perm, 0);
1587 err = PTR_ERR(ipcp);
1591 sma = container_of(ipcp, struct sem_array, sem_perm);
1593 err = security_sem_semctl(sma, cmd);
1599 sem_lock(sma, NULL, -1);
1600 /* freeary unlocks the ipc object and rcu */
1604 sem_lock(sma, NULL, -1);
1605 err = ipc_update_perm(&semid64.sem_perm, ipcp);
1608 sma->sem_ctime = get_seconds();
1616 sem_unlock(sma, -1);
1620 up_write(&sem_ids(ns).rwsem);
1624 SYSCALL_DEFINE4(semctl, int, semid, int, semnum, int, cmd, unsigned long, arg)
1627 struct ipc_namespace *ns;
1628 void __user *p = (void __user *)arg;
1633 version = ipc_parse_version(&cmd);
1634 ns = current->nsproxy->ipc_ns;
1641 return semctl_nolock(ns, semid, cmd, version, p);
1648 return semctl_main(ns, semid, semnum, cmd, p);
1650 return semctl_setval(ns, semid, semnum, arg);
1653 return semctl_down(ns, semid, cmd, version, p);
1659 /* If the task doesn't already have a undo_list, then allocate one
1660 * here. We guarantee there is only one thread using this undo list,
1661 * and current is THE ONE
1663 * If this allocation and assignment succeeds, but later
1664 * portions of this code fail, there is no need to free the sem_undo_list.
1665 * Just let it stay associated with the task, and it'll be freed later
1668 * This can block, so callers must hold no locks.
1670 static inline int get_undo_list(struct sem_undo_list **undo_listp)
1672 struct sem_undo_list *undo_list;
1674 undo_list = current->sysvsem.undo_list;
1676 undo_list = kzalloc(sizeof(*undo_list), GFP_KERNEL);
1677 if (undo_list == NULL)
1679 spin_lock_init(&undo_list->lock);
1680 atomic_set(&undo_list->refcnt, 1);
1681 INIT_LIST_HEAD(&undo_list->list_proc);
1683 current->sysvsem.undo_list = undo_list;
1685 *undo_listp = undo_list;
1689 static struct sem_undo *__lookup_undo(struct sem_undo_list *ulp, int semid)
1691 struct sem_undo *un;
1693 list_for_each_entry_rcu(un, &ulp->list_proc, list_proc) {
1694 if (un->semid == semid)
1700 static struct sem_undo *lookup_undo(struct sem_undo_list *ulp, int semid)
1702 struct sem_undo *un;
1704 assert_spin_locked(&ulp->lock);
1706 un = __lookup_undo(ulp, semid);
1708 list_del_rcu(&un->list_proc);
1709 list_add_rcu(&un->list_proc, &ulp->list_proc);
1715 * find_alloc_undo - lookup (and if not present create) undo array
1717 * @semid: semaphore array id
1719 * The function looks up (and if not present creates) the undo structure.
1720 * The size of the undo structure depends on the size of the semaphore
1721 * array, thus the alloc path is not that straightforward.
1722 * Lifetime-rules: sem_undo is rcu-protected, on success, the function
1723 * performs a rcu_read_lock().
1725 static struct sem_undo *find_alloc_undo(struct ipc_namespace *ns, int semid)
1727 struct sem_array *sma;
1728 struct sem_undo_list *ulp;
1729 struct sem_undo *un, *new;
1732 error = get_undo_list(&ulp);
1734 return ERR_PTR(error);
1737 spin_lock(&ulp->lock);
1738 un = lookup_undo(ulp, semid);
1739 spin_unlock(&ulp->lock);
1740 if (likely(un != NULL))
1743 /* no undo structure around - allocate one. */
1744 /* step 1: figure out the size of the semaphore array */
1745 sma = sem_obtain_object_check(ns, semid);
1748 return ERR_CAST(sma);
1751 nsems = sma->sem_nsems;
1752 if (!ipc_rcu_getref(sma)) {
1754 un = ERR_PTR(-EIDRM);
1759 /* step 2: allocate new undo structure */
1760 new = kzalloc(sizeof(struct sem_undo) + sizeof(short)*nsems, GFP_KERNEL);
1762 ipc_rcu_putref(sma, sem_rcu_free);
1763 return ERR_PTR(-ENOMEM);
1766 /* step 3: Acquire the lock on semaphore array */
1768 sem_lock_and_putref(sma);
1769 if (!ipc_valid_object(&sma->sem_perm)) {
1770 sem_unlock(sma, -1);
1773 un = ERR_PTR(-EIDRM);
1776 spin_lock(&ulp->lock);
1779 * step 4: check for races: did someone else allocate the undo struct?
1781 un = lookup_undo(ulp, semid);
1786 /* step 5: initialize & link new undo structure */
1787 new->semadj = (short *) &new[1];
1790 assert_spin_locked(&ulp->lock);
1791 list_add_rcu(&new->list_proc, &ulp->list_proc);
1792 ipc_assert_locked_object(&sma->sem_perm);
1793 list_add(&new->list_id, &sma->list_id);
1797 spin_unlock(&ulp->lock);
1798 sem_unlock(sma, -1);
1805 * get_queue_result - retrieve the result code from sem_queue
1806 * @q: Pointer to queue structure
1808 * Retrieve the return code from the pending queue. If IN_WAKEUP is found in
1809 * q->status, then we must loop until the value is replaced with the final
1810 * value: This may happen if a task is woken up by an unrelated event (e.g.
1811 * signal) and in parallel the task is woken up by another task because it got
1812 * the requested semaphores.
1814 * The function can be called with or without holding the semaphore spinlock.
1816 static int get_queue_result(struct sem_queue *q)
1821 while (unlikely(error == IN_WAKEUP)) {
1829 SYSCALL_DEFINE4(semtimedop, int, semid, struct sembuf __user *, tsops,
1830 unsigned, nsops, const struct timespec __user *, timeout)
1832 int error = -EINVAL;
1833 struct sem_array *sma;
1834 struct sembuf fast_sops[SEMOPM_FAST];
1835 struct sembuf *sops = fast_sops, *sop;
1836 struct sem_undo *un;
1837 int undos = 0, alter = 0, max, locknum;
1838 struct sem_queue queue;
1839 unsigned long jiffies_left = 0;
1840 struct ipc_namespace *ns;
1841 struct list_head tasks;
1843 ns = current->nsproxy->ipc_ns;
1845 if (nsops < 1 || semid < 0)
1847 if (nsops > ns->sc_semopm)
1849 if (nsops > SEMOPM_FAST) {
1850 sops = kmalloc(sizeof(*sops)*nsops, GFP_KERNEL);
1854 if (copy_from_user(sops, tsops, nsops * sizeof(*tsops))) {
1859 struct timespec _timeout;
1860 if (copy_from_user(&_timeout, timeout, sizeof(*timeout))) {
1864 if (_timeout.tv_sec < 0 || _timeout.tv_nsec < 0 ||
1865 _timeout.tv_nsec >= 1000000000L) {
1869 jiffies_left = timespec_to_jiffies(&_timeout);
1872 for (sop = sops; sop < sops + nsops; sop++) {
1873 if (sop->sem_num >= max)
1875 if (sop->sem_flg & SEM_UNDO)
1877 if (sop->sem_op != 0)
1881 INIT_LIST_HEAD(&tasks);
1884 /* On success, find_alloc_undo takes the rcu_read_lock */
1885 un = find_alloc_undo(ns, semid);
1887 error = PTR_ERR(un);
1895 sma = sem_obtain_object_check(ns, semid);
1898 error = PTR_ERR(sma);
1903 if (max >= sma->sem_nsems)
1904 goto out_rcu_wakeup;
1907 if (ipcperms(ns, &sma->sem_perm, alter ? S_IWUGO : S_IRUGO))
1908 goto out_rcu_wakeup;
1910 error = security_sem_semop(sma, sops, nsops, alter);
1912 goto out_rcu_wakeup;
1915 locknum = sem_lock(sma, sops, nsops);
1917 * We eventually might perform the following check in a lockless
1918 * fashion, considering ipc_valid_object() locking constraints.
1919 * If nsops == 1 and there is no contention for sem_perm.lock, then
1920 * only a per-semaphore lock is held and it's OK to proceed with the
1921 * check below. More details on the fine grained locking scheme
1922 * entangled here and why it's RMID race safe on comments at sem_lock()
1924 if (!ipc_valid_object(&sma->sem_perm))
1925 goto out_unlock_free;
1927 * semid identifiers are not unique - find_alloc_undo may have
1928 * allocated an undo structure, it was invalidated by an RMID
1929 * and now a new array with received the same id. Check and fail.
1930 * This case can be detected checking un->semid. The existence of
1931 * "un" itself is guaranteed by rcu.
1933 if (un && un->semid == -1)
1934 goto out_unlock_free;
1937 queue.nsops = nsops;
1939 queue.pid = task_tgid(current);
1940 queue.alter = alter;
1942 error = perform_atomic_semop(sma, &queue);
1944 /* If the operation was successful, then do
1945 * the required updates.
1948 do_smart_update(sma, sops, nsops, 1, &tasks);
1950 set_semotime(sma, sops);
1953 goto out_unlock_free;
1955 /* We need to sleep on this operation, so we put the current
1956 * task into the pending queue and go to sleep.
1961 curr = &sma->sem_base[sops->sem_num];
1964 if (sma->complex_count) {
1965 list_add_tail(&queue.list,
1966 &sma->pending_alter);
1969 list_add_tail(&queue.list,
1970 &curr->pending_alter);
1973 list_add_tail(&queue.list, &curr->pending_const);
1976 if (!sma->complex_count)
1980 list_add_tail(&queue.list, &sma->pending_alter);
1982 list_add_tail(&queue.list, &sma->pending_const);
1984 sma->complex_count++;
1987 queue.status = -EINTR;
1988 queue.sleeper = current;
1991 current->state = TASK_INTERRUPTIBLE;
1992 sem_unlock(sma, locknum);
1996 jiffies_left = schedule_timeout(jiffies_left);
2000 error = get_queue_result(&queue);
2002 if (error != -EINTR) {
2003 /* fast path: update_queue already obtained all requested
2005 * Perform a smp_mb(): User space could assume that semop()
2006 * is a memory barrier: Without the mb(), the cpu could
2007 * speculatively read in user space stale data that was
2008 * overwritten by the previous owner of the semaphore.
2016 sma = sem_obtain_lock(ns, semid, sops, nsops, &locknum);
2019 * Wait until it's guaranteed that no wakeup_sem_queue_do() is ongoing.
2021 error = get_queue_result(&queue);
2024 * Array removed? If yes, leave without sem_unlock().
2033 * If queue.status != -EINTR we are woken up by another process.
2034 * Leave without unlink_queue(), but with sem_unlock().
2036 if (error != -EINTR)
2037 goto out_unlock_free;
2040 * If an interrupt occurred we have to clean up the queue
2042 if (timeout && jiffies_left == 0)
2046 * If the wakeup was spurious, just retry
2048 if (error == -EINTR && !signal_pending(current))
2051 unlink_queue(sma, &queue);
2054 sem_unlock(sma, locknum);
2057 wake_up_sem_queue_do(&tasks);
2059 if (sops != fast_sops)
2064 SYSCALL_DEFINE3(semop, int, semid, struct sembuf __user *, tsops,
2067 return sys_semtimedop(semid, tsops, nsops, NULL);
2070 /* If CLONE_SYSVSEM is set, establish sharing of SEM_UNDO state between
2071 * parent and child tasks.
2074 int copy_semundo(unsigned long clone_flags, struct task_struct *tsk)
2076 struct sem_undo_list *undo_list;
2079 if (clone_flags & CLONE_SYSVSEM) {
2080 error = get_undo_list(&undo_list);
2083 atomic_inc(&undo_list->refcnt);
2084 tsk->sysvsem.undo_list = undo_list;
2086 tsk->sysvsem.undo_list = NULL;
2092 * add semadj values to semaphores, free undo structures.
2093 * undo structures are not freed when semaphore arrays are destroyed
2094 * so some of them may be out of date.
2095 * IMPLEMENTATION NOTE: There is some confusion over whether the
2096 * set of adjustments that needs to be done should be done in an atomic
2097 * manner or not. That is, if we are attempting to decrement the semval
2098 * should we queue up and wait until we can do so legally?
2099 * The original implementation attempted to do this (queue and wait).
2100 * The current implementation does not do so. The POSIX standard
2101 * and SVID should be consulted to determine what behavior is mandated.
2103 void exit_sem(struct task_struct *tsk)
2105 struct sem_undo_list *ulp;
2107 ulp = tsk->sysvsem.undo_list;
2110 tsk->sysvsem.undo_list = NULL;
2112 if (!atomic_dec_and_test(&ulp->refcnt))
2116 struct sem_array *sma;
2117 struct sem_undo *un;
2118 struct list_head tasks;
2122 un = list_entry_rcu(ulp->list_proc.next,
2123 struct sem_undo, list_proc);
2124 if (&un->list_proc == &ulp->list_proc) {
2126 * We must wait for freeary() before freeing this ulp,
2127 * in case we raced with last sem_undo. There is a small
2128 * possibility where we exit while freeary() didn't
2129 * finish unlocking sem_undo_list.
2131 spin_unlock_wait(&ulp->lock);
2135 spin_lock(&ulp->lock);
2137 spin_unlock(&ulp->lock);
2139 /* exit_sem raced with IPC_RMID, nothing to do */
2145 sma = sem_obtain_object_check(tsk->nsproxy->ipc_ns, semid);
2146 /* exit_sem raced with IPC_RMID, nothing to do */
2152 sem_lock(sma, NULL, -1);
2153 /* exit_sem raced with IPC_RMID, nothing to do */
2154 if (!ipc_valid_object(&sma->sem_perm)) {
2155 sem_unlock(sma, -1);
2159 un = __lookup_undo(ulp, semid);
2161 /* exit_sem raced with IPC_RMID+semget() that created
2162 * exactly the same semid. Nothing to do.
2164 sem_unlock(sma, -1);
2169 /* remove un from the linked lists */
2170 ipc_assert_locked_object(&sma->sem_perm);
2171 list_del(&un->list_id);
2173 spin_lock(&ulp->lock);
2174 list_del_rcu(&un->list_proc);
2175 spin_unlock(&ulp->lock);
2177 /* perform adjustments registered in un */
2178 for (i = 0; i < sma->sem_nsems; i++) {
2179 struct sem *semaphore = &sma->sem_base[i];
2180 if (un->semadj[i]) {
2181 semaphore->semval += un->semadj[i];
2183 * Range checks of the new semaphore value,
2184 * not defined by sus:
2185 * - Some unices ignore the undo entirely
2186 * (e.g. HP UX 11i 11.22, Tru64 V5.1)
2187 * - some cap the value (e.g. FreeBSD caps
2188 * at 0, but doesn't enforce SEMVMX)
2190 * Linux caps the semaphore value, both at 0
2193 * Manfred <manfred@colorfullife.com>
2195 if (semaphore->semval < 0)
2196 semaphore->semval = 0;
2197 if (semaphore->semval > SEMVMX)
2198 semaphore->semval = SEMVMX;
2199 ipc_update_pid(&semaphore->sempid, task_tgid(current));
2202 /* maybe some queued-up processes were waiting for this */
2203 INIT_LIST_HEAD(&tasks);
2204 do_smart_update(sma, NULL, 0, 1, &tasks);
2205 sem_unlock(sma, -1);
2207 wake_up_sem_queue_do(&tasks);
2214 #ifdef CONFIG_PROC_FS
2215 static int sysvipc_sem_proc_show(struct seq_file *s, void *it)
2217 struct user_namespace *user_ns = seq_user_ns(s);
2218 struct sem_array *sma = it;
2222 * The proc interface isn't aware of sem_lock(), it calls
2223 * ipc_lock_object() directly (in sysvipc_find_ipc).
2224 * In order to stay compatible with sem_lock(), we must
2225 * enter / leave complex_mode.
2227 complexmode_enter(sma);
2229 sem_otime = get_semotime(sma);
2232 "%10d %10d %4o %10u %5u %5u %5u %5u %10lu %10lu\n",
2237 from_kuid_munged(user_ns, sma->sem_perm.uid),
2238 from_kgid_munged(user_ns, sma->sem_perm.gid),
2239 from_kuid_munged(user_ns, sma->sem_perm.cuid),
2240 from_kgid_munged(user_ns, sma->sem_perm.cgid),
2244 complexmode_tryleave(sma);