sem.c 56 KB

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