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