]> git.proxmox.com Git - mirror_ubuntu-zesty-kernel.git/blame - ipc/sem.c
ipc/sem: optimize perform_atomic_semop()
[mirror_ubuntu-zesty-kernel.git] / ipc / sem.c
CommitLineData
1da177e4
LT
1/*
2 * linux/ipc/sem.c
3 * Copyright (C) 1992 Krishna Balasubramanian
4 * Copyright (C) 1995 Eric Schenk, Bruno Haible
5 *
1da177e4
LT
6 * /proc/sysvipc/sem support (c) 1999 Dragos Acostachioaie <dragos@iname.com>
7 *
8 * SMP-threaded, sysctl's added
624dffcb 9 * (c) 1999 Manfred Spraul <manfred@colorfullife.com>
1da177e4 10 * Enforced range limit on SEM_UNDO
046c6884 11 * (c) 2001 Red Hat Inc
1da177e4
LT
12 * Lockless wakeup
13 * (c) 2003 Manfred Spraul <manfred@colorfullife.com>
9ae949fa 14 * (c) 2016 Davidlohr Bueso <dave@stgolabs.net>
c5cf6359
MS
15 * Further wakeup optimizations, documentation
16 * (c) 2010 Manfred Spraul <manfred@colorfullife.com>
073115d6
SG
17 *
18 * support for audit of ipc object properties and permission changes
19 * Dustin Kirkland <dustin.kirkland@us.ibm.com>
e3893534
KK
20 *
21 * namespaces support
22 * OpenVZ, SWsoft Inc.
23 * Pavel Emelianov <xemul@openvz.org>
c5cf6359
MS
24 *
25 * Implementation notes: (May 2010)
26 * This file implements System V semaphores.
27 *
28 * User space visible behavior:
29 * - FIFO ordering for semop() operations (just FIFO, not starvation
30 * protection)
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
34 * SETALL calls.
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.
41 *
42 * Internals:
43 * - scalability:
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.
2f2ed41d 51 * - semncnt and semzcnt are calculated on demand in count_semcnt()
c5cf6359
MS
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
9ae949fa 57 * dropping all locks. (see wake_up_sem_queue_prepare())
c5cf6359
MS
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).
c5cf6359
MS
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.
1da177e4
LT
70 */
71
1da177e4
LT
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>
1da177e4
LT
77#include <linux/security.h>
78#include <linux/syscalls.h>
79#include <linux/audit.h>
c59ede7b 80#include <linux/capability.h>
19b4946c 81#include <linux/seq_file.h>
3e148c79 82#include <linux/rwsem.h>
e3893534 83#include <linux/nsproxy.h>
ae5e1b22 84#include <linux/ipc_namespace.h>
5f921ae9 85
7153e402 86#include <linux/uaccess.h>
1da177e4
LT
87#include "util.h"
88
e57940d7
MS
89/* One semaphore structure for each semaphore in the system. */
90struct sem {
91 int semval; /* current value */
a5f4db87
DB
92 /*
93 * PID of the process that last modified the semaphore. For
94 * Linux, specifically these are:
95 * - semop
96 * - semctl, via SETVAL and SETALL.
97 * - at task exit when performing undo adjustments (see exit_sem).
98 */
99 int sempid;
6062a8dc 100 spinlock_t lock; /* spinlock for fine-grained semtimedop */
1a82e9e1
MS
101 struct list_head pending_alter; /* pending single-sop operations */
102 /* that alter the semaphore */
103 struct list_head pending_const; /* pending single-sop operations */
104 /* that do not alter the semaphore*/
d12e1e50 105 time_t sem_otime; /* candidate for sem_otime */
f5c936c0 106} ____cacheline_aligned_in_smp;
e57940d7
MS
107
108/* One queue for each sleeping process in the system. */
109struct sem_queue {
e57940d7
MS
110 struct list_head list; /* queue of pending operations */
111 struct task_struct *sleeper; /* this process */
112 struct sem_undo *undo; /* undo structure */
113 int pid; /* process id of requesting process */
114 int status; /* completion status of operation */
115 struct sembuf *sops; /* array of pending operations */
ed247b7c 116 struct sembuf *blocking; /* the operation that blocked */
e57940d7 117 int nsops; /* number of operations */
4ce33ec2
DB
118 bool alter; /* does *sops alter the array? */
119 bool dupsop; /* sops on more than one sem_num */
e57940d7
MS
120};
121
122/* Each task has a list of undo requests. They are executed automatically
123 * when the process exits.
124 */
125struct sem_undo {
126 struct list_head list_proc; /* per-process list: *
127 * all undos from one process
128 * rcu protected */
129 struct rcu_head rcu; /* rcu struct for sem_undo */
130 struct sem_undo_list *ulp; /* back ptr to sem_undo_list */
131 struct list_head list_id; /* per semaphore array list:
132 * all undos for one array */
133 int semid; /* semaphore set identifier */
134 short *semadj; /* array of adjustments */
135 /* one per semaphore */
136};
137
138/* sem_undo_list controls shared access to the list of sem_undo structures
139 * that may be shared among all a CLONE_SYSVSEM task group.
140 */
141struct sem_undo_list {
142 atomic_t refcnt;
143 spinlock_t lock;
144 struct list_head list_proc;
145};
146
147
ed2ddbf8 148#define sem_ids(ns) ((ns)->ids[IPC_SEM_IDS])
e3893534 149
1b531f21 150#define sem_checkid(sma, semid) ipc_checkid(&sma->sem_perm, semid)
1da177e4 151
7748dbfa 152static int newary(struct ipc_namespace *, struct ipc_params *);
01b8b07a 153static void freeary(struct ipc_namespace *, struct kern_ipc_perm *);
1da177e4 154#ifdef CONFIG_PROC_FS
19b4946c 155static int sysvipc_sem_proc_show(struct seq_file *s, void *it);
1da177e4
LT
156#endif
157
158#define SEMMSL_FAST 256 /* 512 bytes on stack */
159#define SEMOPM_FAST 64 /* ~ 372 bytes on stack */
160
161/*
758a6ba3 162 * Locking:
5864a2fd 163 * a) global sem_lock() for read/write
1da177e4 164 * sem_undo.id_next,
758a6ba3 165 * sem_array.complex_count,
5864a2fd
MS
166 * sem_array.complex_mode
167 * sem_array.pending{_alter,_const},
168 * sem_array.sem_undo
46c0a8ca 169 *
5864a2fd 170 * b) global or semaphore sem_lock() for read/write:
758a6ba3 171 * sem_array.sem_base[i].pending_{const,alter}:
5864a2fd
MS
172 * sem_array.complex_mode (for read)
173 *
174 * c) special:
175 * sem_undo_list.list_proc:
176 * * undo_list->lock for write
177 * * rcu for read
1da177e4
LT
178 */
179
e3893534
KK
180#define sc_semmsl sem_ctls[0]
181#define sc_semmns sem_ctls[1]
182#define sc_semopm sem_ctls[2]
183#define sc_semmni sem_ctls[3]
184
ed2ddbf8 185void sem_init_ns(struct ipc_namespace *ns)
e3893534 186{
e3893534
KK
187 ns->sc_semmsl = SEMMSL;
188 ns->sc_semmns = SEMMNS;
189 ns->sc_semopm = SEMOPM;
190 ns->sc_semmni = SEMMNI;
191 ns->used_sems = 0;
ed2ddbf8 192 ipc_init_ids(&ns->ids[IPC_SEM_IDS]);
e3893534
KK
193}
194
ae5e1b22 195#ifdef CONFIG_IPC_NS
e3893534
KK
196void sem_exit_ns(struct ipc_namespace *ns)
197{
01b8b07a 198 free_ipcs(ns, &sem_ids(ns), freeary);
7d6feeb2 199 idr_destroy(&ns->ids[IPC_SEM_IDS].ipcs_idr);
e3893534 200}
ae5e1b22 201#endif
1da177e4 202
239521f3 203void __init sem_init(void)
1da177e4 204{
ed2ddbf8 205 sem_init_ns(&init_ipc_ns);
19b4946c
MW
206 ipc_init_proc_interface("sysvipc/sem",
207 " key semid perms nsems uid gid cuid cgid otime ctime\n",
e3893534 208 IPC_SEM_IDS, sysvipc_sem_proc_show);
1da177e4
LT
209}
210
f269f40a
MS
211/**
212 * unmerge_queues - unmerge queues, if possible.
213 * @sma: semaphore array
214 *
215 * The function unmerges the wait queues if complex_count is 0.
216 * It must be called prior to dropping the global semaphore array lock.
217 */
218static void unmerge_queues(struct sem_array *sma)
219{
220 struct sem_queue *q, *tq;
221
222 /* complex operations still around? */
223 if (sma->complex_count)
224 return;
225 /*
226 * We will switch back to simple mode.
227 * Move all pending operation back into the per-semaphore
228 * queues.
229 */
230 list_for_each_entry_safe(q, tq, &sma->pending_alter, list) {
231 struct sem *curr;
232 curr = &sma->sem_base[q->sops[0].sem_num];
233
234 list_add_tail(&q->list, &curr->pending_alter);
235 }
236 INIT_LIST_HEAD(&sma->pending_alter);
237}
238
239/**
8001c858 240 * merge_queues - merge single semop queues into global queue
f269f40a
MS
241 * @sma: semaphore array
242 *
243 * This function merges all per-semaphore queues into the global queue.
244 * It is necessary to achieve FIFO ordering for the pending single-sop
245 * operations when a multi-semop operation must sleep.
246 * Only the alter operations must be moved, the const operations can stay.
247 */
248static void merge_queues(struct sem_array *sma)
249{
250 int i;
251 for (i = 0; i < sma->sem_nsems; i++) {
252 struct sem *sem = sma->sem_base + i;
253
254 list_splice_init(&sem->pending_alter, &sma->pending_alter);
255 }
256}
257
53dad6d3
DB
258static void sem_rcu_free(struct rcu_head *head)
259{
260 struct ipc_rcu *p = container_of(head, struct ipc_rcu, rcu);
261 struct sem_array *sma = ipc_rcu_to_struct(p);
262
263 security_sem_free(sma);
264 ipc_rcu_free(head);
265}
266
5e9d5275 267/*
5864a2fd 268 * Enter the mode suitable for non-simple operations:
5e9d5275 269 * Caller must own sem_perm.lock.
5e9d5275 270 */
5864a2fd 271static void complexmode_enter(struct sem_array *sma)
5e9d5275
MS
272{
273 int i;
274 struct sem *sem;
275
5864a2fd
MS
276 if (sma->complex_mode) {
277 /* We are already in complex_mode. Nothing to do */
6d07b68c
MS
278 return;
279 }
280
5864a2fd
MS
281 /* We need a full barrier after seting complex_mode:
282 * The write to complex_mode must be visible
283 * before we read the first sem->lock spinlock state.
284 */
285 smp_store_mb(sma->complex_mode, true);
286
5e9d5275
MS
287 for (i = 0; i < sma->sem_nsems; i++) {
288 sem = sma->sem_base + i;
289 spin_unlock_wait(&sem->lock);
290 }
5864a2fd
MS
291 /*
292 * spin_unlock_wait() is not a memory barriers, it is only a
293 * control barrier. The code must pair with spin_unlock(&sem->lock),
294 * thus just the control barrier is insufficient.
295 *
296 * smp_rmb() is sufficient, as writes cannot pass the control barrier.
297 */
298 smp_rmb();
299}
300
301/*
302 * Try to leave the mode that disallows simple operations:
303 * Caller must own sem_perm.lock.
304 */
305static void complexmode_tryleave(struct sem_array *sma)
306{
307 if (sma->complex_count) {
308 /* Complex ops are sleeping.
309 * We must stay in complex mode
310 */
311 return;
312 }
313 /*
314 * Immediately after setting complex_mode to false,
315 * a simple op can start. Thus: all memory writes
316 * performed by the current operation must be visible
317 * before we set complex_mode to false.
318 */
319 smp_store_release(&sma->complex_mode, false);
5e9d5275
MS
320}
321
5864a2fd 322#define SEM_GLOBAL_LOCK (-1)
6062a8dc
RR
323/*
324 * If the request contains only one semaphore operation, and there are
325 * no complex transactions pending, lock only the semaphore involved.
326 * Otherwise, lock the entire semaphore array, since we either have
327 * multiple semaphores in our own semops, or we need to look at
328 * semaphores from other pending complex operations.
6062a8dc
RR
329 */
330static inline int sem_lock(struct sem_array *sma, struct sembuf *sops,
331 int nsops)
332{
5e9d5275 333 struct sem *sem;
6062a8dc 334
5e9d5275
MS
335 if (nsops != 1) {
336 /* Complex operation - acquire a full lock */
337 ipc_lock_object(&sma->sem_perm);
6062a8dc 338
5864a2fd
MS
339 /* Prevent parallel simple ops */
340 complexmode_enter(sma);
341 return SEM_GLOBAL_LOCK;
5e9d5275
MS
342 }
343
344 /*
345 * Only one semaphore affected - try to optimize locking.
5864a2fd
MS
346 * Optimized locking is possible if no complex operation
347 * is either enqueued or processed right now.
348 *
349 * Both facts are tracked by complex_mode.
5e9d5275
MS
350 */
351 sem = sma->sem_base + sops->sem_num;
6062a8dc 352
5864a2fd
MS
353 /*
354 * Initial check for complex_mode. Just an optimization,
355 * no locking, no memory barrier.
356 */
357 if (!sma->complex_mode) {
6062a8dc 358 /*
5e9d5275
MS
359 * It appears that no complex operation is around.
360 * Acquire the per-semaphore lock.
6062a8dc 361 */
5e9d5275
MS
362 spin_lock(&sem->lock);
363
5864a2fd
MS
364 /*
365 * See 51d7d5205d33
366 * ("powerpc: Add smp_mb() to arch_spin_is_locked()"):
367 * A full barrier is required: the write of sem->lock
368 * must be visible before the read is executed
369 */
370 smp_mb();
5e9d5275 371
5864a2fd
MS
372 if (!smp_load_acquire(&sma->complex_mode)) {
373 /* fast path successful! */
374 return sops->sem_num;
6062a8dc 375 }
5e9d5275
MS
376 spin_unlock(&sem->lock);
377 }
378
379 /* slow path: acquire the full lock */
380 ipc_lock_object(&sma->sem_perm);
6062a8dc 381
5e9d5275
MS
382 if (sma->complex_count == 0) {
383 /* False alarm:
384 * There is no complex operation, thus we can switch
385 * back to the fast path.
386 */
387 spin_lock(&sem->lock);
388 ipc_unlock_object(&sma->sem_perm);
389 return sops->sem_num;
6062a8dc 390 } else {
5e9d5275
MS
391 /* Not a false alarm, thus complete the sequence for a
392 * full lock.
6062a8dc 393 */
5864a2fd
MS
394 complexmode_enter(sma);
395 return SEM_GLOBAL_LOCK;
6062a8dc 396 }
6062a8dc
RR
397}
398
399static inline void sem_unlock(struct sem_array *sma, int locknum)
400{
5864a2fd 401 if (locknum == SEM_GLOBAL_LOCK) {
f269f40a 402 unmerge_queues(sma);
5864a2fd 403 complexmode_tryleave(sma);
cf9d5d78 404 ipc_unlock_object(&sma->sem_perm);
6062a8dc
RR
405 } else {
406 struct sem *sem = sma->sem_base + locknum;
407 spin_unlock(&sem->lock);
408 }
6062a8dc
RR
409}
410
3e148c79 411/*
d9a605e4 412 * sem_lock_(check_) routines are called in the paths where the rwsem
3e148c79 413 * is not held.
321310ce
LT
414 *
415 * The caller holds the RCU read lock.
3e148c79 416 */
6062a8dc
RR
417static inline struct sem_array *sem_obtain_lock(struct ipc_namespace *ns,
418 int id, struct sembuf *sops, int nsops, int *locknum)
023a5355 419{
c460b662
RR
420 struct kern_ipc_perm *ipcp;
421 struct sem_array *sma;
03f02c76 422
55b7ae50 423 ipcp = ipc_obtain_object_idr(&sem_ids(ns), id);
321310ce
LT
424 if (IS_ERR(ipcp))
425 return ERR_CAST(ipcp);
b1ed88b4 426
6062a8dc
RR
427 sma = container_of(ipcp, struct sem_array, sem_perm);
428 *locknum = sem_lock(sma, sops, nsops);
c460b662
RR
429
430 /* ipc_rmid() may have already freed the ID while sem_lock
431 * was spinning: verify that the structure is still valid
432 */
72a8ff2f 433 if (ipc_valid_object(ipcp))
c460b662
RR
434 return container_of(ipcp, struct sem_array, sem_perm);
435
6062a8dc 436 sem_unlock(sma, *locknum);
321310ce 437 return ERR_PTR(-EINVAL);
023a5355
ND
438}
439
16df3674
DB
440static inline struct sem_array *sem_obtain_object(struct ipc_namespace *ns, int id)
441{
55b7ae50 442 struct kern_ipc_perm *ipcp = ipc_obtain_object_idr(&sem_ids(ns), id);
16df3674
DB
443
444 if (IS_ERR(ipcp))
445 return ERR_CAST(ipcp);
446
447 return container_of(ipcp, struct sem_array, sem_perm);
448}
449
16df3674
DB
450static inline struct sem_array *sem_obtain_object_check(struct ipc_namespace *ns,
451 int id)
452{
453 struct kern_ipc_perm *ipcp = ipc_obtain_object_check(&sem_ids(ns), id);
454
455 if (IS_ERR(ipcp))
456 return ERR_CAST(ipcp);
b1ed88b4 457
03f02c76 458 return container_of(ipcp, struct sem_array, sem_perm);
023a5355
ND
459}
460
6ff37972
PP
461static inline void sem_lock_and_putref(struct sem_array *sma)
462{
6062a8dc 463 sem_lock(sma, NULL, -1);
9b24fef9 464 ipc_rcu_putref(sma, sem_rcu_free);
6ff37972
PP
465}
466
7ca7e564
ND
467static inline void sem_rmid(struct ipc_namespace *ns, struct sem_array *s)
468{
469 ipc_rmid(&sem_ids(ns), &s->sem_perm);
470}
471
f4566f04
ND
472/**
473 * newary - Create a new semaphore set
474 * @ns: namespace
475 * @params: ptr to the structure that contains key, semflg and nsems
476 *
d9a605e4 477 * Called with sem_ids.rwsem held (as a writer)
f4566f04 478 */
7748dbfa 479static int newary(struct ipc_namespace *ns, struct ipc_params *params)
1da177e4
LT
480{
481 int id;
482 int retval;
483 struct sem_array *sma;
484 int size;
7748dbfa
ND
485 key_t key = params->key;
486 int nsems = params->u.nsems;
487 int semflg = params->flg;
b97e820f 488 int i;
1da177e4
LT
489
490 if (!nsems)
491 return -EINVAL;
e3893534 492 if (ns->used_sems + nsems > ns->sc_semmns)
1da177e4
LT
493 return -ENOSPC;
494
239521f3 495 size = sizeof(*sma) + nsems * sizeof(struct sem);
1da177e4 496 sma = ipc_rcu_alloc(size);
3ab08fe2 497 if (!sma)
1da177e4 498 return -ENOMEM;
3ab08fe2 499
239521f3 500 memset(sma, 0, size);
1da177e4
LT
501
502 sma->sem_perm.mode = (semflg & S_IRWXUGO);
503 sma->sem_perm.key = key;
504
505 sma->sem_perm.security = NULL;
506 retval = security_sem_alloc(sma);
507 if (retval) {
53dad6d3 508 ipc_rcu_putref(sma, ipc_rcu_free);
1da177e4
LT
509 return retval;
510 }
511
1da177e4 512 sma->sem_base = (struct sem *) &sma[1];
b97e820f 513
6062a8dc 514 for (i = 0; i < nsems; i++) {
1a82e9e1
MS
515 INIT_LIST_HEAD(&sma->sem_base[i].pending_alter);
516 INIT_LIST_HEAD(&sma->sem_base[i].pending_const);
6062a8dc
RR
517 spin_lock_init(&sma->sem_base[i].lock);
518 }
b97e820f
MS
519
520 sma->complex_count = 0;
5864a2fd 521 sma->complex_mode = true; /* dropped by sem_unlock below */
1a82e9e1
MS
522 INIT_LIST_HEAD(&sma->pending_alter);
523 INIT_LIST_HEAD(&sma->pending_const);
4daa28f6 524 INIT_LIST_HEAD(&sma->list_id);
1da177e4
LT
525 sma->sem_nsems = nsems;
526 sma->sem_ctime = get_seconds();
e8577d1f
MS
527
528 id = ipc_addid(&sem_ids(ns), &sma->sem_perm, ns->sc_semmni);
529 if (id < 0) {
530 ipc_rcu_putref(sma, sem_rcu_free);
531 return id;
532 }
533 ns->used_sems += nsems;
534
6062a8dc 535 sem_unlock(sma, -1);
6d49dab8 536 rcu_read_unlock();
1da177e4 537
7ca7e564 538 return sma->sem_perm.id;
1da177e4
LT
539}
540
7748dbfa 541
f4566f04 542/*
d9a605e4 543 * Called with sem_ids.rwsem and ipcp locked.
f4566f04 544 */
03f02c76 545static inline int sem_security(struct kern_ipc_perm *ipcp, int semflg)
7748dbfa 546{
03f02c76
ND
547 struct sem_array *sma;
548
549 sma = container_of(ipcp, struct sem_array, sem_perm);
550 return security_sem_associate(sma, semflg);
7748dbfa
ND
551}
552
f4566f04 553/*
d9a605e4 554 * Called with sem_ids.rwsem and ipcp locked.
f4566f04 555 */
03f02c76
ND
556static inline int sem_more_checks(struct kern_ipc_perm *ipcp,
557 struct ipc_params *params)
7748dbfa 558{
03f02c76
ND
559 struct sem_array *sma;
560
561 sma = container_of(ipcp, struct sem_array, sem_perm);
562 if (params->u.nsems > sma->sem_nsems)
7748dbfa
ND
563 return -EINVAL;
564
565 return 0;
566}
567
d5460c99 568SYSCALL_DEFINE3(semget, key_t, key, int, nsems, int, semflg)
1da177e4 569{
e3893534 570 struct ipc_namespace *ns;
eb66ec44
MK
571 static const struct ipc_ops sem_ops = {
572 .getnew = newary,
573 .associate = sem_security,
574 .more_checks = sem_more_checks,
575 };
7748dbfa 576 struct ipc_params sem_params;
e3893534
KK
577
578 ns = current->nsproxy->ipc_ns;
1da177e4 579
e3893534 580 if (nsems < 0 || nsems > ns->sc_semmsl)
1da177e4 581 return -EINVAL;
7ca7e564 582
7748dbfa
ND
583 sem_params.key = key;
584 sem_params.flg = semflg;
585 sem_params.u.nsems = nsems;
1da177e4 586
7748dbfa 587 return ipcget(ns, &sem_ids(ns), &sem_ops, &sem_params);
1da177e4
LT
588}
589
78f5009c 590/**
4ce33ec2
DB
591 * perform_atomic_semop[_slow] - Attempt to perform semaphore
592 * operations on a given array.
758a6ba3 593 * @sma: semaphore array
d198cd6d 594 * @q: struct sem_queue that describes the operation
758a6ba3 595 *
4ce33ec2
DB
596 * Caller blocking are as follows, based the value
597 * indicated by the semaphore operation (sem_op):
598 *
599 * (1) >0 never blocks.
600 * (2) 0 (wait-for-zero operation): semval is non-zero.
601 * (3) <0 attempting to decrement semval to a value smaller than zero.
602 *
758a6ba3
MS
603 * Returns 0 if the operation was possible.
604 * Returns 1 if the operation is impossible, the caller must sleep.
4ce33ec2 605 * Returns <0 for error codes.
1da177e4 606 */
4ce33ec2 607static int perform_atomic_semop_slow(struct sem_array *sma, struct sem_queue *q)
1da177e4 608{
d198cd6d 609 int result, sem_op, nsops, pid;
1da177e4 610 struct sembuf *sop;
239521f3 611 struct sem *curr;
d198cd6d
MS
612 struct sembuf *sops;
613 struct sem_undo *un;
614
615 sops = q->sops;
616 nsops = q->nsops;
617 un = q->undo;
1da177e4
LT
618
619 for (sop = sops; sop < sops + nsops; sop++) {
620 curr = sma->sem_base + sop->sem_num;
621 sem_op = sop->sem_op;
622 result = curr->semval;
78f5009c 623
1da177e4
LT
624 if (!sem_op && result)
625 goto would_block;
626
627 result += sem_op;
628 if (result < 0)
629 goto would_block;
630 if (result > SEMVMX)
631 goto out_of_range;
78f5009c 632
1da177e4
LT
633 if (sop->sem_flg & SEM_UNDO) {
634 int undo = un->semadj[sop->sem_num] - sem_op;
78f5009c 635 /* Exceeding the undo range is an error. */
1da177e4
LT
636 if (undo < (-SEMAEM - 1) || undo > SEMAEM)
637 goto out_of_range;
78f5009c 638 un->semadj[sop->sem_num] = undo;
1da177e4 639 }
78f5009c 640
1da177e4
LT
641 curr->semval = result;
642 }
643
644 sop--;
d198cd6d 645 pid = q->pid;
1da177e4
LT
646 while (sop >= sops) {
647 sma->sem_base[sop->sem_num].sempid = pid;
1da177e4
LT
648 sop--;
649 }
78f5009c 650
1da177e4
LT
651 return 0;
652
653out_of_range:
654 result = -ERANGE;
655 goto undo;
656
657would_block:
ed247b7c
MS
658 q->blocking = sop;
659
1da177e4
LT
660 if (sop->sem_flg & IPC_NOWAIT)
661 result = -EAGAIN;
662 else
663 result = 1;
664
665undo:
666 sop--;
667 while (sop >= sops) {
78f5009c
PM
668 sem_op = sop->sem_op;
669 sma->sem_base[sop->sem_num].semval -= sem_op;
670 if (sop->sem_flg & SEM_UNDO)
671 un->semadj[sop->sem_num] += sem_op;
1da177e4
LT
672 sop--;
673 }
674
675 return result;
676}
677
4ce33ec2
DB
678static int perform_atomic_semop(struct sem_array *sma, struct sem_queue *q)
679{
680 int result, sem_op, nsops;
681 struct sembuf *sop;
682 struct sem *curr;
683 struct sembuf *sops;
684 struct sem_undo *un;
685
686 sops = q->sops;
687 nsops = q->nsops;
688 un = q->undo;
689
690 if (unlikely(q->dupsop))
691 return perform_atomic_semop_slow(sma, q);
692
693 /*
694 * We scan the semaphore set twice, first to ensure that the entire
695 * operation can succeed, therefore avoiding any pointless writes
696 * to shared memory and having to undo such changes in order to block
697 * until the operations can go through.
698 */
699 for (sop = sops; sop < sops + nsops; sop++) {
700 curr = sma->sem_base + sop->sem_num;
701 sem_op = sop->sem_op;
702 result = curr->semval;
703
704 if (!sem_op && result)
705 goto would_block; /* wait-for-zero */
706
707 result += sem_op;
708 if (result < 0)
709 goto would_block;
710
711 if (result > SEMVMX)
712 return -ERANGE;
713
714 if (sop->sem_flg & SEM_UNDO) {
715 int undo = un->semadj[sop->sem_num] - sem_op;
716
717 /* Exceeding the undo range is an error. */
718 if (undo < (-SEMAEM - 1) || undo > SEMAEM)
719 return -ERANGE;
720 }
721 }
722
723 for (sop = sops; sop < sops + nsops; sop++) {
724 curr = sma->sem_base + sop->sem_num;
725 sem_op = sop->sem_op;
726 result = curr->semval;
727
728 if (sop->sem_flg & SEM_UNDO) {
729 int undo = un->semadj[sop->sem_num] - sem_op;
730
731 un->semadj[sop->sem_num] = undo;
732 }
733 curr->semval += sem_op;
734 curr->sempid = q->pid;
735 }
736
737 return 0;
738
739would_block:
740 q->blocking = sop;
741 return sop->sem_flg & IPC_NOWAIT ? -EAGAIN : 1;
742}
743
9ae949fa
DB
744static inline void wake_up_sem_queue_prepare(struct sem_queue *q, int error,
745 struct wake_q_head *wake_q)
0a2b9d4c 746{
9ae949fa
DB
747 wake_q_add(wake_q, q->sleeper);
748 /*
749 * Rely on the above implicit barrier, such that we can
750 * ensure that we hold reference to the task before setting
751 * q->status. Otherwise we could race with do_exit if the
752 * task is awoken by an external event before calling
753 * wake_up_process().
754 */
755 WRITE_ONCE(q->status, error);
d4212093
NP
756}
757
b97e820f
MS
758static void unlink_queue(struct sem_array *sma, struct sem_queue *q)
759{
760 list_del(&q->list);
9f1bc2c9 761 if (q->nsops > 1)
b97e820f
MS
762 sma->complex_count--;
763}
764
fd5db422
MS
765/** check_restart(sma, q)
766 * @sma: semaphore array
767 * @q: the operation that just completed
768 *
769 * update_queue is O(N^2) when it restarts scanning the whole queue of
770 * waiting operations. Therefore this function checks if the restart is
771 * really necessary. It is called after a previously waiting operation
1a82e9e1
MS
772 * modified the array.
773 * Note that wait-for-zero operations are handled without restart.
fd5db422
MS
774 */
775static int check_restart(struct sem_array *sma, struct sem_queue *q)
776{
1a82e9e1
MS
777 /* pending complex alter operations are too difficult to analyse */
778 if (!list_empty(&sma->pending_alter))
fd5db422
MS
779 return 1;
780
781 /* we were a sleeping complex operation. Too difficult */
782 if (q->nsops > 1)
783 return 1;
784
1a82e9e1
MS
785 /* It is impossible that someone waits for the new value:
786 * - complex operations always restart.
787 * - wait-for-zero are handled seperately.
788 * - q is a previously sleeping simple operation that
789 * altered the array. It must be a decrement, because
790 * simple increments never sleep.
791 * - If there are older (higher priority) decrements
792 * in the queue, then they have observed the original
793 * semval value and couldn't proceed. The operation
794 * decremented to value - thus they won't proceed either.
795 */
796 return 0;
797}
fd5db422 798
1a82e9e1 799/**
8001c858 800 * wake_const_ops - wake up non-alter tasks
1a82e9e1
MS
801 * @sma: semaphore array.
802 * @semnum: semaphore that was modified.
9ae949fa 803 * @wake_q: lockless wake-queue head.
1a82e9e1
MS
804 *
805 * wake_const_ops must be called after a semaphore in a semaphore array
806 * was set to 0. If complex const operations are pending, wake_const_ops must
807 * be called with semnum = -1, as well as with the number of each modified
808 * semaphore.
9ae949fa 809 * The tasks that must be woken up are added to @wake_q. The return code
1a82e9e1
MS
810 * is stored in q->pid.
811 * The function returns 1 if at least one operation was completed successfully.
812 */
813static int wake_const_ops(struct sem_array *sma, int semnum,
9ae949fa 814 struct wake_q_head *wake_q)
1a82e9e1
MS
815{
816 struct sem_queue *q;
817 struct list_head *walk;
818 struct list_head *pending_list;
819 int semop_completed = 0;
820
821 if (semnum == -1)
822 pending_list = &sma->pending_const;
823 else
824 pending_list = &sma->sem_base[semnum].pending_const;
fd5db422 825
1a82e9e1
MS
826 walk = pending_list->next;
827 while (walk != pending_list) {
828 int error;
829
830 q = container_of(walk, struct sem_queue, list);
831 walk = walk->next;
832
d198cd6d 833 error = perform_atomic_semop(sma, q);
1a82e9e1
MS
834
835 if (error <= 0) {
836 /* operation completed, remove from queue & wakeup */
837
838 unlink_queue(sma, q);
839
9ae949fa 840 wake_up_sem_queue_prepare(q, error, wake_q);
1a82e9e1
MS
841 if (error == 0)
842 semop_completed = 1;
843 }
844 }
845 return semop_completed;
846}
847
848/**
8001c858 849 * do_smart_wakeup_zero - wakeup all wait for zero tasks
1a82e9e1
MS
850 * @sma: semaphore array
851 * @sops: operations that were performed
852 * @nsops: number of operations
9ae949fa 853 * @wake_q: lockless wake-queue head
1a82e9e1 854 *
8001c858
DB
855 * Checks all required queue for wait-for-zero operations, based
856 * on the actual changes that were performed on the semaphore array.
1a82e9e1
MS
857 * The function returns 1 if at least one operation was completed successfully.
858 */
859static int do_smart_wakeup_zero(struct sem_array *sma, struct sembuf *sops,
9ae949fa 860 int nsops, struct wake_q_head *wake_q)
1a82e9e1
MS
861{
862 int i;
863 int semop_completed = 0;
864 int got_zero = 0;
865
866 /* first: the per-semaphore queues, if known */
867 if (sops) {
868 for (i = 0; i < nsops; i++) {
869 int num = sops[i].sem_num;
870
871 if (sma->sem_base[num].semval == 0) {
872 got_zero = 1;
9ae949fa 873 semop_completed |= wake_const_ops(sma, num, wake_q);
1a82e9e1
MS
874 }
875 }
876 } else {
877 /*
878 * No sops means modified semaphores not known.
879 * Assume all were changed.
fd5db422 880 */
1a82e9e1
MS
881 for (i = 0; i < sma->sem_nsems; i++) {
882 if (sma->sem_base[i].semval == 0) {
883 got_zero = 1;
9ae949fa 884 semop_completed |= wake_const_ops(sma, i, wake_q);
1a82e9e1
MS
885 }
886 }
fd5db422
MS
887 }
888 /*
1a82e9e1
MS
889 * If one of the modified semaphores got 0,
890 * then check the global queue, too.
fd5db422 891 */
1a82e9e1 892 if (got_zero)
9ae949fa 893 semop_completed |= wake_const_ops(sma, -1, wake_q);
fd5db422 894
1a82e9e1 895 return semop_completed;
fd5db422
MS
896}
897
636c6be8
MS
898
899/**
8001c858 900 * update_queue - look for tasks that can be completed.
636c6be8
MS
901 * @sma: semaphore array.
902 * @semnum: semaphore that was modified.
9ae949fa 903 * @wake_q: lockless wake-queue head.
636c6be8
MS
904 *
905 * update_queue must be called after a semaphore in a semaphore array
9f1bc2c9
RR
906 * was modified. If multiple semaphores were modified, update_queue must
907 * be called with semnum = -1, as well as with the number of each modified
908 * semaphore.
9ae949fa 909 * The tasks that must be woken up are added to @wake_q. The return code
0a2b9d4c 910 * is stored in q->pid.
1a82e9e1
MS
911 * The function internally checks if const operations can now succeed.
912 *
0a2b9d4c 913 * The function return 1 if at least one semop was completed successfully.
1da177e4 914 */
9ae949fa 915static int update_queue(struct sem_array *sma, int semnum, struct wake_q_head *wake_q)
1da177e4 916{
636c6be8
MS
917 struct sem_queue *q;
918 struct list_head *walk;
919 struct list_head *pending_list;
0a2b9d4c 920 int semop_completed = 0;
636c6be8 921
9f1bc2c9 922 if (semnum == -1)
1a82e9e1 923 pending_list = &sma->pending_alter;
9f1bc2c9 924 else
1a82e9e1 925 pending_list = &sma->sem_base[semnum].pending_alter;
9cad200c
NP
926
927again:
636c6be8
MS
928 walk = pending_list->next;
929 while (walk != pending_list) {
fd5db422 930 int error, restart;
636c6be8 931
9f1bc2c9 932 q = container_of(walk, struct sem_queue, list);
636c6be8 933 walk = walk->next;
1da177e4 934
d987f8b2
MS
935 /* If we are scanning the single sop, per-semaphore list of
936 * one semaphore and that semaphore is 0, then it is not
1a82e9e1 937 * necessary to scan further: simple increments
d987f8b2
MS
938 * that affect only one entry succeed immediately and cannot
939 * be in the per semaphore pending queue, and decrements
940 * cannot be successful if the value is already 0.
941 */
1a82e9e1 942 if (semnum != -1 && sma->sem_base[semnum].semval == 0)
d987f8b2
MS
943 break;
944
d198cd6d 945 error = perform_atomic_semop(sma, q);
1da177e4
LT
946
947 /* Does q->sleeper still need to sleep? */
9cad200c
NP
948 if (error > 0)
949 continue;
950
b97e820f 951 unlink_queue(sma, q);
9cad200c 952
0a2b9d4c 953 if (error) {
fd5db422 954 restart = 0;
0a2b9d4c
MS
955 } else {
956 semop_completed = 1;
9ae949fa 957 do_smart_wakeup_zero(sma, q->sops, q->nsops, wake_q);
fd5db422 958 restart = check_restart(sma, q);
0a2b9d4c 959 }
fd5db422 960
9ae949fa 961 wake_up_sem_queue_prepare(q, error, wake_q);
fd5db422 962 if (restart)
9cad200c 963 goto again;
1da177e4 964 }
0a2b9d4c 965 return semop_completed;
1da177e4
LT
966}
967
0e8c6656 968/**
8001c858 969 * set_semotime - set sem_otime
0e8c6656
MS
970 * @sma: semaphore array
971 * @sops: operations that modified the array, may be NULL
972 *
973 * sem_otime is replicated to avoid cache line trashing.
974 * This function sets one instance to the current time.
975 */
976static void set_semotime(struct sem_array *sma, struct sembuf *sops)
977{
978 if (sops == NULL) {
979 sma->sem_base[0].sem_otime = get_seconds();
980 } else {
981 sma->sem_base[sops[0].sem_num].sem_otime =
982 get_seconds();
983 }
984}
985
0a2b9d4c 986/**
8001c858 987 * do_smart_update - optimized update_queue
fd5db422
MS
988 * @sma: semaphore array
989 * @sops: operations that were performed
990 * @nsops: number of operations
0a2b9d4c 991 * @otime: force setting otime
9ae949fa 992 * @wake_q: lockless wake-queue head
fd5db422 993 *
1a82e9e1
MS
994 * do_smart_update() does the required calls to update_queue and wakeup_zero,
995 * based on the actual changes that were performed on the semaphore array.
0a2b9d4c 996 * Note that the function does not do the actual wake-up: the caller is
9ae949fa 997 * responsible for calling wake_up_q().
0a2b9d4c 998 * It is safe to perform this call after dropping all locks.
fd5db422 999 */
0a2b9d4c 1000static void do_smart_update(struct sem_array *sma, struct sembuf *sops, int nsops,
9ae949fa 1001 int otime, struct wake_q_head *wake_q)
fd5db422
MS
1002{
1003 int i;
1004
9ae949fa 1005 otime |= do_smart_wakeup_zero(sma, sops, nsops, wake_q);
1a82e9e1 1006
f269f40a
MS
1007 if (!list_empty(&sma->pending_alter)) {
1008 /* semaphore array uses the global queue - just process it. */
9ae949fa 1009 otime |= update_queue(sma, -1, wake_q);
f269f40a
MS
1010 } else {
1011 if (!sops) {
1012 /*
1013 * No sops, thus the modified semaphores are not
1014 * known. Check all.
1015 */
1016 for (i = 0; i < sma->sem_nsems; i++)
9ae949fa 1017 otime |= update_queue(sma, i, wake_q);
f269f40a
MS
1018 } else {
1019 /*
1020 * Check the semaphores that were increased:
1021 * - No complex ops, thus all sleeping ops are
1022 * decrease.
1023 * - if we decreased the value, then any sleeping
1024 * semaphore ops wont be able to run: If the
1025 * previous value was too small, then the new
1026 * value will be too small, too.
1027 */
1028 for (i = 0; i < nsops; i++) {
1029 if (sops[i].sem_op > 0) {
1030 otime |= update_queue(sma,
9ae949fa 1031 sops[i].sem_num, wake_q);
f269f40a 1032 }
ab465df9 1033 }
9f1bc2c9 1034 }
fd5db422 1035 }
0e8c6656
MS
1036 if (otime)
1037 set_semotime(sma, sops);
fd5db422
MS
1038}
1039
2f2ed41d 1040/*
b220c57a 1041 * check_qop: Test if a queued operation sleeps on the semaphore semnum
2f2ed41d
MS
1042 */
1043static int check_qop(struct sem_array *sma, int semnum, struct sem_queue *q,
1044 bool count_zero)
1045{
b220c57a 1046 struct sembuf *sop = q->blocking;
2f2ed41d 1047
9b44ee2e
MS
1048 /*
1049 * Linux always (since 0.99.10) reported a task as sleeping on all
1050 * semaphores. This violates SUS, therefore it was changed to the
1051 * standard compliant behavior.
1052 * Give the administrators a chance to notice that an application
1053 * might misbehave because it relies on the Linux behavior.
1054 */
1055 pr_info_once("semctl(GETNCNT/GETZCNT) is since 3.16 Single Unix Specification compliant.\n"
1056 "The task %s (%d) triggered the difference, watch for misbehavior.\n",
1057 current->comm, task_pid_nr(current));
1058
b220c57a
MS
1059 if (sop->sem_num != semnum)
1060 return 0;
2f2ed41d 1061
b220c57a
MS
1062 if (count_zero && sop->sem_op == 0)
1063 return 1;
1064 if (!count_zero && sop->sem_op < 0)
1065 return 1;
1066
1067 return 0;
2f2ed41d
MS
1068}
1069
1da177e4
LT
1070/* The following counts are associated to each semaphore:
1071 * semncnt number of tasks waiting on semval being nonzero
1072 * semzcnt number of tasks waiting on semval being zero
b220c57a
MS
1073 *
1074 * Per definition, a task waits only on the semaphore of the first semop
1075 * that cannot proceed, even if additional operation would block, too.
1da177e4 1076 */
2f2ed41d
MS
1077static int count_semcnt(struct sem_array *sma, ushort semnum,
1078 bool count_zero)
1da177e4 1079{
2f2ed41d 1080 struct list_head *l;
239521f3 1081 struct sem_queue *q;
2f2ed41d 1082 int semcnt;
1da177e4 1083
2f2ed41d
MS
1084 semcnt = 0;
1085 /* First: check the simple operations. They are easy to evaluate */
1086 if (count_zero)
1087 l = &sma->sem_base[semnum].pending_const;
1088 else
1089 l = &sma->sem_base[semnum].pending_alter;
1da177e4 1090
2f2ed41d
MS
1091 list_for_each_entry(q, l, list) {
1092 /* all task on a per-semaphore list sleep on exactly
1093 * that semaphore
1094 */
1095 semcnt++;
ebc2e5e6
RR
1096 }
1097
2f2ed41d 1098 /* Then: check the complex operations. */
1994862d 1099 list_for_each_entry(q, &sma->pending_alter, list) {
2f2ed41d
MS
1100 semcnt += check_qop(sma, semnum, q, count_zero);
1101 }
1102 if (count_zero) {
1103 list_for_each_entry(q, &sma->pending_const, list) {
1104 semcnt += check_qop(sma, semnum, q, count_zero);
1105 }
1994862d 1106 }
2f2ed41d 1107 return semcnt;
1da177e4
LT
1108}
1109
d9a605e4
DB
1110/* Free a semaphore set. freeary() is called with sem_ids.rwsem locked
1111 * as a writer and the spinlock for this semaphore set hold. sem_ids.rwsem
3e148c79 1112 * remains locked on exit.
1da177e4 1113 */
01b8b07a 1114static void freeary(struct ipc_namespace *ns, struct kern_ipc_perm *ipcp)
1da177e4 1115{
380af1b3
MS
1116 struct sem_undo *un, *tu;
1117 struct sem_queue *q, *tq;
01b8b07a 1118 struct sem_array *sma = container_of(ipcp, struct sem_array, sem_perm);
9f1bc2c9 1119 int i;
9ae949fa 1120 DEFINE_WAKE_Q(wake_q);
1da177e4 1121
380af1b3 1122 /* Free the existing undo structures for this semaphore set. */
cf9d5d78 1123 ipc_assert_locked_object(&sma->sem_perm);
380af1b3
MS
1124 list_for_each_entry_safe(un, tu, &sma->list_id, list_id) {
1125 list_del(&un->list_id);
1126 spin_lock(&un->ulp->lock);
1da177e4 1127 un->semid = -1;
380af1b3
MS
1128 list_del_rcu(&un->list_proc);
1129 spin_unlock(&un->ulp->lock);
693a8b6e 1130 kfree_rcu(un, rcu);
380af1b3 1131 }
1da177e4
LT
1132
1133 /* Wake up all pending processes and let them fail with EIDRM. */
1a82e9e1
MS
1134 list_for_each_entry_safe(q, tq, &sma->pending_const, list) {
1135 unlink_queue(sma, q);
9ae949fa 1136 wake_up_sem_queue_prepare(q, -EIDRM, &wake_q);
1a82e9e1
MS
1137 }
1138
1139 list_for_each_entry_safe(q, tq, &sma->pending_alter, list) {
b97e820f 1140 unlink_queue(sma, q);
9ae949fa 1141 wake_up_sem_queue_prepare(q, -EIDRM, &wake_q);
1da177e4 1142 }
9f1bc2c9
RR
1143 for (i = 0; i < sma->sem_nsems; i++) {
1144 struct sem *sem = sma->sem_base + i;
1a82e9e1
MS
1145 list_for_each_entry_safe(q, tq, &sem->pending_const, list) {
1146 unlink_queue(sma, q);
9ae949fa 1147 wake_up_sem_queue_prepare(q, -EIDRM, &wake_q);
1a82e9e1
MS
1148 }
1149 list_for_each_entry_safe(q, tq, &sem->pending_alter, list) {
9f1bc2c9 1150 unlink_queue(sma, q);
9ae949fa 1151 wake_up_sem_queue_prepare(q, -EIDRM, &wake_q);
9f1bc2c9
RR
1152 }
1153 }
1da177e4 1154
7ca7e564
ND
1155 /* Remove the semaphore set from the IDR */
1156 sem_rmid(ns, sma);
6062a8dc 1157 sem_unlock(sma, -1);
6d49dab8 1158 rcu_read_unlock();
1da177e4 1159
9ae949fa 1160 wake_up_q(&wake_q);
e3893534 1161 ns->used_sems -= sma->sem_nsems;
53dad6d3 1162 ipc_rcu_putref(sma, sem_rcu_free);
1da177e4
LT
1163}
1164
1165static unsigned long copy_semid_to_user(void __user *buf, struct semid64_ds *in, int version)
1166{
239521f3 1167 switch (version) {
1da177e4
LT
1168 case IPC_64:
1169 return copy_to_user(buf, in, sizeof(*in));
1170 case IPC_OLD:
1171 {
1172 struct semid_ds out;
1173
982f7c2b
DR
1174 memset(&out, 0, sizeof(out));
1175
1da177e4
LT
1176 ipc64_perm_to_ipc_perm(&in->sem_perm, &out.sem_perm);
1177
1178 out.sem_otime = in->sem_otime;
1179 out.sem_ctime = in->sem_ctime;
1180 out.sem_nsems = in->sem_nsems;
1181
1182 return copy_to_user(buf, &out, sizeof(out));
1183 }
1184 default:
1185 return -EINVAL;
1186 }
1187}
1188
d12e1e50
MS
1189static time_t get_semotime(struct sem_array *sma)
1190{
1191 int i;
1192 time_t res;
1193
1194 res = sma->sem_base[0].sem_otime;
1195 for (i = 1; i < sma->sem_nsems; i++) {
1196 time_t to = sma->sem_base[i].sem_otime;
1197
1198 if (to > res)
1199 res = to;
1200 }
1201 return res;
1202}
1203
4b9fcb0e 1204static int semctl_nolock(struct ipc_namespace *ns, int semid,
e1fd1f49 1205 int cmd, int version, void __user *p)
1da177e4 1206{
e5cc9c7b 1207 int err;
1da177e4
LT
1208 struct sem_array *sma;
1209
239521f3 1210 switch (cmd) {
1da177e4
LT
1211 case IPC_INFO:
1212 case SEM_INFO:
1213 {
1214 struct seminfo seminfo;
1215 int max_id;
1216
1217 err = security_sem_semctl(NULL, cmd);
1218 if (err)
1219 return err;
46c0a8ca 1220
239521f3 1221 memset(&seminfo, 0, sizeof(seminfo));
e3893534
KK
1222 seminfo.semmni = ns->sc_semmni;
1223 seminfo.semmns = ns->sc_semmns;
1224 seminfo.semmsl = ns->sc_semmsl;
1225 seminfo.semopm = ns->sc_semopm;
1da177e4
LT
1226 seminfo.semvmx = SEMVMX;
1227 seminfo.semmnu = SEMMNU;
1228 seminfo.semmap = SEMMAP;
1229 seminfo.semume = SEMUME;
d9a605e4 1230 down_read(&sem_ids(ns).rwsem);
1da177e4 1231 if (cmd == SEM_INFO) {
e3893534
KK
1232 seminfo.semusz = sem_ids(ns).in_use;
1233 seminfo.semaem = ns->used_sems;
1da177e4
LT
1234 } else {
1235 seminfo.semusz = SEMUSZ;
1236 seminfo.semaem = SEMAEM;
1237 }
7ca7e564 1238 max_id = ipc_get_maxid(&sem_ids(ns));
d9a605e4 1239 up_read(&sem_ids(ns).rwsem);
46c0a8ca 1240 if (copy_to_user(p, &seminfo, sizeof(struct seminfo)))
1da177e4 1241 return -EFAULT;
239521f3 1242 return (max_id < 0) ? 0 : max_id;
1da177e4 1243 }
4b9fcb0e 1244 case IPC_STAT:
1da177e4
LT
1245 case SEM_STAT:
1246 {
1247 struct semid64_ds tbuf;
16df3674
DB
1248 int id = 0;
1249
1250 memset(&tbuf, 0, sizeof(tbuf));
1da177e4 1251
941b0304 1252 rcu_read_lock();
4b9fcb0e 1253 if (cmd == SEM_STAT) {
16df3674
DB
1254 sma = sem_obtain_object(ns, semid);
1255 if (IS_ERR(sma)) {
1256 err = PTR_ERR(sma);
1257 goto out_unlock;
1258 }
4b9fcb0e
PP
1259 id = sma->sem_perm.id;
1260 } else {
16df3674
DB
1261 sma = sem_obtain_object_check(ns, semid);
1262 if (IS_ERR(sma)) {
1263 err = PTR_ERR(sma);
1264 goto out_unlock;
1265 }
4b9fcb0e 1266 }
1da177e4
LT
1267
1268 err = -EACCES;
b0e77598 1269 if (ipcperms(ns, &sma->sem_perm, S_IRUGO))
1da177e4
LT
1270 goto out_unlock;
1271
1272 err = security_sem_semctl(sma, cmd);
1273 if (err)
1274 goto out_unlock;
1275
1da177e4 1276 kernel_to_ipc64_perm(&sma->sem_perm, &tbuf.sem_perm);
d12e1e50
MS
1277 tbuf.sem_otime = get_semotime(sma);
1278 tbuf.sem_ctime = sma->sem_ctime;
1279 tbuf.sem_nsems = sma->sem_nsems;
16df3674 1280 rcu_read_unlock();
e1fd1f49 1281 if (copy_semid_to_user(p, &tbuf, version))
1da177e4
LT
1282 return -EFAULT;
1283 return id;
1284 }
1285 default:
1286 return -EINVAL;
1287 }
1da177e4 1288out_unlock:
16df3674 1289 rcu_read_unlock();
1da177e4
LT
1290 return err;
1291}
1292
e1fd1f49
AV
1293static int semctl_setval(struct ipc_namespace *ns, int semid, int semnum,
1294 unsigned long arg)
1295{
1296 struct sem_undo *un;
1297 struct sem_array *sma;
239521f3 1298 struct sem *curr;
9ae949fa
DB
1299 int err, val;
1300 DEFINE_WAKE_Q(wake_q);
1301
e1fd1f49
AV
1302#if defined(CONFIG_64BIT) && defined(__BIG_ENDIAN)
1303 /* big-endian 64bit */
1304 val = arg >> 32;
1305#else
1306 /* 32bit or little-endian 64bit */
1307 val = arg;
1308#endif
1309
6062a8dc
RR
1310 if (val > SEMVMX || val < 0)
1311 return -ERANGE;
e1fd1f49 1312
6062a8dc
RR
1313 rcu_read_lock();
1314 sma = sem_obtain_object_check(ns, semid);
1315 if (IS_ERR(sma)) {
1316 rcu_read_unlock();
1317 return PTR_ERR(sma);
1318 }
1319
1320 if (semnum < 0 || semnum >= sma->sem_nsems) {
1321 rcu_read_unlock();
1322 return -EINVAL;
1323 }
1324
1325
1326 if (ipcperms(ns, &sma->sem_perm, S_IWUGO)) {
1327 rcu_read_unlock();
1328 return -EACCES;
1329 }
e1fd1f49
AV
1330
1331 err = security_sem_semctl(sma, SETVAL);
6062a8dc
RR
1332 if (err) {
1333 rcu_read_unlock();
1334 return -EACCES;
1335 }
e1fd1f49 1336
6062a8dc 1337 sem_lock(sma, NULL, -1);
e1fd1f49 1338
0f3d2b01 1339 if (!ipc_valid_object(&sma->sem_perm)) {
6e224f94
MS
1340 sem_unlock(sma, -1);
1341 rcu_read_unlock();
1342 return -EIDRM;
1343 }
1344
e1fd1f49
AV
1345 curr = &sma->sem_base[semnum];
1346
cf9d5d78 1347 ipc_assert_locked_object(&sma->sem_perm);
e1fd1f49
AV
1348 list_for_each_entry(un, &sma->list_id, list_id)
1349 un->semadj[semnum] = 0;
1350
1351 curr->semval = val;
1352 curr->sempid = task_tgid_vnr(current);
1353 sma->sem_ctime = get_seconds();
1354 /* maybe some queued-up processes were waiting for this */
9ae949fa 1355 do_smart_update(sma, NULL, 0, 0, &wake_q);
6062a8dc 1356 sem_unlock(sma, -1);
6d49dab8 1357 rcu_read_unlock();
9ae949fa 1358 wake_up_q(&wake_q);
6062a8dc 1359 return 0;
e1fd1f49
AV
1360}
1361
e3893534 1362static int semctl_main(struct ipc_namespace *ns, int semid, int semnum,
e1fd1f49 1363 int cmd, void __user *p)
1da177e4
LT
1364{
1365 struct sem_array *sma;
239521f3 1366 struct sem *curr;
16df3674 1367 int err, nsems;
1da177e4 1368 ushort fast_sem_io[SEMMSL_FAST];
239521f3 1369 ushort *sem_io = fast_sem_io;
9ae949fa 1370 DEFINE_WAKE_Q(wake_q);
16df3674
DB
1371
1372 rcu_read_lock();
1373 sma = sem_obtain_object_check(ns, semid);
1374 if (IS_ERR(sma)) {
1375 rcu_read_unlock();
023a5355 1376 return PTR_ERR(sma);
16df3674 1377 }
1da177e4
LT
1378
1379 nsems = sma->sem_nsems;
1380
1da177e4 1381 err = -EACCES;
c728b9c8
LT
1382 if (ipcperms(ns, &sma->sem_perm, cmd == SETALL ? S_IWUGO : S_IRUGO))
1383 goto out_rcu_wakeup;
1da177e4
LT
1384
1385 err = security_sem_semctl(sma, cmd);
c728b9c8
LT
1386 if (err)
1387 goto out_rcu_wakeup;
1da177e4
LT
1388
1389 err = -EACCES;
1390 switch (cmd) {
1391 case GETALL:
1392 {
e1fd1f49 1393 ushort __user *array = p;
1da177e4
LT
1394 int i;
1395
ce857229 1396 sem_lock(sma, NULL, -1);
0f3d2b01 1397 if (!ipc_valid_object(&sma->sem_perm)) {
6e224f94
MS
1398 err = -EIDRM;
1399 goto out_unlock;
1400 }
239521f3 1401 if (nsems > SEMMSL_FAST) {
ce857229 1402 if (!ipc_rcu_getref(sma)) {
ce857229 1403 err = -EIDRM;
6e224f94 1404 goto out_unlock;
ce857229
AV
1405 }
1406 sem_unlock(sma, -1);
6d49dab8 1407 rcu_read_unlock();
1da177e4 1408 sem_io = ipc_alloc(sizeof(ushort)*nsems);
239521f3 1409 if (sem_io == NULL) {
9b24fef9 1410 ipc_rcu_putref(sma, sem_rcu_free);
1da177e4
LT
1411 return -ENOMEM;
1412 }
1413
4091fd94 1414 rcu_read_lock();
6ff37972 1415 sem_lock_and_putref(sma);
0f3d2b01 1416 if (!ipc_valid_object(&sma->sem_perm)) {
1da177e4 1417 err = -EIDRM;
6e224f94 1418 goto out_unlock;
1da177e4 1419 }
ce857229 1420 }
1da177e4
LT
1421 for (i = 0; i < sma->sem_nsems; i++)
1422 sem_io[i] = sma->sem_base[i].semval;
6062a8dc 1423 sem_unlock(sma, -1);
6d49dab8 1424 rcu_read_unlock();
1da177e4 1425 err = 0;
239521f3 1426 if (copy_to_user(array, sem_io, nsems*sizeof(ushort)))
1da177e4
LT
1427 err = -EFAULT;
1428 goto out_free;
1429 }
1430 case SETALL:
1431 {
1432 int i;
1433 struct sem_undo *un;
1434
6062a8dc 1435 if (!ipc_rcu_getref(sma)) {
6e224f94
MS
1436 err = -EIDRM;
1437 goto out_rcu_wakeup;
6062a8dc 1438 }
16df3674 1439 rcu_read_unlock();
1da177e4 1440
239521f3 1441 if (nsems > SEMMSL_FAST) {
1da177e4 1442 sem_io = ipc_alloc(sizeof(ushort)*nsems);
239521f3 1443 if (sem_io == NULL) {
9b24fef9 1444 ipc_rcu_putref(sma, sem_rcu_free);
1da177e4
LT
1445 return -ENOMEM;
1446 }
1447 }
1448
239521f3 1449 if (copy_from_user(sem_io, p, nsems*sizeof(ushort))) {
9b24fef9 1450 ipc_rcu_putref(sma, sem_rcu_free);
1da177e4
LT
1451 err = -EFAULT;
1452 goto out_free;
1453 }
1454
1455 for (i = 0; i < nsems; i++) {
1456 if (sem_io[i] > SEMVMX) {
9b24fef9 1457 ipc_rcu_putref(sma, sem_rcu_free);
1da177e4
LT
1458 err = -ERANGE;
1459 goto out_free;
1460 }
1461 }
4091fd94 1462 rcu_read_lock();
6ff37972 1463 sem_lock_and_putref(sma);
0f3d2b01 1464 if (!ipc_valid_object(&sma->sem_perm)) {
1da177e4 1465 err = -EIDRM;
6e224f94 1466 goto out_unlock;
1da177e4
LT
1467 }
1468
a5f4db87 1469 for (i = 0; i < nsems; i++) {
1da177e4 1470 sma->sem_base[i].semval = sem_io[i];
a5f4db87
DB
1471 sma->sem_base[i].sempid = task_tgid_vnr(current);
1472 }
4daa28f6 1473
cf9d5d78 1474 ipc_assert_locked_object(&sma->sem_perm);
4daa28f6 1475 list_for_each_entry(un, &sma->list_id, list_id) {
1da177e4
LT
1476 for (i = 0; i < nsems; i++)
1477 un->semadj[i] = 0;
4daa28f6 1478 }
1da177e4
LT
1479 sma->sem_ctime = get_seconds();
1480 /* maybe some queued-up processes were waiting for this */
9ae949fa 1481 do_smart_update(sma, NULL, 0, 0, &wake_q);
1da177e4
LT
1482 err = 0;
1483 goto out_unlock;
1484 }
e1fd1f49 1485 /* GETVAL, GETPID, GETNCTN, GETZCNT: fall-through */
1da177e4
LT
1486 }
1487 err = -EINVAL;
c728b9c8
LT
1488 if (semnum < 0 || semnum >= nsems)
1489 goto out_rcu_wakeup;
1da177e4 1490
6062a8dc 1491 sem_lock(sma, NULL, -1);
0f3d2b01 1492 if (!ipc_valid_object(&sma->sem_perm)) {
6e224f94
MS
1493 err = -EIDRM;
1494 goto out_unlock;
1495 }
1da177e4
LT
1496 curr = &sma->sem_base[semnum];
1497
1498 switch (cmd) {
1499 case GETVAL:
1500 err = curr->semval;
1501 goto out_unlock;
1502 case GETPID:
1503 err = curr->sempid;
1504 goto out_unlock;
1505 case GETNCNT:
2f2ed41d 1506 err = count_semcnt(sma, semnum, 0);
1da177e4
LT
1507 goto out_unlock;
1508 case GETZCNT:
2f2ed41d 1509 err = count_semcnt(sma, semnum, 1);
1da177e4 1510 goto out_unlock;
1da177e4 1511 }
16df3674 1512
1da177e4 1513out_unlock:
6062a8dc 1514 sem_unlock(sma, -1);
c728b9c8 1515out_rcu_wakeup:
6d49dab8 1516 rcu_read_unlock();
9ae949fa 1517 wake_up_q(&wake_q);
1da177e4 1518out_free:
239521f3 1519 if (sem_io != fast_sem_io)
1d5cfdb0 1520 ipc_free(sem_io);
1da177e4
LT
1521 return err;
1522}
1523
016d7132
PP
1524static inline unsigned long
1525copy_semid_from_user(struct semid64_ds *out, void __user *buf, int version)
1da177e4 1526{
239521f3 1527 switch (version) {
1da177e4 1528 case IPC_64:
016d7132 1529 if (copy_from_user(out, buf, sizeof(*out)))
1da177e4 1530 return -EFAULT;
1da177e4 1531 return 0;
1da177e4
LT
1532 case IPC_OLD:
1533 {
1534 struct semid_ds tbuf_old;
1535
239521f3 1536 if (copy_from_user(&tbuf_old, buf, sizeof(tbuf_old)))
1da177e4
LT
1537 return -EFAULT;
1538
016d7132
PP
1539 out->sem_perm.uid = tbuf_old.sem_perm.uid;
1540 out->sem_perm.gid = tbuf_old.sem_perm.gid;
1541 out->sem_perm.mode = tbuf_old.sem_perm.mode;
1da177e4
LT
1542
1543 return 0;
1544 }
1545 default:
1546 return -EINVAL;
1547 }
1548}
1549
522bb2a2 1550/*
d9a605e4 1551 * This function handles some semctl commands which require the rwsem
522bb2a2 1552 * to be held in write mode.
d9a605e4 1553 * NOTE: no locks must be held, the rwsem is taken inside this function.
522bb2a2 1554 */
21a4826a 1555static int semctl_down(struct ipc_namespace *ns, int semid,
e1fd1f49 1556 int cmd, int version, void __user *p)
1da177e4
LT
1557{
1558 struct sem_array *sma;
1559 int err;
016d7132 1560 struct semid64_ds semid64;
1da177e4
LT
1561 struct kern_ipc_perm *ipcp;
1562
239521f3 1563 if (cmd == IPC_SET) {
e1fd1f49 1564 if (copy_semid_from_user(&semid64, p, version))
1da177e4 1565 return -EFAULT;
1da177e4 1566 }
073115d6 1567
d9a605e4 1568 down_write(&sem_ids(ns).rwsem);
7b4cc5d8
DB
1569 rcu_read_lock();
1570
16df3674
DB
1571 ipcp = ipcctl_pre_down_nolock(ns, &sem_ids(ns), semid, cmd,
1572 &semid64.sem_perm, 0);
7b4cc5d8
DB
1573 if (IS_ERR(ipcp)) {
1574 err = PTR_ERR(ipcp);
7b4cc5d8
DB
1575 goto out_unlock1;
1576 }
073115d6 1577
a5f75e7f 1578 sma = container_of(ipcp, struct sem_array, sem_perm);
1da177e4
LT
1579
1580 err = security_sem_semctl(sma, cmd);
7b4cc5d8
DB
1581 if (err)
1582 goto out_unlock1;
1da177e4 1583
7b4cc5d8 1584 switch (cmd) {
1da177e4 1585 case IPC_RMID:
6062a8dc 1586 sem_lock(sma, NULL, -1);
7b4cc5d8 1587 /* freeary unlocks the ipc object and rcu */
01b8b07a 1588 freeary(ns, ipcp);
522bb2a2 1589 goto out_up;
1da177e4 1590 case IPC_SET:
6062a8dc 1591 sem_lock(sma, NULL, -1);
1efdb69b
EB
1592 err = ipc_update_perm(&semid64.sem_perm, ipcp);
1593 if (err)
7b4cc5d8 1594 goto out_unlock0;
1da177e4 1595 sma->sem_ctime = get_seconds();
1da177e4
LT
1596 break;
1597 default:
1da177e4 1598 err = -EINVAL;
7b4cc5d8 1599 goto out_unlock1;
1da177e4 1600 }
1da177e4 1601
7b4cc5d8 1602out_unlock0:
6062a8dc 1603 sem_unlock(sma, -1);
7b4cc5d8 1604out_unlock1:
6d49dab8 1605 rcu_read_unlock();
522bb2a2 1606out_up:
d9a605e4 1607 up_write(&sem_ids(ns).rwsem);
1da177e4
LT
1608 return err;
1609}
1610
e1fd1f49 1611SYSCALL_DEFINE4(semctl, int, semid, int, semnum, int, cmd, unsigned long, arg)
1da177e4 1612{
1da177e4 1613 int version;
e3893534 1614 struct ipc_namespace *ns;
e1fd1f49 1615 void __user *p = (void __user *)arg;
1da177e4
LT
1616
1617 if (semid < 0)
1618 return -EINVAL;
1619
1620 version = ipc_parse_version(&cmd);
e3893534 1621 ns = current->nsproxy->ipc_ns;
1da177e4 1622
239521f3 1623 switch (cmd) {
1da177e4
LT
1624 case IPC_INFO:
1625 case SEM_INFO:
4b9fcb0e 1626 case IPC_STAT:
1da177e4 1627 case SEM_STAT:
e1fd1f49 1628 return semctl_nolock(ns, semid, cmd, version, p);
1da177e4
LT
1629 case GETALL:
1630 case GETVAL:
1631 case GETPID:
1632 case GETNCNT:
1633 case GETZCNT:
1da177e4 1634 case SETALL:
e1fd1f49
AV
1635 return semctl_main(ns, semid, semnum, cmd, p);
1636 case SETVAL:
1637 return semctl_setval(ns, semid, semnum, arg);
1da177e4
LT
1638 case IPC_RMID:
1639 case IPC_SET:
e1fd1f49 1640 return semctl_down(ns, semid, cmd, version, p);
1da177e4
LT
1641 default:
1642 return -EINVAL;
1643 }
1644}
1645
1da177e4
LT
1646/* If the task doesn't already have a undo_list, then allocate one
1647 * here. We guarantee there is only one thread using this undo list,
1648 * and current is THE ONE
1649 *
1650 * If this allocation and assignment succeeds, but later
1651 * portions of this code fail, there is no need to free the sem_undo_list.
1652 * Just let it stay associated with the task, and it'll be freed later
1653 * at exit time.
1654 *
1655 * This can block, so callers must hold no locks.
1656 */
1657static inline int get_undo_list(struct sem_undo_list **undo_listp)
1658{
1659 struct sem_undo_list *undo_list;
1da177e4
LT
1660
1661 undo_list = current->sysvsem.undo_list;
1662 if (!undo_list) {
2453a306 1663 undo_list = kzalloc(sizeof(*undo_list), GFP_KERNEL);
1da177e4
LT
1664 if (undo_list == NULL)
1665 return -ENOMEM;
00a5dfdb 1666 spin_lock_init(&undo_list->lock);
1da177e4 1667 atomic_set(&undo_list->refcnt, 1);
4daa28f6
MS
1668 INIT_LIST_HEAD(&undo_list->list_proc);
1669
1da177e4
LT
1670 current->sysvsem.undo_list = undo_list;
1671 }
1672 *undo_listp = undo_list;
1673 return 0;
1674}
1675
bf17bb71 1676static struct sem_undo *__lookup_undo(struct sem_undo_list *ulp, int semid)
1da177e4 1677{
bf17bb71 1678 struct sem_undo *un;
4daa28f6 1679
bf17bb71
NP
1680 list_for_each_entry_rcu(un, &ulp->list_proc, list_proc) {
1681 if (un->semid == semid)
1682 return un;
1da177e4 1683 }
4daa28f6 1684 return NULL;
1da177e4
LT
1685}
1686
bf17bb71
NP
1687static struct sem_undo *lookup_undo(struct sem_undo_list *ulp, int semid)
1688{
1689 struct sem_undo *un;
1690
239521f3 1691 assert_spin_locked(&ulp->lock);
bf17bb71
NP
1692
1693 un = __lookup_undo(ulp, semid);
1694 if (un) {
1695 list_del_rcu(&un->list_proc);
1696 list_add_rcu(&un->list_proc, &ulp->list_proc);
1697 }
1698 return un;
1699}
1700
4daa28f6 1701/**
8001c858 1702 * find_alloc_undo - lookup (and if not present create) undo array
4daa28f6
MS
1703 * @ns: namespace
1704 * @semid: semaphore array id
1705 *
1706 * The function looks up (and if not present creates) the undo structure.
1707 * The size of the undo structure depends on the size of the semaphore
1708 * array, thus the alloc path is not that straightforward.
380af1b3
MS
1709 * Lifetime-rules: sem_undo is rcu-protected, on success, the function
1710 * performs a rcu_read_lock().
4daa28f6
MS
1711 */
1712static struct sem_undo *find_alloc_undo(struct ipc_namespace *ns, int semid)
1da177e4
LT
1713{
1714 struct sem_array *sma;
1715 struct sem_undo_list *ulp;
1716 struct sem_undo *un, *new;
6062a8dc 1717 int nsems, error;
1da177e4
LT
1718
1719 error = get_undo_list(&ulp);
1720 if (error)
1721 return ERR_PTR(error);
1722
380af1b3 1723 rcu_read_lock();
c530c6ac 1724 spin_lock(&ulp->lock);
1da177e4 1725 un = lookup_undo(ulp, semid);
c530c6ac 1726 spin_unlock(&ulp->lock);
239521f3 1727 if (likely(un != NULL))
1da177e4
LT
1728 goto out;
1729
1730 /* no undo structure around - allocate one. */
4daa28f6 1731 /* step 1: figure out the size of the semaphore array */
16df3674
DB
1732 sma = sem_obtain_object_check(ns, semid);
1733 if (IS_ERR(sma)) {
1734 rcu_read_unlock();
4de85cd6 1735 return ERR_CAST(sma);
16df3674 1736 }
023a5355 1737
1da177e4 1738 nsems = sma->sem_nsems;
6062a8dc
RR
1739 if (!ipc_rcu_getref(sma)) {
1740 rcu_read_unlock();
1741 un = ERR_PTR(-EIDRM);
1742 goto out;
1743 }
16df3674 1744 rcu_read_unlock();
1da177e4 1745
4daa28f6 1746 /* step 2: allocate new undo structure */
4668edc3 1747 new = kzalloc(sizeof(struct sem_undo) + sizeof(short)*nsems, GFP_KERNEL);
1da177e4 1748 if (!new) {
9b24fef9 1749 ipc_rcu_putref(sma, sem_rcu_free);
1da177e4
LT
1750 return ERR_PTR(-ENOMEM);
1751 }
1da177e4 1752
380af1b3 1753 /* step 3: Acquire the lock on semaphore array */
4091fd94 1754 rcu_read_lock();
6ff37972 1755 sem_lock_and_putref(sma);
0f3d2b01 1756 if (!ipc_valid_object(&sma->sem_perm)) {
6062a8dc 1757 sem_unlock(sma, -1);
6d49dab8 1758 rcu_read_unlock();
1da177e4
LT
1759 kfree(new);
1760 un = ERR_PTR(-EIDRM);
1761 goto out;
1762 }
380af1b3
MS
1763 spin_lock(&ulp->lock);
1764
1765 /*
1766 * step 4: check for races: did someone else allocate the undo struct?
1767 */
1768 un = lookup_undo(ulp, semid);
1769 if (un) {
1770 kfree(new);
1771 goto success;
1772 }
4daa28f6
MS
1773 /* step 5: initialize & link new undo structure */
1774 new->semadj = (short *) &new[1];
380af1b3 1775 new->ulp = ulp;
4daa28f6
MS
1776 new->semid = semid;
1777 assert_spin_locked(&ulp->lock);
380af1b3 1778 list_add_rcu(&new->list_proc, &ulp->list_proc);
cf9d5d78 1779 ipc_assert_locked_object(&sma->sem_perm);
4daa28f6 1780 list_add(&new->list_id, &sma->list_id);
380af1b3 1781 un = new;
4daa28f6 1782
380af1b3 1783success:
c530c6ac 1784 spin_unlock(&ulp->lock);
6062a8dc 1785 sem_unlock(sma, -1);
1da177e4
LT
1786out:
1787 return un;
1788}
1789
d5460c99
HC
1790SYSCALL_DEFINE4(semtimedop, int, semid, struct sembuf __user *, tsops,
1791 unsigned, nsops, const struct timespec __user *, timeout)
1da177e4
LT
1792{
1793 int error = -EINVAL;
1794 struct sem_array *sma;
1795 struct sembuf fast_sops[SEMOPM_FAST];
239521f3 1796 struct sembuf *sops = fast_sops, *sop;
1da177e4 1797 struct sem_undo *un;
4ce33ec2
DB
1798 int max, locknum;
1799 bool undos = false, alter = false, dupsop = false;
1da177e4 1800 struct sem_queue queue;
4ce33ec2 1801 unsigned long dup = 0, jiffies_left = 0;
e3893534
KK
1802 struct ipc_namespace *ns;
1803
1804 ns = current->nsproxy->ipc_ns;
1da177e4
LT
1805
1806 if (nsops < 1 || semid < 0)
1807 return -EINVAL;
e3893534 1808 if (nsops > ns->sc_semopm)
1da177e4 1809 return -E2BIG;
239521f3
MS
1810 if (nsops > SEMOPM_FAST) {
1811 sops = kmalloc(sizeof(*sops)*nsops, GFP_KERNEL);
1812 if (sops == NULL)
1da177e4
LT
1813 return -ENOMEM;
1814 }
4ce33ec2 1815
239521f3
MS
1816 if (copy_from_user(sops, tsops, nsops * sizeof(*tsops))) {
1817 error = -EFAULT;
1da177e4
LT
1818 goto out_free;
1819 }
4ce33ec2 1820
1da177e4
LT
1821 if (timeout) {
1822 struct timespec _timeout;
1823 if (copy_from_user(&_timeout, timeout, sizeof(*timeout))) {
1824 error = -EFAULT;
1825 goto out_free;
1826 }
1827 if (_timeout.tv_sec < 0 || _timeout.tv_nsec < 0 ||
1828 _timeout.tv_nsec >= 1000000000L) {
1829 error = -EINVAL;
1830 goto out_free;
1831 }
1832 jiffies_left = timespec_to_jiffies(&_timeout);
1833 }
4ce33ec2 1834
1da177e4
LT
1835 max = 0;
1836 for (sop = sops; sop < sops + nsops; sop++) {
4ce33ec2
DB
1837 unsigned long mask = 1ULL << ((sop->sem_num) % BITS_PER_LONG);
1838
1da177e4
LT
1839 if (sop->sem_num >= max)
1840 max = sop->sem_num;
1841 if (sop->sem_flg & SEM_UNDO)
4ce33ec2
DB
1842 undos = true;
1843 if (dup & mask) {
1844 /*
1845 * There was a previous alter access that appears
1846 * to have accessed the same semaphore, thus use
1847 * the dupsop logic. "appears", because the detection
1848 * can only check % BITS_PER_LONG.
1849 */
1850 dupsop = true;
1851 }
1852 if (sop->sem_op != 0) {
1853 alter = true;
1854 dup |= mask;
1855 }
1da177e4 1856 }
1da177e4 1857
1da177e4 1858 if (undos) {
6062a8dc 1859 /* On success, find_alloc_undo takes the rcu_read_lock */
4daa28f6 1860 un = find_alloc_undo(ns, semid);
1da177e4
LT
1861 if (IS_ERR(un)) {
1862 error = PTR_ERR(un);
1863 goto out_free;
1864 }
6062a8dc 1865 } else {
1da177e4 1866 un = NULL;
6062a8dc
RR
1867 rcu_read_lock();
1868 }
1da177e4 1869
16df3674 1870 sma = sem_obtain_object_check(ns, semid);
023a5355 1871 if (IS_ERR(sma)) {
6062a8dc 1872 rcu_read_unlock();
023a5355 1873 error = PTR_ERR(sma);
1da177e4 1874 goto out_free;
023a5355
ND
1875 }
1876
16df3674 1877 error = -EFBIG;
248e7357
DB
1878 if (max >= sma->sem_nsems) {
1879 rcu_read_unlock();
1880 goto out_free;
1881 }
16df3674
DB
1882
1883 error = -EACCES;
248e7357
DB
1884 if (ipcperms(ns, &sma->sem_perm, alter ? S_IWUGO : S_IRUGO)) {
1885 rcu_read_unlock();
1886 goto out_free;
1887 }
16df3674
DB
1888
1889 error = security_sem_semop(sma, sops, nsops, alter);
248e7357
DB
1890 if (error) {
1891 rcu_read_unlock();
1892 goto out_free;
1893 }
16df3674 1894
6e224f94
MS
1895 error = -EIDRM;
1896 locknum = sem_lock(sma, sops, nsops);
0f3d2b01
RA
1897 /*
1898 * We eventually might perform the following check in a lockless
1899 * fashion, considering ipc_valid_object() locking constraints.
1900 * If nsops == 1 and there is no contention for sem_perm.lock, then
1901 * only a per-semaphore lock is held and it's OK to proceed with the
1902 * check below. More details on the fine grained locking scheme
1903 * entangled here and why it's RMID race safe on comments at sem_lock()
1904 */
1905 if (!ipc_valid_object(&sma->sem_perm))
6e224f94 1906 goto out_unlock_free;
1da177e4 1907 /*
4daa28f6 1908 * semid identifiers are not unique - find_alloc_undo may have
1da177e4 1909 * allocated an undo structure, it was invalidated by an RMID
4daa28f6 1910 * and now a new array with received the same id. Check and fail.
25985edc 1911 * This case can be detected checking un->semid. The existence of
380af1b3 1912 * "un" itself is guaranteed by rcu.
1da177e4 1913 */
6062a8dc
RR
1914 if (un && un->semid == -1)
1915 goto out_unlock_free;
4daa28f6 1916
d198cd6d
MS
1917 queue.sops = sops;
1918 queue.nsops = nsops;
1919 queue.undo = un;
1920 queue.pid = task_tgid_vnr(current);
1921 queue.alter = alter;
4ce33ec2 1922 queue.dupsop = dupsop;
d198cd6d
MS
1923
1924 error = perform_atomic_semop(sma, &queue);
9ae949fa
DB
1925 if (error == 0) { /* non-blocking succesfull path */
1926 DEFINE_WAKE_Q(wake_q);
1927
1928 /*
1929 * If the operation was successful, then do
0e8c6656
MS
1930 * the required updates.
1931 */
1932 if (alter)
9ae949fa 1933 do_smart_update(sma, sops, nsops, 1, &wake_q);
0e8c6656
MS
1934 else
1935 set_semotime(sma, sops);
9ae949fa
DB
1936
1937 sem_unlock(sma, locknum);
1938 rcu_read_unlock();
1939 wake_up_q(&wake_q);
1940
1941 goto out_free;
1da177e4 1942 }
9ae949fa 1943 if (error < 0) /* non-blocking error path */
0e8c6656 1944 goto out_unlock_free;
1da177e4 1945
9ae949fa
DB
1946 /*
1947 * We need to sleep on this operation, so we put the current
1da177e4
LT
1948 * task into the pending queue and go to sleep.
1949 */
b97e820f
MS
1950 if (nsops == 1) {
1951 struct sem *curr;
1952 curr = &sma->sem_base[sops->sem_num];
1953
f269f40a
MS
1954 if (alter) {
1955 if (sma->complex_count) {
1956 list_add_tail(&queue.list,
1957 &sma->pending_alter);
1958 } else {
1959
1960 list_add_tail(&queue.list,
1961 &curr->pending_alter);
1962 }
1963 } else {
1a82e9e1 1964 list_add_tail(&queue.list, &curr->pending_const);
f269f40a 1965 }
b97e820f 1966 } else {
f269f40a
MS
1967 if (!sma->complex_count)
1968 merge_queues(sma);
1969
9f1bc2c9 1970 if (alter)
1a82e9e1 1971 list_add_tail(&queue.list, &sma->pending_alter);
9f1bc2c9 1972 else
1a82e9e1
MS
1973 list_add_tail(&queue.list, &sma->pending_const);
1974
b97e820f
MS
1975 sma->complex_count++;
1976 }
1977
9ae949fa 1978sleep_again:
1da177e4
LT
1979 queue.status = -EINTR;
1980 queue.sleeper = current;
0b0577f6 1981
52644c9a 1982 __set_current_state(TASK_INTERRUPTIBLE);
6062a8dc 1983 sem_unlock(sma, locknum);
6d49dab8 1984 rcu_read_unlock();
1da177e4
LT
1985
1986 if (timeout)
1987 jiffies_left = schedule_timeout(jiffies_left);
1988 else
1989 schedule();
1990
9ae949fa
DB
1991 /*
1992 * fastpath: the semop has completed, either successfully or not, from
1993 * the syscall pov, is quite irrelevant to us at this point; we're done.
1994 *
1995 * We _do_ care, nonetheless, about being awoken by a signal or
1996 * spuriously. The queue.status is checked again in the slowpath (aka
1997 * after taking sem_lock), such that we can detect scenarios where we
1998 * were awakened externally, during the window between wake_q_add() and
1999 * wake_up_q().
2000 */
2001 error = READ_ONCE(queue.status);
1da177e4 2002 if (error != -EINTR) {
9ae949fa
DB
2003 /*
2004 * User space could assume that semop() is a memory barrier:
2005 * Without the mb(), the cpu could speculatively read in user
2006 * space stale data that was overwritten by the previous owner
2007 * of the semaphore.
c61284e9
MS
2008 */
2009 smp_mb();
1da177e4
LT
2010 goto out_free;
2011 }
2012
321310ce 2013 rcu_read_lock();
6062a8dc 2014 sma = sem_obtain_lock(ns, semid, sops, nsops, &locknum);
9ae949fa 2015 error = READ_ONCE(queue.status);
d694ad62
MS
2016
2017 /*
2018 * Array removed? If yes, leave without sem_unlock().
2019 */
023a5355 2020 if (IS_ERR(sma)) {
321310ce 2021 rcu_read_unlock();
1da177e4
LT
2022 goto out_free;
2023 }
2024
2025 /*
d694ad62
MS
2026 * If queue.status != -EINTR we are woken up by another process.
2027 * Leave without unlink_queue(), but with sem_unlock().
1da177e4 2028 */
3ab08fe2 2029 if (error != -EINTR)
1da177e4 2030 goto out_unlock_free;
1da177e4
LT
2031
2032 /*
9ae949fa 2033 * If an interrupt occurred we have to clean up the queue.
1da177e4
LT
2034 */
2035 if (timeout && jiffies_left == 0)
2036 error = -EAGAIN;
0b0577f6
MS
2037
2038 /*
9ae949fa 2039 * If the wakeup was spurious, just retry.
0b0577f6
MS
2040 */
2041 if (error == -EINTR && !signal_pending(current))
2042 goto sleep_again;
2043
b97e820f 2044 unlink_queue(sma, &queue);
1da177e4
LT
2045
2046out_unlock_free:
6062a8dc 2047 sem_unlock(sma, locknum);
6d49dab8 2048 rcu_read_unlock();
1da177e4 2049out_free:
239521f3 2050 if (sops != fast_sops)
1da177e4
LT
2051 kfree(sops);
2052 return error;
2053}
2054
d5460c99
HC
2055SYSCALL_DEFINE3(semop, int, semid, struct sembuf __user *, tsops,
2056 unsigned, nsops)
1da177e4
LT
2057{
2058 return sys_semtimedop(semid, tsops, nsops, NULL);
2059}
2060
2061/* If CLONE_SYSVSEM is set, establish sharing of SEM_UNDO state between
2062 * parent and child tasks.
1da177e4
LT
2063 */
2064
2065int copy_semundo(unsigned long clone_flags, struct task_struct *tsk)
2066{
2067 struct sem_undo_list *undo_list;
2068 int error;
2069
2070 if (clone_flags & CLONE_SYSVSEM) {
2071 error = get_undo_list(&undo_list);
2072 if (error)
2073 return error;
1da177e4
LT
2074 atomic_inc(&undo_list->refcnt);
2075 tsk->sysvsem.undo_list = undo_list;
46c0a8ca 2076 } else
1da177e4
LT
2077 tsk->sysvsem.undo_list = NULL;
2078
2079 return 0;
2080}
2081
2082/*
2083 * add semadj values to semaphores, free undo structures.
2084 * undo structures are not freed when semaphore arrays are destroyed
2085 * so some of them may be out of date.
2086 * IMPLEMENTATION NOTE: There is some confusion over whether the
2087 * set of adjustments that needs to be done should be done in an atomic
2088 * manner or not. That is, if we are attempting to decrement the semval
2089 * should we queue up and wait until we can do so legally?
2090 * The original implementation attempted to do this (queue and wait).
2091 * The current implementation does not do so. The POSIX standard
2092 * and SVID should be consulted to determine what behavior is mandated.
2093 */
2094void exit_sem(struct task_struct *tsk)
2095{
4daa28f6 2096 struct sem_undo_list *ulp;
1da177e4 2097
4daa28f6
MS
2098 ulp = tsk->sysvsem.undo_list;
2099 if (!ulp)
1da177e4 2100 return;
9edff4ab 2101 tsk->sysvsem.undo_list = NULL;
1da177e4 2102
4daa28f6 2103 if (!atomic_dec_and_test(&ulp->refcnt))
1da177e4
LT
2104 return;
2105
380af1b3 2106 for (;;) {
1da177e4 2107 struct sem_array *sma;
380af1b3 2108 struct sem_undo *un;
6062a8dc 2109 int semid, i;
9ae949fa 2110 DEFINE_WAKE_Q(wake_q);
4daa28f6 2111
2a1613a5
NB
2112 cond_resched();
2113
380af1b3 2114 rcu_read_lock();
05725f7e
JP
2115 un = list_entry_rcu(ulp->list_proc.next,
2116 struct sem_undo, list_proc);
602b8593
HK
2117 if (&un->list_proc == &ulp->list_proc) {
2118 /*
2119 * We must wait for freeary() before freeing this ulp,
2120 * in case we raced with last sem_undo. There is a small
2121 * possibility where we exit while freeary() didn't
2122 * finish unlocking sem_undo_list.
2123 */
2124 spin_unlock_wait(&ulp->lock);
2125 rcu_read_unlock();
2126 break;
2127 }
2128 spin_lock(&ulp->lock);
2129 semid = un->semid;
2130 spin_unlock(&ulp->lock);
4daa28f6 2131
602b8593 2132 /* exit_sem raced with IPC_RMID, nothing to do */
6062a8dc
RR
2133 if (semid == -1) {
2134 rcu_read_unlock();
602b8593 2135 continue;
6062a8dc 2136 }
1da177e4 2137
602b8593 2138 sma = sem_obtain_object_check(tsk->nsproxy->ipc_ns, semid);
380af1b3 2139 /* exit_sem raced with IPC_RMID, nothing to do */
6062a8dc
RR
2140 if (IS_ERR(sma)) {
2141 rcu_read_unlock();
380af1b3 2142 continue;
6062a8dc 2143 }
1da177e4 2144
6062a8dc 2145 sem_lock(sma, NULL, -1);
6e224f94 2146 /* exit_sem raced with IPC_RMID, nothing to do */
0f3d2b01 2147 if (!ipc_valid_object(&sma->sem_perm)) {
6e224f94
MS
2148 sem_unlock(sma, -1);
2149 rcu_read_unlock();
2150 continue;
2151 }
bf17bb71 2152 un = __lookup_undo(ulp, semid);
380af1b3
MS
2153 if (un == NULL) {
2154 /* exit_sem raced with IPC_RMID+semget() that created
2155 * exactly the same semid. Nothing to do.
2156 */
6062a8dc 2157 sem_unlock(sma, -1);
6d49dab8 2158 rcu_read_unlock();
380af1b3
MS
2159 continue;
2160 }
2161
2162 /* remove un from the linked lists */
cf9d5d78 2163 ipc_assert_locked_object(&sma->sem_perm);
4daa28f6
MS
2164 list_del(&un->list_id);
2165
a9795584
HK
2166 /* we are the last process using this ulp, acquiring ulp->lock
2167 * isn't required. Besides that, we are also protected against
2168 * IPC_RMID as we hold sma->sem_perm lock now
2169 */
380af1b3 2170 list_del_rcu(&un->list_proc);
380af1b3 2171
4daa28f6
MS
2172 /* perform adjustments registered in un */
2173 for (i = 0; i < sma->sem_nsems; i++) {
239521f3 2174 struct sem *semaphore = &sma->sem_base[i];
4daa28f6
MS
2175 if (un->semadj[i]) {
2176 semaphore->semval += un->semadj[i];
1da177e4
LT
2177 /*
2178 * Range checks of the new semaphore value,
2179 * not defined by sus:
2180 * - Some unices ignore the undo entirely
2181 * (e.g. HP UX 11i 11.22, Tru64 V5.1)
2182 * - some cap the value (e.g. FreeBSD caps
2183 * at 0, but doesn't enforce SEMVMX)
2184 *
2185 * Linux caps the semaphore value, both at 0
2186 * and at SEMVMX.
2187 *
239521f3 2188 * Manfred <manfred@colorfullife.com>
1da177e4 2189 */
5f921ae9
IM
2190 if (semaphore->semval < 0)
2191 semaphore->semval = 0;
2192 if (semaphore->semval > SEMVMX)
2193 semaphore->semval = SEMVMX;
b488893a 2194 semaphore->sempid = task_tgid_vnr(current);
1da177e4
LT
2195 }
2196 }
1da177e4 2197 /* maybe some queued-up processes were waiting for this */
9ae949fa 2198 do_smart_update(sma, NULL, 0, 1, &wake_q);
6062a8dc 2199 sem_unlock(sma, -1);
6d49dab8 2200 rcu_read_unlock();
9ae949fa 2201 wake_up_q(&wake_q);
380af1b3 2202
693a8b6e 2203 kfree_rcu(un, rcu);
1da177e4 2204 }
4daa28f6 2205 kfree(ulp);
1da177e4
LT
2206}
2207
2208#ifdef CONFIG_PROC_FS
19b4946c 2209static int sysvipc_sem_proc_show(struct seq_file *s, void *it)
1da177e4 2210{
1efdb69b 2211 struct user_namespace *user_ns = seq_user_ns(s);
19b4946c 2212 struct sem_array *sma = it;
d12e1e50
MS
2213 time_t sem_otime;
2214
d8c63376
MS
2215 /*
2216 * The proc interface isn't aware of sem_lock(), it calls
2217 * ipc_lock_object() directly (in sysvipc_find_ipc).
5864a2fd
MS
2218 * In order to stay compatible with sem_lock(), we must
2219 * enter / leave complex_mode.
d8c63376 2220 */
5864a2fd 2221 complexmode_enter(sma);
d8c63376 2222
d12e1e50 2223 sem_otime = get_semotime(sma);
19b4946c 2224
7f032d6e
JP
2225 seq_printf(s,
2226 "%10d %10d %4o %10u %5u %5u %5u %5u %10lu %10lu\n",
2227 sma->sem_perm.key,
2228 sma->sem_perm.id,
2229 sma->sem_perm.mode,
2230 sma->sem_nsems,
2231 from_kuid_munged(user_ns, sma->sem_perm.uid),
2232 from_kgid_munged(user_ns, sma->sem_perm.gid),
2233 from_kuid_munged(user_ns, sma->sem_perm.cuid),
2234 from_kgid_munged(user_ns, sma->sem_perm.cgid),
2235 sem_otime,
2236 sma->sem_ctime);
2237
5864a2fd
MS
2238 complexmode_tryleave(sma);
2239
7f032d6e 2240 return 0;
1da177e4
LT
2241}
2242#endif