sem.c 56 KB

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