sem.c 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899
  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. * Further wakeup optimizations, documentation
  15. * (c) 2010 Manfred Spraul <manfred@colorfullife.com>
  16. *
  17. * support for audit of ipc object properties and permission changes
  18. * Dustin Kirkland <dustin.kirkland@us.ibm.com>
  19. *
  20. * namespaces support
  21. * OpenVZ, SWsoft Inc.
  22. * Pavel Emelianov <xemul@openvz.org>
  23. *
  24. * Implementation notes: (May 2010)
  25. * This file implements System V semaphores.
  26. *
  27. * User space visible behavior:
  28. * - FIFO ordering for semop() operations (just FIFO, not starvation
  29. * protection)
  30. * - multiple semaphore operations that alter the same semaphore in
  31. * one semop() are handled.
  32. * - sem_ctime (time of last semctl()) is updated in the IPC_SET, SETVAL and
  33. * SETALL calls.
  34. * - two Linux specific semctl() commands: SEM_STAT, SEM_INFO.
  35. * - undo adjustments at process exit are limited to 0..SEMVMX.
  36. * - namespace are supported.
  37. * - SEMMSL, SEMMNS, SEMOPM and SEMMNI can be configured at runtine by writing
  38. * to /proc/sys/kernel/sem.
  39. * - statistics about the usage are reported in /proc/sysvipc/sem.
  40. *
  41. * Internals:
  42. * - scalability:
  43. * - all global variables are read-mostly.
  44. * - semop() calls and semctl(RMID) are synchronized by RCU.
  45. * - most operations do write operations (actually: spin_lock calls) to
  46. * the per-semaphore array structure.
  47. * Thus: Perfect SMP scaling between independent semaphore arrays.
  48. * If multiple semaphores in one array are used, then cache line
  49. * trashing on the semaphore array spinlock will limit the scaling.
  50. * - semncnt and semzcnt are calculated on demand in count_semncnt() and
  51. * count_semzcnt()
  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. * wake_up_sem_queue_do())
  59. * - All work is done by the waker, the woken up task does not have to do
  60. * anything - not even acquiring a lock or dropping a refcount.
  61. * - A woken up task may not even touch the semaphore array anymore, it may
  62. * have been destroyed already by a semctl(RMID).
  63. * - The synchronizations between wake-ups due to a timeout/signal and a
  64. * wake-up due to a completed semaphore operation is achieved by using an
  65. * intermediate state (IN_WAKEUP).
  66. * - UNDO values are stored in an array (one per process and per
  67. * semaphore array, lazily allocated). For backwards compatibility, multiple
  68. * modes for the UNDO variables are supported (per process, per thread)
  69. * (see copy_semundo, CLONE_SYSVSEM)
  70. * - There are two lists of the pending operations: a per-array list
  71. * and per-semaphore list (stored in the array). This allows to achieve FIFO
  72. * ordering without always scanning all pending operations.
  73. * The worst-case behavior is nevertheless O(N^2) for N wakeups.
  74. */
  75. #include <linux/slab.h>
  76. #include <linux/spinlock.h>
  77. #include <linux/init.h>
  78. #include <linux/proc_fs.h>
  79. #include <linux/time.h>
  80. #include <linux/security.h>
  81. #include <linux/syscalls.h>
  82. #include <linux/audit.h>
  83. #include <linux/capability.h>
  84. #include <linux/seq_file.h>
  85. #include <linux/rwsem.h>
  86. #include <linux/nsproxy.h>
  87. #include <linux/ipc_namespace.h>
  88. #include <asm/uaccess.h>
  89. #include "util.h"
  90. /* One semaphore structure for each semaphore in the system. */
  91. struct sem {
  92. int semval; /* current value */
  93. int sempid; /* pid of last operation */
  94. spinlock_t lock; /* spinlock for fine-grained semtimedop */
  95. struct list_head sem_pending; /* pending single-sop operations */
  96. };
  97. /* One queue for each sleeping process in the system. */
  98. struct sem_queue {
  99. struct list_head list; /* queue of pending operations */
  100. struct task_struct *sleeper; /* this process */
  101. struct sem_undo *undo; /* undo structure */
  102. int pid; /* process id of requesting process */
  103. int status; /* completion status of operation */
  104. struct sembuf *sops; /* array of pending operations */
  105. int nsops; /* number of operations */
  106. int alter; /* does *sops alter the array? */
  107. };
  108. /* Each task has a list of undo requests. They are executed automatically
  109. * when the process exits.
  110. */
  111. struct sem_undo {
  112. struct list_head list_proc; /* per-process list: *
  113. * all undos from one process
  114. * rcu protected */
  115. struct rcu_head rcu; /* rcu struct for sem_undo */
  116. struct sem_undo_list *ulp; /* back ptr to sem_undo_list */
  117. struct list_head list_id; /* per semaphore array list:
  118. * all undos for one array */
  119. int semid; /* semaphore set identifier */
  120. short *semadj; /* array of adjustments */
  121. /* one per semaphore */
  122. };
  123. /* sem_undo_list controls shared access to the list of sem_undo structures
  124. * that may be shared among all a CLONE_SYSVSEM task group.
  125. */
  126. struct sem_undo_list {
  127. atomic_t refcnt;
  128. spinlock_t lock;
  129. struct list_head list_proc;
  130. };
  131. #define sem_ids(ns) ((ns)->ids[IPC_SEM_IDS])
  132. #define sem_checkid(sma, semid) ipc_checkid(&sma->sem_perm, semid)
  133. static int newary(struct ipc_namespace *, struct ipc_params *);
  134. static void freeary(struct ipc_namespace *, struct kern_ipc_perm *);
  135. #ifdef CONFIG_PROC_FS
  136. static int sysvipc_sem_proc_show(struct seq_file *s, void *it);
  137. #endif
  138. #define SEMMSL_FAST 256 /* 512 bytes on stack */
  139. #define SEMOPM_FAST 64 /* ~ 372 bytes on stack */
  140. /*
  141. * linked list protection:
  142. * sem_undo.id_next,
  143. * sem_array.sem_pending{,last},
  144. * sem_array.sem_undo: sem_lock() for read/write
  145. * sem_undo.proc_next: only "current" is allowed to read/write that field.
  146. *
  147. */
  148. #define sc_semmsl sem_ctls[0]
  149. #define sc_semmns sem_ctls[1]
  150. #define sc_semopm sem_ctls[2]
  151. #define sc_semmni sem_ctls[3]
  152. void sem_init_ns(struct ipc_namespace *ns)
  153. {
  154. ns->sc_semmsl = SEMMSL;
  155. ns->sc_semmns = SEMMNS;
  156. ns->sc_semopm = SEMOPM;
  157. ns->sc_semmni = SEMMNI;
  158. ns->used_sems = 0;
  159. ipc_init_ids(&ns->ids[IPC_SEM_IDS]);
  160. }
  161. #ifdef CONFIG_IPC_NS
  162. void sem_exit_ns(struct ipc_namespace *ns)
  163. {
  164. free_ipcs(ns, &sem_ids(ns), freeary);
  165. idr_destroy(&ns->ids[IPC_SEM_IDS].ipcs_idr);
  166. }
  167. #endif
  168. void __init sem_init (void)
  169. {
  170. sem_init_ns(&init_ipc_ns);
  171. ipc_init_proc_interface("sysvipc/sem",
  172. " key semid perms nsems uid gid cuid cgid otime ctime\n",
  173. IPC_SEM_IDS, sysvipc_sem_proc_show);
  174. }
  175. /*
  176. * If the request contains only one semaphore operation, and there are
  177. * no complex transactions pending, lock only the semaphore involved.
  178. * Otherwise, lock the entire semaphore array, since we either have
  179. * multiple semaphores in our own semops, or we need to look at
  180. * semaphores from other pending complex operations.
  181. *
  182. * Carefully guard against sma->complex_count changing between zero
  183. * and non-zero while we are spinning for the lock. The value of
  184. * sma->complex_count cannot change while we are holding the lock,
  185. * so sem_unlock should be fine.
  186. *
  187. * The global lock path checks that all the local locks have been released,
  188. * checking each local lock once. This means that the local lock paths
  189. * cannot start their critical sections while the global lock is held.
  190. */
  191. static inline int sem_lock(struct sem_array *sma, struct sembuf *sops,
  192. int nsops)
  193. {
  194. int locknum;
  195. again:
  196. if (nsops == 1 && !sma->complex_count) {
  197. struct sem *sem = sma->sem_base + sops->sem_num;
  198. /* Lock just the semaphore we are interested in. */
  199. spin_lock(&sem->lock);
  200. /*
  201. * If sma->complex_count was set while we were spinning,
  202. * we may need to look at things we did not lock here.
  203. */
  204. if (unlikely(sma->complex_count)) {
  205. spin_unlock(&sem->lock);
  206. goto lock_array;
  207. }
  208. /*
  209. * Another process is holding the global lock on the
  210. * sem_array; we cannot enter our critical section,
  211. * but have to wait for the global lock to be released.
  212. */
  213. if (unlikely(spin_is_locked(&sma->sem_perm.lock))) {
  214. spin_unlock(&sem->lock);
  215. spin_unlock_wait(&sma->sem_perm.lock);
  216. goto again;
  217. }
  218. locknum = sops->sem_num;
  219. } else {
  220. int i;
  221. /*
  222. * Lock the semaphore array, and wait for all of the
  223. * individual semaphore locks to go away. The code
  224. * above ensures no new single-lock holders will enter
  225. * their critical section while the array lock is held.
  226. */
  227. lock_array:
  228. spin_lock(&sma->sem_perm.lock);
  229. for (i = 0; i < sma->sem_nsems; i++) {
  230. struct sem *sem = sma->sem_base + i;
  231. spin_unlock_wait(&sem->lock);
  232. }
  233. locknum = -1;
  234. }
  235. return locknum;
  236. }
  237. static inline void sem_unlock(struct sem_array *sma, int locknum)
  238. {
  239. if (locknum == -1) {
  240. spin_unlock(&sma->sem_perm.lock);
  241. } else {
  242. struct sem *sem = sma->sem_base + locknum;
  243. spin_unlock(&sem->lock);
  244. }
  245. }
  246. /*
  247. * sem_lock_(check_) routines are called in the paths where the rw_mutex
  248. * is not held.
  249. *
  250. * The caller holds the RCU read lock.
  251. */
  252. static inline struct sem_array *sem_obtain_lock(struct ipc_namespace *ns,
  253. int id, struct sembuf *sops, int nsops, int *locknum)
  254. {
  255. struct kern_ipc_perm *ipcp;
  256. struct sem_array *sma;
  257. ipcp = ipc_obtain_object(&sem_ids(ns), id);
  258. if (IS_ERR(ipcp))
  259. return ERR_CAST(ipcp);
  260. sma = container_of(ipcp, struct sem_array, sem_perm);
  261. *locknum = sem_lock(sma, sops, nsops);
  262. /* ipc_rmid() may have already freed the ID while sem_lock
  263. * was spinning: verify that the structure is still valid
  264. */
  265. if (!ipcp->deleted)
  266. return container_of(ipcp, struct sem_array, sem_perm);
  267. sem_unlock(sma, *locknum);
  268. return ERR_PTR(-EINVAL);
  269. }
  270. static inline struct sem_array *sem_obtain_object(struct ipc_namespace *ns, int id)
  271. {
  272. struct kern_ipc_perm *ipcp = ipc_obtain_object(&sem_ids(ns), id);
  273. if (IS_ERR(ipcp))
  274. return ERR_CAST(ipcp);
  275. return container_of(ipcp, struct sem_array, sem_perm);
  276. }
  277. static inline struct sem_array *sem_obtain_object_check(struct ipc_namespace *ns,
  278. int id)
  279. {
  280. struct kern_ipc_perm *ipcp = ipc_obtain_object_check(&sem_ids(ns), id);
  281. if (IS_ERR(ipcp))
  282. return ERR_CAST(ipcp);
  283. return container_of(ipcp, struct sem_array, sem_perm);
  284. }
  285. static inline void sem_lock_and_putref(struct sem_array *sma)
  286. {
  287. sem_lock(sma, NULL, -1);
  288. ipc_rcu_putref(sma);
  289. }
  290. static inline void sem_putref(struct sem_array *sma)
  291. {
  292. ipc_rcu_putref(sma);
  293. }
  294. static inline void sem_rmid(struct ipc_namespace *ns, struct sem_array *s)
  295. {
  296. ipc_rmid(&sem_ids(ns), &s->sem_perm);
  297. }
  298. /*
  299. * Lockless wakeup algorithm:
  300. * Without the check/retry algorithm a lockless wakeup is possible:
  301. * - queue.status is initialized to -EINTR before blocking.
  302. * - wakeup is performed by
  303. * * unlinking the queue entry from sma->sem_pending
  304. * * setting queue.status to IN_WAKEUP
  305. * This is the notification for the blocked thread that a
  306. * result value is imminent.
  307. * * call wake_up_process
  308. * * set queue.status to the final value.
  309. * - the previously blocked thread checks queue.status:
  310. * * if it's IN_WAKEUP, then it must wait until the value changes
  311. * * if it's not -EINTR, then the operation was completed by
  312. * update_queue. semtimedop can return queue.status without
  313. * performing any operation on the sem array.
  314. * * otherwise it must acquire the spinlock and check what's up.
  315. *
  316. * The two-stage algorithm is necessary to protect against the following
  317. * races:
  318. * - if queue.status is set after wake_up_process, then the woken up idle
  319. * thread could race forward and try (and fail) to acquire sma->lock
  320. * before update_queue had a chance to set queue.status
  321. * - if queue.status is written before wake_up_process and if the
  322. * blocked process is woken up by a signal between writing
  323. * queue.status and the wake_up_process, then the woken up
  324. * process could return from semtimedop and die by calling
  325. * sys_exit before wake_up_process is called. Then wake_up_process
  326. * will oops, because the task structure is already invalid.
  327. * (yes, this happened on s390 with sysv msg).
  328. *
  329. */
  330. #define IN_WAKEUP 1
  331. /**
  332. * newary - Create a new semaphore set
  333. * @ns: namespace
  334. * @params: ptr to the structure that contains key, semflg and nsems
  335. *
  336. * Called with sem_ids.rw_mutex held (as a writer)
  337. */
  338. static int newary(struct ipc_namespace *ns, struct ipc_params *params)
  339. {
  340. int id;
  341. int retval;
  342. struct sem_array *sma;
  343. int size;
  344. key_t key = params->key;
  345. int nsems = params->u.nsems;
  346. int semflg = params->flg;
  347. int i;
  348. if (!nsems)
  349. return -EINVAL;
  350. if (ns->used_sems + nsems > ns->sc_semmns)
  351. return -ENOSPC;
  352. size = sizeof (*sma) + nsems * sizeof (struct sem);
  353. sma = ipc_rcu_alloc(size);
  354. if (!sma) {
  355. return -ENOMEM;
  356. }
  357. memset (sma, 0, size);
  358. sma->sem_perm.mode = (semflg & S_IRWXUGO);
  359. sma->sem_perm.key = key;
  360. sma->sem_perm.security = NULL;
  361. retval = security_sem_alloc(sma);
  362. if (retval) {
  363. ipc_rcu_putref(sma);
  364. return retval;
  365. }
  366. id = ipc_addid(&sem_ids(ns), &sma->sem_perm, ns->sc_semmni);
  367. if (id < 0) {
  368. security_sem_free(sma);
  369. ipc_rcu_putref(sma);
  370. return id;
  371. }
  372. ns->used_sems += nsems;
  373. sma->sem_base = (struct sem *) &sma[1];
  374. for (i = 0; i < nsems; i++) {
  375. INIT_LIST_HEAD(&sma->sem_base[i].sem_pending);
  376. spin_lock_init(&sma->sem_base[i].lock);
  377. }
  378. sma->complex_count = 0;
  379. INIT_LIST_HEAD(&sma->sem_pending);
  380. INIT_LIST_HEAD(&sma->list_id);
  381. sma->sem_nsems = nsems;
  382. sma->sem_ctime = get_seconds();
  383. sem_unlock(sma, -1);
  384. rcu_read_unlock();
  385. return sma->sem_perm.id;
  386. }
  387. /*
  388. * Called with sem_ids.rw_mutex and ipcp locked.
  389. */
  390. static inline int sem_security(struct kern_ipc_perm *ipcp, int semflg)
  391. {
  392. struct sem_array *sma;
  393. sma = container_of(ipcp, struct sem_array, sem_perm);
  394. return security_sem_associate(sma, semflg);
  395. }
  396. /*
  397. * Called with sem_ids.rw_mutex and ipcp locked.
  398. */
  399. static inline int sem_more_checks(struct kern_ipc_perm *ipcp,
  400. struct ipc_params *params)
  401. {
  402. struct sem_array *sma;
  403. sma = container_of(ipcp, struct sem_array, sem_perm);
  404. if (params->u.nsems > sma->sem_nsems)
  405. return -EINVAL;
  406. return 0;
  407. }
  408. SYSCALL_DEFINE3(semget, key_t, key, int, nsems, int, semflg)
  409. {
  410. struct ipc_namespace *ns;
  411. struct ipc_ops sem_ops;
  412. struct ipc_params sem_params;
  413. ns = current->nsproxy->ipc_ns;
  414. if (nsems < 0 || nsems > ns->sc_semmsl)
  415. return -EINVAL;
  416. sem_ops.getnew = newary;
  417. sem_ops.associate = sem_security;
  418. sem_ops.more_checks = sem_more_checks;
  419. sem_params.key = key;
  420. sem_params.flg = semflg;
  421. sem_params.u.nsems = nsems;
  422. return ipcget(ns, &sem_ids(ns), &sem_ops, &sem_params);
  423. }
  424. /*
  425. * Determine whether a sequence of semaphore operations would succeed
  426. * all at once. Return 0 if yes, 1 if need to sleep, else return error code.
  427. */
  428. static int try_atomic_semop (struct sem_array * sma, struct sembuf * sops,
  429. int nsops, struct sem_undo *un, int pid)
  430. {
  431. int result, sem_op;
  432. struct sembuf *sop;
  433. struct sem * curr;
  434. for (sop = sops; sop < sops + nsops; sop++) {
  435. curr = sma->sem_base + sop->sem_num;
  436. sem_op = sop->sem_op;
  437. result = curr->semval;
  438. if (!sem_op && result)
  439. goto would_block;
  440. result += sem_op;
  441. if (result < 0)
  442. goto would_block;
  443. if (result > SEMVMX)
  444. goto out_of_range;
  445. if (sop->sem_flg & SEM_UNDO) {
  446. int undo = un->semadj[sop->sem_num] - sem_op;
  447. /*
  448. * Exceeding the undo range is an error.
  449. */
  450. if (undo < (-SEMAEM - 1) || undo > SEMAEM)
  451. goto out_of_range;
  452. }
  453. curr->semval = result;
  454. }
  455. sop--;
  456. while (sop >= sops) {
  457. sma->sem_base[sop->sem_num].sempid = pid;
  458. if (sop->sem_flg & SEM_UNDO)
  459. un->semadj[sop->sem_num] -= sop->sem_op;
  460. sop--;
  461. }
  462. return 0;
  463. out_of_range:
  464. result = -ERANGE;
  465. goto undo;
  466. would_block:
  467. if (sop->sem_flg & IPC_NOWAIT)
  468. result = -EAGAIN;
  469. else
  470. result = 1;
  471. undo:
  472. sop--;
  473. while (sop >= sops) {
  474. sma->sem_base[sop->sem_num].semval -= sop->sem_op;
  475. sop--;
  476. }
  477. return result;
  478. }
  479. /** wake_up_sem_queue_prepare(q, error): Prepare wake-up
  480. * @q: queue entry that must be signaled
  481. * @error: Error value for the signal
  482. *
  483. * Prepare the wake-up of the queue entry q.
  484. */
  485. static void wake_up_sem_queue_prepare(struct list_head *pt,
  486. struct sem_queue *q, int error)
  487. {
  488. if (list_empty(pt)) {
  489. /*
  490. * Hold preempt off so that we don't get preempted and have the
  491. * wakee busy-wait until we're scheduled back on.
  492. */
  493. preempt_disable();
  494. }
  495. q->status = IN_WAKEUP;
  496. q->pid = error;
  497. list_add_tail(&q->list, pt);
  498. }
  499. /**
  500. * wake_up_sem_queue_do(pt) - do the actual wake-up
  501. * @pt: list of tasks to be woken up
  502. *
  503. * Do the actual wake-up.
  504. * The function is called without any locks held, thus the semaphore array
  505. * could be destroyed already and the tasks can disappear as soon as the
  506. * status is set to the actual return code.
  507. */
  508. static void wake_up_sem_queue_do(struct list_head *pt)
  509. {
  510. struct sem_queue *q, *t;
  511. int did_something;
  512. did_something = !list_empty(pt);
  513. list_for_each_entry_safe(q, t, pt, list) {
  514. wake_up_process(q->sleeper);
  515. /* q can disappear immediately after writing q->status. */
  516. smp_wmb();
  517. q->status = q->pid;
  518. }
  519. if (did_something)
  520. preempt_enable();
  521. }
  522. static void unlink_queue(struct sem_array *sma, struct sem_queue *q)
  523. {
  524. list_del(&q->list);
  525. if (q->nsops > 1)
  526. sma->complex_count--;
  527. }
  528. /** check_restart(sma, q)
  529. * @sma: semaphore array
  530. * @q: the operation that just completed
  531. *
  532. * update_queue is O(N^2) when it restarts scanning the whole queue of
  533. * waiting operations. Therefore this function checks if the restart is
  534. * really necessary. It is called after a previously waiting operation
  535. * was completed.
  536. */
  537. static int check_restart(struct sem_array *sma, struct sem_queue *q)
  538. {
  539. struct sem *curr;
  540. struct sem_queue *h;
  541. /* if the operation didn't modify the array, then no restart */
  542. if (q->alter == 0)
  543. return 0;
  544. /* pending complex operations are too difficult to analyse */
  545. if (sma->complex_count)
  546. return 1;
  547. /* we were a sleeping complex operation. Too difficult */
  548. if (q->nsops > 1)
  549. return 1;
  550. curr = sma->sem_base + q->sops[0].sem_num;
  551. /* No-one waits on this queue */
  552. if (list_empty(&curr->sem_pending))
  553. return 0;
  554. /* the new semaphore value */
  555. if (curr->semval) {
  556. /* It is impossible that someone waits for the new value:
  557. * - q is a previously sleeping simple operation that
  558. * altered the array. It must be a decrement, because
  559. * simple increments never sleep.
  560. * - The value is not 0, thus wait-for-zero won't proceed.
  561. * - If there are older (higher priority) decrements
  562. * in the queue, then they have observed the original
  563. * semval value and couldn't proceed. The operation
  564. * decremented to value - thus they won't proceed either.
  565. */
  566. BUG_ON(q->sops[0].sem_op >= 0);
  567. return 0;
  568. }
  569. /*
  570. * semval is 0. Check if there are wait-for-zero semops.
  571. * They must be the first entries in the per-semaphore queue
  572. */
  573. h = list_first_entry(&curr->sem_pending, struct sem_queue, list);
  574. BUG_ON(h->nsops != 1);
  575. BUG_ON(h->sops[0].sem_num != q->sops[0].sem_num);
  576. /* Yes, there is a wait-for-zero semop. Restart */
  577. if (h->sops[0].sem_op == 0)
  578. return 1;
  579. /* Again - no-one is waiting for the new value. */
  580. return 0;
  581. }
  582. /**
  583. * update_queue(sma, semnum): Look for tasks that can be completed.
  584. * @sma: semaphore array.
  585. * @semnum: semaphore that was modified.
  586. * @pt: list head for the tasks that must be woken up.
  587. *
  588. * update_queue must be called after a semaphore in a semaphore array
  589. * was modified. If multiple semaphores were modified, update_queue must
  590. * be called with semnum = -1, as well as with the number of each modified
  591. * semaphore.
  592. * The tasks that must be woken up are added to @pt. The return code
  593. * is stored in q->pid.
  594. * The function return 1 if at least one semop was completed successfully.
  595. */
  596. static int update_queue(struct sem_array *sma, int semnum, struct list_head *pt)
  597. {
  598. struct sem_queue *q;
  599. struct list_head *walk;
  600. struct list_head *pending_list;
  601. int semop_completed = 0;
  602. if (semnum == -1)
  603. pending_list = &sma->sem_pending;
  604. else
  605. pending_list = &sma->sem_base[semnum].sem_pending;
  606. again:
  607. walk = pending_list->next;
  608. while (walk != pending_list) {
  609. int error, restart;
  610. q = container_of(walk, struct sem_queue, list);
  611. walk = walk->next;
  612. /* If we are scanning the single sop, per-semaphore list of
  613. * one semaphore and that semaphore is 0, then it is not
  614. * necessary to scan the "alter" entries: simple increments
  615. * that affect only one entry succeed immediately and cannot
  616. * be in the per semaphore pending queue, and decrements
  617. * cannot be successful if the value is already 0.
  618. */
  619. if (semnum != -1 && sma->sem_base[semnum].semval == 0 &&
  620. q->alter)
  621. break;
  622. error = try_atomic_semop(sma, q->sops, q->nsops,
  623. q->undo, q->pid);
  624. /* Does q->sleeper still need to sleep? */
  625. if (error > 0)
  626. continue;
  627. unlink_queue(sma, q);
  628. if (error) {
  629. restart = 0;
  630. } else {
  631. semop_completed = 1;
  632. restart = check_restart(sma, q);
  633. }
  634. wake_up_sem_queue_prepare(pt, q, error);
  635. if (restart)
  636. goto again;
  637. }
  638. return semop_completed;
  639. }
  640. /**
  641. * do_smart_update(sma, sops, nsops, otime, pt) - optimized update_queue
  642. * @sma: semaphore array
  643. * @sops: operations that were performed
  644. * @nsops: number of operations
  645. * @otime: force setting otime
  646. * @pt: list head of the tasks that must be woken up.
  647. *
  648. * do_smart_update() does the required called to update_queue, based on the
  649. * actual changes that were performed on the semaphore array.
  650. * Note that the function does not do the actual wake-up: the caller is
  651. * responsible for calling wake_up_sem_queue_do(@pt).
  652. * It is safe to perform this call after dropping all locks.
  653. */
  654. static void do_smart_update(struct sem_array *sma, struct sembuf *sops, int nsops,
  655. int otime, struct list_head *pt)
  656. {
  657. int i;
  658. int progress;
  659. progress = 1;
  660. retry_global:
  661. if (sma->complex_count) {
  662. if (update_queue(sma, -1, pt)) {
  663. progress = 1;
  664. otime = 1;
  665. sops = NULL;
  666. }
  667. }
  668. if (!progress)
  669. goto done;
  670. if (!sops) {
  671. /* No semops; something special is going on. */
  672. for (i = 0; i < sma->sem_nsems; i++) {
  673. if (update_queue(sma, i, pt)) {
  674. otime = 1;
  675. progress = 1;
  676. }
  677. }
  678. goto done_checkretry;
  679. }
  680. /* Check the semaphores that were modified. */
  681. for (i = 0; i < nsops; i++) {
  682. if (sops[i].sem_op > 0 ||
  683. (sops[i].sem_op < 0 &&
  684. sma->sem_base[sops[i].sem_num].semval == 0))
  685. if (update_queue(sma, sops[i].sem_num, pt)) {
  686. otime = 1;
  687. progress = 1;
  688. }
  689. }
  690. done_checkretry:
  691. if (progress) {
  692. progress = 0;
  693. goto retry_global;
  694. }
  695. done:
  696. if (otime)
  697. sma->sem_otime = get_seconds();
  698. }
  699. /* The following counts are associated to each semaphore:
  700. * semncnt number of tasks waiting on semval being nonzero
  701. * semzcnt number of tasks waiting on semval being zero
  702. * This model assumes that a task waits on exactly one semaphore.
  703. * Since semaphore operations are to be performed atomically, tasks actually
  704. * wait on a whole sequence of semaphores simultaneously.
  705. * The counts we return here are a rough approximation, but still
  706. * warrant that semncnt+semzcnt>0 if the task is on the pending queue.
  707. */
  708. static int count_semncnt (struct sem_array * sma, ushort semnum)
  709. {
  710. int semncnt;
  711. struct sem_queue * q;
  712. semncnt = 0;
  713. list_for_each_entry(q, &sma->sem_base[semnum].sem_pending, list) {
  714. struct sembuf * sops = q->sops;
  715. BUG_ON(sops->sem_num != semnum);
  716. if ((sops->sem_op < 0) && !(sops->sem_flg & IPC_NOWAIT))
  717. semncnt++;
  718. }
  719. list_for_each_entry(q, &sma->sem_pending, list) {
  720. struct sembuf * sops = q->sops;
  721. int nsops = q->nsops;
  722. int i;
  723. for (i = 0; i < nsops; i++)
  724. if (sops[i].sem_num == semnum
  725. && (sops[i].sem_op < 0)
  726. && !(sops[i].sem_flg & IPC_NOWAIT))
  727. semncnt++;
  728. }
  729. return semncnt;
  730. }
  731. static int count_semzcnt (struct sem_array * sma, ushort semnum)
  732. {
  733. int semzcnt;
  734. struct sem_queue * q;
  735. semzcnt = 0;
  736. list_for_each_entry(q, &sma->sem_base[semnum].sem_pending, list) {
  737. struct sembuf * sops = q->sops;
  738. BUG_ON(sops->sem_num != semnum);
  739. if ((sops->sem_op == 0) && !(sops->sem_flg & IPC_NOWAIT))
  740. semzcnt++;
  741. }
  742. list_for_each_entry(q, &sma->sem_pending, list) {
  743. struct sembuf * sops = q->sops;
  744. int nsops = q->nsops;
  745. int i;
  746. for (i = 0; i < nsops; i++)
  747. if (sops[i].sem_num == semnum
  748. && (sops[i].sem_op == 0)
  749. && !(sops[i].sem_flg & IPC_NOWAIT))
  750. semzcnt++;
  751. }
  752. return semzcnt;
  753. }
  754. /* Free a semaphore set. freeary() is called with sem_ids.rw_mutex locked
  755. * as a writer and the spinlock for this semaphore set hold. sem_ids.rw_mutex
  756. * remains locked on exit.
  757. */
  758. static void freeary(struct ipc_namespace *ns, struct kern_ipc_perm *ipcp)
  759. {
  760. struct sem_undo *un, *tu;
  761. struct sem_queue *q, *tq;
  762. struct sem_array *sma = container_of(ipcp, struct sem_array, sem_perm);
  763. struct list_head tasks;
  764. int i;
  765. /* Free the existing undo structures for this semaphore set. */
  766. assert_spin_locked(&sma->sem_perm.lock);
  767. list_for_each_entry_safe(un, tu, &sma->list_id, list_id) {
  768. list_del(&un->list_id);
  769. spin_lock(&un->ulp->lock);
  770. un->semid = -1;
  771. list_del_rcu(&un->list_proc);
  772. spin_unlock(&un->ulp->lock);
  773. kfree_rcu(un, rcu);
  774. }
  775. /* Wake up all pending processes and let them fail with EIDRM. */
  776. INIT_LIST_HEAD(&tasks);
  777. list_for_each_entry_safe(q, tq, &sma->sem_pending, list) {
  778. unlink_queue(sma, q);
  779. wake_up_sem_queue_prepare(&tasks, q, -EIDRM);
  780. }
  781. for (i = 0; i < sma->sem_nsems; i++) {
  782. struct sem *sem = sma->sem_base + i;
  783. list_for_each_entry_safe(q, tq, &sem->sem_pending, list) {
  784. unlink_queue(sma, q);
  785. wake_up_sem_queue_prepare(&tasks, q, -EIDRM);
  786. }
  787. }
  788. /* Remove the semaphore set from the IDR */
  789. sem_rmid(ns, sma);
  790. sem_unlock(sma, -1);
  791. rcu_read_unlock();
  792. wake_up_sem_queue_do(&tasks);
  793. ns->used_sems -= sma->sem_nsems;
  794. security_sem_free(sma);
  795. ipc_rcu_putref(sma);
  796. }
  797. static unsigned long copy_semid_to_user(void __user *buf, struct semid64_ds *in, int version)
  798. {
  799. switch(version) {
  800. case IPC_64:
  801. return copy_to_user(buf, in, sizeof(*in));
  802. case IPC_OLD:
  803. {
  804. struct semid_ds out;
  805. memset(&out, 0, sizeof(out));
  806. ipc64_perm_to_ipc_perm(&in->sem_perm, &out.sem_perm);
  807. out.sem_otime = in->sem_otime;
  808. out.sem_ctime = in->sem_ctime;
  809. out.sem_nsems = in->sem_nsems;
  810. return copy_to_user(buf, &out, sizeof(out));
  811. }
  812. default:
  813. return -EINVAL;
  814. }
  815. }
  816. static int semctl_nolock(struct ipc_namespace *ns, int semid,
  817. int cmd, int version, void __user *p)
  818. {
  819. int err;
  820. struct sem_array *sma;
  821. switch(cmd) {
  822. case IPC_INFO:
  823. case SEM_INFO:
  824. {
  825. struct seminfo seminfo;
  826. int max_id;
  827. err = security_sem_semctl(NULL, cmd);
  828. if (err)
  829. return err;
  830. memset(&seminfo,0,sizeof(seminfo));
  831. seminfo.semmni = ns->sc_semmni;
  832. seminfo.semmns = ns->sc_semmns;
  833. seminfo.semmsl = ns->sc_semmsl;
  834. seminfo.semopm = ns->sc_semopm;
  835. seminfo.semvmx = SEMVMX;
  836. seminfo.semmnu = SEMMNU;
  837. seminfo.semmap = SEMMAP;
  838. seminfo.semume = SEMUME;
  839. down_read(&sem_ids(ns).rw_mutex);
  840. if (cmd == SEM_INFO) {
  841. seminfo.semusz = sem_ids(ns).in_use;
  842. seminfo.semaem = ns->used_sems;
  843. } else {
  844. seminfo.semusz = SEMUSZ;
  845. seminfo.semaem = SEMAEM;
  846. }
  847. max_id = ipc_get_maxid(&sem_ids(ns));
  848. up_read(&sem_ids(ns).rw_mutex);
  849. if (copy_to_user(p, &seminfo, sizeof(struct seminfo)))
  850. return -EFAULT;
  851. return (max_id < 0) ? 0: max_id;
  852. }
  853. case IPC_STAT:
  854. case SEM_STAT:
  855. {
  856. struct semid64_ds tbuf;
  857. int id = 0;
  858. memset(&tbuf, 0, sizeof(tbuf));
  859. rcu_read_lock();
  860. if (cmd == SEM_STAT) {
  861. sma = sem_obtain_object(ns, semid);
  862. if (IS_ERR(sma)) {
  863. err = PTR_ERR(sma);
  864. goto out_unlock;
  865. }
  866. id = sma->sem_perm.id;
  867. } else {
  868. sma = sem_obtain_object_check(ns, semid);
  869. if (IS_ERR(sma)) {
  870. err = PTR_ERR(sma);
  871. goto out_unlock;
  872. }
  873. }
  874. err = -EACCES;
  875. if (ipcperms(ns, &sma->sem_perm, S_IRUGO))
  876. goto out_unlock;
  877. err = security_sem_semctl(sma, cmd);
  878. if (err)
  879. goto out_unlock;
  880. kernel_to_ipc64_perm(&sma->sem_perm, &tbuf.sem_perm);
  881. tbuf.sem_otime = sma->sem_otime;
  882. tbuf.sem_ctime = sma->sem_ctime;
  883. tbuf.sem_nsems = sma->sem_nsems;
  884. rcu_read_unlock();
  885. if (copy_semid_to_user(p, &tbuf, version))
  886. return -EFAULT;
  887. return id;
  888. }
  889. default:
  890. return -EINVAL;
  891. }
  892. out_unlock:
  893. rcu_read_unlock();
  894. return err;
  895. }
  896. static int semctl_setval(struct ipc_namespace *ns, int semid, int semnum,
  897. unsigned long arg)
  898. {
  899. struct sem_undo *un;
  900. struct sem_array *sma;
  901. struct sem* curr;
  902. int err;
  903. struct list_head tasks;
  904. int val;
  905. #if defined(CONFIG_64BIT) && defined(__BIG_ENDIAN)
  906. /* big-endian 64bit */
  907. val = arg >> 32;
  908. #else
  909. /* 32bit or little-endian 64bit */
  910. val = arg;
  911. #endif
  912. if (val > SEMVMX || val < 0)
  913. return -ERANGE;
  914. INIT_LIST_HEAD(&tasks);
  915. rcu_read_lock();
  916. sma = sem_obtain_object_check(ns, semid);
  917. if (IS_ERR(sma)) {
  918. rcu_read_unlock();
  919. return PTR_ERR(sma);
  920. }
  921. if (semnum < 0 || semnum >= sma->sem_nsems) {
  922. rcu_read_unlock();
  923. return -EINVAL;
  924. }
  925. if (ipcperms(ns, &sma->sem_perm, S_IWUGO)) {
  926. rcu_read_unlock();
  927. return -EACCES;
  928. }
  929. err = security_sem_semctl(sma, SETVAL);
  930. if (err) {
  931. rcu_read_unlock();
  932. return -EACCES;
  933. }
  934. sem_lock(sma, NULL, -1);
  935. curr = &sma->sem_base[semnum];
  936. assert_spin_locked(&sma->sem_perm.lock);
  937. list_for_each_entry(un, &sma->list_id, list_id)
  938. un->semadj[semnum] = 0;
  939. curr->semval = val;
  940. curr->sempid = task_tgid_vnr(current);
  941. sma->sem_ctime = get_seconds();
  942. /* maybe some queued-up processes were waiting for this */
  943. do_smart_update(sma, NULL, 0, 0, &tasks);
  944. sem_unlock(sma, -1);
  945. rcu_read_unlock();
  946. wake_up_sem_queue_do(&tasks);
  947. return 0;
  948. }
  949. static int semctl_main(struct ipc_namespace *ns, int semid, int semnum,
  950. int cmd, void __user *p)
  951. {
  952. struct sem_array *sma;
  953. struct sem* curr;
  954. int err, nsems;
  955. ushort fast_sem_io[SEMMSL_FAST];
  956. ushort* sem_io = fast_sem_io;
  957. struct list_head tasks;
  958. INIT_LIST_HEAD(&tasks);
  959. rcu_read_lock();
  960. sma = sem_obtain_object_check(ns, semid);
  961. if (IS_ERR(sma)) {
  962. rcu_read_unlock();
  963. return PTR_ERR(sma);
  964. }
  965. nsems = sma->sem_nsems;
  966. err = -EACCES;
  967. if (ipcperms(ns, &sma->sem_perm, cmd == SETALL ? S_IWUGO : S_IRUGO))
  968. goto out_rcu_wakeup;
  969. err = security_sem_semctl(sma, cmd);
  970. if (err)
  971. goto out_rcu_wakeup;
  972. err = -EACCES;
  973. switch (cmd) {
  974. case GETALL:
  975. {
  976. ushort __user *array = p;
  977. int i;
  978. sem_lock(sma, NULL, -1);
  979. if(nsems > SEMMSL_FAST) {
  980. if (!ipc_rcu_getref(sma)) {
  981. sem_unlock(sma, -1);
  982. rcu_read_unlock();
  983. err = -EIDRM;
  984. goto out_free;
  985. }
  986. sem_unlock(sma, -1);
  987. rcu_read_unlock();
  988. sem_io = ipc_alloc(sizeof(ushort)*nsems);
  989. if(sem_io == NULL) {
  990. sem_putref(sma);
  991. return -ENOMEM;
  992. }
  993. rcu_read_lock();
  994. sem_lock_and_putref(sma);
  995. if (sma->sem_perm.deleted) {
  996. sem_unlock(sma, -1);
  997. rcu_read_unlock();
  998. err = -EIDRM;
  999. goto out_free;
  1000. }
  1001. }
  1002. for (i = 0; i < sma->sem_nsems; i++)
  1003. sem_io[i] = sma->sem_base[i].semval;
  1004. sem_unlock(sma, -1);
  1005. rcu_read_unlock();
  1006. err = 0;
  1007. if(copy_to_user(array, sem_io, nsems*sizeof(ushort)))
  1008. err = -EFAULT;
  1009. goto out_free;
  1010. }
  1011. case SETALL:
  1012. {
  1013. int i;
  1014. struct sem_undo *un;
  1015. if (!ipc_rcu_getref(sma)) {
  1016. rcu_read_unlock();
  1017. return -EIDRM;
  1018. }
  1019. rcu_read_unlock();
  1020. if(nsems > SEMMSL_FAST) {
  1021. sem_io = ipc_alloc(sizeof(ushort)*nsems);
  1022. if(sem_io == NULL) {
  1023. sem_putref(sma);
  1024. return -ENOMEM;
  1025. }
  1026. }
  1027. if (copy_from_user (sem_io, p, nsems*sizeof(ushort))) {
  1028. sem_putref(sma);
  1029. err = -EFAULT;
  1030. goto out_free;
  1031. }
  1032. for (i = 0; i < nsems; i++) {
  1033. if (sem_io[i] > SEMVMX) {
  1034. sem_putref(sma);
  1035. err = -ERANGE;
  1036. goto out_free;
  1037. }
  1038. }
  1039. rcu_read_lock();
  1040. sem_lock_and_putref(sma);
  1041. if (sma->sem_perm.deleted) {
  1042. sem_unlock(sma, -1);
  1043. rcu_read_unlock();
  1044. err = -EIDRM;
  1045. goto out_free;
  1046. }
  1047. for (i = 0; i < nsems; i++)
  1048. sma->sem_base[i].semval = sem_io[i];
  1049. assert_spin_locked(&sma->sem_perm.lock);
  1050. list_for_each_entry(un, &sma->list_id, list_id) {
  1051. for (i = 0; i < nsems; i++)
  1052. un->semadj[i] = 0;
  1053. }
  1054. sma->sem_ctime = get_seconds();
  1055. /* maybe some queued-up processes were waiting for this */
  1056. do_smart_update(sma, NULL, 0, 0, &tasks);
  1057. err = 0;
  1058. goto out_unlock;
  1059. }
  1060. /* GETVAL, GETPID, GETNCTN, GETZCNT: fall-through */
  1061. }
  1062. err = -EINVAL;
  1063. if (semnum < 0 || semnum >= nsems)
  1064. goto out_rcu_wakeup;
  1065. sem_lock(sma, NULL, -1);
  1066. curr = &sma->sem_base[semnum];
  1067. switch (cmd) {
  1068. case GETVAL:
  1069. err = curr->semval;
  1070. goto out_unlock;
  1071. case GETPID:
  1072. err = curr->sempid;
  1073. goto out_unlock;
  1074. case GETNCNT:
  1075. err = count_semncnt(sma,semnum);
  1076. goto out_unlock;
  1077. case GETZCNT:
  1078. err = count_semzcnt(sma,semnum);
  1079. goto out_unlock;
  1080. }
  1081. out_unlock:
  1082. sem_unlock(sma, -1);
  1083. out_rcu_wakeup:
  1084. rcu_read_unlock();
  1085. wake_up_sem_queue_do(&tasks);
  1086. out_free:
  1087. if(sem_io != fast_sem_io)
  1088. ipc_free(sem_io, sizeof(ushort)*nsems);
  1089. return err;
  1090. }
  1091. static inline unsigned long
  1092. copy_semid_from_user(struct semid64_ds *out, void __user *buf, int version)
  1093. {
  1094. switch(version) {
  1095. case IPC_64:
  1096. if (copy_from_user(out, buf, sizeof(*out)))
  1097. return -EFAULT;
  1098. return 0;
  1099. case IPC_OLD:
  1100. {
  1101. struct semid_ds tbuf_old;
  1102. if(copy_from_user(&tbuf_old, buf, sizeof(tbuf_old)))
  1103. return -EFAULT;
  1104. out->sem_perm.uid = tbuf_old.sem_perm.uid;
  1105. out->sem_perm.gid = tbuf_old.sem_perm.gid;
  1106. out->sem_perm.mode = tbuf_old.sem_perm.mode;
  1107. return 0;
  1108. }
  1109. default:
  1110. return -EINVAL;
  1111. }
  1112. }
  1113. /*
  1114. * This function handles some semctl commands which require the rw_mutex
  1115. * to be held in write mode.
  1116. * NOTE: no locks must be held, the rw_mutex is taken inside this function.
  1117. */
  1118. static int semctl_down(struct ipc_namespace *ns, int semid,
  1119. int cmd, int version, void __user *p)
  1120. {
  1121. struct sem_array *sma;
  1122. int err;
  1123. struct semid64_ds semid64;
  1124. struct kern_ipc_perm *ipcp;
  1125. if(cmd == IPC_SET) {
  1126. if (copy_semid_from_user(&semid64, p, version))
  1127. return -EFAULT;
  1128. }
  1129. ipcp = ipcctl_pre_down_nolock(ns, &sem_ids(ns), semid, cmd,
  1130. &semid64.sem_perm, 0);
  1131. if (IS_ERR(ipcp))
  1132. return PTR_ERR(ipcp);
  1133. sma = container_of(ipcp, struct sem_array, sem_perm);
  1134. err = security_sem_semctl(sma, cmd);
  1135. if (err) {
  1136. rcu_read_unlock();
  1137. goto out_up;
  1138. }
  1139. switch(cmd){
  1140. case IPC_RMID:
  1141. sem_lock(sma, NULL, -1);
  1142. freeary(ns, ipcp);
  1143. goto out_up;
  1144. case IPC_SET:
  1145. sem_lock(sma, NULL, -1);
  1146. err = ipc_update_perm(&semid64.sem_perm, ipcp);
  1147. if (err)
  1148. goto out_unlock;
  1149. sma->sem_ctime = get_seconds();
  1150. break;
  1151. default:
  1152. rcu_read_unlock();
  1153. err = -EINVAL;
  1154. goto out_up;
  1155. }
  1156. out_unlock:
  1157. sem_unlock(sma, -1);
  1158. rcu_read_unlock();
  1159. out_up:
  1160. up_write(&sem_ids(ns).rw_mutex);
  1161. return err;
  1162. }
  1163. SYSCALL_DEFINE4(semctl, int, semid, int, semnum, int, cmd, unsigned long, arg)
  1164. {
  1165. int version;
  1166. struct ipc_namespace *ns;
  1167. void __user *p = (void __user *)arg;
  1168. if (semid < 0)
  1169. return -EINVAL;
  1170. version = ipc_parse_version(&cmd);
  1171. ns = current->nsproxy->ipc_ns;
  1172. switch(cmd) {
  1173. case IPC_INFO:
  1174. case SEM_INFO:
  1175. case IPC_STAT:
  1176. case SEM_STAT:
  1177. return semctl_nolock(ns, semid, cmd, version, p);
  1178. case GETALL:
  1179. case GETVAL:
  1180. case GETPID:
  1181. case GETNCNT:
  1182. case GETZCNT:
  1183. case SETALL:
  1184. return semctl_main(ns, semid, semnum, cmd, p);
  1185. case SETVAL:
  1186. return semctl_setval(ns, semid, semnum, arg);
  1187. case IPC_RMID:
  1188. case IPC_SET:
  1189. return semctl_down(ns, semid, cmd, version, p);
  1190. default:
  1191. return -EINVAL;
  1192. }
  1193. }
  1194. /* If the task doesn't already have a undo_list, then allocate one
  1195. * here. We guarantee there is only one thread using this undo list,
  1196. * and current is THE ONE
  1197. *
  1198. * If this allocation and assignment succeeds, but later
  1199. * portions of this code fail, there is no need to free the sem_undo_list.
  1200. * Just let it stay associated with the task, and it'll be freed later
  1201. * at exit time.
  1202. *
  1203. * This can block, so callers must hold no locks.
  1204. */
  1205. static inline int get_undo_list(struct sem_undo_list **undo_listp)
  1206. {
  1207. struct sem_undo_list *undo_list;
  1208. undo_list = current->sysvsem.undo_list;
  1209. if (!undo_list) {
  1210. undo_list = kzalloc(sizeof(*undo_list), GFP_KERNEL);
  1211. if (undo_list == NULL)
  1212. return -ENOMEM;
  1213. spin_lock_init(&undo_list->lock);
  1214. atomic_set(&undo_list->refcnt, 1);
  1215. INIT_LIST_HEAD(&undo_list->list_proc);
  1216. current->sysvsem.undo_list = undo_list;
  1217. }
  1218. *undo_listp = undo_list;
  1219. return 0;
  1220. }
  1221. static struct sem_undo *__lookup_undo(struct sem_undo_list *ulp, int semid)
  1222. {
  1223. struct sem_undo *un;
  1224. list_for_each_entry_rcu(un, &ulp->list_proc, list_proc) {
  1225. if (un->semid == semid)
  1226. return un;
  1227. }
  1228. return NULL;
  1229. }
  1230. static struct sem_undo *lookup_undo(struct sem_undo_list *ulp, int semid)
  1231. {
  1232. struct sem_undo *un;
  1233. assert_spin_locked(&ulp->lock);
  1234. un = __lookup_undo(ulp, semid);
  1235. if (un) {
  1236. list_del_rcu(&un->list_proc);
  1237. list_add_rcu(&un->list_proc, &ulp->list_proc);
  1238. }
  1239. return un;
  1240. }
  1241. /**
  1242. * find_alloc_undo - Lookup (and if not present create) undo array
  1243. * @ns: namespace
  1244. * @semid: semaphore array id
  1245. *
  1246. * The function looks up (and if not present creates) the undo structure.
  1247. * The size of the undo structure depends on the size of the semaphore
  1248. * array, thus the alloc path is not that straightforward.
  1249. * Lifetime-rules: sem_undo is rcu-protected, on success, the function
  1250. * performs a rcu_read_lock().
  1251. */
  1252. static struct sem_undo *find_alloc_undo(struct ipc_namespace *ns, int semid)
  1253. {
  1254. struct sem_array *sma;
  1255. struct sem_undo_list *ulp;
  1256. struct sem_undo *un, *new;
  1257. int nsems, error;
  1258. error = get_undo_list(&ulp);
  1259. if (error)
  1260. return ERR_PTR(error);
  1261. rcu_read_lock();
  1262. spin_lock(&ulp->lock);
  1263. un = lookup_undo(ulp, semid);
  1264. spin_unlock(&ulp->lock);
  1265. if (likely(un!=NULL))
  1266. goto out;
  1267. /* no undo structure around - allocate one. */
  1268. /* step 1: figure out the size of the semaphore array */
  1269. sma = sem_obtain_object_check(ns, semid);
  1270. if (IS_ERR(sma)) {
  1271. rcu_read_unlock();
  1272. return ERR_CAST(sma);
  1273. }
  1274. nsems = sma->sem_nsems;
  1275. if (!ipc_rcu_getref(sma)) {
  1276. rcu_read_unlock();
  1277. un = ERR_PTR(-EIDRM);
  1278. goto out;
  1279. }
  1280. rcu_read_unlock();
  1281. /* step 2: allocate new undo structure */
  1282. new = kzalloc(sizeof(struct sem_undo) + sizeof(short)*nsems, GFP_KERNEL);
  1283. if (!new) {
  1284. sem_putref(sma);
  1285. return ERR_PTR(-ENOMEM);
  1286. }
  1287. /* step 3: Acquire the lock on semaphore array */
  1288. rcu_read_lock();
  1289. sem_lock_and_putref(sma);
  1290. if (sma->sem_perm.deleted) {
  1291. sem_unlock(sma, -1);
  1292. rcu_read_unlock();
  1293. kfree(new);
  1294. un = ERR_PTR(-EIDRM);
  1295. goto out;
  1296. }
  1297. spin_lock(&ulp->lock);
  1298. /*
  1299. * step 4: check for races: did someone else allocate the undo struct?
  1300. */
  1301. un = lookup_undo(ulp, semid);
  1302. if (un) {
  1303. kfree(new);
  1304. goto success;
  1305. }
  1306. /* step 5: initialize & link new undo structure */
  1307. new->semadj = (short *) &new[1];
  1308. new->ulp = ulp;
  1309. new->semid = semid;
  1310. assert_spin_locked(&ulp->lock);
  1311. list_add_rcu(&new->list_proc, &ulp->list_proc);
  1312. assert_spin_locked(&sma->sem_perm.lock);
  1313. list_add(&new->list_id, &sma->list_id);
  1314. un = new;
  1315. success:
  1316. spin_unlock(&ulp->lock);
  1317. sem_unlock(sma, -1);
  1318. out:
  1319. return un;
  1320. }
  1321. /**
  1322. * get_queue_result - Retrieve the result code from sem_queue
  1323. * @q: Pointer to queue structure
  1324. *
  1325. * Retrieve the return code from the pending queue. If IN_WAKEUP is found in
  1326. * q->status, then we must loop until the value is replaced with the final
  1327. * value: This may happen if a task is woken up by an unrelated event (e.g.
  1328. * signal) and in parallel the task is woken up by another task because it got
  1329. * the requested semaphores.
  1330. *
  1331. * The function can be called with or without holding the semaphore spinlock.
  1332. */
  1333. static int get_queue_result(struct sem_queue *q)
  1334. {
  1335. int error;
  1336. error = q->status;
  1337. while (unlikely(error == IN_WAKEUP)) {
  1338. cpu_relax();
  1339. error = q->status;
  1340. }
  1341. return error;
  1342. }
  1343. SYSCALL_DEFINE4(semtimedop, int, semid, struct sembuf __user *, tsops,
  1344. unsigned, nsops, const struct timespec __user *, timeout)
  1345. {
  1346. int error = -EINVAL;
  1347. struct sem_array *sma;
  1348. struct sembuf fast_sops[SEMOPM_FAST];
  1349. struct sembuf* sops = fast_sops, *sop;
  1350. struct sem_undo *un;
  1351. int undos = 0, alter = 0, max, locknum;
  1352. struct sem_queue queue;
  1353. unsigned long jiffies_left = 0;
  1354. struct ipc_namespace *ns;
  1355. struct list_head tasks;
  1356. ns = current->nsproxy->ipc_ns;
  1357. if (nsops < 1 || semid < 0)
  1358. return -EINVAL;
  1359. if (nsops > ns->sc_semopm)
  1360. return -E2BIG;
  1361. if(nsops > SEMOPM_FAST) {
  1362. sops = kmalloc(sizeof(*sops)*nsops,GFP_KERNEL);
  1363. if(sops==NULL)
  1364. return -ENOMEM;
  1365. }
  1366. if (copy_from_user (sops, tsops, nsops * sizeof(*tsops))) {
  1367. error=-EFAULT;
  1368. goto out_free;
  1369. }
  1370. if (timeout) {
  1371. struct timespec _timeout;
  1372. if (copy_from_user(&_timeout, timeout, sizeof(*timeout))) {
  1373. error = -EFAULT;
  1374. goto out_free;
  1375. }
  1376. if (_timeout.tv_sec < 0 || _timeout.tv_nsec < 0 ||
  1377. _timeout.tv_nsec >= 1000000000L) {
  1378. error = -EINVAL;
  1379. goto out_free;
  1380. }
  1381. jiffies_left = timespec_to_jiffies(&_timeout);
  1382. }
  1383. max = 0;
  1384. for (sop = sops; sop < sops + nsops; sop++) {
  1385. if (sop->sem_num >= max)
  1386. max = sop->sem_num;
  1387. if (sop->sem_flg & SEM_UNDO)
  1388. undos = 1;
  1389. if (sop->sem_op != 0)
  1390. alter = 1;
  1391. }
  1392. INIT_LIST_HEAD(&tasks);
  1393. if (undos) {
  1394. /* On success, find_alloc_undo takes the rcu_read_lock */
  1395. un = find_alloc_undo(ns, semid);
  1396. if (IS_ERR(un)) {
  1397. error = PTR_ERR(un);
  1398. goto out_free;
  1399. }
  1400. } else {
  1401. un = NULL;
  1402. rcu_read_lock();
  1403. }
  1404. sma = sem_obtain_object_check(ns, semid);
  1405. if (IS_ERR(sma)) {
  1406. rcu_read_unlock();
  1407. error = PTR_ERR(sma);
  1408. goto out_free;
  1409. }
  1410. error = -EFBIG;
  1411. if (max >= sma->sem_nsems)
  1412. goto out_rcu_wakeup;
  1413. error = -EACCES;
  1414. if (ipcperms(ns, &sma->sem_perm, alter ? S_IWUGO : S_IRUGO))
  1415. goto out_rcu_wakeup;
  1416. error = security_sem_semop(sma, sops, nsops, alter);
  1417. if (error)
  1418. goto out_rcu_wakeup;
  1419. /*
  1420. * semid identifiers are not unique - find_alloc_undo may have
  1421. * allocated an undo structure, it was invalidated by an RMID
  1422. * and now a new array with received the same id. Check and fail.
  1423. * This case can be detected checking un->semid. The existence of
  1424. * "un" itself is guaranteed by rcu.
  1425. */
  1426. error = -EIDRM;
  1427. locknum = sem_lock(sma, sops, nsops);
  1428. if (un && un->semid == -1)
  1429. goto out_unlock_free;
  1430. error = try_atomic_semop (sma, sops, nsops, un, task_tgid_vnr(current));
  1431. if (error <= 0) {
  1432. if (alter && error == 0)
  1433. do_smart_update(sma, sops, nsops, 1, &tasks);
  1434. goto out_unlock_free;
  1435. }
  1436. /* We need to sleep on this operation, so we put the current
  1437. * task into the pending queue and go to sleep.
  1438. */
  1439. queue.sops = sops;
  1440. queue.nsops = nsops;
  1441. queue.undo = un;
  1442. queue.pid = task_tgid_vnr(current);
  1443. queue.alter = alter;
  1444. if (nsops == 1) {
  1445. struct sem *curr;
  1446. curr = &sma->sem_base[sops->sem_num];
  1447. if (alter)
  1448. list_add_tail(&queue.list, &curr->sem_pending);
  1449. else
  1450. list_add(&queue.list, &curr->sem_pending);
  1451. } else {
  1452. if (alter)
  1453. list_add_tail(&queue.list, &sma->sem_pending);
  1454. else
  1455. list_add(&queue.list, &sma->sem_pending);
  1456. sma->complex_count++;
  1457. }
  1458. queue.status = -EINTR;
  1459. queue.sleeper = current;
  1460. sleep_again:
  1461. current->state = TASK_INTERRUPTIBLE;
  1462. sem_unlock(sma, locknum);
  1463. rcu_read_unlock();
  1464. if (timeout)
  1465. jiffies_left = schedule_timeout(jiffies_left);
  1466. else
  1467. schedule();
  1468. error = get_queue_result(&queue);
  1469. if (error != -EINTR) {
  1470. /* fast path: update_queue already obtained all requested
  1471. * resources.
  1472. * Perform a smp_mb(): User space could assume that semop()
  1473. * is a memory barrier: Without the mb(), the cpu could
  1474. * speculatively read in user space stale data that was
  1475. * overwritten by the previous owner of the semaphore.
  1476. */
  1477. smp_mb();
  1478. goto out_free;
  1479. }
  1480. rcu_read_lock();
  1481. sma = sem_obtain_lock(ns, semid, sops, nsops, &locknum);
  1482. /*
  1483. * Wait until it's guaranteed that no wakeup_sem_queue_do() is ongoing.
  1484. */
  1485. error = get_queue_result(&queue);
  1486. /*
  1487. * Array removed? If yes, leave without sem_unlock().
  1488. */
  1489. if (IS_ERR(sma)) {
  1490. rcu_read_unlock();
  1491. goto out_free;
  1492. }
  1493. /*
  1494. * If queue.status != -EINTR we are woken up by another process.
  1495. * Leave without unlink_queue(), but with sem_unlock().
  1496. */
  1497. if (error != -EINTR) {
  1498. goto out_unlock_free;
  1499. }
  1500. /*
  1501. * If an interrupt occurred we have to clean up the queue
  1502. */
  1503. if (timeout && jiffies_left == 0)
  1504. error = -EAGAIN;
  1505. /*
  1506. * If the wakeup was spurious, just retry
  1507. */
  1508. if (error == -EINTR && !signal_pending(current))
  1509. goto sleep_again;
  1510. unlink_queue(sma, &queue);
  1511. out_unlock_free:
  1512. sem_unlock(sma, locknum);
  1513. out_rcu_wakeup:
  1514. rcu_read_unlock();
  1515. wake_up_sem_queue_do(&tasks);
  1516. out_free:
  1517. if(sops != fast_sops)
  1518. kfree(sops);
  1519. return error;
  1520. }
  1521. SYSCALL_DEFINE3(semop, int, semid, struct sembuf __user *, tsops,
  1522. unsigned, nsops)
  1523. {
  1524. return sys_semtimedop(semid, tsops, nsops, NULL);
  1525. }
  1526. /* If CLONE_SYSVSEM is set, establish sharing of SEM_UNDO state between
  1527. * parent and child tasks.
  1528. */
  1529. int copy_semundo(unsigned long clone_flags, struct task_struct *tsk)
  1530. {
  1531. struct sem_undo_list *undo_list;
  1532. int error;
  1533. if (clone_flags & CLONE_SYSVSEM) {
  1534. error = get_undo_list(&undo_list);
  1535. if (error)
  1536. return error;
  1537. atomic_inc(&undo_list->refcnt);
  1538. tsk->sysvsem.undo_list = undo_list;
  1539. } else
  1540. tsk->sysvsem.undo_list = NULL;
  1541. return 0;
  1542. }
  1543. /*
  1544. * add semadj values to semaphores, free undo structures.
  1545. * undo structures are not freed when semaphore arrays are destroyed
  1546. * so some of them may be out of date.
  1547. * IMPLEMENTATION NOTE: There is some confusion over whether the
  1548. * set of adjustments that needs to be done should be done in an atomic
  1549. * manner or not. That is, if we are attempting to decrement the semval
  1550. * should we queue up and wait until we can do so legally?
  1551. * The original implementation attempted to do this (queue and wait).
  1552. * The current implementation does not do so. The POSIX standard
  1553. * and SVID should be consulted to determine what behavior is mandated.
  1554. */
  1555. void exit_sem(struct task_struct *tsk)
  1556. {
  1557. struct sem_undo_list *ulp;
  1558. ulp = tsk->sysvsem.undo_list;
  1559. if (!ulp)
  1560. return;
  1561. tsk->sysvsem.undo_list = NULL;
  1562. if (!atomic_dec_and_test(&ulp->refcnt))
  1563. return;
  1564. for (;;) {
  1565. struct sem_array *sma;
  1566. struct sem_undo *un;
  1567. struct list_head tasks;
  1568. int semid, i;
  1569. rcu_read_lock();
  1570. un = list_entry_rcu(ulp->list_proc.next,
  1571. struct sem_undo, list_proc);
  1572. if (&un->list_proc == &ulp->list_proc)
  1573. semid = -1;
  1574. else
  1575. semid = un->semid;
  1576. if (semid == -1) {
  1577. rcu_read_unlock();
  1578. break;
  1579. }
  1580. sma = sem_obtain_object_check(tsk->nsproxy->ipc_ns, un->semid);
  1581. /* exit_sem raced with IPC_RMID, nothing to do */
  1582. if (IS_ERR(sma)) {
  1583. rcu_read_unlock();
  1584. continue;
  1585. }
  1586. sem_lock(sma, NULL, -1);
  1587. un = __lookup_undo(ulp, semid);
  1588. if (un == NULL) {
  1589. /* exit_sem raced with IPC_RMID+semget() that created
  1590. * exactly the same semid. Nothing to do.
  1591. */
  1592. sem_unlock(sma, -1);
  1593. rcu_read_unlock();
  1594. continue;
  1595. }
  1596. /* remove un from the linked lists */
  1597. assert_spin_locked(&sma->sem_perm.lock);
  1598. list_del(&un->list_id);
  1599. spin_lock(&ulp->lock);
  1600. list_del_rcu(&un->list_proc);
  1601. spin_unlock(&ulp->lock);
  1602. /* perform adjustments registered in un */
  1603. for (i = 0; i < sma->sem_nsems; i++) {
  1604. struct sem * semaphore = &sma->sem_base[i];
  1605. if (un->semadj[i]) {
  1606. semaphore->semval += un->semadj[i];
  1607. /*
  1608. * Range checks of the new semaphore value,
  1609. * not defined by sus:
  1610. * - Some unices ignore the undo entirely
  1611. * (e.g. HP UX 11i 11.22, Tru64 V5.1)
  1612. * - some cap the value (e.g. FreeBSD caps
  1613. * at 0, but doesn't enforce SEMVMX)
  1614. *
  1615. * Linux caps the semaphore value, both at 0
  1616. * and at SEMVMX.
  1617. *
  1618. * Manfred <manfred@colorfullife.com>
  1619. */
  1620. if (semaphore->semval < 0)
  1621. semaphore->semval = 0;
  1622. if (semaphore->semval > SEMVMX)
  1623. semaphore->semval = SEMVMX;
  1624. semaphore->sempid = task_tgid_vnr(current);
  1625. }
  1626. }
  1627. /* maybe some queued-up processes were waiting for this */
  1628. INIT_LIST_HEAD(&tasks);
  1629. do_smart_update(sma, NULL, 0, 1, &tasks);
  1630. sem_unlock(sma, -1);
  1631. rcu_read_unlock();
  1632. wake_up_sem_queue_do(&tasks);
  1633. kfree_rcu(un, rcu);
  1634. }
  1635. kfree(ulp);
  1636. }
  1637. #ifdef CONFIG_PROC_FS
  1638. static int sysvipc_sem_proc_show(struct seq_file *s, void *it)
  1639. {
  1640. struct user_namespace *user_ns = seq_user_ns(s);
  1641. struct sem_array *sma = it;
  1642. return seq_printf(s,
  1643. "%10d %10d %4o %10u %5u %5u %5u %5u %10lu %10lu\n",
  1644. sma->sem_perm.key,
  1645. sma->sem_perm.id,
  1646. sma->sem_perm.mode,
  1647. sma->sem_nsems,
  1648. from_kuid_munged(user_ns, sma->sem_perm.uid),
  1649. from_kgid_munged(user_ns, sma->sem_perm.gid),
  1650. from_kuid_munged(user_ns, sma->sem_perm.cuid),
  1651. from_kgid_munged(user_ns, sma->sem_perm.cgid),
  1652. sma->sem_otime,
  1653. sma->sem_ctime);
  1654. }
  1655. #endif