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