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>
90 /* One semaphore structure for each semaphore in the system. */
92 int semval
; /* current value */
94 * PID of the process that last modified the semaphore. For
95 * Linux, specifically these are:
97 * - semctl, via SETVAL and SETALL.
98 * - at task exit when performing undo adjustments (see exit_sem).
101 spinlock_t lock
; /* spinlock for fine-grained semtimedop */
102 struct list_head pending_alter
; /* pending single-sop operations */
103 /* that alter the semaphore */
104 struct list_head pending_const
; /* pending single-sop operations */
105 /* that do not alter the semaphore*/
106 time_t sem_otime
; /* candidate for sem_otime */
107 } ____cacheline_aligned_in_smp
;
109 /* One queue for each sleeping process in the system. */
111 struct list_head list
; /* queue of pending operations */
112 struct task_struct
*sleeper
; /* this process */
113 struct sem_undo
*undo
; /* undo structure */
114 int pid
; /* process id of requesting process */
115 int status
; /* completion status of operation */
116 struct sembuf
*sops
; /* array of pending operations */
117 struct sembuf
*blocking
; /* the operation that blocked */
118 int nsops
; /* number of operations */
119 bool alter
; /* does *sops alter the array? */
120 bool dupsop
; /* sops on more than one sem_num */
123 /* Each task has a list of undo requests. They are executed automatically
124 * when the process exits.
127 struct list_head list_proc
; /* per-process list: *
128 * all undos from one process
130 struct rcu_head rcu
; /* rcu struct for sem_undo */
131 struct sem_undo_list
*ulp
; /* back ptr to sem_undo_list */
132 struct list_head list_id
; /* per semaphore array list:
133 * all undos for one array */
134 int semid
; /* semaphore set identifier */
135 short *semadj
; /* array of adjustments */
136 /* one per semaphore */
139 /* sem_undo_list controls shared access to the list of sem_undo structures
140 * that may be shared among all a CLONE_SYSVSEM task group.
142 struct sem_undo_list
{
145 struct list_head list_proc
;
149 #define sem_ids(ns) ((ns)->ids[IPC_SEM_IDS])
151 #define sem_checkid(sma, semid) ipc_checkid(&sma->sem_perm, semid)
153 static int newary(struct ipc_namespace
*, struct ipc_params
*);
154 static void freeary(struct ipc_namespace
*, struct kern_ipc_perm
*);
155 #ifdef CONFIG_PROC_FS
156 static int sysvipc_sem_proc_show(struct seq_file
*s
, void *it
);
159 #define SEMMSL_FAST 256 /* 512 bytes on stack */
160 #define SEMOPM_FAST 64 /* ~ 372 bytes on stack */
163 * Switching from the mode suitable for simple ops
164 * to the mode for complex ops is costly. Therefore:
165 * use some hysteresis
167 #define USE_GLOBAL_LOCK_HYSTERESIS 10
171 * a) global sem_lock() for read/write
173 * sem_array.complex_count,
174 * sem_array.pending{_alter,_const},
177 * b) global or semaphore sem_lock() for read/write:
178 * sem_array.sem_base[i].pending_{const,alter}:
181 * sem_undo_list.list_proc:
182 * * undo_list->lock for write
185 * * global sem_lock() for write
186 * * either local or global sem_lock() for read.
189 * Most ordering is enforced by using spin_lock() and spin_unlock().
190 * The special case is use_global_lock:
191 * Setting it from non-zero to 0 is a RELEASE, this is ensured by
192 * using smp_store_release().
193 * Testing if it is non-zero is an ACQUIRE, this is ensured by using
194 * smp_load_acquire().
195 * Setting it from 0 to non-zero must be ordered with regards to
196 * this smp_load_acquire(), this is guaranteed because the smp_load_acquire()
197 * is inside a spin_lock() and after a write from 0 to non-zero a
198 * spin_lock()+spin_unlock() is done.
201 #define sc_semmsl sem_ctls[0]
202 #define sc_semmns sem_ctls[1]
203 #define sc_semopm sem_ctls[2]
204 #define sc_semmni sem_ctls[3]
206 void sem_init_ns(struct ipc_namespace
*ns
)
208 ns
->sc_semmsl
= SEMMSL
;
209 ns
->sc_semmns
= SEMMNS
;
210 ns
->sc_semopm
= SEMOPM
;
211 ns
->sc_semmni
= SEMMNI
;
213 ipc_init_ids(&ns
->ids
[IPC_SEM_IDS
]);
217 void sem_exit_ns(struct ipc_namespace
*ns
)
219 free_ipcs(ns
, &sem_ids(ns
), freeary
);
220 idr_destroy(&ns
->ids
[IPC_SEM_IDS
].ipcs_idr
);
224 void __init
sem_init(void)
226 sem_init_ns(&init_ipc_ns
);
227 ipc_init_proc_interface("sysvipc/sem",
228 " key semid perms nsems uid gid cuid cgid otime ctime\n",
229 IPC_SEM_IDS
, sysvipc_sem_proc_show
);
233 * unmerge_queues - unmerge queues, if possible.
234 * @sma: semaphore array
236 * The function unmerges the wait queues if complex_count is 0.
237 * It must be called prior to dropping the global semaphore array lock.
239 static void unmerge_queues(struct sem_array
*sma
)
241 struct sem_queue
*q
, *tq
;
243 /* complex operations still around? */
244 if (sma
->complex_count
)
247 * We will switch back to simple mode.
248 * Move all pending operation back into the per-semaphore
251 list_for_each_entry_safe(q
, tq
, &sma
->pending_alter
, list
) {
253 curr
= &sma
->sem_base
[q
->sops
[0].sem_num
];
255 list_add_tail(&q
->list
, &curr
->pending_alter
);
257 INIT_LIST_HEAD(&sma
->pending_alter
);
261 * merge_queues - merge single semop queues into global queue
262 * @sma: semaphore array
264 * This function merges all per-semaphore queues into the global queue.
265 * It is necessary to achieve FIFO ordering for the pending single-sop
266 * operations when a multi-semop operation must sleep.
267 * Only the alter operations must be moved, the const operations can stay.
269 static void merge_queues(struct sem_array
*sma
)
272 for (i
= 0; i
< sma
->sem_nsems
; i
++) {
273 struct sem
*sem
= sma
->sem_base
+ i
;
275 list_splice_init(&sem
->pending_alter
, &sma
->pending_alter
);
279 static void sem_rcu_free(struct rcu_head
*head
)
281 struct ipc_rcu
*p
= container_of(head
, struct ipc_rcu
, rcu
);
282 struct sem_array
*sma
= ipc_rcu_to_struct(p
);
284 security_sem_free(sma
);
289 * Enter the mode suitable for non-simple operations:
290 * Caller must own sem_perm.lock.
292 static void complexmode_enter(struct sem_array
*sma
)
297 if (sma
->use_global_lock
> 0) {
299 * We are already in global lock mode.
300 * Nothing to do, just reset the
301 * counter until we return to simple mode.
303 sma
->use_global_lock
= USE_GLOBAL_LOCK_HYSTERESIS
;
306 sma
->use_global_lock
= USE_GLOBAL_LOCK_HYSTERESIS
;
308 for (i
= 0; i
< sma
->sem_nsems
; i
++) {
309 sem
= sma
->sem_base
+ i
;
310 spin_lock(&sem
->lock
);
311 spin_unlock(&sem
->lock
);
316 * Try to leave the mode that disallows simple operations:
317 * Caller must own sem_perm.lock.
319 static void complexmode_tryleave(struct sem_array
*sma
)
321 if (sma
->complex_count
) {
322 /* Complex ops are sleeping.
323 * We must stay in complex mode
327 if (sma
->use_global_lock
== 1) {
329 * Immediately after setting use_global_lock to 0,
330 * a simple op can start. Thus: all memory writes
331 * performed by the current operation must be visible
332 * before we set use_global_lock to 0.
334 smp_store_release(&sma
->use_global_lock
, 0);
336 sma
->use_global_lock
--;
340 #define SEM_GLOBAL_LOCK (-1)
342 * If the request contains only one semaphore operation, and there are
343 * no complex transactions pending, lock only the semaphore involved.
344 * Otherwise, lock the entire semaphore array, since we either have
345 * multiple semaphores in our own semops, or we need to look at
346 * semaphores from other pending complex operations.
348 static inline int sem_lock(struct sem_array
*sma
, struct sembuf
*sops
,
354 /* Complex operation - acquire a full lock */
355 ipc_lock_object(&sma
->sem_perm
);
357 /* Prevent parallel simple ops */
358 complexmode_enter(sma
);
359 return SEM_GLOBAL_LOCK
;
363 * Only one semaphore affected - try to optimize locking.
364 * Optimized locking is possible if no complex operation
365 * is either enqueued or processed right now.
367 * Both facts are tracked by use_global_mode.
369 sem
= sma
->sem_base
+ sops
->sem_num
;
372 * Initial check for use_global_lock. Just an optimization,
373 * no locking, no memory barrier.
375 if (!sma
->use_global_lock
) {
377 * It appears that no complex operation is around.
378 * Acquire the per-semaphore lock.
380 spin_lock(&sem
->lock
);
382 /* pairs with smp_store_release() */
383 if (!smp_load_acquire(&sma
->use_global_lock
)) {
384 /* fast path successful! */
385 return sops
->sem_num
;
387 spin_unlock(&sem
->lock
);
390 /* slow path: acquire the full lock */
391 ipc_lock_object(&sma
->sem_perm
);
393 if (sma
->use_global_lock
== 0) {
395 * The use_global_lock mode ended while we waited for
396 * sma->sem_perm.lock. Thus we must switch to locking
398 * Unlike in the fast path, there is no need to recheck
399 * sma->use_global_lock after we have acquired sem->lock:
400 * We own sma->sem_perm.lock, thus use_global_lock cannot
403 spin_lock(&sem
->lock
);
405 ipc_unlock_object(&sma
->sem_perm
);
406 return sops
->sem_num
;
409 * Not a false alarm, thus continue to use the global lock
410 * mode. No need for complexmode_enter(), this was done by
411 * the caller that has set use_global_mode to non-zero.
413 return SEM_GLOBAL_LOCK
;
417 static inline void sem_unlock(struct sem_array
*sma
, int locknum
)
419 if (locknum
== SEM_GLOBAL_LOCK
) {
421 complexmode_tryleave(sma
);
422 ipc_unlock_object(&sma
->sem_perm
);
424 struct sem
*sem
= sma
->sem_base
+ locknum
;
425 spin_unlock(&sem
->lock
);
430 * sem_lock_(check_) routines are called in the paths where the rwsem
433 * The caller holds the RCU read lock.
435 static inline struct sem_array
*sem_obtain_object(struct ipc_namespace
*ns
, int id
)
437 struct kern_ipc_perm
*ipcp
= ipc_obtain_object_idr(&sem_ids(ns
), id
);
440 return ERR_CAST(ipcp
);
442 return container_of(ipcp
, struct sem_array
, sem_perm
);
445 static inline struct sem_array
*sem_obtain_object_check(struct ipc_namespace
*ns
,
448 struct kern_ipc_perm
*ipcp
= ipc_obtain_object_check(&sem_ids(ns
), id
);
451 return ERR_CAST(ipcp
);
453 return container_of(ipcp
, struct sem_array
, sem_perm
);
456 static inline void sem_lock_and_putref(struct sem_array
*sma
)
458 sem_lock(sma
, NULL
, -1);
459 ipc_rcu_putref(sma
, sem_rcu_free
);
462 static inline void sem_rmid(struct ipc_namespace
*ns
, struct sem_array
*s
)
464 ipc_rmid(&sem_ids(ns
), &s
->sem_perm
);
468 * newary - Create a new semaphore set
470 * @params: ptr to the structure that contains key, semflg and nsems
472 * Called with sem_ids.rwsem held (as a writer)
474 static int newary(struct ipc_namespace
*ns
, struct ipc_params
*params
)
478 struct sem_array
*sma
;
480 key_t key
= params
->key
;
481 int nsems
= params
->u
.nsems
;
482 int semflg
= params
->flg
;
487 if (ns
->used_sems
+ nsems
> ns
->sc_semmns
)
490 size
= sizeof(*sma
) + nsems
* sizeof(struct sem
);
491 sma
= ipc_rcu_alloc(size
);
495 memset(sma
, 0, size
);
497 sma
->sem_perm
.mode
= (semflg
& S_IRWXUGO
);
498 sma
->sem_perm
.key
= key
;
500 sma
->sem_perm
.security
= NULL
;
501 retval
= security_sem_alloc(sma
);
503 ipc_rcu_putref(sma
, ipc_rcu_free
);
507 sma
->sem_base
= (struct sem
*) &sma
[1];
509 for (i
= 0; i
< nsems
; i
++) {
510 INIT_LIST_HEAD(&sma
->sem_base
[i
].pending_alter
);
511 INIT_LIST_HEAD(&sma
->sem_base
[i
].pending_const
);
512 spin_lock_init(&sma
->sem_base
[i
].lock
);
515 sma
->complex_count
= 0;
516 sma
->use_global_lock
= USE_GLOBAL_LOCK_HYSTERESIS
;
517 INIT_LIST_HEAD(&sma
->pending_alter
);
518 INIT_LIST_HEAD(&sma
->pending_const
);
519 INIT_LIST_HEAD(&sma
->list_id
);
520 sma
->sem_nsems
= nsems
;
521 sma
->sem_ctime
= get_seconds();
523 id
= ipc_addid(&sem_ids(ns
), &sma
->sem_perm
, ns
->sc_semmni
);
525 ipc_rcu_putref(sma
, sem_rcu_free
);
528 ns
->used_sems
+= nsems
;
533 return sma
->sem_perm
.id
;
538 * Called with sem_ids.rwsem and ipcp locked.
540 static inline int sem_security(struct kern_ipc_perm
*ipcp
, int semflg
)
542 struct sem_array
*sma
;
544 sma
= container_of(ipcp
, struct sem_array
, sem_perm
);
545 return security_sem_associate(sma
, semflg
);
549 * Called with sem_ids.rwsem and ipcp locked.
551 static inline int sem_more_checks(struct kern_ipc_perm
*ipcp
,
552 struct ipc_params
*params
)
554 struct sem_array
*sma
;
556 sma
= container_of(ipcp
, struct sem_array
, sem_perm
);
557 if (params
->u
.nsems
> sma
->sem_nsems
)
563 SYSCALL_DEFINE3(semget
, key_t
, key
, int, nsems
, int, semflg
)
565 struct ipc_namespace
*ns
;
566 static const struct ipc_ops sem_ops
= {
568 .associate
= sem_security
,
569 .more_checks
= sem_more_checks
,
571 struct ipc_params sem_params
;
573 ns
= current
->nsproxy
->ipc_ns
;
575 if (nsems
< 0 || nsems
> ns
->sc_semmsl
)
578 sem_params
.key
= key
;
579 sem_params
.flg
= semflg
;
580 sem_params
.u
.nsems
= nsems
;
582 return ipcget(ns
, &sem_ids(ns
), &sem_ops
, &sem_params
);
586 * perform_atomic_semop[_slow] - Attempt to perform semaphore
587 * operations on a given array.
588 * @sma: semaphore array
589 * @q: struct sem_queue that describes the operation
591 * Caller blocking are as follows, based the value
592 * indicated by the semaphore operation (sem_op):
594 * (1) >0 never blocks.
595 * (2) 0 (wait-for-zero operation): semval is non-zero.
596 * (3) <0 attempting to decrement semval to a value smaller than zero.
598 * Returns 0 if the operation was possible.
599 * Returns 1 if the operation is impossible, the caller must sleep.
600 * Returns <0 for error codes.
602 static int perform_atomic_semop_slow(struct sem_array
*sma
, struct sem_queue
*q
)
604 int result
, sem_op
, nsops
, pid
;
614 for (sop
= sops
; sop
< sops
+ nsops
; sop
++) {
615 curr
= sma
->sem_base
+ sop
->sem_num
;
616 sem_op
= sop
->sem_op
;
617 result
= curr
->semval
;
619 if (!sem_op
&& result
)
628 if (sop
->sem_flg
& SEM_UNDO
) {
629 int undo
= un
->semadj
[sop
->sem_num
] - sem_op
;
630 /* Exceeding the undo range is an error. */
631 if (undo
< (-SEMAEM
- 1) || undo
> SEMAEM
)
633 un
->semadj
[sop
->sem_num
] = undo
;
636 curr
->semval
= result
;
641 while (sop
>= sops
) {
642 sma
->sem_base
[sop
->sem_num
].sempid
= pid
;
655 if (sop
->sem_flg
& IPC_NOWAIT
)
662 while (sop
>= sops
) {
663 sem_op
= sop
->sem_op
;
664 sma
->sem_base
[sop
->sem_num
].semval
-= sem_op
;
665 if (sop
->sem_flg
& SEM_UNDO
)
666 un
->semadj
[sop
->sem_num
] += sem_op
;
673 static int perform_atomic_semop(struct sem_array
*sma
, struct sem_queue
*q
)
675 int result
, sem_op
, nsops
;
685 if (unlikely(q
->dupsop
))
686 return perform_atomic_semop_slow(sma
, q
);
689 * We scan the semaphore set twice, first to ensure that the entire
690 * operation can succeed, therefore avoiding any pointless writes
691 * to shared memory and having to undo such changes in order to block
692 * until the operations can go through.
694 for (sop
= sops
; sop
< sops
+ nsops
; sop
++) {
695 curr
= sma
->sem_base
+ sop
->sem_num
;
696 sem_op
= sop
->sem_op
;
697 result
= curr
->semval
;
699 if (!sem_op
&& result
)
700 goto would_block
; /* wait-for-zero */
709 if (sop
->sem_flg
& SEM_UNDO
) {
710 int undo
= un
->semadj
[sop
->sem_num
] - sem_op
;
712 /* Exceeding the undo range is an error. */
713 if (undo
< (-SEMAEM
- 1) || undo
> SEMAEM
)
718 for (sop
= sops
; sop
< sops
+ nsops
; sop
++) {
719 curr
= sma
->sem_base
+ sop
->sem_num
;
720 sem_op
= sop
->sem_op
;
721 result
= curr
->semval
;
723 if (sop
->sem_flg
& SEM_UNDO
) {
724 int undo
= un
->semadj
[sop
->sem_num
] - sem_op
;
726 un
->semadj
[sop
->sem_num
] = undo
;
728 curr
->semval
+= sem_op
;
729 curr
->sempid
= q
->pid
;
736 return sop
->sem_flg
& IPC_NOWAIT
? -EAGAIN
: 1;
739 static inline void wake_up_sem_queue_prepare(struct sem_queue
*q
, int error
,
740 struct wake_q_head
*wake_q
)
742 wake_q_add(wake_q
, q
->sleeper
);
744 * Rely on the above implicit barrier, such that we can
745 * ensure that we hold reference to the task before setting
746 * q->status. Otherwise we could race with do_exit if the
747 * task is awoken by an external event before calling
750 WRITE_ONCE(q
->status
, error
);
753 static void unlink_queue(struct sem_array
*sma
, struct sem_queue
*q
)
757 sma
->complex_count
--;
760 /** check_restart(sma, q)
761 * @sma: semaphore array
762 * @q: the operation that just completed
764 * update_queue is O(N^2) when it restarts scanning the whole queue of
765 * waiting operations. Therefore this function checks if the restart is
766 * really necessary. It is called after a previously waiting operation
767 * modified the array.
768 * Note that wait-for-zero operations are handled without restart.
770 static inline int check_restart(struct sem_array
*sma
, struct sem_queue
*q
)
772 /* pending complex alter operations are too difficult to analyse */
773 if (!list_empty(&sma
->pending_alter
))
776 /* we were a sleeping complex operation. Too difficult */
780 /* It is impossible that someone waits for the new value:
781 * - complex operations always restart.
782 * - wait-for-zero are handled seperately.
783 * - q is a previously sleeping simple operation that
784 * altered the array. It must be a decrement, because
785 * simple increments never sleep.
786 * - If there are older (higher priority) decrements
787 * in the queue, then they have observed the original
788 * semval value and couldn't proceed. The operation
789 * decremented to value - thus they won't proceed either.
795 * wake_const_ops - wake up non-alter tasks
796 * @sma: semaphore array.
797 * @semnum: semaphore that was modified.
798 * @wake_q: lockless wake-queue head.
800 * wake_const_ops must be called after a semaphore in a semaphore array
801 * was set to 0. If complex const operations are pending, wake_const_ops must
802 * be called with semnum = -1, as well as with the number of each modified
804 * The tasks that must be woken up are added to @wake_q. The return code
805 * is stored in q->pid.
806 * The function returns 1 if at least one operation was completed successfully.
808 static int wake_const_ops(struct sem_array
*sma
, int semnum
,
809 struct wake_q_head
*wake_q
)
811 struct sem_queue
*q
, *tmp
;
812 struct list_head
*pending_list
;
813 int semop_completed
= 0;
816 pending_list
= &sma
->pending_const
;
818 pending_list
= &sma
->sem_base
[semnum
].pending_const
;
820 list_for_each_entry_safe(q
, tmp
, pending_list
, list
) {
821 int error
= perform_atomic_semop(sma
, q
);
825 /* operation completed, remove from queue & wakeup */
826 unlink_queue(sma
, q
);
828 wake_up_sem_queue_prepare(q
, error
, wake_q
);
833 return semop_completed
;
837 * do_smart_wakeup_zero - wakeup all wait for zero tasks
838 * @sma: semaphore array
839 * @sops: operations that were performed
840 * @nsops: number of operations
841 * @wake_q: lockless wake-queue head
843 * Checks all required queue for wait-for-zero operations, based
844 * on the actual changes that were performed on the semaphore array.
845 * The function returns 1 if at least one operation was completed successfully.
847 static int do_smart_wakeup_zero(struct sem_array
*sma
, struct sembuf
*sops
,
848 int nsops
, struct wake_q_head
*wake_q
)
851 int semop_completed
= 0;
854 /* first: the per-semaphore queues, if known */
856 for (i
= 0; i
< nsops
; i
++) {
857 int num
= sops
[i
].sem_num
;
859 if (sma
->sem_base
[num
].semval
== 0) {
861 semop_completed
|= wake_const_ops(sma
, num
, wake_q
);
866 * No sops means modified semaphores not known.
867 * Assume all were changed.
869 for (i
= 0; i
< sma
->sem_nsems
; i
++) {
870 if (sma
->sem_base
[i
].semval
== 0) {
872 semop_completed
|= wake_const_ops(sma
, i
, wake_q
);
877 * If one of the modified semaphores got 0,
878 * then check the global queue, too.
881 semop_completed
|= wake_const_ops(sma
, -1, wake_q
);
883 return semop_completed
;
888 * update_queue - look for tasks that can be completed.
889 * @sma: semaphore array.
890 * @semnum: semaphore that was modified.
891 * @wake_q: lockless wake-queue head.
893 * update_queue must be called after a semaphore in a semaphore array
894 * was modified. If multiple semaphores were modified, update_queue must
895 * be called with semnum = -1, as well as with the number of each modified
897 * The tasks that must be woken up are added to @wake_q. The return code
898 * is stored in q->pid.
899 * The function internally checks if const operations can now succeed.
901 * The function return 1 if at least one semop was completed successfully.
903 static int update_queue(struct sem_array
*sma
, int semnum
, struct wake_q_head
*wake_q
)
905 struct sem_queue
*q
, *tmp
;
906 struct list_head
*pending_list
;
907 int semop_completed
= 0;
910 pending_list
= &sma
->pending_alter
;
912 pending_list
= &sma
->sem_base
[semnum
].pending_alter
;
915 list_for_each_entry_safe(q
, tmp
, pending_list
, list
) {
918 /* If we are scanning the single sop, per-semaphore list of
919 * one semaphore and that semaphore is 0, then it is not
920 * necessary to scan further: simple increments
921 * that affect only one entry succeed immediately and cannot
922 * be in the per semaphore pending queue, and decrements
923 * cannot be successful if the value is already 0.
925 if (semnum
!= -1 && sma
->sem_base
[semnum
].semval
== 0)
928 error
= perform_atomic_semop(sma
, q
);
930 /* Does q->sleeper still need to sleep? */
934 unlink_queue(sma
, q
);
940 do_smart_wakeup_zero(sma
, q
->sops
, q
->nsops
, wake_q
);
941 restart
= check_restart(sma
, q
);
944 wake_up_sem_queue_prepare(q
, error
, wake_q
);
948 return semop_completed
;
952 * set_semotime - set sem_otime
953 * @sma: semaphore array
954 * @sops: operations that modified the array, may be NULL
956 * sem_otime is replicated to avoid cache line trashing.
957 * This function sets one instance to the current time.
959 static void set_semotime(struct sem_array
*sma
, struct sembuf
*sops
)
962 sma
->sem_base
[0].sem_otime
= get_seconds();
964 sma
->sem_base
[sops
[0].sem_num
].sem_otime
=
970 * do_smart_update - optimized update_queue
971 * @sma: semaphore array
972 * @sops: operations that were performed
973 * @nsops: number of operations
974 * @otime: force setting otime
975 * @wake_q: lockless wake-queue head
977 * do_smart_update() does the required calls to update_queue and wakeup_zero,
978 * based on the actual changes that were performed on the semaphore array.
979 * Note that the function does not do the actual wake-up: the caller is
980 * responsible for calling wake_up_q().
981 * It is safe to perform this call after dropping all locks.
983 static void do_smart_update(struct sem_array
*sma
, struct sembuf
*sops
, int nsops
,
984 int otime
, struct wake_q_head
*wake_q
)
988 otime
|= do_smart_wakeup_zero(sma
, sops
, nsops
, wake_q
);
990 if (!list_empty(&sma
->pending_alter
)) {
991 /* semaphore array uses the global queue - just process it. */
992 otime
|= update_queue(sma
, -1, wake_q
);
996 * No sops, thus the modified semaphores are not
999 for (i
= 0; i
< sma
->sem_nsems
; i
++)
1000 otime
|= update_queue(sma
, i
, wake_q
);
1003 * Check the semaphores that were increased:
1004 * - No complex ops, thus all sleeping ops are
1006 * - if we decreased the value, then any sleeping
1007 * semaphore ops wont be able to run: If the
1008 * previous value was too small, then the new
1009 * value will be too small, too.
1011 for (i
= 0; i
< nsops
; i
++) {
1012 if (sops
[i
].sem_op
> 0) {
1013 otime
|= update_queue(sma
,
1014 sops
[i
].sem_num
, wake_q
);
1020 set_semotime(sma
, sops
);
1024 * check_qop: Test if a queued operation sleeps on the semaphore semnum
1026 static int check_qop(struct sem_array
*sma
, int semnum
, struct sem_queue
*q
,
1029 struct sembuf
*sop
= q
->blocking
;
1032 * Linux always (since 0.99.10) reported a task as sleeping on all
1033 * semaphores. This violates SUS, therefore it was changed to the
1034 * standard compliant behavior.
1035 * Give the administrators a chance to notice that an application
1036 * might misbehave because it relies on the Linux behavior.
1038 pr_info_once("semctl(GETNCNT/GETZCNT) is since 3.16 Single Unix Specification compliant.\n"
1039 "The task %s (%d) triggered the difference, watch for misbehavior.\n",
1040 current
->comm
, task_pid_nr(current
));
1042 if (sop
->sem_num
!= semnum
)
1045 if (count_zero
&& sop
->sem_op
== 0)
1047 if (!count_zero
&& sop
->sem_op
< 0)
1053 /* The following counts are associated to each semaphore:
1054 * semncnt number of tasks waiting on semval being nonzero
1055 * semzcnt number of tasks waiting on semval being zero
1057 * Per definition, a task waits only on the semaphore of the first semop
1058 * that cannot proceed, even if additional operation would block, too.
1060 static int count_semcnt(struct sem_array
*sma
, ushort semnum
,
1063 struct list_head
*l
;
1064 struct sem_queue
*q
;
1068 /* First: check the simple operations. They are easy to evaluate */
1070 l
= &sma
->sem_base
[semnum
].pending_const
;
1072 l
= &sma
->sem_base
[semnum
].pending_alter
;
1074 list_for_each_entry(q
, l
, list
) {
1075 /* all task on a per-semaphore list sleep on exactly
1081 /* Then: check the complex operations. */
1082 list_for_each_entry(q
, &sma
->pending_alter
, list
) {
1083 semcnt
+= check_qop(sma
, semnum
, q
, count_zero
);
1086 list_for_each_entry(q
, &sma
->pending_const
, list
) {
1087 semcnt
+= check_qop(sma
, semnum
, q
, count_zero
);
1093 /* Free a semaphore set. freeary() is called with sem_ids.rwsem locked
1094 * as a writer and the spinlock for this semaphore set hold. sem_ids.rwsem
1095 * remains locked on exit.
1097 static void freeary(struct ipc_namespace
*ns
, struct kern_ipc_perm
*ipcp
)
1099 struct sem_undo
*un
, *tu
;
1100 struct sem_queue
*q
, *tq
;
1101 struct sem_array
*sma
= container_of(ipcp
, struct sem_array
, sem_perm
);
1103 DEFINE_WAKE_Q(wake_q
);
1105 /* Free the existing undo structures for this semaphore set. */
1106 ipc_assert_locked_object(&sma
->sem_perm
);
1107 list_for_each_entry_safe(un
, tu
, &sma
->list_id
, list_id
) {
1108 list_del(&un
->list_id
);
1109 spin_lock(&un
->ulp
->lock
);
1111 list_del_rcu(&un
->list_proc
);
1112 spin_unlock(&un
->ulp
->lock
);
1116 /* Wake up all pending processes and let them fail with EIDRM. */
1117 list_for_each_entry_safe(q
, tq
, &sma
->pending_const
, list
) {
1118 unlink_queue(sma
, q
);
1119 wake_up_sem_queue_prepare(q
, -EIDRM
, &wake_q
);
1122 list_for_each_entry_safe(q
, tq
, &sma
->pending_alter
, list
) {
1123 unlink_queue(sma
, q
);
1124 wake_up_sem_queue_prepare(q
, -EIDRM
, &wake_q
);
1126 for (i
= 0; i
< sma
->sem_nsems
; i
++) {
1127 struct sem
*sem
= sma
->sem_base
+ i
;
1128 list_for_each_entry_safe(q
, tq
, &sem
->pending_const
, list
) {
1129 unlink_queue(sma
, q
);
1130 wake_up_sem_queue_prepare(q
, -EIDRM
, &wake_q
);
1132 list_for_each_entry_safe(q
, tq
, &sem
->pending_alter
, list
) {
1133 unlink_queue(sma
, q
);
1134 wake_up_sem_queue_prepare(q
, -EIDRM
, &wake_q
);
1138 /* Remove the semaphore set from the IDR */
1140 sem_unlock(sma
, -1);
1144 ns
->used_sems
-= sma
->sem_nsems
;
1145 ipc_rcu_putref(sma
, sem_rcu_free
);
1148 static unsigned long copy_semid_to_user(void __user
*buf
, struct semid64_ds
*in
, int version
)
1152 return copy_to_user(buf
, in
, sizeof(*in
));
1155 struct semid_ds out
;
1157 memset(&out
, 0, sizeof(out
));
1159 ipc64_perm_to_ipc_perm(&in
->sem_perm
, &out
.sem_perm
);
1161 out
.sem_otime
= in
->sem_otime
;
1162 out
.sem_ctime
= in
->sem_ctime
;
1163 out
.sem_nsems
= in
->sem_nsems
;
1165 return copy_to_user(buf
, &out
, sizeof(out
));
1172 static time_t get_semotime(struct sem_array
*sma
)
1177 res
= sma
->sem_base
[0].sem_otime
;
1178 for (i
= 1; i
< sma
->sem_nsems
; i
++) {
1179 time_t to
= sma
->sem_base
[i
].sem_otime
;
1187 static int semctl_nolock(struct ipc_namespace
*ns
, int semid
,
1188 int cmd
, int version
, void __user
*p
)
1191 struct sem_array
*sma
;
1197 struct seminfo seminfo
;
1200 err
= security_sem_semctl(NULL
, cmd
);
1204 memset(&seminfo
, 0, sizeof(seminfo
));
1205 seminfo
.semmni
= ns
->sc_semmni
;
1206 seminfo
.semmns
= ns
->sc_semmns
;
1207 seminfo
.semmsl
= ns
->sc_semmsl
;
1208 seminfo
.semopm
= ns
->sc_semopm
;
1209 seminfo
.semvmx
= SEMVMX
;
1210 seminfo
.semmnu
= SEMMNU
;
1211 seminfo
.semmap
= SEMMAP
;
1212 seminfo
.semume
= SEMUME
;
1213 down_read(&sem_ids(ns
).rwsem
);
1214 if (cmd
== SEM_INFO
) {
1215 seminfo
.semusz
= sem_ids(ns
).in_use
;
1216 seminfo
.semaem
= ns
->used_sems
;
1218 seminfo
.semusz
= SEMUSZ
;
1219 seminfo
.semaem
= SEMAEM
;
1221 max_id
= ipc_get_maxid(&sem_ids(ns
));
1222 up_read(&sem_ids(ns
).rwsem
);
1223 if (copy_to_user(p
, &seminfo
, sizeof(struct seminfo
)))
1225 return (max_id
< 0) ? 0 : max_id
;
1230 struct semid64_ds tbuf
;
1233 memset(&tbuf
, 0, sizeof(tbuf
));
1236 if (cmd
== SEM_STAT
) {
1237 sma
= sem_obtain_object(ns
, semid
);
1242 id
= sma
->sem_perm
.id
;
1244 sma
= sem_obtain_object_check(ns
, semid
);
1252 if (ipcperms(ns
, &sma
->sem_perm
, S_IRUGO
))
1255 err
= security_sem_semctl(sma
, cmd
);
1259 kernel_to_ipc64_perm(&sma
->sem_perm
, &tbuf
.sem_perm
);
1260 tbuf
.sem_otime
= get_semotime(sma
);
1261 tbuf
.sem_ctime
= sma
->sem_ctime
;
1262 tbuf
.sem_nsems
= sma
->sem_nsems
;
1264 if (copy_semid_to_user(p
, &tbuf
, version
))
1276 static int semctl_setval(struct ipc_namespace
*ns
, int semid
, int semnum
,
1279 struct sem_undo
*un
;
1280 struct sem_array
*sma
;
1283 DEFINE_WAKE_Q(wake_q
);
1285 #if defined(CONFIG_64BIT) && defined(__BIG_ENDIAN)
1286 /* big-endian 64bit */
1289 /* 32bit or little-endian 64bit */
1293 if (val
> SEMVMX
|| val
< 0)
1297 sma
= sem_obtain_object_check(ns
, semid
);
1300 return PTR_ERR(sma
);
1303 if (semnum
< 0 || semnum
>= sma
->sem_nsems
) {
1309 if (ipcperms(ns
, &sma
->sem_perm
, S_IWUGO
)) {
1314 err
= security_sem_semctl(sma
, SETVAL
);
1320 sem_lock(sma
, NULL
, -1);
1322 if (!ipc_valid_object(&sma
->sem_perm
)) {
1323 sem_unlock(sma
, -1);
1328 curr
= &sma
->sem_base
[semnum
];
1330 ipc_assert_locked_object(&sma
->sem_perm
);
1331 list_for_each_entry(un
, &sma
->list_id
, list_id
)
1332 un
->semadj
[semnum
] = 0;
1335 curr
->sempid
= task_tgid_vnr(current
);
1336 sma
->sem_ctime
= get_seconds();
1337 /* maybe some queued-up processes were waiting for this */
1338 do_smart_update(sma
, NULL
, 0, 0, &wake_q
);
1339 sem_unlock(sma
, -1);
1345 static int semctl_main(struct ipc_namespace
*ns
, int semid
, int semnum
,
1346 int cmd
, void __user
*p
)
1348 struct sem_array
*sma
;
1351 ushort fast_sem_io
[SEMMSL_FAST
];
1352 ushort
*sem_io
= fast_sem_io
;
1353 DEFINE_WAKE_Q(wake_q
);
1356 sma
= sem_obtain_object_check(ns
, semid
);
1359 return PTR_ERR(sma
);
1362 nsems
= sma
->sem_nsems
;
1365 if (ipcperms(ns
, &sma
->sem_perm
, cmd
== SETALL
? S_IWUGO
: S_IRUGO
))
1366 goto out_rcu_wakeup
;
1368 err
= security_sem_semctl(sma
, cmd
);
1370 goto out_rcu_wakeup
;
1376 ushort __user
*array
= p
;
1379 sem_lock(sma
, NULL
, -1);
1380 if (!ipc_valid_object(&sma
->sem_perm
)) {
1384 if (nsems
> SEMMSL_FAST
) {
1385 if (!ipc_rcu_getref(sma
)) {
1389 sem_unlock(sma
, -1);
1391 sem_io
= ipc_alloc(sizeof(ushort
)*nsems
);
1392 if (sem_io
== NULL
) {
1393 ipc_rcu_putref(sma
, sem_rcu_free
);
1398 sem_lock_and_putref(sma
);
1399 if (!ipc_valid_object(&sma
->sem_perm
)) {
1404 for (i
= 0; i
< sma
->sem_nsems
; i
++)
1405 sem_io
[i
] = sma
->sem_base
[i
].semval
;
1406 sem_unlock(sma
, -1);
1409 if (copy_to_user(array
, sem_io
, nsems
*sizeof(ushort
)))
1416 struct sem_undo
*un
;
1418 if (!ipc_rcu_getref(sma
)) {
1420 goto out_rcu_wakeup
;
1424 if (nsems
> SEMMSL_FAST
) {
1425 sem_io
= ipc_alloc(sizeof(ushort
)*nsems
);
1426 if (sem_io
== NULL
) {
1427 ipc_rcu_putref(sma
, sem_rcu_free
);
1432 if (copy_from_user(sem_io
, p
, nsems
*sizeof(ushort
))) {
1433 ipc_rcu_putref(sma
, sem_rcu_free
);
1438 for (i
= 0; i
< nsems
; i
++) {
1439 if (sem_io
[i
] > SEMVMX
) {
1440 ipc_rcu_putref(sma
, sem_rcu_free
);
1446 sem_lock_and_putref(sma
);
1447 if (!ipc_valid_object(&sma
->sem_perm
)) {
1452 for (i
= 0; i
< nsems
; i
++) {
1453 sma
->sem_base
[i
].semval
= sem_io
[i
];
1454 sma
->sem_base
[i
].sempid
= task_tgid_vnr(current
);
1457 ipc_assert_locked_object(&sma
->sem_perm
);
1458 list_for_each_entry(un
, &sma
->list_id
, list_id
) {
1459 for (i
= 0; i
< nsems
; i
++)
1462 sma
->sem_ctime
= get_seconds();
1463 /* maybe some queued-up processes were waiting for this */
1464 do_smart_update(sma
, NULL
, 0, 0, &wake_q
);
1468 /* GETVAL, GETPID, GETNCTN, GETZCNT: fall-through */
1471 if (semnum
< 0 || semnum
>= nsems
)
1472 goto out_rcu_wakeup
;
1474 sem_lock(sma
, NULL
, -1);
1475 if (!ipc_valid_object(&sma
->sem_perm
)) {
1479 curr
= &sma
->sem_base
[semnum
];
1489 err
= count_semcnt(sma
, semnum
, 0);
1492 err
= count_semcnt(sma
, semnum
, 1);
1497 sem_unlock(sma
, -1);
1502 if (sem_io
!= fast_sem_io
)
1507 static inline unsigned long
1508 copy_semid_from_user(struct semid64_ds
*out
, void __user
*buf
, int version
)
1512 if (copy_from_user(out
, buf
, sizeof(*out
)))
1517 struct semid_ds tbuf_old
;
1519 if (copy_from_user(&tbuf_old
, buf
, sizeof(tbuf_old
)))
1522 out
->sem_perm
.uid
= tbuf_old
.sem_perm
.uid
;
1523 out
->sem_perm
.gid
= tbuf_old
.sem_perm
.gid
;
1524 out
->sem_perm
.mode
= tbuf_old
.sem_perm
.mode
;
1534 * This function handles some semctl commands which require the rwsem
1535 * to be held in write mode.
1536 * NOTE: no locks must be held, the rwsem is taken inside this function.
1538 static int semctl_down(struct ipc_namespace
*ns
, int semid
,
1539 int cmd
, int version
, void __user
*p
)
1541 struct sem_array
*sma
;
1543 struct semid64_ds semid64
;
1544 struct kern_ipc_perm
*ipcp
;
1546 if (cmd
== IPC_SET
) {
1547 if (copy_semid_from_user(&semid64
, p
, version
))
1551 down_write(&sem_ids(ns
).rwsem
);
1554 ipcp
= ipcctl_pre_down_nolock(ns
, &sem_ids(ns
), semid
, cmd
,
1555 &semid64
.sem_perm
, 0);
1557 err
= PTR_ERR(ipcp
);
1561 sma
= container_of(ipcp
, struct sem_array
, sem_perm
);
1563 err
= security_sem_semctl(sma
, cmd
);
1569 sem_lock(sma
, NULL
, -1);
1570 /* freeary unlocks the ipc object and rcu */
1574 sem_lock(sma
, NULL
, -1);
1575 err
= ipc_update_perm(&semid64
.sem_perm
, ipcp
);
1578 sma
->sem_ctime
= get_seconds();
1586 sem_unlock(sma
, -1);
1590 up_write(&sem_ids(ns
).rwsem
);
1594 SYSCALL_DEFINE4(semctl
, int, semid
, int, semnum
, int, cmd
, unsigned long, arg
)
1597 struct ipc_namespace
*ns
;
1598 void __user
*p
= (void __user
*)arg
;
1603 version
= ipc_parse_version(&cmd
);
1604 ns
= current
->nsproxy
->ipc_ns
;
1611 return semctl_nolock(ns
, semid
, cmd
, version
, p
);
1618 return semctl_main(ns
, semid
, semnum
, cmd
, p
);
1620 return semctl_setval(ns
, semid
, semnum
, arg
);
1623 return semctl_down(ns
, semid
, cmd
, version
, p
);
1629 /* If the task doesn't already have a undo_list, then allocate one
1630 * here. We guarantee there is only one thread using this undo list,
1631 * and current is THE ONE
1633 * If this allocation and assignment succeeds, but later
1634 * portions of this code fail, there is no need to free the sem_undo_list.
1635 * Just let it stay associated with the task, and it'll be freed later
1638 * This can block, so callers must hold no locks.
1640 static inline int get_undo_list(struct sem_undo_list
**undo_listp
)
1642 struct sem_undo_list
*undo_list
;
1644 undo_list
= current
->sysvsem
.undo_list
;
1646 undo_list
= kzalloc(sizeof(*undo_list
), GFP_KERNEL
);
1647 if (undo_list
== NULL
)
1649 spin_lock_init(&undo_list
->lock
);
1650 atomic_set(&undo_list
->refcnt
, 1);
1651 INIT_LIST_HEAD(&undo_list
->list_proc
);
1653 current
->sysvsem
.undo_list
= undo_list
;
1655 *undo_listp
= undo_list
;
1659 static struct sem_undo
*__lookup_undo(struct sem_undo_list
*ulp
, int semid
)
1661 struct sem_undo
*un
;
1663 list_for_each_entry_rcu(un
, &ulp
->list_proc
, list_proc
) {
1664 if (un
->semid
== semid
)
1670 static struct sem_undo
*lookup_undo(struct sem_undo_list
*ulp
, int semid
)
1672 struct sem_undo
*un
;
1674 assert_spin_locked(&ulp
->lock
);
1676 un
= __lookup_undo(ulp
, semid
);
1678 list_del_rcu(&un
->list_proc
);
1679 list_add_rcu(&un
->list_proc
, &ulp
->list_proc
);
1685 * find_alloc_undo - lookup (and if not present create) undo array
1687 * @semid: semaphore array id
1689 * The function looks up (and if not present creates) the undo structure.
1690 * The size of the undo structure depends on the size of the semaphore
1691 * array, thus the alloc path is not that straightforward.
1692 * Lifetime-rules: sem_undo is rcu-protected, on success, the function
1693 * performs a rcu_read_lock().
1695 static struct sem_undo
*find_alloc_undo(struct ipc_namespace
*ns
, int semid
)
1697 struct sem_array
*sma
;
1698 struct sem_undo_list
*ulp
;
1699 struct sem_undo
*un
, *new;
1702 error
= get_undo_list(&ulp
);
1704 return ERR_PTR(error
);
1707 spin_lock(&ulp
->lock
);
1708 un
= lookup_undo(ulp
, semid
);
1709 spin_unlock(&ulp
->lock
);
1710 if (likely(un
!= NULL
))
1713 /* no undo structure around - allocate one. */
1714 /* step 1: figure out the size of the semaphore array */
1715 sma
= sem_obtain_object_check(ns
, semid
);
1718 return ERR_CAST(sma
);
1721 nsems
= sma
->sem_nsems
;
1722 if (!ipc_rcu_getref(sma
)) {
1724 un
= ERR_PTR(-EIDRM
);
1729 /* step 2: allocate new undo structure */
1730 new = kzalloc(sizeof(struct sem_undo
) + sizeof(short)*nsems
, GFP_KERNEL
);
1732 ipc_rcu_putref(sma
, sem_rcu_free
);
1733 return ERR_PTR(-ENOMEM
);
1736 /* step 3: Acquire the lock on semaphore array */
1738 sem_lock_and_putref(sma
);
1739 if (!ipc_valid_object(&sma
->sem_perm
)) {
1740 sem_unlock(sma
, -1);
1743 un
= ERR_PTR(-EIDRM
);
1746 spin_lock(&ulp
->lock
);
1749 * step 4: check for races: did someone else allocate the undo struct?
1751 un
= lookup_undo(ulp
, semid
);
1756 /* step 5: initialize & link new undo structure */
1757 new->semadj
= (short *) &new[1];
1760 assert_spin_locked(&ulp
->lock
);
1761 list_add_rcu(&new->list_proc
, &ulp
->list_proc
);
1762 ipc_assert_locked_object(&sma
->sem_perm
);
1763 list_add(&new->list_id
, &sma
->list_id
);
1767 spin_unlock(&ulp
->lock
);
1768 sem_unlock(sma
, -1);
1773 SYSCALL_DEFINE4(semtimedop
, int, semid
, struct sembuf __user
*, tsops
,
1774 unsigned, nsops
, const struct timespec __user
*, timeout
)
1776 int error
= -EINVAL
;
1777 struct sem_array
*sma
;
1778 struct sembuf fast_sops
[SEMOPM_FAST
];
1779 struct sembuf
*sops
= fast_sops
, *sop
;
1780 struct sem_undo
*un
;
1782 bool undos
= false, alter
= false, dupsop
= false;
1783 struct sem_queue queue
;
1784 unsigned long dup
= 0, jiffies_left
= 0;
1785 struct ipc_namespace
*ns
;
1787 ns
= current
->nsproxy
->ipc_ns
;
1789 if (nsops
< 1 || semid
< 0)
1791 if (nsops
> ns
->sc_semopm
)
1793 if (nsops
> SEMOPM_FAST
) {
1794 sops
= kmalloc(sizeof(*sops
)*nsops
, GFP_KERNEL
);
1799 if (copy_from_user(sops
, tsops
, nsops
* sizeof(*tsops
))) {
1805 struct timespec _timeout
;
1806 if (copy_from_user(&_timeout
, timeout
, sizeof(*timeout
))) {
1810 if (_timeout
.tv_sec
< 0 || _timeout
.tv_nsec
< 0 ||
1811 _timeout
.tv_nsec
>= 1000000000L) {
1815 jiffies_left
= timespec_to_jiffies(&_timeout
);
1819 for (sop
= sops
; sop
< sops
+ nsops
; sop
++) {
1820 unsigned long mask
= 1ULL << ((sop
->sem_num
) % BITS_PER_LONG
);
1822 if (sop
->sem_num
>= max
)
1824 if (sop
->sem_flg
& SEM_UNDO
)
1828 * There was a previous alter access that appears
1829 * to have accessed the same semaphore, thus use
1830 * the dupsop logic. "appears", because the detection
1831 * can only check % BITS_PER_LONG.
1835 if (sop
->sem_op
!= 0) {
1842 /* On success, find_alloc_undo takes the rcu_read_lock */
1843 un
= find_alloc_undo(ns
, semid
);
1845 error
= PTR_ERR(un
);
1853 sma
= sem_obtain_object_check(ns
, semid
);
1856 error
= PTR_ERR(sma
);
1861 if (max
>= sma
->sem_nsems
) {
1867 if (ipcperms(ns
, &sma
->sem_perm
, alter
? S_IWUGO
: S_IRUGO
)) {
1872 error
= security_sem_semop(sma
, sops
, nsops
, alter
);
1879 locknum
= sem_lock(sma
, sops
, nsops
);
1881 * We eventually might perform the following check in a lockless
1882 * fashion, considering ipc_valid_object() locking constraints.
1883 * If nsops == 1 and there is no contention for sem_perm.lock, then
1884 * only a per-semaphore lock is held and it's OK to proceed with the
1885 * check below. More details on the fine grained locking scheme
1886 * entangled here and why it's RMID race safe on comments at sem_lock()
1888 if (!ipc_valid_object(&sma
->sem_perm
))
1889 goto out_unlock_free
;
1891 * semid identifiers are not unique - find_alloc_undo may have
1892 * allocated an undo structure, it was invalidated by an RMID
1893 * and now a new array with received the same id. Check and fail.
1894 * This case can be detected checking un->semid. The existence of
1895 * "un" itself is guaranteed by rcu.
1897 if (un
&& un
->semid
== -1)
1898 goto out_unlock_free
;
1901 queue
.nsops
= nsops
;
1903 queue
.pid
= task_tgid_vnr(current
);
1904 queue
.alter
= alter
;
1905 queue
.dupsop
= dupsop
;
1907 error
= perform_atomic_semop(sma
, &queue
);
1908 if (error
== 0) { /* non-blocking succesfull path */
1909 DEFINE_WAKE_Q(wake_q
);
1912 * If the operation was successful, then do
1913 * the required updates.
1916 do_smart_update(sma
, sops
, nsops
, 1, &wake_q
);
1918 set_semotime(sma
, sops
);
1920 sem_unlock(sma
, locknum
);
1926 if (error
< 0) /* non-blocking error path */
1927 goto out_unlock_free
;
1930 * We need to sleep on this operation, so we put the current
1931 * task into the pending queue and go to sleep.
1935 curr
= &sma
->sem_base
[sops
->sem_num
];
1938 if (sma
->complex_count
) {
1939 list_add_tail(&queue
.list
,
1940 &sma
->pending_alter
);
1943 list_add_tail(&queue
.list
,
1944 &curr
->pending_alter
);
1947 list_add_tail(&queue
.list
, &curr
->pending_const
);
1950 if (!sma
->complex_count
)
1954 list_add_tail(&queue
.list
, &sma
->pending_alter
);
1956 list_add_tail(&queue
.list
, &sma
->pending_const
);
1958 sma
->complex_count
++;
1962 queue
.status
= -EINTR
;
1963 queue
.sleeper
= current
;
1965 __set_current_state(TASK_INTERRUPTIBLE
);
1966 sem_unlock(sma
, locknum
);
1970 jiffies_left
= schedule_timeout(jiffies_left
);
1975 * fastpath: the semop has completed, either successfully or
1976 * not, from the syscall pov, is quite irrelevant to us at this
1977 * point; we're done.
1979 * We _do_ care, nonetheless, about being awoken by a signal or
1980 * spuriously. The queue.status is checked again in the
1981 * slowpath (aka after taking sem_lock), such that we can detect
1982 * scenarios where we were awakened externally, during the
1983 * window between wake_q_add() and wake_up_q().
1985 error
= READ_ONCE(queue
.status
);
1986 if (error
!= -EINTR
) {
1988 * User space could assume that semop() is a memory
1989 * barrier: Without the mb(), the cpu could
1990 * speculatively read in userspace stale data that was
1991 * overwritten by the previous owner of the semaphore.
1998 locknum
= sem_lock(sma
, sops
, nsops
);
2000 if (!ipc_valid_object(&sma
->sem_perm
))
2001 goto out_unlock_free
;
2003 error
= READ_ONCE(queue
.status
);
2006 * If queue.status != -EINTR we are woken up by another process.
2007 * Leave without unlink_queue(), but with sem_unlock().
2009 if (error
!= -EINTR
)
2010 goto out_unlock_free
;
2013 * If an interrupt occurred we have to clean up the queue.
2015 if (timeout
&& jiffies_left
== 0)
2017 } while (error
== -EINTR
&& !signal_pending(current
)); /* spurious */
2019 unlink_queue(sma
, &queue
);
2022 sem_unlock(sma
, locknum
);
2025 if (sops
!= fast_sops
)
2030 SYSCALL_DEFINE3(semop
, int, semid
, struct sembuf __user
*, tsops
,
2033 return sys_semtimedop(semid
, tsops
, nsops
, NULL
);
2036 /* If CLONE_SYSVSEM is set, establish sharing of SEM_UNDO state between
2037 * parent and child tasks.
2040 int copy_semundo(unsigned long clone_flags
, struct task_struct
*tsk
)
2042 struct sem_undo_list
*undo_list
;
2045 if (clone_flags
& CLONE_SYSVSEM
) {
2046 error
= get_undo_list(&undo_list
);
2049 atomic_inc(&undo_list
->refcnt
);
2050 tsk
->sysvsem
.undo_list
= undo_list
;
2052 tsk
->sysvsem
.undo_list
= NULL
;
2058 * add semadj values to semaphores, free undo structures.
2059 * undo structures are not freed when semaphore arrays are destroyed
2060 * so some of them may be out of date.
2061 * IMPLEMENTATION NOTE: There is some confusion over whether the
2062 * set of adjustments that needs to be done should be done in an atomic
2063 * manner or not. That is, if we are attempting to decrement the semval
2064 * should we queue up and wait until we can do so legally?
2065 * The original implementation attempted to do this (queue and wait).
2066 * The current implementation does not do so. The POSIX standard
2067 * and SVID should be consulted to determine what behavior is mandated.
2069 void exit_sem(struct task_struct
*tsk
)
2071 struct sem_undo_list
*ulp
;
2073 ulp
= tsk
->sysvsem
.undo_list
;
2076 tsk
->sysvsem
.undo_list
= NULL
;
2078 if (!atomic_dec_and_test(&ulp
->refcnt
))
2082 struct sem_array
*sma
;
2083 struct sem_undo
*un
;
2085 DEFINE_WAKE_Q(wake_q
);
2090 un
= list_entry_rcu(ulp
->list_proc
.next
,
2091 struct sem_undo
, list_proc
);
2092 if (&un
->list_proc
== &ulp
->list_proc
) {
2094 * We must wait for freeary() before freeing this ulp,
2095 * in case we raced with last sem_undo. There is a small
2096 * possibility where we exit while freeary() didn't
2097 * finish unlocking sem_undo_list.
2099 spin_unlock_wait(&ulp
->lock
);
2103 spin_lock(&ulp
->lock
);
2105 spin_unlock(&ulp
->lock
);
2107 /* exit_sem raced with IPC_RMID, nothing to do */
2113 sma
= sem_obtain_object_check(tsk
->nsproxy
->ipc_ns
, semid
);
2114 /* exit_sem raced with IPC_RMID, nothing to do */
2120 sem_lock(sma
, NULL
, -1);
2121 /* exit_sem raced with IPC_RMID, nothing to do */
2122 if (!ipc_valid_object(&sma
->sem_perm
)) {
2123 sem_unlock(sma
, -1);
2127 un
= __lookup_undo(ulp
, semid
);
2129 /* exit_sem raced with IPC_RMID+semget() that created
2130 * exactly the same semid. Nothing to do.
2132 sem_unlock(sma
, -1);
2137 /* remove un from the linked lists */
2138 ipc_assert_locked_object(&sma
->sem_perm
);
2139 list_del(&un
->list_id
);
2141 /* we are the last process using this ulp, acquiring ulp->lock
2142 * isn't required. Besides that, we are also protected against
2143 * IPC_RMID as we hold sma->sem_perm lock now
2145 list_del_rcu(&un
->list_proc
);
2147 /* perform adjustments registered in un */
2148 for (i
= 0; i
< sma
->sem_nsems
; i
++) {
2149 struct sem
*semaphore
= &sma
->sem_base
[i
];
2150 if (un
->semadj
[i
]) {
2151 semaphore
->semval
+= un
->semadj
[i
];
2153 * Range checks of the new semaphore value,
2154 * not defined by sus:
2155 * - Some unices ignore the undo entirely
2156 * (e.g. HP UX 11i 11.22, Tru64 V5.1)
2157 * - some cap the value (e.g. FreeBSD caps
2158 * at 0, but doesn't enforce SEMVMX)
2160 * Linux caps the semaphore value, both at 0
2163 * Manfred <manfred@colorfullife.com>
2165 if (semaphore
->semval
< 0)
2166 semaphore
->semval
= 0;
2167 if (semaphore
->semval
> SEMVMX
)
2168 semaphore
->semval
= SEMVMX
;
2169 semaphore
->sempid
= task_tgid_vnr(current
);
2172 /* maybe some queued-up processes were waiting for this */
2173 do_smart_update(sma
, NULL
, 0, 1, &wake_q
);
2174 sem_unlock(sma
, -1);
2183 #ifdef CONFIG_PROC_FS
2184 static int sysvipc_sem_proc_show(struct seq_file
*s
, void *it
)
2186 struct user_namespace
*user_ns
= seq_user_ns(s
);
2187 struct sem_array
*sma
= it
;
2191 * The proc interface isn't aware of sem_lock(), it calls
2192 * ipc_lock_object() directly (in sysvipc_find_ipc).
2193 * In order to stay compatible with sem_lock(), we must
2194 * enter / leave complex_mode.
2196 complexmode_enter(sma
);
2198 sem_otime
= get_semotime(sma
);
2201 "%10d %10d %4o %10u %5u %5u %5u %5u %10lu %10lu\n",
2206 from_kuid_munged(user_ns
, sma
->sem_perm
.uid
),
2207 from_kgid_munged(user_ns
, sma
->sem_perm
.gid
),
2208 from_kuid_munged(user_ns
, sma
->sem_perm
.cuid
),
2209 from_kgid_munged(user_ns
, sma
->sem_perm
.cgid
),
2213 complexmode_tryleave(sma
);