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 * (c) 2016 Davidlohr Bueso <dave@stgolabs.net>
15 * Further wakeup optimizations, documentation
16 * (c) 2010 Manfred Spraul <manfred@colorfullife.com>
18 * support for audit of ipc object properties and permission changes
19 * Dustin Kirkland <dustin.kirkland@us.ibm.com>
23 * Pavel Emelianov <xemul@openvz.org>
25 * Implementation notes: (May 2010)
26 * This file implements System V semaphores.
28 * User space visible behavior:
29 * - FIFO ordering for semop() operations (just FIFO, not starvation
31 * - multiple semaphore operations that alter the same semaphore in
32 * one semop() are handled.
33 * - sem_ctime (time of last semctl()) is updated in the IPC_SET, SETVAL and
35 * - two Linux specific semctl() commands: SEM_STAT, SEM_INFO.
36 * - undo adjustments at process exit are limited to 0..SEMVMX.
37 * - namespace are supported.
38 * - SEMMSL, SEMMNS, SEMOPM and SEMMNI can be configured at runtine by writing
39 * to /proc/sys/kernel/sem.
40 * - statistics about the usage are reported in /proc/sysvipc/sem.
44 * - all global variables are read-mostly.
45 * - semop() calls and semctl(RMID) are synchronized by RCU.
46 * - most operations do write operations (actually: spin_lock calls) to
47 * the per-semaphore array structure.
48 * Thus: Perfect SMP scaling between independent semaphore arrays.
49 * If multiple semaphores in one array are used, then cache line
50 * trashing on the semaphore array spinlock will limit the scaling.
51 * - semncnt and semzcnt are calculated on demand in count_semcnt()
52 * - the task that performs a successful semop() scans the list of all
53 * sleeping tasks and completes any pending operations that can be fulfilled.
54 * Semaphores are actively given to waiting tasks (necessary for FIFO).
55 * (see update_queue())
56 * - To improve the scalability, the actual wake-up calls are performed after
57 * dropping all locks. (see wake_up_sem_queue_prepare())
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 * - UNDO values are stored in an array (one per process and per
63 * semaphore array, lazily allocated). For backwards compatibility, multiple
64 * modes for the UNDO variables are supported (per process, per thread)
65 * (see copy_semundo, CLONE_SYSVSEM)
66 * - There are two lists of the pending operations: a per-array list
67 * and per-semaphore list (stored in the array). This allows to achieve FIFO
68 * ordering without always scanning all pending operations.
69 * The worst-case behavior is nevertheless O(N^2) for N wakeups.
72 #include <linux/slab.h>
73 #include <linux/spinlock.h>
74 #include <linux/init.h>
75 #include <linux/proc_fs.h>
76 #include <linux/time.h>
77 #include <linux/security.h>
78 #include <linux/syscalls.h>
79 #include <linux/audit.h>
80 #include <linux/capability.h>
81 #include <linux/seq_file.h>
82 #include <linux/rwsem.h>
83 #include <linux/nsproxy.h>
84 #include <linux/ipc_namespace.h>
85 #include <linux/sched/wake_q.h>
87 #include <linux/uaccess.h>
91 /* One queue for each sleeping process in the system. */
93 struct list_head list; /* queue of pending operations */
94 struct task_struct *sleeper; /* this process */
95 struct sem_undo *undo; /* undo structure */
96 int pid; /* process id of requesting process */
97 int status; /* completion status of operation */
98 struct sembuf *sops; /* array of pending operations */
99 struct sembuf *blocking; /* the operation that blocked */
100 int nsops; /* number of operations */
101 bool alter; /* does *sops alter the array? */
102 bool dupsop; /* sops on more than one sem_num */
105 /* Each task has a list of undo requests. They are executed automatically
106 * when the process exits.
109 struct list_head list_proc; /* per-process list: *
110 * all undos from one process
112 struct rcu_head rcu; /* rcu struct for sem_undo */
113 struct sem_undo_list *ulp; /* back ptr to sem_undo_list */
114 struct list_head list_id; /* per semaphore array list:
115 * all undos for one array */
116 int semid; /* semaphore set identifier */
117 short *semadj; /* array of adjustments */
118 /* one per semaphore */
121 /* sem_undo_list controls shared access to the list of sem_undo structures
122 * that may be shared among all a CLONE_SYSVSEM task group.
124 struct sem_undo_list {
127 struct list_head list_proc;
131 #define sem_ids(ns) ((ns)->ids[IPC_SEM_IDS])
133 static int newary(struct ipc_namespace *, struct ipc_params *);
134 static void freeary(struct ipc_namespace *, struct kern_ipc_perm *);
135 #ifdef CONFIG_PROC_FS
136 static int sysvipc_sem_proc_show(struct seq_file *s, void *it);
139 #define SEMMSL_FAST 256 /* 512 bytes on stack */
140 #define SEMOPM_FAST 64 /* ~ 372 bytes on stack */
143 * Switching from the mode suitable for simple ops
144 * to the mode for complex ops is costly. Therefore:
145 * use some hysteresis
147 #define USE_GLOBAL_LOCK_HYSTERESIS 10
151 * a) global sem_lock() for read/write
153 * sem_array.complex_count,
154 * sem_array.pending{_alter,_const},
157 * b) global or semaphore sem_lock() for read/write:
158 * sem_array.sems[i].pending_{const,alter}:
161 * sem_undo_list.list_proc:
162 * * undo_list->lock for write
165 * * global sem_lock() for write
166 * * either local or global sem_lock() for read.
169 * Most ordering is enforced by using spin_lock() and spin_unlock().
170 * The special case is use_global_lock:
171 * Setting it from non-zero to 0 is a RELEASE, this is ensured by
172 * using smp_store_release().
173 * Testing if it is non-zero is an ACQUIRE, this is ensured by using
174 * smp_load_acquire().
175 * Setting it from 0 to non-zero must be ordered with regards to
176 * this smp_load_acquire(), this is guaranteed because the smp_load_acquire()
177 * is inside a spin_lock() and after a write from 0 to non-zero a
178 * spin_lock()+spin_unlock() is done.
181 #define sc_semmsl sem_ctls[0]
182 #define sc_semmns sem_ctls[1]
183 #define sc_semopm sem_ctls[2]
184 #define sc_semmni sem_ctls[3]
186 void sem_init_ns(struct ipc_namespace *ns)
188 ns->sc_semmsl = SEMMSL;
189 ns->sc_semmns = SEMMNS;
190 ns->sc_semopm = SEMOPM;
191 ns->sc_semmni = SEMMNI;
193 ipc_init_ids(&ns->ids[IPC_SEM_IDS]);
197 void sem_exit_ns(struct ipc_namespace *ns)
199 free_ipcs(ns, &sem_ids(ns), freeary);
200 idr_destroy(&ns->ids[IPC_SEM_IDS].ipcs_idr);
204 void __init sem_init(void)
206 sem_init_ns(&init_ipc_ns);
207 ipc_init_proc_interface("sysvipc/sem",
208 " key semid perms nsems uid gid cuid cgid otime ctime\n",
209 IPC_SEM_IDS, sysvipc_sem_proc_show);
213 * unmerge_queues - unmerge queues, if possible.
214 * @sma: semaphore array
216 * The function unmerges the wait queues if complex_count is 0.
217 * It must be called prior to dropping the global semaphore array lock.
219 static void unmerge_queues(struct sem_array *sma)
221 struct sem_queue *q, *tq;
223 /* complex operations still around? */
224 if (sma->complex_count)
227 * We will switch back to simple mode.
228 * Move all pending operation back into the per-semaphore
231 list_for_each_entry_safe(q, tq, &sma->pending_alter, list) {
233 curr = &sma->sems[q->sops[0].sem_num];
235 list_add_tail(&q->list, &curr->pending_alter);
237 INIT_LIST_HEAD(&sma->pending_alter);
241 * merge_queues - merge single semop queues into global queue
242 * @sma: semaphore array
244 * This function merges all per-semaphore queues into the global queue.
245 * It is necessary to achieve FIFO ordering for the pending single-sop
246 * operations when a multi-semop operation must sleep.
247 * Only the alter operations must be moved, the const operations can stay.
249 static void merge_queues(struct sem_array *sma)
252 for (i = 0; i < sma->sem_nsems; i++) {
253 struct sem *sem = &sma->sems[i];
255 list_splice_init(&sem->pending_alter, &sma->pending_alter);
259 static void sem_rcu_free(struct rcu_head *head)
261 struct kern_ipc_perm *p = container_of(head, struct kern_ipc_perm, rcu);
262 struct sem_array *sma = container_of(p, struct sem_array, sem_perm);
264 security_sem_free(sma);
269 * Enter the mode suitable for non-simple operations:
270 * Caller must own sem_perm.lock.
272 static void complexmode_enter(struct sem_array *sma)
277 if (sma->use_global_lock > 0) {
279 * We are already in global lock mode.
280 * Nothing to do, just reset the
281 * counter until we return to simple mode.
283 sma->use_global_lock = USE_GLOBAL_LOCK_HYSTERESIS;
286 sma->use_global_lock = USE_GLOBAL_LOCK_HYSTERESIS;
288 for (i = 0; i < sma->sem_nsems; i++) {
290 spin_lock(&sem->lock);
291 spin_unlock(&sem->lock);
296 * Try to leave the mode that disallows simple operations:
297 * Caller must own sem_perm.lock.
299 static void complexmode_tryleave(struct sem_array *sma)
301 if (sma->complex_count) {
302 /* Complex ops are sleeping.
303 * We must stay in complex mode
307 if (sma->use_global_lock == 1) {
309 * Immediately after setting use_global_lock to 0,
310 * a simple op can start. Thus: all memory writes
311 * performed by the current operation must be visible
312 * before we set use_global_lock to 0.
314 smp_store_release(&sma->use_global_lock, 0);
316 sma->use_global_lock--;
320 #define SEM_GLOBAL_LOCK (-1)
322 * If the request contains only one semaphore operation, and there are
323 * no complex transactions pending, lock only the semaphore involved.
324 * Otherwise, lock the entire semaphore array, since we either have
325 * multiple semaphores in our own semops, or we need to look at
326 * semaphores from other pending complex operations.
328 static inline int sem_lock(struct sem_array *sma, struct sembuf *sops,
334 /* Complex operation - acquire a full lock */
335 ipc_lock_object(&sma->sem_perm);
337 /* Prevent parallel simple ops */
338 complexmode_enter(sma);
339 return SEM_GLOBAL_LOCK;
343 * Only one semaphore affected - try to optimize locking.
344 * Optimized locking is possible if no complex operation
345 * is either enqueued or processed right now.
347 * Both facts are tracked by use_global_mode.
349 sem = &sma->sems[sops->sem_num];
352 * Initial check for use_global_lock. Just an optimization,
353 * no locking, no memory barrier.
355 if (!sma->use_global_lock) {
357 * It appears that no complex operation is around.
358 * Acquire the per-semaphore lock.
360 spin_lock(&sem->lock);
362 /* pairs with smp_store_release() */
363 if (!smp_load_acquire(&sma->use_global_lock)) {
364 /* fast path successful! */
365 return sops->sem_num;
367 spin_unlock(&sem->lock);
370 /* slow path: acquire the full lock */
371 ipc_lock_object(&sma->sem_perm);
373 if (sma->use_global_lock == 0) {
375 * The use_global_lock mode ended while we waited for
376 * sma->sem_perm.lock. Thus we must switch to locking
378 * Unlike in the fast path, there is no need to recheck
379 * sma->use_global_lock after we have acquired sem->lock:
380 * We own sma->sem_perm.lock, thus use_global_lock cannot
383 spin_lock(&sem->lock);
385 ipc_unlock_object(&sma->sem_perm);
386 return sops->sem_num;
389 * Not a false alarm, thus continue to use the global lock
390 * mode. No need for complexmode_enter(), this was done by
391 * the caller that has set use_global_mode to non-zero.
393 return SEM_GLOBAL_LOCK;
397 static inline void sem_unlock(struct sem_array *sma, int locknum)
399 if (locknum == SEM_GLOBAL_LOCK) {
401 complexmode_tryleave(sma);
402 ipc_unlock_object(&sma->sem_perm);
404 struct sem *sem = &sma->sems[locknum];
405 spin_unlock(&sem->lock);
410 * sem_lock_(check_) routines are called in the paths where the rwsem
413 * The caller holds the RCU read lock.
415 static inline struct sem_array *sem_obtain_object(struct ipc_namespace *ns, int id)
417 struct kern_ipc_perm *ipcp = ipc_obtain_object_idr(&sem_ids(ns), id);
420 return ERR_CAST(ipcp);
422 return container_of(ipcp, struct sem_array, sem_perm);
425 static inline struct sem_array *sem_obtain_object_check(struct ipc_namespace *ns,
428 struct kern_ipc_perm *ipcp = ipc_obtain_object_check(&sem_ids(ns), id);
431 return ERR_CAST(ipcp);
433 return container_of(ipcp, struct sem_array, sem_perm);
436 static inline void sem_lock_and_putref(struct sem_array *sma)
438 sem_lock(sma, NULL, -1);
439 ipc_rcu_putref(&sma->sem_perm, sem_rcu_free);
442 static inline void sem_rmid(struct ipc_namespace *ns, struct sem_array *s)
444 ipc_rmid(&sem_ids(ns), &s->sem_perm);
447 static struct sem_array *sem_alloc(size_t nsems)
449 struct sem_array *sma;
452 if (nsems > (INT_MAX - sizeof(*sma)) / sizeof(sma->sems[0]))
455 size = sizeof(*sma) + nsems * sizeof(sma->sems[0]);
456 sma = kvmalloc(size, GFP_KERNEL);
460 memset(sma, 0, size);
466 * newary - Create a new semaphore set
468 * @params: ptr to the structure that contains key, semflg and nsems
470 * Called with sem_ids.rwsem held (as a writer)
472 static int newary(struct ipc_namespace *ns, struct ipc_params *params)
475 struct sem_array *sma;
476 key_t key = params->key;
477 int nsems = params->u.nsems;
478 int semflg = params->flg;
483 if (ns->used_sems + nsems > ns->sc_semmns)
486 sma = sem_alloc(nsems);
490 sma->sem_perm.mode = (semflg & S_IRWXUGO);
491 sma->sem_perm.key = key;
493 sma->sem_perm.security = NULL;
494 retval = security_sem_alloc(sma);
500 for (i = 0; i < nsems; i++) {
501 INIT_LIST_HEAD(&sma->sems[i].pending_alter);
502 INIT_LIST_HEAD(&sma->sems[i].pending_const);
503 spin_lock_init(&sma->sems[i].lock);
506 sma->complex_count = 0;
507 sma->use_global_lock = USE_GLOBAL_LOCK_HYSTERESIS;
508 INIT_LIST_HEAD(&sma->pending_alter);
509 INIT_LIST_HEAD(&sma->pending_const);
510 INIT_LIST_HEAD(&sma->list_id);
511 sma->sem_nsems = nsems;
512 sma->sem_ctime = get_seconds();
514 retval = ipc_addid(&sem_ids(ns), &sma->sem_perm, ns->sc_semmni);
516 call_rcu(&sma->sem_perm.rcu, sem_rcu_free);
519 ns->used_sems += nsems;
524 return sma->sem_perm.id;
529 * Called with sem_ids.rwsem and ipcp locked.
531 static inline int sem_security(struct kern_ipc_perm *ipcp, int semflg)
533 struct sem_array *sma;
535 sma = container_of(ipcp, struct sem_array, sem_perm);
536 return security_sem_associate(sma, semflg);
540 * Called with sem_ids.rwsem and ipcp locked.
542 static inline int sem_more_checks(struct kern_ipc_perm *ipcp,
543 struct ipc_params *params)
545 struct sem_array *sma;
547 sma = container_of(ipcp, struct sem_array, sem_perm);
548 if (params->u.nsems > sma->sem_nsems)
554 SYSCALL_DEFINE3(semget, key_t, key, int, nsems, int, semflg)
556 struct ipc_namespace *ns;
557 static const struct ipc_ops sem_ops = {
559 .associate = sem_security,
560 .more_checks = sem_more_checks,
562 struct ipc_params sem_params;
564 ns = current->nsproxy->ipc_ns;
566 if (nsems < 0 || nsems > ns->sc_semmsl)
569 sem_params.key = key;
570 sem_params.flg = semflg;
571 sem_params.u.nsems = nsems;
573 return ipcget(ns, &sem_ids(ns), &sem_ops, &sem_params);
577 * perform_atomic_semop[_slow] - Attempt to perform semaphore
578 * operations on a given array.
579 * @sma: semaphore array
580 * @q: struct sem_queue that describes the operation
582 * Caller blocking are as follows, based the value
583 * indicated by the semaphore operation (sem_op):
585 * (1) >0 never blocks.
586 * (2) 0 (wait-for-zero operation): semval is non-zero.
587 * (3) <0 attempting to decrement semval to a value smaller than zero.
589 * Returns 0 if the operation was possible.
590 * Returns 1 if the operation is impossible, the caller must sleep.
591 * Returns <0 for error codes.
593 static int perform_atomic_semop_slow(struct sem_array *sma, struct sem_queue *q)
595 int result, sem_op, nsops, pid;
605 for (sop = sops; sop < sops + nsops; sop++) {
606 curr = &sma->sems[sop->sem_num];
607 sem_op = sop->sem_op;
608 result = curr->semval;
610 if (!sem_op && result)
619 if (sop->sem_flg & SEM_UNDO) {
620 int undo = un->semadj[sop->sem_num] - sem_op;
621 /* Exceeding the undo range is an error. */
622 if (undo < (-SEMAEM - 1) || undo > SEMAEM)
624 un->semadj[sop->sem_num] = undo;
627 curr->semval = result;
632 while (sop >= sops) {
633 sma->sems[sop->sem_num].sempid = pid;
646 if (sop->sem_flg & IPC_NOWAIT)
653 while (sop >= sops) {
654 sem_op = sop->sem_op;
655 sma->sems[sop->sem_num].semval -= sem_op;
656 if (sop->sem_flg & SEM_UNDO)
657 un->semadj[sop->sem_num] += sem_op;
664 static int perform_atomic_semop(struct sem_array *sma, struct sem_queue *q)
666 int result, sem_op, nsops;
676 if (unlikely(q->dupsop))
677 return perform_atomic_semop_slow(sma, q);
680 * We scan the semaphore set twice, first to ensure that the entire
681 * operation can succeed, therefore avoiding any pointless writes
682 * to shared memory and having to undo such changes in order to block
683 * until the operations can go through.
685 for (sop = sops; sop < sops + nsops; sop++) {
686 curr = &sma->sems[sop->sem_num];
687 sem_op = sop->sem_op;
688 result = curr->semval;
690 if (!sem_op && result)
691 goto would_block; /* wait-for-zero */
700 if (sop->sem_flg & SEM_UNDO) {
701 int undo = un->semadj[sop->sem_num] - sem_op;
703 /* Exceeding the undo range is an error. */
704 if (undo < (-SEMAEM - 1) || undo > SEMAEM)
709 for (sop = sops; sop < sops + nsops; sop++) {
710 curr = &sma->sems[sop->sem_num];
711 sem_op = sop->sem_op;
712 result = curr->semval;
714 if (sop->sem_flg & SEM_UNDO) {
715 int undo = un->semadj[sop->sem_num] - sem_op;
717 un->semadj[sop->sem_num] = undo;
719 curr->semval += sem_op;
720 curr->sempid = q->pid;
727 return sop->sem_flg & IPC_NOWAIT ? -EAGAIN : 1;
730 static inline void wake_up_sem_queue_prepare(struct sem_queue *q, int error,
731 struct wake_q_head *wake_q)
733 wake_q_add(wake_q, q->sleeper);
735 * Rely on the above implicit barrier, such that we can
736 * ensure that we hold reference to the task before setting
737 * q->status. Otherwise we could race with do_exit if the
738 * task is awoken by an external event before calling
741 WRITE_ONCE(q->status, error);
744 static void unlink_queue(struct sem_array *sma, struct sem_queue *q)
748 sma->complex_count--;
751 /** check_restart(sma, q)
752 * @sma: semaphore array
753 * @q: the operation that just completed
755 * update_queue is O(N^2) when it restarts scanning the whole queue of
756 * waiting operations. Therefore this function checks if the restart is
757 * really necessary. It is called after a previously waiting operation
758 * modified the array.
759 * Note that wait-for-zero operations are handled without restart.
761 static inline int check_restart(struct sem_array *sma, struct sem_queue *q)
763 /* pending complex alter operations are too difficult to analyse */
764 if (!list_empty(&sma->pending_alter))
767 /* we were a sleeping complex operation. Too difficult */
771 /* It is impossible that someone waits for the new value:
772 * - complex operations always restart.
773 * - wait-for-zero are handled seperately.
774 * - q is a previously sleeping simple operation that
775 * altered the array. It must be a decrement, because
776 * simple increments never sleep.
777 * - If there are older (higher priority) decrements
778 * in the queue, then they have observed the original
779 * semval value and couldn't proceed. The operation
780 * decremented to value - thus they won't proceed either.
786 * wake_const_ops - wake up non-alter tasks
787 * @sma: semaphore array.
788 * @semnum: semaphore that was modified.
789 * @wake_q: lockless wake-queue head.
791 * wake_const_ops must be called after a semaphore in a semaphore array
792 * was set to 0. If complex const operations are pending, wake_const_ops must
793 * be called with semnum = -1, as well as with the number of each modified
795 * The tasks that must be woken up are added to @wake_q. The return code
796 * is stored in q->pid.
797 * The function returns 1 if at least one operation was completed successfully.
799 static int wake_const_ops(struct sem_array *sma, int semnum,
800 struct wake_q_head *wake_q)
802 struct sem_queue *q, *tmp;
803 struct list_head *pending_list;
804 int semop_completed = 0;
807 pending_list = &sma->pending_const;
809 pending_list = &sma->sems[semnum].pending_const;
811 list_for_each_entry_safe(q, tmp, pending_list, list) {
812 int error = perform_atomic_semop(sma, q);
816 /* operation completed, remove from queue & wakeup */
817 unlink_queue(sma, q);
819 wake_up_sem_queue_prepare(q, error, wake_q);
824 return semop_completed;
828 * do_smart_wakeup_zero - wakeup all wait for zero tasks
829 * @sma: semaphore array
830 * @sops: operations that were performed
831 * @nsops: number of operations
832 * @wake_q: lockless wake-queue head
834 * Checks all required queue for wait-for-zero operations, based
835 * on the actual changes that were performed on the semaphore array.
836 * The function returns 1 if at least one operation was completed successfully.
838 static int do_smart_wakeup_zero(struct sem_array *sma, struct sembuf *sops,
839 int nsops, struct wake_q_head *wake_q)
842 int semop_completed = 0;
845 /* first: the per-semaphore queues, if known */
847 for (i = 0; i < nsops; i++) {
848 int num = sops[i].sem_num;
850 if (sma->sems[num].semval == 0) {
852 semop_completed |= wake_const_ops(sma, num, wake_q);
857 * No sops means modified semaphores not known.
858 * Assume all were changed.
860 for (i = 0; i < sma->sem_nsems; i++) {
861 if (sma->sems[i].semval == 0) {
863 semop_completed |= wake_const_ops(sma, i, wake_q);
868 * If one of the modified semaphores got 0,
869 * then check the global queue, too.
872 semop_completed |= wake_const_ops(sma, -1, wake_q);
874 return semop_completed;
879 * update_queue - look for tasks that can be completed.
880 * @sma: semaphore array.
881 * @semnum: semaphore that was modified.
882 * @wake_q: lockless wake-queue head.
884 * update_queue must be called after a semaphore in a semaphore array
885 * was modified. If multiple semaphores were modified, update_queue must
886 * be called with semnum = -1, as well as with the number of each modified
888 * The tasks that must be woken up are added to @wake_q. The return code
889 * is stored in q->pid.
890 * The function internally checks if const operations can now succeed.
892 * The function return 1 if at least one semop was completed successfully.
894 static int update_queue(struct sem_array *sma, int semnum, struct wake_q_head *wake_q)
896 struct sem_queue *q, *tmp;
897 struct list_head *pending_list;
898 int semop_completed = 0;
901 pending_list = &sma->pending_alter;
903 pending_list = &sma->sems[semnum].pending_alter;
906 list_for_each_entry_safe(q, tmp, pending_list, list) {
909 /* If we are scanning the single sop, per-semaphore list of
910 * one semaphore and that semaphore is 0, then it is not
911 * necessary to scan further: simple increments
912 * that affect only one entry succeed immediately and cannot
913 * be in the per semaphore pending queue, and decrements
914 * cannot be successful if the value is already 0.
916 if (semnum != -1 && sma->sems[semnum].semval == 0)
919 error = perform_atomic_semop(sma, q);
921 /* Does q->sleeper still need to sleep? */
925 unlink_queue(sma, q);
931 do_smart_wakeup_zero(sma, q->sops, q->nsops, wake_q);
932 restart = check_restart(sma, q);
935 wake_up_sem_queue_prepare(q, error, wake_q);
939 return semop_completed;
943 * set_semotime - set sem_otime
944 * @sma: semaphore array
945 * @sops: operations that modified the array, may be NULL
947 * sem_otime is replicated to avoid cache line trashing.
948 * This function sets one instance to the current time.
950 static void set_semotime(struct sem_array *sma, struct sembuf *sops)
953 sma->sems[0].sem_otime = get_seconds();
955 sma->sems[sops[0].sem_num].sem_otime =
961 * do_smart_update - optimized update_queue
962 * @sma: semaphore array
963 * @sops: operations that were performed
964 * @nsops: number of operations
965 * @otime: force setting otime
966 * @wake_q: lockless wake-queue head
968 * do_smart_update() does the required calls to update_queue and wakeup_zero,
969 * based on the actual changes that were performed on the semaphore array.
970 * Note that the function does not do the actual wake-up: the caller is
971 * responsible for calling wake_up_q().
972 * It is safe to perform this call after dropping all locks.
974 static void do_smart_update(struct sem_array *sma, struct sembuf *sops, int nsops,
975 int otime, struct wake_q_head *wake_q)
979 otime |= do_smart_wakeup_zero(sma, sops, nsops, wake_q);
981 if (!list_empty(&sma->pending_alter)) {
982 /* semaphore array uses the global queue - just process it. */
983 otime |= update_queue(sma, -1, wake_q);
987 * No sops, thus the modified semaphores are not
990 for (i = 0; i < sma->sem_nsems; i++)
991 otime |= update_queue(sma, i, wake_q);
994 * Check the semaphores that were increased:
995 * - No complex ops, thus all sleeping ops are
997 * - if we decreased the value, then any sleeping
998 * semaphore ops wont be able to run: If the
999 * previous value was too small, then the new
1000 * value will be too small, too.
1002 for (i = 0; i < nsops; i++) {
1003 if (sops[i].sem_op > 0) {
1004 otime |= update_queue(sma,
1005 sops[i].sem_num, wake_q);
1011 set_semotime(sma, sops);
1015 * check_qop: Test if a queued operation sleeps on the semaphore semnum
1017 static int check_qop(struct sem_array *sma, int semnum, struct sem_queue *q,
1020 struct sembuf *sop = q->blocking;
1023 * Linux always (since 0.99.10) reported a task as sleeping on all
1024 * semaphores. This violates SUS, therefore it was changed to the
1025 * standard compliant behavior.
1026 * Give the administrators a chance to notice that an application
1027 * might misbehave because it relies on the Linux behavior.
1029 pr_info_once("semctl(GETNCNT/GETZCNT) is since 3.16 Single Unix Specification compliant.\n"
1030 "The task %s (%d) triggered the difference, watch for misbehavior.\n",
1031 current->comm, task_pid_nr(current));
1033 if (sop->sem_num != semnum)
1036 if (count_zero && sop->sem_op == 0)
1038 if (!count_zero && sop->sem_op < 0)
1044 /* The following counts are associated to each semaphore:
1045 * semncnt number of tasks waiting on semval being nonzero
1046 * semzcnt number of tasks waiting on semval being zero
1048 * Per definition, a task waits only on the semaphore of the first semop
1049 * that cannot proceed, even if additional operation would block, too.
1051 static int count_semcnt(struct sem_array *sma, ushort semnum,
1054 struct list_head *l;
1055 struct sem_queue *q;
1059 /* First: check the simple operations. They are easy to evaluate */
1061 l = &sma->sems[semnum].pending_const;
1063 l = &sma->sems[semnum].pending_alter;
1065 list_for_each_entry(q, l, list) {
1066 /* all task on a per-semaphore list sleep on exactly
1072 /* Then: check the complex operations. */
1073 list_for_each_entry(q, &sma->pending_alter, list) {
1074 semcnt += check_qop(sma, semnum, q, count_zero);
1077 list_for_each_entry(q, &sma->pending_const, list) {
1078 semcnt += check_qop(sma, semnum, q, count_zero);
1084 /* Free a semaphore set. freeary() is called with sem_ids.rwsem locked
1085 * as a writer and the spinlock for this semaphore set hold. sem_ids.rwsem
1086 * remains locked on exit.
1088 static void freeary(struct ipc_namespace *ns, struct kern_ipc_perm *ipcp)
1090 struct sem_undo *un, *tu;
1091 struct sem_queue *q, *tq;
1092 struct sem_array *sma = container_of(ipcp, struct sem_array, sem_perm);
1094 DEFINE_WAKE_Q(wake_q);
1096 /* Free the existing undo structures for this semaphore set. */
1097 ipc_assert_locked_object(&sma->sem_perm);
1098 list_for_each_entry_safe(un, tu, &sma->list_id, list_id) {
1099 list_del(&un->list_id);
1100 spin_lock(&un->ulp->lock);
1102 list_del_rcu(&un->list_proc);
1103 spin_unlock(&un->ulp->lock);
1107 /* Wake up all pending processes and let them fail with EIDRM. */
1108 list_for_each_entry_safe(q, tq, &sma->pending_const, list) {
1109 unlink_queue(sma, q);
1110 wake_up_sem_queue_prepare(q, -EIDRM, &wake_q);
1113 list_for_each_entry_safe(q, tq, &sma->pending_alter, list) {
1114 unlink_queue(sma, q);
1115 wake_up_sem_queue_prepare(q, -EIDRM, &wake_q);
1117 for (i = 0; i < sma->sem_nsems; i++) {
1118 struct sem *sem = &sma->sems[i];
1119 list_for_each_entry_safe(q, tq, &sem->pending_const, list) {
1120 unlink_queue(sma, q);
1121 wake_up_sem_queue_prepare(q, -EIDRM, &wake_q);
1123 list_for_each_entry_safe(q, tq, &sem->pending_alter, list) {
1124 unlink_queue(sma, q);
1125 wake_up_sem_queue_prepare(q, -EIDRM, &wake_q);
1129 /* Remove the semaphore set from the IDR */
1131 sem_unlock(sma, -1);
1135 ns->used_sems -= sma->sem_nsems;
1136 ipc_rcu_putref(&sma->sem_perm, sem_rcu_free);
1139 static unsigned long copy_semid_to_user(void __user *buf, struct semid64_ds *in, int version)
1143 return copy_to_user(buf, in, sizeof(*in));
1146 struct semid_ds out;
1148 memset(&out, 0, sizeof(out));
1150 ipc64_perm_to_ipc_perm(&in->sem_perm, &out.sem_perm);
1152 out.sem_otime = in->sem_otime;
1153 out.sem_ctime = in->sem_ctime;
1154 out.sem_nsems = in->sem_nsems;
1156 return copy_to_user(buf, &out, sizeof(out));
1163 static time_t get_semotime(struct sem_array *sma)
1168 res = sma->sems[0].sem_otime;
1169 for (i = 1; i < sma->sem_nsems; i++) {
1170 time_t to = sma->sems[i].sem_otime;
1178 static int semctl_nolock(struct ipc_namespace *ns, int semid,
1179 int cmd, int version, void __user *p)
1182 struct sem_array *sma;
1188 struct seminfo seminfo;
1191 err = security_sem_semctl(NULL, cmd);
1195 memset(&seminfo, 0, sizeof(seminfo));
1196 seminfo.semmni = ns->sc_semmni;
1197 seminfo.semmns = ns->sc_semmns;
1198 seminfo.semmsl = ns->sc_semmsl;
1199 seminfo.semopm = ns->sc_semopm;
1200 seminfo.semvmx = SEMVMX;
1201 seminfo.semmnu = SEMMNU;
1202 seminfo.semmap = SEMMAP;
1203 seminfo.semume = SEMUME;
1204 down_read(&sem_ids(ns).rwsem);
1205 if (cmd == SEM_INFO) {
1206 seminfo.semusz = sem_ids(ns).in_use;
1207 seminfo.semaem = ns->used_sems;
1209 seminfo.semusz = SEMUSZ;
1210 seminfo.semaem = SEMAEM;
1212 max_id = ipc_get_maxid(&sem_ids(ns));
1213 up_read(&sem_ids(ns).rwsem);
1214 if (copy_to_user(p, &seminfo, sizeof(struct seminfo)))
1216 return (max_id < 0) ? 0 : max_id;
1221 struct semid64_ds tbuf;
1224 memset(&tbuf, 0, sizeof(tbuf));
1227 if (cmd == SEM_STAT) {
1228 sma = sem_obtain_object(ns, semid);
1233 id = sma->sem_perm.id;
1235 sma = sem_obtain_object_check(ns, semid);
1243 if (ipcperms(ns, &sma->sem_perm, S_IRUGO))
1246 err = security_sem_semctl(sma, cmd);
1250 kernel_to_ipc64_perm(&sma->sem_perm, &tbuf.sem_perm);
1251 tbuf.sem_otime = get_semotime(sma);
1252 tbuf.sem_ctime = sma->sem_ctime;
1253 tbuf.sem_nsems = sma->sem_nsems;
1255 if (copy_semid_to_user(p, &tbuf, version))
1267 static int semctl_setval(struct ipc_namespace *ns, int semid, int semnum,
1270 struct sem_undo *un;
1271 struct sem_array *sma;
1274 DEFINE_WAKE_Q(wake_q);
1276 #if defined(CONFIG_64BIT) && defined(__BIG_ENDIAN)
1277 /* big-endian 64bit */
1280 /* 32bit or little-endian 64bit */
1284 if (val > SEMVMX || val < 0)
1288 sma = sem_obtain_object_check(ns, semid);
1291 return PTR_ERR(sma);
1294 if (semnum < 0 || semnum >= sma->sem_nsems) {
1300 if (ipcperms(ns, &sma->sem_perm, S_IWUGO)) {
1305 err = security_sem_semctl(sma, SETVAL);
1311 sem_lock(sma, NULL, -1);
1313 if (!ipc_valid_object(&sma->sem_perm)) {
1314 sem_unlock(sma, -1);
1319 curr = &sma->sems[semnum];
1321 ipc_assert_locked_object(&sma->sem_perm);
1322 list_for_each_entry(un, &sma->list_id, list_id)
1323 un->semadj[semnum] = 0;
1326 curr->sempid = task_tgid_vnr(current);
1327 sma->sem_ctime = get_seconds();
1328 /* maybe some queued-up processes were waiting for this */
1329 do_smart_update(sma, NULL, 0, 0, &wake_q);
1330 sem_unlock(sma, -1);
1336 static int semctl_main(struct ipc_namespace *ns, int semid, int semnum,
1337 int cmd, void __user *p)
1339 struct sem_array *sma;
1342 ushort fast_sem_io[SEMMSL_FAST];
1343 ushort *sem_io = fast_sem_io;
1344 DEFINE_WAKE_Q(wake_q);
1347 sma = sem_obtain_object_check(ns, semid);
1350 return PTR_ERR(sma);
1353 nsems = sma->sem_nsems;
1356 if (ipcperms(ns, &sma->sem_perm, cmd == SETALL ? S_IWUGO : S_IRUGO))
1357 goto out_rcu_wakeup;
1359 err = security_sem_semctl(sma, cmd);
1361 goto out_rcu_wakeup;
1367 ushort __user *array = p;
1370 sem_lock(sma, NULL, -1);
1371 if (!ipc_valid_object(&sma->sem_perm)) {
1375 if (nsems > SEMMSL_FAST) {
1376 if (!ipc_rcu_getref(&sma->sem_perm)) {
1380 sem_unlock(sma, -1);
1382 sem_io = kvmalloc_array(nsems, sizeof(ushort),
1384 if (sem_io == NULL) {
1385 ipc_rcu_putref(&sma->sem_perm, sem_rcu_free);
1390 sem_lock_and_putref(sma);
1391 if (!ipc_valid_object(&sma->sem_perm)) {
1396 for (i = 0; i < sma->sem_nsems; i++)
1397 sem_io[i] = sma->sems[i].semval;
1398 sem_unlock(sma, -1);
1401 if (copy_to_user(array, sem_io, nsems*sizeof(ushort)))
1408 struct sem_undo *un;
1410 if (!ipc_rcu_getref(&sma->sem_perm)) {
1412 goto out_rcu_wakeup;
1416 if (nsems > SEMMSL_FAST) {
1417 sem_io = kvmalloc_array(nsems, sizeof(ushort),
1419 if (sem_io == NULL) {
1420 ipc_rcu_putref(&sma->sem_perm, sem_rcu_free);
1425 if (copy_from_user(sem_io, p, nsems*sizeof(ushort))) {
1426 ipc_rcu_putref(&sma->sem_perm, sem_rcu_free);
1431 for (i = 0; i < nsems; i++) {
1432 if (sem_io[i] > SEMVMX) {
1433 ipc_rcu_putref(&sma->sem_perm, sem_rcu_free);
1439 sem_lock_and_putref(sma);
1440 if (!ipc_valid_object(&sma->sem_perm)) {
1445 for (i = 0; i < nsems; i++) {
1446 sma->sems[i].semval = sem_io[i];
1447 sma->sems[i].sempid = task_tgid_vnr(current);
1450 ipc_assert_locked_object(&sma->sem_perm);
1451 list_for_each_entry(un, &sma->list_id, list_id) {
1452 for (i = 0; i < nsems; i++)
1455 sma->sem_ctime = get_seconds();
1456 /* maybe some queued-up processes were waiting for this */
1457 do_smart_update(sma, NULL, 0, 0, &wake_q);
1461 /* GETVAL, GETPID, GETNCTN, GETZCNT: fall-through */
1464 if (semnum < 0 || semnum >= nsems)
1465 goto out_rcu_wakeup;
1467 sem_lock(sma, NULL, -1);
1468 if (!ipc_valid_object(&sma->sem_perm)) {
1472 curr = &sma->sems[semnum];
1482 err = count_semcnt(sma, semnum, 0);
1485 err = count_semcnt(sma, semnum, 1);
1490 sem_unlock(sma, -1);
1495 if (sem_io != fast_sem_io)
1500 static inline unsigned long
1501 copy_semid_from_user(struct semid64_ds *out, void __user *buf, int version)
1505 if (copy_from_user(out, buf, sizeof(*out)))
1510 struct semid_ds tbuf_old;
1512 if (copy_from_user(&tbuf_old, buf, sizeof(tbuf_old)))
1515 out->sem_perm.uid = tbuf_old.sem_perm.uid;
1516 out->sem_perm.gid = tbuf_old.sem_perm.gid;
1517 out->sem_perm.mode = tbuf_old.sem_perm.mode;
1527 * This function handles some semctl commands which require the rwsem
1528 * to be held in write mode.
1529 * NOTE: no locks must be held, the rwsem is taken inside this function.
1531 static int semctl_down(struct ipc_namespace *ns, int semid,
1532 int cmd, int version, void __user *p)
1534 struct sem_array *sma;
1536 struct semid64_ds semid64;
1537 struct kern_ipc_perm *ipcp;
1539 if (cmd == IPC_SET) {
1540 if (copy_semid_from_user(&semid64, p, version))
1544 down_write(&sem_ids(ns).rwsem);
1547 ipcp = ipcctl_pre_down_nolock(ns, &sem_ids(ns), semid, cmd,
1548 &semid64.sem_perm, 0);
1550 err = PTR_ERR(ipcp);
1554 sma = container_of(ipcp, struct sem_array, sem_perm);
1556 err = security_sem_semctl(sma, cmd);
1562 sem_lock(sma, NULL, -1);
1563 /* freeary unlocks the ipc object and rcu */
1567 sem_lock(sma, NULL, -1);
1568 err = ipc_update_perm(&semid64.sem_perm, ipcp);
1571 sma->sem_ctime = get_seconds();
1579 sem_unlock(sma, -1);
1583 up_write(&sem_ids(ns).rwsem);
1587 SYSCALL_DEFINE4(semctl, int, semid, int, semnum, int, cmd, unsigned long, arg)
1590 struct ipc_namespace *ns;
1591 void __user *p = (void __user *)arg;
1596 version = ipc_parse_version(&cmd);
1597 ns = current->nsproxy->ipc_ns;
1604 return semctl_nolock(ns, semid, cmd, version, p);
1611 return semctl_main(ns, semid, semnum, cmd, p);
1613 return semctl_setval(ns, semid, semnum, arg);
1616 return semctl_down(ns, semid, cmd, version, p);
1622 /* If the task doesn't already have a undo_list, then allocate one
1623 * here. We guarantee there is only one thread using this undo list,
1624 * and current is THE ONE
1626 * If this allocation and assignment succeeds, but later
1627 * portions of this code fail, there is no need to free the sem_undo_list.
1628 * Just let it stay associated with the task, and it'll be freed later
1631 * This can block, so callers must hold no locks.
1633 static inline int get_undo_list(struct sem_undo_list **undo_listp)
1635 struct sem_undo_list *undo_list;
1637 undo_list = current->sysvsem.undo_list;
1639 undo_list = kzalloc(sizeof(*undo_list), GFP_KERNEL);
1640 if (undo_list == NULL)
1642 spin_lock_init(&undo_list->lock);
1643 refcount_set(&undo_list->refcnt, 1);
1644 INIT_LIST_HEAD(&undo_list->list_proc);
1646 current->sysvsem.undo_list = undo_list;
1648 *undo_listp = undo_list;
1652 static struct sem_undo *__lookup_undo(struct sem_undo_list *ulp, int semid)
1654 struct sem_undo *un;
1656 list_for_each_entry_rcu(un, &ulp->list_proc, list_proc) {
1657 if (un->semid == semid)
1663 static struct sem_undo *lookup_undo(struct sem_undo_list *ulp, int semid)
1665 struct sem_undo *un;
1667 assert_spin_locked(&ulp->lock);
1669 un = __lookup_undo(ulp, semid);
1671 list_del_rcu(&un->list_proc);
1672 list_add_rcu(&un->list_proc, &ulp->list_proc);
1678 * find_alloc_undo - lookup (and if not present create) undo array
1680 * @semid: semaphore array id
1682 * The function looks up (and if not present creates) the undo structure.
1683 * The size of the undo structure depends on the size of the semaphore
1684 * array, thus the alloc path is not that straightforward.
1685 * Lifetime-rules: sem_undo is rcu-protected, on success, the function
1686 * performs a rcu_read_lock().
1688 static struct sem_undo *find_alloc_undo(struct ipc_namespace *ns, int semid)
1690 struct sem_array *sma;
1691 struct sem_undo_list *ulp;
1692 struct sem_undo *un, *new;
1695 error = get_undo_list(&ulp);
1697 return ERR_PTR(error);
1700 spin_lock(&ulp->lock);
1701 un = lookup_undo(ulp, semid);
1702 spin_unlock(&ulp->lock);
1703 if (likely(un != NULL))
1706 /* no undo structure around - allocate one. */
1707 /* step 1: figure out the size of the semaphore array */
1708 sma = sem_obtain_object_check(ns, semid);
1711 return ERR_CAST(sma);
1714 nsems = sma->sem_nsems;
1715 if (!ipc_rcu_getref(&sma->sem_perm)) {
1717 un = ERR_PTR(-EIDRM);
1722 /* step 2: allocate new undo structure */
1723 new = kzalloc(sizeof(struct sem_undo) + sizeof(short)*nsems, GFP_KERNEL);
1725 ipc_rcu_putref(&sma->sem_perm, sem_rcu_free);
1726 return ERR_PTR(-ENOMEM);
1729 /* step 3: Acquire the lock on semaphore array */
1731 sem_lock_and_putref(sma);
1732 if (!ipc_valid_object(&sma->sem_perm)) {
1733 sem_unlock(sma, -1);
1736 un = ERR_PTR(-EIDRM);
1739 spin_lock(&ulp->lock);
1742 * step 4: check for races: did someone else allocate the undo struct?
1744 un = lookup_undo(ulp, semid);
1749 /* step 5: initialize & link new undo structure */
1750 new->semadj = (short *) &new[1];
1753 assert_spin_locked(&ulp->lock);
1754 list_add_rcu(&new->list_proc, &ulp->list_proc);
1755 ipc_assert_locked_object(&sma->sem_perm);
1756 list_add(&new->list_id, &sma->list_id);
1760 spin_unlock(&ulp->lock);
1761 sem_unlock(sma, -1);
1766 SYSCALL_DEFINE4(semtimedop, int, semid, struct sembuf __user *, tsops,
1767 unsigned, nsops, const struct timespec __user *, timeout)
1769 int error = -EINVAL;
1770 struct sem_array *sma;
1771 struct sembuf fast_sops[SEMOPM_FAST];
1772 struct sembuf *sops = fast_sops, *sop;
1773 struct sem_undo *un;
1775 bool undos = false, alter = false, dupsop = false;
1776 struct sem_queue queue;
1777 unsigned long dup = 0, jiffies_left = 0;
1778 struct ipc_namespace *ns;
1780 ns = current->nsproxy->ipc_ns;
1782 if (nsops < 1 || semid < 0)
1784 if (nsops > ns->sc_semopm)
1786 if (nsops > SEMOPM_FAST) {
1787 sops = kvmalloc(sizeof(*sops)*nsops, GFP_KERNEL);
1792 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);
1812 for (sop = sops; sop < sops + nsops; sop++) {
1813 unsigned long mask = 1ULL << ((sop->sem_num) % BITS_PER_LONG);
1815 if (sop->sem_num >= max)
1817 if (sop->sem_flg & SEM_UNDO)
1821 * There was a previous alter access that appears
1822 * to have accessed the same semaphore, thus use
1823 * the dupsop logic. "appears", because the detection
1824 * can only check % BITS_PER_LONG.
1828 if (sop->sem_op != 0) {
1835 /* On success, find_alloc_undo takes the rcu_read_lock */
1836 un = find_alloc_undo(ns, semid);
1838 error = PTR_ERR(un);
1846 sma = sem_obtain_object_check(ns, semid);
1849 error = PTR_ERR(sma);
1854 if (max >= sma->sem_nsems) {
1860 if (ipcperms(ns, &sma->sem_perm, alter ? S_IWUGO : S_IRUGO)) {
1865 error = security_sem_semop(sma, sops, nsops, alter);
1872 locknum = sem_lock(sma, sops, nsops);
1874 * We eventually might perform the following check in a lockless
1875 * fashion, considering ipc_valid_object() locking constraints.
1876 * If nsops == 1 and there is no contention for sem_perm.lock, then
1877 * only a per-semaphore lock is held and it's OK to proceed with the
1878 * check below. More details on the fine grained locking scheme
1879 * entangled here and why it's RMID race safe on comments at sem_lock()
1881 if (!ipc_valid_object(&sma->sem_perm))
1882 goto out_unlock_free;
1884 * semid identifiers are not unique - find_alloc_undo may have
1885 * allocated an undo structure, it was invalidated by an RMID
1886 * and now a new array with received the same id. Check and fail.
1887 * This case can be detected checking un->semid. The existence of
1888 * "un" itself is guaranteed by rcu.
1890 if (un && un->semid == -1)
1891 goto out_unlock_free;
1894 queue.nsops = nsops;
1896 queue.pid = task_tgid_vnr(current);
1897 queue.alter = alter;
1898 queue.dupsop = dupsop;
1900 error = perform_atomic_semop(sma, &queue);
1901 if (error == 0) { /* non-blocking succesfull path */
1902 DEFINE_WAKE_Q(wake_q);
1905 * If the operation was successful, then do
1906 * the required updates.
1909 do_smart_update(sma, sops, nsops, 1, &wake_q);
1911 set_semotime(sma, sops);
1913 sem_unlock(sma, locknum);
1919 if (error < 0) /* non-blocking error path */
1920 goto out_unlock_free;
1923 * We need to sleep on this operation, so we put the current
1924 * task into the pending queue and go to sleep.
1928 curr = &sma->sems[sops->sem_num];
1931 if (sma->complex_count) {
1932 list_add_tail(&queue.list,
1933 &sma->pending_alter);
1936 list_add_tail(&queue.list,
1937 &curr->pending_alter);
1940 list_add_tail(&queue.list, &curr->pending_const);
1943 if (!sma->complex_count)
1947 list_add_tail(&queue.list, &sma->pending_alter);
1949 list_add_tail(&queue.list, &sma->pending_const);
1951 sma->complex_count++;
1955 queue.status = -EINTR;
1956 queue.sleeper = current;
1958 __set_current_state(TASK_INTERRUPTIBLE);
1959 sem_unlock(sma, locknum);
1963 jiffies_left = schedule_timeout(jiffies_left);
1968 * fastpath: the semop has completed, either successfully or
1969 * not, from the syscall pov, is quite irrelevant to us at this
1970 * point; we're done.
1972 * We _do_ care, nonetheless, about being awoken by a signal or
1973 * spuriously. The queue.status is checked again in the
1974 * slowpath (aka after taking sem_lock), such that we can detect
1975 * scenarios where we were awakened externally, during the
1976 * window between wake_q_add() and wake_up_q().
1978 error = READ_ONCE(queue.status);
1979 if (error != -EINTR) {
1981 * User space could assume that semop() is a memory
1982 * barrier: Without the mb(), the cpu could
1983 * speculatively read in userspace stale data that was
1984 * overwritten by the previous owner of the semaphore.
1991 locknum = sem_lock(sma, sops, nsops);
1993 if (!ipc_valid_object(&sma->sem_perm))
1994 goto out_unlock_free;
1996 error = READ_ONCE(queue.status);
1999 * If queue.status != -EINTR we are woken up by another process.
2000 * Leave without unlink_queue(), but with sem_unlock().
2002 if (error != -EINTR)
2003 goto out_unlock_free;
2006 * If an interrupt occurred we have to clean up the queue.
2008 if (timeout && jiffies_left == 0)
2010 } while (error == -EINTR && !signal_pending(current)); /* spurious */
2012 unlink_queue(sma, &queue);
2015 sem_unlock(sma, locknum);
2018 if (sops != fast_sops)
2023 SYSCALL_DEFINE3(semop, int, semid, struct sembuf __user *, tsops,
2026 return sys_semtimedop(semid, tsops, nsops, NULL);
2029 /* If CLONE_SYSVSEM is set, establish sharing of SEM_UNDO state between
2030 * parent and child tasks.
2033 int copy_semundo(unsigned long clone_flags, struct task_struct *tsk)
2035 struct sem_undo_list *undo_list;
2038 if (clone_flags & CLONE_SYSVSEM) {
2039 error = get_undo_list(&undo_list);
2042 refcount_inc(&undo_list->refcnt);
2043 tsk->sysvsem.undo_list = undo_list;
2045 tsk->sysvsem.undo_list = NULL;
2051 * add semadj values to semaphores, free undo structures.
2052 * undo structures are not freed when semaphore arrays are destroyed
2053 * so some of them may be out of date.
2054 * IMPLEMENTATION NOTE: There is some confusion over whether the
2055 * set of adjustments that needs to be done should be done in an atomic
2056 * manner or not. That is, if we are attempting to decrement the semval
2057 * should we queue up and wait until we can do so legally?
2058 * The original implementation attempted to do this (queue and wait).
2059 * The current implementation does not do so. The POSIX standard
2060 * and SVID should be consulted to determine what behavior is mandated.
2062 void exit_sem(struct task_struct *tsk)
2064 struct sem_undo_list *ulp;
2066 ulp = tsk->sysvsem.undo_list;
2069 tsk->sysvsem.undo_list = NULL;
2071 if (!refcount_dec_and_test(&ulp->refcnt))
2075 struct sem_array *sma;
2076 struct sem_undo *un;
2078 DEFINE_WAKE_Q(wake_q);
2083 un = list_entry_rcu(ulp->list_proc.next,
2084 struct sem_undo, list_proc);
2085 if (&un->list_proc == &ulp->list_proc) {
2087 * We must wait for freeary() before freeing this ulp,
2088 * in case we raced with last sem_undo. There is a small
2089 * possibility where we exit while freeary() didn't
2090 * finish unlocking sem_undo_list.
2092 spin_lock(&ulp->lock);
2093 spin_unlock(&ulp->lock);
2097 spin_lock(&ulp->lock);
2099 spin_unlock(&ulp->lock);
2101 /* exit_sem raced with IPC_RMID, nothing to do */
2107 sma = sem_obtain_object_check(tsk->nsproxy->ipc_ns, semid);
2108 /* exit_sem raced with IPC_RMID, nothing to do */
2114 sem_lock(sma, NULL, -1);
2115 /* exit_sem raced with IPC_RMID, nothing to do */
2116 if (!ipc_valid_object(&sma->sem_perm)) {
2117 sem_unlock(sma, -1);
2121 un = __lookup_undo(ulp, semid);
2123 /* exit_sem raced with IPC_RMID+semget() that created
2124 * exactly the same semid. Nothing to do.
2126 sem_unlock(sma, -1);
2131 /* remove un from the linked lists */
2132 ipc_assert_locked_object(&sma->sem_perm);
2133 list_del(&un->list_id);
2135 /* we are the last process using this ulp, acquiring ulp->lock
2136 * isn't required. Besides that, we are also protected against
2137 * IPC_RMID as we hold sma->sem_perm lock now
2139 list_del_rcu(&un->list_proc);
2141 /* perform adjustments registered in un */
2142 for (i = 0; i < sma->sem_nsems; i++) {
2143 struct sem *semaphore = &sma->sems[i];
2144 if (un->semadj[i]) {
2145 semaphore->semval += un->semadj[i];
2147 * Range checks of the new semaphore value,
2148 * not defined by sus:
2149 * - Some unices ignore the undo entirely
2150 * (e.g. HP UX 11i 11.22, Tru64 V5.1)
2151 * - some cap the value (e.g. FreeBSD caps
2152 * at 0, but doesn't enforce SEMVMX)
2154 * Linux caps the semaphore value, both at 0
2157 * Manfred <manfred@colorfullife.com>
2159 if (semaphore->semval < 0)
2160 semaphore->semval = 0;
2161 if (semaphore->semval > SEMVMX)
2162 semaphore->semval = SEMVMX;
2163 semaphore->sempid = task_tgid_vnr(current);
2166 /* maybe some queued-up processes were waiting for this */
2167 do_smart_update(sma, NULL, 0, 1, &wake_q);
2168 sem_unlock(sma, -1);
2177 #ifdef CONFIG_PROC_FS
2178 static int sysvipc_sem_proc_show(struct seq_file *s, void *it)
2180 struct user_namespace *user_ns = seq_user_ns(s);
2181 struct kern_ipc_perm *ipcp = it;
2182 struct sem_array *sma = container_of(ipcp, struct sem_array, sem_perm);
2186 * The proc interface isn't aware of sem_lock(), it calls
2187 * ipc_lock_object() directly (in sysvipc_find_ipc).
2188 * In order to stay compatible with sem_lock(), we must
2189 * enter / leave complex_mode.
2191 complexmode_enter(sma);
2193 sem_otime = get_semotime(sma);
2196 "%10d %10d %4o %10u %5u %5u %5u %5u %10lu %10lu\n",
2201 from_kuid_munged(user_ns, sma->sem_perm.uid),
2202 from_kgid_munged(user_ns, sma->sem_perm.gid),
2203 from_kuid_munged(user_ns, sma->sem_perm.cuid),
2204 from_kgid_munged(user_ns, sma->sem_perm.cgid),
2208 complexmode_tryleave(sma);