sem.c 55 KB

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