eventpoll.c 59 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138
  1. /*
  2. * fs/eventpoll.c (Efficient event retrieval implementation)
  3. * Copyright (C) 2001,...,2009 Davide Libenzi
  4. *
  5. * This program is free software; you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation; either version 2 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * Davide Libenzi <davidel@xmailserver.org>
  11. *
  12. */
  13. #include <linux/init.h>
  14. #include <linux/kernel.h>
  15. #include <linux/sched.h>
  16. #include <linux/fs.h>
  17. #include <linux/file.h>
  18. #include <linux/signal.h>
  19. #include <linux/errno.h>
  20. #include <linux/mm.h>
  21. #include <linux/slab.h>
  22. #include <linux/poll.h>
  23. #include <linux/string.h>
  24. #include <linux/list.h>
  25. #include <linux/hash.h>
  26. #include <linux/spinlock.h>
  27. #include <linux/syscalls.h>
  28. #include <linux/rbtree.h>
  29. #include <linux/wait.h>
  30. #include <linux/eventpoll.h>
  31. #include <linux/mount.h>
  32. #include <linux/bitops.h>
  33. #include <linux/mutex.h>
  34. #include <linux/anon_inodes.h>
  35. #include <linux/device.h>
  36. #include <linux/freezer.h>
  37. #include <asm/uaccess.h>
  38. #include <asm/io.h>
  39. #include <asm/mman.h>
  40. #include <linux/atomic.h>
  41. #include <linux/proc_fs.h>
  42. #include <linux/seq_file.h>
  43. #include <linux/compat.h>
  44. #include <linux/rculist.h>
  45. /*
  46. * LOCKING:
  47. * There are three level of locking required by epoll :
  48. *
  49. * 1) epmutex (mutex)
  50. * 2) ep->mtx (mutex)
  51. * 3) ep->lock (spinlock)
  52. *
  53. * The acquire order is the one listed above, from 1 to 3.
  54. * We need a spinlock (ep->lock) because we manipulate objects
  55. * from inside the poll callback, that might be triggered from
  56. * a wake_up() that in turn might be called from IRQ context.
  57. * So we can't sleep inside the poll callback and hence we need
  58. * a spinlock. During the event transfer loop (from kernel to
  59. * user space) we could end up sleeping due a copy_to_user(), so
  60. * we need a lock that will allow us to sleep. This lock is a
  61. * mutex (ep->mtx). It is acquired during the event transfer loop,
  62. * during epoll_ctl(EPOLL_CTL_DEL) and during eventpoll_release_file().
  63. * Then we also need a global mutex to serialize eventpoll_release_file()
  64. * and ep_free().
  65. * This mutex is acquired by ep_free() during the epoll file
  66. * cleanup path and it is also acquired by eventpoll_release_file()
  67. * if a file has been pushed inside an epoll set and it is then
  68. * close()d without a previous call to epoll_ctl(EPOLL_CTL_DEL).
  69. * It is also acquired when inserting an epoll fd onto another epoll
  70. * fd. We do this so that we walk the epoll tree and ensure that this
  71. * insertion does not create a cycle of epoll file descriptors, which
  72. * could lead to deadlock. We need a global mutex to prevent two
  73. * simultaneous inserts (A into B and B into A) from racing and
  74. * constructing a cycle without either insert observing that it is
  75. * going to.
  76. * It is necessary to acquire multiple "ep->mtx"es at once in the
  77. * case when one epoll fd is added to another. In this case, we
  78. * always acquire the locks in the order of nesting (i.e. after
  79. * epoll_ctl(e1, EPOLL_CTL_ADD, e2), e1->mtx will always be acquired
  80. * before e2->mtx). Since we disallow cycles of epoll file
  81. * descriptors, this ensures that the mutexes are well-ordered. In
  82. * order to communicate this nesting to lockdep, when walking a tree
  83. * of epoll file descriptors, we use the current recursion depth as
  84. * the lockdep subkey.
  85. * It is possible to drop the "ep->mtx" and to use the global
  86. * mutex "epmutex" (together with "ep->lock") to have it working,
  87. * but having "ep->mtx" will make the interface more scalable.
  88. * Events that require holding "epmutex" are very rare, while for
  89. * normal operations the epoll private "ep->mtx" will guarantee
  90. * a better scalability.
  91. */
  92. /* Epoll private bits inside the event mask */
  93. #define EP_PRIVATE_BITS (EPOLLWAKEUP | EPOLLONESHOT | EPOLLET)
  94. /* Maximum number of nesting allowed inside epoll sets */
  95. #define EP_MAX_NESTS 4
  96. #define EP_MAX_EVENTS (INT_MAX / sizeof(struct epoll_event))
  97. #define EP_UNACTIVE_PTR ((void *) -1L)
  98. #define EP_ITEM_COST (sizeof(struct epitem) + sizeof(struct eppoll_entry))
  99. struct epoll_filefd {
  100. struct file *file;
  101. int fd;
  102. } __packed;
  103. /*
  104. * Structure used to track possible nested calls, for too deep recursions
  105. * and loop cycles.
  106. */
  107. struct nested_call_node {
  108. struct list_head llink;
  109. void *cookie;
  110. void *ctx;
  111. };
  112. /*
  113. * This structure is used as collector for nested calls, to check for
  114. * maximum recursion dept and loop cycles.
  115. */
  116. struct nested_calls {
  117. struct list_head tasks_call_list;
  118. spinlock_t lock;
  119. };
  120. /*
  121. * Each file descriptor added to the eventpoll interface will
  122. * have an entry of this type linked to the "rbr" RB tree.
  123. * Avoid increasing the size of this struct, there can be many thousands
  124. * of these on a server and we do not want this to take another cache line.
  125. */
  126. struct epitem {
  127. union {
  128. /* RB tree node links this structure to the eventpoll RB tree */
  129. struct rb_node rbn;
  130. /* Used to free the struct epitem */
  131. struct rcu_head rcu;
  132. };
  133. /* List header used to link this structure to the eventpoll ready list */
  134. struct list_head rdllink;
  135. /*
  136. * Works together "struct eventpoll"->ovflist in keeping the
  137. * single linked chain of items.
  138. */
  139. struct epitem *next;
  140. /* The file descriptor information this item refers to */
  141. struct epoll_filefd ffd;
  142. /* Number of active wait queue attached to poll operations */
  143. int nwait;
  144. /* List containing poll wait queues */
  145. struct list_head pwqlist;
  146. /* The "container" of this item */
  147. struct eventpoll *ep;
  148. /* List header used to link this item to the "struct file" items list */
  149. struct list_head fllink;
  150. /* wakeup_source used when EPOLLWAKEUP is set */
  151. struct wakeup_source __rcu *ws;
  152. /* The structure that describe the interested events and the source fd */
  153. struct epoll_event event;
  154. };
  155. /*
  156. * This structure is stored inside the "private_data" member of the file
  157. * structure and represents the main data structure for the eventpoll
  158. * interface.
  159. */
  160. struct eventpoll {
  161. /* Protect the access to this structure */
  162. spinlock_t lock;
  163. /*
  164. * This mutex is used to ensure that files are not removed
  165. * while epoll is using them. This is held during the event
  166. * collection loop, the file cleanup path, the epoll file exit
  167. * code and the ctl operations.
  168. */
  169. struct mutex mtx;
  170. /* Wait queue used by sys_epoll_wait() */
  171. wait_queue_head_t wq;
  172. /* Wait queue used by file->poll() */
  173. wait_queue_head_t poll_wait;
  174. /* List of ready file descriptors */
  175. struct list_head rdllist;
  176. /* RB tree root used to store monitored fd structs */
  177. struct rb_root rbr;
  178. /*
  179. * This is a single linked list that chains all the "struct epitem" that
  180. * happened while transferring ready events to userspace w/out
  181. * holding ->lock.
  182. */
  183. struct epitem *ovflist;
  184. /* wakeup_source used when ep_scan_ready_list is running */
  185. struct wakeup_source *ws;
  186. /* The user that created the eventpoll descriptor */
  187. struct user_struct *user;
  188. struct file *file;
  189. /* used to optimize loop detection check */
  190. int visited;
  191. struct list_head visited_list_link;
  192. };
  193. /* Wait structure used by the poll hooks */
  194. struct eppoll_entry {
  195. /* List header used to link this structure to the "struct epitem" */
  196. struct list_head llink;
  197. /* The "base" pointer is set to the container "struct epitem" */
  198. struct epitem *base;
  199. /*
  200. * Wait queue item that will be linked to the target file wait
  201. * queue head.
  202. */
  203. wait_queue_t wait;
  204. /* The wait queue head that linked the "wait" wait queue item */
  205. wait_queue_head_t *whead;
  206. };
  207. /* Wrapper struct used by poll queueing */
  208. struct ep_pqueue {
  209. poll_table pt;
  210. struct epitem *epi;
  211. };
  212. /* Used by the ep_send_events() function as callback private data */
  213. struct ep_send_events_data {
  214. int maxevents;
  215. struct epoll_event __user *events;
  216. };
  217. /*
  218. * Configuration options available inside /proc/sys/fs/epoll/
  219. */
  220. /* Maximum number of epoll watched descriptors, per user */
  221. static long max_user_watches __read_mostly;
  222. /*
  223. * This mutex is used to serialize ep_free() and eventpoll_release_file().
  224. */
  225. static DEFINE_MUTEX(epmutex);
  226. /* Used to check for epoll file descriptor inclusion loops */
  227. static struct nested_calls poll_loop_ncalls;
  228. /* Used for safe wake up implementation */
  229. static struct nested_calls poll_safewake_ncalls;
  230. /* Used to call file's f_op->poll() under the nested calls boundaries */
  231. static struct nested_calls poll_readywalk_ncalls;
  232. /* Slab cache used to allocate "struct epitem" */
  233. static struct kmem_cache *epi_cache __read_mostly;
  234. /* Slab cache used to allocate "struct eppoll_entry" */
  235. static struct kmem_cache *pwq_cache __read_mostly;
  236. /* Visited nodes during ep_loop_check(), so we can unset them when we finish */
  237. static LIST_HEAD(visited_list);
  238. /*
  239. * List of files with newly added links, where we may need to limit the number
  240. * of emanating paths. Protected by the epmutex.
  241. */
  242. static LIST_HEAD(tfile_check_list);
  243. #ifdef CONFIG_SYSCTL
  244. #include <linux/sysctl.h>
  245. static long zero;
  246. static long long_max = LONG_MAX;
  247. struct ctl_table epoll_table[] = {
  248. {
  249. .procname = "max_user_watches",
  250. .data = &max_user_watches,
  251. .maxlen = sizeof(max_user_watches),
  252. .mode = 0644,
  253. .proc_handler = proc_doulongvec_minmax,
  254. .extra1 = &zero,
  255. .extra2 = &long_max,
  256. },
  257. { }
  258. };
  259. #endif /* CONFIG_SYSCTL */
  260. static const struct file_operations eventpoll_fops;
  261. static inline int is_file_epoll(struct file *f)
  262. {
  263. return f->f_op == &eventpoll_fops;
  264. }
  265. /* Setup the structure that is used as key for the RB tree */
  266. static inline void ep_set_ffd(struct epoll_filefd *ffd,
  267. struct file *file, int fd)
  268. {
  269. ffd->file = file;
  270. ffd->fd = fd;
  271. }
  272. /* Compare RB tree keys */
  273. static inline int ep_cmp_ffd(struct epoll_filefd *p1,
  274. struct epoll_filefd *p2)
  275. {
  276. return (p1->file > p2->file ? +1:
  277. (p1->file < p2->file ? -1 : p1->fd - p2->fd));
  278. }
  279. /* Tells us if the item is currently linked */
  280. static inline int ep_is_linked(struct list_head *p)
  281. {
  282. return !list_empty(p);
  283. }
  284. static inline struct eppoll_entry *ep_pwq_from_wait(wait_queue_t *p)
  285. {
  286. return container_of(p, struct eppoll_entry, wait);
  287. }
  288. /* Get the "struct epitem" from a wait queue pointer */
  289. static inline struct epitem *ep_item_from_wait(wait_queue_t *p)
  290. {
  291. return container_of(p, struct eppoll_entry, wait)->base;
  292. }
  293. /* Get the "struct epitem" from an epoll queue wrapper */
  294. static inline struct epitem *ep_item_from_epqueue(poll_table *p)
  295. {
  296. return container_of(p, struct ep_pqueue, pt)->epi;
  297. }
  298. /* Tells if the epoll_ctl(2) operation needs an event copy from userspace */
  299. static inline int ep_op_has_event(int op)
  300. {
  301. return op != EPOLL_CTL_DEL;
  302. }
  303. /* Initialize the poll safe wake up structure */
  304. static void ep_nested_calls_init(struct nested_calls *ncalls)
  305. {
  306. INIT_LIST_HEAD(&ncalls->tasks_call_list);
  307. spin_lock_init(&ncalls->lock);
  308. }
  309. /**
  310. * ep_events_available - Checks if ready events might be available.
  311. *
  312. * @ep: Pointer to the eventpoll context.
  313. *
  314. * Returns: Returns a value different than zero if ready events are available,
  315. * or zero otherwise.
  316. */
  317. static inline int ep_events_available(struct eventpoll *ep)
  318. {
  319. return !list_empty(&ep->rdllist) || ep->ovflist != EP_UNACTIVE_PTR;
  320. }
  321. /**
  322. * ep_call_nested - Perform a bound (possibly) nested call, by checking
  323. * that the recursion limit is not exceeded, and that
  324. * the same nested call (by the meaning of same cookie) is
  325. * no re-entered.
  326. *
  327. * @ncalls: Pointer to the nested_calls structure to be used for this call.
  328. * @max_nests: Maximum number of allowed nesting calls.
  329. * @nproc: Nested call core function pointer.
  330. * @priv: Opaque data to be passed to the @nproc callback.
  331. * @cookie: Cookie to be used to identify this nested call.
  332. * @ctx: This instance context.
  333. *
  334. * Returns: Returns the code returned by the @nproc callback, or -1 if
  335. * the maximum recursion limit has been exceeded.
  336. */
  337. static int ep_call_nested(struct nested_calls *ncalls, int max_nests,
  338. int (*nproc)(void *, void *, int), void *priv,
  339. void *cookie, void *ctx)
  340. {
  341. int error, call_nests = 0;
  342. unsigned long flags;
  343. struct list_head *lsthead = &ncalls->tasks_call_list;
  344. struct nested_call_node *tncur;
  345. struct nested_call_node tnode;
  346. spin_lock_irqsave(&ncalls->lock, flags);
  347. /*
  348. * Try to see if the current task is already inside this wakeup call.
  349. * We use a list here, since the population inside this set is always
  350. * very much limited.
  351. */
  352. list_for_each_entry(tncur, lsthead, llink) {
  353. if (tncur->ctx == ctx &&
  354. (tncur->cookie == cookie || ++call_nests > max_nests)) {
  355. /*
  356. * Ops ... loop detected or maximum nest level reached.
  357. * We abort this wake by breaking the cycle itself.
  358. */
  359. error = -1;
  360. goto out_unlock;
  361. }
  362. }
  363. /* Add the current task and cookie to the list */
  364. tnode.ctx = ctx;
  365. tnode.cookie = cookie;
  366. list_add(&tnode.llink, lsthead);
  367. spin_unlock_irqrestore(&ncalls->lock, flags);
  368. /* Call the nested function */
  369. error = (*nproc)(priv, cookie, call_nests);
  370. /* Remove the current task from the list */
  371. spin_lock_irqsave(&ncalls->lock, flags);
  372. list_del(&tnode.llink);
  373. out_unlock:
  374. spin_unlock_irqrestore(&ncalls->lock, flags);
  375. return error;
  376. }
  377. /*
  378. * As described in commit 0ccf831cb lockdep: annotate epoll
  379. * the use of wait queues used by epoll is done in a very controlled
  380. * manner. Wake ups can nest inside each other, but are never done
  381. * with the same locking. For example:
  382. *
  383. * dfd = socket(...);
  384. * efd1 = epoll_create();
  385. * efd2 = epoll_create();
  386. * epoll_ctl(efd1, EPOLL_CTL_ADD, dfd, ...);
  387. * epoll_ctl(efd2, EPOLL_CTL_ADD, efd1, ...);
  388. *
  389. * When a packet arrives to the device underneath "dfd", the net code will
  390. * issue a wake_up() on its poll wake list. Epoll (efd1) has installed a
  391. * callback wakeup entry on that queue, and the wake_up() performed by the
  392. * "dfd" net code will end up in ep_poll_callback(). At this point epoll
  393. * (efd1) notices that it may have some event ready, so it needs to wake up
  394. * the waiters on its poll wait list (efd2). So it calls ep_poll_safewake()
  395. * that ends up in another wake_up(), after having checked about the
  396. * recursion constraints. That are, no more than EP_MAX_POLLWAKE_NESTS, to
  397. * avoid stack blasting.
  398. *
  399. * When CONFIG_DEBUG_LOCK_ALLOC is enabled, make sure lockdep can handle
  400. * this special case of epoll.
  401. */
  402. #ifdef CONFIG_DEBUG_LOCK_ALLOC
  403. static inline void ep_wake_up_nested(wait_queue_head_t *wqueue,
  404. unsigned long events, int subclass)
  405. {
  406. unsigned long flags;
  407. spin_lock_irqsave_nested(&wqueue->lock, flags, subclass);
  408. wake_up_locked_poll(wqueue, events);
  409. spin_unlock_irqrestore(&wqueue->lock, flags);
  410. }
  411. #else
  412. static inline void ep_wake_up_nested(wait_queue_head_t *wqueue,
  413. unsigned long events, int subclass)
  414. {
  415. wake_up_poll(wqueue, events);
  416. }
  417. #endif
  418. static int ep_poll_wakeup_proc(void *priv, void *cookie, int call_nests)
  419. {
  420. ep_wake_up_nested((wait_queue_head_t *) cookie, POLLIN,
  421. 1 + call_nests);
  422. return 0;
  423. }
  424. /*
  425. * Perform a safe wake up of the poll wait list. The problem is that
  426. * with the new callback'd wake up system, it is possible that the
  427. * poll callback is reentered from inside the call to wake_up() done
  428. * on the poll wait queue head. The rule is that we cannot reenter the
  429. * wake up code from the same task more than EP_MAX_NESTS times,
  430. * and we cannot reenter the same wait queue head at all. This will
  431. * enable to have a hierarchy of epoll file descriptor of no more than
  432. * EP_MAX_NESTS deep.
  433. */
  434. static void ep_poll_safewake(wait_queue_head_t *wq)
  435. {
  436. int this_cpu = get_cpu();
  437. ep_call_nested(&poll_safewake_ncalls, EP_MAX_NESTS,
  438. ep_poll_wakeup_proc, NULL, wq, (void *) (long) this_cpu);
  439. put_cpu();
  440. }
  441. static void ep_remove_wait_queue(struct eppoll_entry *pwq)
  442. {
  443. wait_queue_head_t *whead;
  444. rcu_read_lock();
  445. /* If it is cleared by POLLFREE, it should be rcu-safe */
  446. whead = rcu_dereference(pwq->whead);
  447. if (whead)
  448. remove_wait_queue(whead, &pwq->wait);
  449. rcu_read_unlock();
  450. }
  451. /*
  452. * This function unregisters poll callbacks from the associated file
  453. * descriptor. Must be called with "mtx" held (or "epmutex" if called from
  454. * ep_free).
  455. */
  456. static void ep_unregister_pollwait(struct eventpoll *ep, struct epitem *epi)
  457. {
  458. struct list_head *lsthead = &epi->pwqlist;
  459. struct eppoll_entry *pwq;
  460. while (!list_empty(lsthead)) {
  461. pwq = list_first_entry(lsthead, struct eppoll_entry, llink);
  462. list_del(&pwq->llink);
  463. ep_remove_wait_queue(pwq);
  464. kmem_cache_free(pwq_cache, pwq);
  465. }
  466. }
  467. /* call only when ep->mtx is held */
  468. static inline struct wakeup_source *ep_wakeup_source(struct epitem *epi)
  469. {
  470. return rcu_dereference_check(epi->ws, lockdep_is_held(&epi->ep->mtx));
  471. }
  472. /* call only when ep->mtx is held */
  473. static inline void ep_pm_stay_awake(struct epitem *epi)
  474. {
  475. struct wakeup_source *ws = ep_wakeup_source(epi);
  476. if (ws)
  477. __pm_stay_awake(ws);
  478. }
  479. static inline bool ep_has_wakeup_source(struct epitem *epi)
  480. {
  481. return rcu_access_pointer(epi->ws) ? true : false;
  482. }
  483. /* call when ep->mtx cannot be held (ep_poll_callback) */
  484. static inline void ep_pm_stay_awake_rcu(struct epitem *epi)
  485. {
  486. struct wakeup_source *ws;
  487. rcu_read_lock();
  488. ws = rcu_dereference(epi->ws);
  489. if (ws)
  490. __pm_stay_awake(ws);
  491. rcu_read_unlock();
  492. }
  493. /**
  494. * ep_scan_ready_list - Scans the ready list in a way that makes possible for
  495. * the scan code, to call f_op->poll(). Also allows for
  496. * O(NumReady) performance.
  497. *
  498. * @ep: Pointer to the epoll private data structure.
  499. * @sproc: Pointer to the scan callback.
  500. * @priv: Private opaque data passed to the @sproc callback.
  501. * @depth: The current depth of recursive f_op->poll calls.
  502. * @ep_locked: caller already holds ep->mtx
  503. *
  504. * Returns: The same integer error code returned by the @sproc callback.
  505. */
  506. static int ep_scan_ready_list(struct eventpoll *ep,
  507. int (*sproc)(struct eventpoll *,
  508. struct list_head *, void *),
  509. void *priv, int depth, bool ep_locked)
  510. {
  511. int error, pwake = 0;
  512. unsigned long flags;
  513. struct epitem *epi, *nepi;
  514. LIST_HEAD(txlist);
  515. /*
  516. * We need to lock this because we could be hit by
  517. * eventpoll_release_file() and epoll_ctl().
  518. */
  519. if (!ep_locked)
  520. mutex_lock_nested(&ep->mtx, depth);
  521. /*
  522. * Steal the ready list, and re-init the original one to the
  523. * empty list. Also, set ep->ovflist to NULL so that events
  524. * happening while looping w/out locks, are not lost. We cannot
  525. * have the poll callback to queue directly on ep->rdllist,
  526. * because we want the "sproc" callback to be able to do it
  527. * in a lockless way.
  528. */
  529. spin_lock_irqsave(&ep->lock, flags);
  530. list_splice_init(&ep->rdllist, &txlist);
  531. ep->ovflist = NULL;
  532. spin_unlock_irqrestore(&ep->lock, flags);
  533. /*
  534. * Now call the callback function.
  535. */
  536. error = (*sproc)(ep, &txlist, priv);
  537. spin_lock_irqsave(&ep->lock, flags);
  538. /*
  539. * During the time we spent inside the "sproc" callback, some
  540. * other events might have been queued by the poll callback.
  541. * We re-insert them inside the main ready-list here.
  542. */
  543. for (nepi = ep->ovflist; (epi = nepi) != NULL;
  544. nepi = epi->next, epi->next = EP_UNACTIVE_PTR) {
  545. /*
  546. * We need to check if the item is already in the list.
  547. * During the "sproc" callback execution time, items are
  548. * queued into ->ovflist but the "txlist" might already
  549. * contain them, and the list_splice() below takes care of them.
  550. */
  551. if (!ep_is_linked(&epi->rdllink)) {
  552. list_add_tail(&epi->rdllink, &ep->rdllist);
  553. ep_pm_stay_awake(epi);
  554. }
  555. }
  556. /*
  557. * We need to set back ep->ovflist to EP_UNACTIVE_PTR, so that after
  558. * releasing the lock, events will be queued in the normal way inside
  559. * ep->rdllist.
  560. */
  561. ep->ovflist = EP_UNACTIVE_PTR;
  562. /*
  563. * Quickly re-inject items left on "txlist".
  564. */
  565. list_splice(&txlist, &ep->rdllist);
  566. __pm_relax(ep->ws);
  567. if (!list_empty(&ep->rdllist)) {
  568. /*
  569. * Wake up (if active) both the eventpoll wait list and
  570. * the ->poll() wait list (delayed after we release the lock).
  571. */
  572. if (waitqueue_active(&ep->wq))
  573. wake_up_locked(&ep->wq);
  574. if (waitqueue_active(&ep->poll_wait))
  575. pwake++;
  576. }
  577. spin_unlock_irqrestore(&ep->lock, flags);
  578. if (!ep_locked)
  579. mutex_unlock(&ep->mtx);
  580. /* We have to call this outside the lock */
  581. if (pwake)
  582. ep_poll_safewake(&ep->poll_wait);
  583. return error;
  584. }
  585. static void epi_rcu_free(struct rcu_head *head)
  586. {
  587. struct epitem *epi = container_of(head, struct epitem, rcu);
  588. kmem_cache_free(epi_cache, epi);
  589. }
  590. /*
  591. * Removes a "struct epitem" from the eventpoll RB tree and deallocates
  592. * all the associated resources. Must be called with "mtx" held.
  593. */
  594. static int ep_remove(struct eventpoll *ep, struct epitem *epi)
  595. {
  596. unsigned long flags;
  597. struct file *file = epi->ffd.file;
  598. /*
  599. * Removes poll wait queue hooks. We _have_ to do this without holding
  600. * the "ep->lock" otherwise a deadlock might occur. This because of the
  601. * sequence of the lock acquisition. Here we do "ep->lock" then the wait
  602. * queue head lock when unregistering the wait queue. The wakeup callback
  603. * will run by holding the wait queue head lock and will call our callback
  604. * that will try to get "ep->lock".
  605. */
  606. ep_unregister_pollwait(ep, epi);
  607. /* Remove the current item from the list of epoll hooks */
  608. spin_lock(&file->f_lock);
  609. list_del_rcu(&epi->fllink);
  610. spin_unlock(&file->f_lock);
  611. rb_erase(&epi->rbn, &ep->rbr);
  612. spin_lock_irqsave(&ep->lock, flags);
  613. if (ep_is_linked(&epi->rdllink))
  614. list_del_init(&epi->rdllink);
  615. spin_unlock_irqrestore(&ep->lock, flags);
  616. wakeup_source_unregister(ep_wakeup_source(epi));
  617. /*
  618. * At this point it is safe to free the eventpoll item. Use the union
  619. * field epi->rcu, since we are trying to minimize the size of
  620. * 'struct epitem'. The 'rbn' field is no longer in use. Protected by
  621. * ep->mtx. The rcu read side, reverse_path_check_proc(), does not make
  622. * use of the rbn field.
  623. */
  624. call_rcu(&epi->rcu, epi_rcu_free);
  625. atomic_long_dec(&ep->user->epoll_watches);
  626. return 0;
  627. }
  628. static void ep_free(struct eventpoll *ep)
  629. {
  630. struct rb_node *rbp;
  631. struct epitem *epi;
  632. /* We need to release all tasks waiting for these file */
  633. if (waitqueue_active(&ep->poll_wait))
  634. ep_poll_safewake(&ep->poll_wait);
  635. /*
  636. * We need to lock this because we could be hit by
  637. * eventpoll_release_file() while we're freeing the "struct eventpoll".
  638. * We do not need to hold "ep->mtx" here because the epoll file
  639. * is on the way to be removed and no one has references to it
  640. * anymore. The only hit might come from eventpoll_release_file() but
  641. * holding "epmutex" is sufficient here.
  642. */
  643. mutex_lock(&epmutex);
  644. /*
  645. * Walks through the whole tree by unregistering poll callbacks.
  646. */
  647. for (rbp = rb_first(&ep->rbr); rbp; rbp = rb_next(rbp)) {
  648. epi = rb_entry(rbp, struct epitem, rbn);
  649. ep_unregister_pollwait(ep, epi);
  650. cond_resched();
  651. }
  652. /*
  653. * Walks through the whole tree by freeing each "struct epitem". At this
  654. * point we are sure no poll callbacks will be lingering around, and also by
  655. * holding "epmutex" we can be sure that no file cleanup code will hit
  656. * us during this operation. So we can avoid the lock on "ep->lock".
  657. * We do not need to lock ep->mtx, either, we only do it to prevent
  658. * a lockdep warning.
  659. */
  660. mutex_lock(&ep->mtx);
  661. while ((rbp = rb_first(&ep->rbr)) != NULL) {
  662. epi = rb_entry(rbp, struct epitem, rbn);
  663. ep_remove(ep, epi);
  664. cond_resched();
  665. }
  666. mutex_unlock(&ep->mtx);
  667. mutex_unlock(&epmutex);
  668. mutex_destroy(&ep->mtx);
  669. free_uid(ep->user);
  670. wakeup_source_unregister(ep->ws);
  671. kfree(ep);
  672. }
  673. static int ep_eventpoll_release(struct inode *inode, struct file *file)
  674. {
  675. struct eventpoll *ep = file->private_data;
  676. if (ep)
  677. ep_free(ep);
  678. return 0;
  679. }
  680. static inline unsigned int ep_item_poll(struct epitem *epi, poll_table *pt)
  681. {
  682. pt->_key = epi->event.events;
  683. return epi->ffd.file->f_op->poll(epi->ffd.file, pt) & epi->event.events;
  684. }
  685. static int ep_read_events_proc(struct eventpoll *ep, struct list_head *head,
  686. void *priv)
  687. {
  688. struct epitem *epi, *tmp;
  689. poll_table pt;
  690. init_poll_funcptr(&pt, NULL);
  691. list_for_each_entry_safe(epi, tmp, head, rdllink) {
  692. if (ep_item_poll(epi, &pt))
  693. return POLLIN | POLLRDNORM;
  694. else {
  695. /*
  696. * Item has been dropped into the ready list by the poll
  697. * callback, but it's not actually ready, as far as
  698. * caller requested events goes. We can remove it here.
  699. */
  700. __pm_relax(ep_wakeup_source(epi));
  701. list_del_init(&epi->rdllink);
  702. }
  703. }
  704. return 0;
  705. }
  706. static void ep_ptable_queue_proc(struct file *file, wait_queue_head_t *whead,
  707. poll_table *pt);
  708. struct readyevents_arg {
  709. struct eventpoll *ep;
  710. bool locked;
  711. };
  712. static int ep_poll_readyevents_proc(void *priv, void *cookie, int call_nests)
  713. {
  714. struct readyevents_arg *arg = priv;
  715. return ep_scan_ready_list(arg->ep, ep_read_events_proc, NULL,
  716. call_nests + 1, arg->locked);
  717. }
  718. static unsigned int ep_eventpoll_poll(struct file *file, poll_table *wait)
  719. {
  720. int pollflags;
  721. struct eventpoll *ep = file->private_data;
  722. struct readyevents_arg arg;
  723. /*
  724. * During ep_insert() we already hold the ep->mtx for the tfile.
  725. * Prevent re-aquisition.
  726. */
  727. arg.locked = wait && (wait->_qproc == ep_ptable_queue_proc);
  728. arg.ep = ep;
  729. /* Insert inside our poll wait queue */
  730. poll_wait(file, &ep->poll_wait, wait);
  731. /*
  732. * Proceed to find out if wanted events are really available inside
  733. * the ready list. This need to be done under ep_call_nested()
  734. * supervision, since the call to f_op->poll() done on listed files
  735. * could re-enter here.
  736. */
  737. pollflags = ep_call_nested(&poll_readywalk_ncalls, EP_MAX_NESTS,
  738. ep_poll_readyevents_proc, &arg, ep, current);
  739. return pollflags != -1 ? pollflags : 0;
  740. }
  741. #ifdef CONFIG_PROC_FS
  742. static int ep_show_fdinfo(struct seq_file *m, struct file *f)
  743. {
  744. struct eventpoll *ep = f->private_data;
  745. struct rb_node *rbp;
  746. int ret = 0;
  747. mutex_lock(&ep->mtx);
  748. for (rbp = rb_first(&ep->rbr); rbp; rbp = rb_next(rbp)) {
  749. struct epitem *epi = rb_entry(rbp, struct epitem, rbn);
  750. ret = seq_printf(m, "tfd: %8d events: %8x data: %16llx\n",
  751. epi->ffd.fd, epi->event.events,
  752. (long long)epi->event.data);
  753. if (ret)
  754. break;
  755. }
  756. mutex_unlock(&ep->mtx);
  757. return ret;
  758. }
  759. #endif
  760. /* File callbacks that implement the eventpoll file behaviour */
  761. static const struct file_operations eventpoll_fops = {
  762. #ifdef CONFIG_PROC_FS
  763. .show_fdinfo = ep_show_fdinfo,
  764. #endif
  765. .release = ep_eventpoll_release,
  766. .poll = ep_eventpoll_poll,
  767. .llseek = noop_llseek,
  768. };
  769. /*
  770. * This is called from eventpoll_release() to unlink files from the eventpoll
  771. * interface. We need to have this facility to cleanup correctly files that are
  772. * closed without being removed from the eventpoll interface.
  773. */
  774. void eventpoll_release_file(struct file *file)
  775. {
  776. struct eventpoll *ep;
  777. struct epitem *epi, *next;
  778. /*
  779. * We don't want to get "file->f_lock" because it is not
  780. * necessary. It is not necessary because we're in the "struct file"
  781. * cleanup path, and this means that no one is using this file anymore.
  782. * So, for example, epoll_ctl() cannot hit here since if we reach this
  783. * point, the file counter already went to zero and fget() would fail.
  784. * The only hit might come from ep_free() but by holding the mutex
  785. * will correctly serialize the operation. We do need to acquire
  786. * "ep->mtx" after "epmutex" because ep_remove() requires it when called
  787. * from anywhere but ep_free().
  788. *
  789. * Besides, ep_remove() acquires the lock, so we can't hold it here.
  790. */
  791. mutex_lock(&epmutex);
  792. list_for_each_entry_safe(epi, next, &file->f_ep_links, fllink) {
  793. ep = epi->ep;
  794. mutex_lock_nested(&ep->mtx, 0);
  795. ep_remove(ep, epi);
  796. mutex_unlock(&ep->mtx);
  797. }
  798. mutex_unlock(&epmutex);
  799. }
  800. static int ep_alloc(struct eventpoll **pep)
  801. {
  802. int error;
  803. struct user_struct *user;
  804. struct eventpoll *ep;
  805. user = get_current_user();
  806. error = -ENOMEM;
  807. ep = kzalloc(sizeof(*ep), GFP_KERNEL);
  808. if (unlikely(!ep))
  809. goto free_uid;
  810. spin_lock_init(&ep->lock);
  811. mutex_init(&ep->mtx);
  812. init_waitqueue_head(&ep->wq);
  813. init_waitqueue_head(&ep->poll_wait);
  814. INIT_LIST_HEAD(&ep->rdllist);
  815. ep->rbr = RB_ROOT;
  816. ep->ovflist = EP_UNACTIVE_PTR;
  817. ep->user = user;
  818. *pep = ep;
  819. return 0;
  820. free_uid:
  821. free_uid(user);
  822. return error;
  823. }
  824. /*
  825. * Search the file inside the eventpoll tree. The RB tree operations
  826. * are protected by the "mtx" mutex, and ep_find() must be called with
  827. * "mtx" held.
  828. */
  829. static struct epitem *ep_find(struct eventpoll *ep, struct file *file, int fd)
  830. {
  831. int kcmp;
  832. struct rb_node *rbp;
  833. struct epitem *epi, *epir = NULL;
  834. struct epoll_filefd ffd;
  835. ep_set_ffd(&ffd, file, fd);
  836. for (rbp = ep->rbr.rb_node; rbp; ) {
  837. epi = rb_entry(rbp, struct epitem, rbn);
  838. kcmp = ep_cmp_ffd(&ffd, &epi->ffd);
  839. if (kcmp > 0)
  840. rbp = rbp->rb_right;
  841. else if (kcmp < 0)
  842. rbp = rbp->rb_left;
  843. else {
  844. epir = epi;
  845. break;
  846. }
  847. }
  848. return epir;
  849. }
  850. /*
  851. * This is the callback that is passed to the wait queue wakeup
  852. * mechanism. It is called by the stored file descriptors when they
  853. * have events to report.
  854. */
  855. static int ep_poll_callback(wait_queue_t *wait, unsigned mode, int sync, void *key)
  856. {
  857. int pwake = 0;
  858. unsigned long flags;
  859. struct epitem *epi = ep_item_from_wait(wait);
  860. struct eventpoll *ep = epi->ep;
  861. if ((unsigned long)key & POLLFREE) {
  862. ep_pwq_from_wait(wait)->whead = NULL;
  863. /*
  864. * whead = NULL above can race with ep_remove_wait_queue()
  865. * which can do another remove_wait_queue() after us, so we
  866. * can't use __remove_wait_queue(). whead->lock is held by
  867. * the caller.
  868. */
  869. list_del_init(&wait->task_list);
  870. }
  871. spin_lock_irqsave(&ep->lock, flags);
  872. /*
  873. * If the event mask does not contain any poll(2) event, we consider the
  874. * descriptor to be disabled. This condition is likely the effect of the
  875. * EPOLLONESHOT bit that disables the descriptor when an event is received,
  876. * until the next EPOLL_CTL_MOD will be issued.
  877. */
  878. if (!(epi->event.events & ~EP_PRIVATE_BITS))
  879. goto out_unlock;
  880. /*
  881. * Check the events coming with the callback. At this stage, not
  882. * every device reports the events in the "key" parameter of the
  883. * callback. We need to be able to handle both cases here, hence the
  884. * test for "key" != NULL before the event match test.
  885. */
  886. if (key && !((unsigned long) key & epi->event.events))
  887. goto out_unlock;
  888. /*
  889. * If we are transferring events to userspace, we can hold no locks
  890. * (because we're accessing user memory, and because of linux f_op->poll()
  891. * semantics). All the events that happen during that period of time are
  892. * chained in ep->ovflist and requeued later on.
  893. */
  894. if (unlikely(ep->ovflist != EP_UNACTIVE_PTR)) {
  895. if (epi->next == EP_UNACTIVE_PTR) {
  896. epi->next = ep->ovflist;
  897. ep->ovflist = epi;
  898. if (epi->ws) {
  899. /*
  900. * Activate ep->ws since epi->ws may get
  901. * deactivated at any time.
  902. */
  903. __pm_stay_awake(ep->ws);
  904. }
  905. }
  906. goto out_unlock;
  907. }
  908. /* If this file is already in the ready list we exit soon */
  909. if (!ep_is_linked(&epi->rdllink)) {
  910. list_add_tail(&epi->rdllink, &ep->rdllist);
  911. ep_pm_stay_awake_rcu(epi);
  912. }
  913. /*
  914. * Wake up ( if active ) both the eventpoll wait list and the ->poll()
  915. * wait list.
  916. */
  917. if (waitqueue_active(&ep->wq))
  918. wake_up_locked(&ep->wq);
  919. if (waitqueue_active(&ep->poll_wait))
  920. pwake++;
  921. out_unlock:
  922. spin_unlock_irqrestore(&ep->lock, flags);
  923. /* We have to call this outside the lock */
  924. if (pwake)
  925. ep_poll_safewake(&ep->poll_wait);
  926. return 1;
  927. }
  928. /*
  929. * This is the callback that is used to add our wait queue to the
  930. * target file wakeup lists.
  931. */
  932. static void ep_ptable_queue_proc(struct file *file, wait_queue_head_t *whead,
  933. poll_table *pt)
  934. {
  935. struct epitem *epi = ep_item_from_epqueue(pt);
  936. struct eppoll_entry *pwq;
  937. if (epi->nwait >= 0 && (pwq = kmem_cache_alloc(pwq_cache, GFP_KERNEL))) {
  938. init_waitqueue_func_entry(&pwq->wait, ep_poll_callback);
  939. pwq->whead = whead;
  940. pwq->base = epi;
  941. add_wait_queue(whead, &pwq->wait);
  942. list_add_tail(&pwq->llink, &epi->pwqlist);
  943. epi->nwait++;
  944. } else {
  945. /* We have to signal that an error occurred */
  946. epi->nwait = -1;
  947. }
  948. }
  949. static void ep_rbtree_insert(struct eventpoll *ep, struct epitem *epi)
  950. {
  951. int kcmp;
  952. struct rb_node **p = &ep->rbr.rb_node, *parent = NULL;
  953. struct epitem *epic;
  954. while (*p) {
  955. parent = *p;
  956. epic = rb_entry(parent, struct epitem, rbn);
  957. kcmp = ep_cmp_ffd(&epi->ffd, &epic->ffd);
  958. if (kcmp > 0)
  959. p = &parent->rb_right;
  960. else
  961. p = &parent->rb_left;
  962. }
  963. rb_link_node(&epi->rbn, parent, p);
  964. rb_insert_color(&epi->rbn, &ep->rbr);
  965. }
  966. #define PATH_ARR_SIZE 5
  967. /*
  968. * These are the number paths of length 1 to 5, that we are allowing to emanate
  969. * from a single file of interest. For example, we allow 1000 paths of length
  970. * 1, to emanate from each file of interest. This essentially represents the
  971. * potential wakeup paths, which need to be limited in order to avoid massive
  972. * uncontrolled wakeup storms. The common use case should be a single ep which
  973. * is connected to n file sources. In this case each file source has 1 path
  974. * of length 1. Thus, the numbers below should be more than sufficient. These
  975. * path limits are enforced during an EPOLL_CTL_ADD operation, since a modify
  976. * and delete can't add additional paths. Protected by the epmutex.
  977. */
  978. static const int path_limits[PATH_ARR_SIZE] = { 1000, 500, 100, 50, 10 };
  979. static int path_count[PATH_ARR_SIZE];
  980. static int path_count_inc(int nests)
  981. {
  982. /* Allow an arbitrary number of depth 1 paths */
  983. if (nests == 0)
  984. return 0;
  985. if (++path_count[nests] > path_limits[nests])
  986. return -1;
  987. return 0;
  988. }
  989. static void path_count_init(void)
  990. {
  991. int i;
  992. for (i = 0; i < PATH_ARR_SIZE; i++)
  993. path_count[i] = 0;
  994. }
  995. static int reverse_path_check_proc(void *priv, void *cookie, int call_nests)
  996. {
  997. int error = 0;
  998. struct file *file = priv;
  999. struct file *child_file;
  1000. struct epitem *epi;
  1001. /* CTL_DEL can remove links here, but that can't increase our count */
  1002. rcu_read_lock();
  1003. list_for_each_entry_rcu(epi, &file->f_ep_links, fllink) {
  1004. child_file = epi->ep->file;
  1005. if (is_file_epoll(child_file)) {
  1006. if (list_empty(&child_file->f_ep_links)) {
  1007. if (path_count_inc(call_nests)) {
  1008. error = -1;
  1009. break;
  1010. }
  1011. } else {
  1012. error = ep_call_nested(&poll_loop_ncalls,
  1013. EP_MAX_NESTS,
  1014. reverse_path_check_proc,
  1015. child_file, child_file,
  1016. current);
  1017. }
  1018. if (error != 0)
  1019. break;
  1020. } else {
  1021. printk(KERN_ERR "reverse_path_check_proc: "
  1022. "file is not an ep!\n");
  1023. }
  1024. }
  1025. rcu_read_unlock();
  1026. return error;
  1027. }
  1028. /**
  1029. * reverse_path_check - The tfile_check_list is list of file *, which have
  1030. * links that are proposed to be newly added. We need to
  1031. * make sure that those added links don't add too many
  1032. * paths such that we will spend all our time waking up
  1033. * eventpoll objects.
  1034. *
  1035. * Returns: Returns zero if the proposed links don't create too many paths,
  1036. * -1 otherwise.
  1037. */
  1038. static int reverse_path_check(void)
  1039. {
  1040. int error = 0;
  1041. struct file *current_file;
  1042. /* let's call this for all tfiles */
  1043. list_for_each_entry(current_file, &tfile_check_list, f_tfile_llink) {
  1044. path_count_init();
  1045. error = ep_call_nested(&poll_loop_ncalls, EP_MAX_NESTS,
  1046. reverse_path_check_proc, current_file,
  1047. current_file, current);
  1048. if (error)
  1049. break;
  1050. }
  1051. return error;
  1052. }
  1053. static int ep_create_wakeup_source(struct epitem *epi)
  1054. {
  1055. const char *name;
  1056. struct wakeup_source *ws;
  1057. if (!epi->ep->ws) {
  1058. epi->ep->ws = wakeup_source_register("eventpoll");
  1059. if (!epi->ep->ws)
  1060. return -ENOMEM;
  1061. }
  1062. name = epi->ffd.file->f_path.dentry->d_name.name;
  1063. ws = wakeup_source_register(name);
  1064. if (!ws)
  1065. return -ENOMEM;
  1066. rcu_assign_pointer(epi->ws, ws);
  1067. return 0;
  1068. }
  1069. /* rare code path, only used when EPOLL_CTL_MOD removes a wakeup source */
  1070. static noinline void ep_destroy_wakeup_source(struct epitem *epi)
  1071. {
  1072. struct wakeup_source *ws = ep_wakeup_source(epi);
  1073. RCU_INIT_POINTER(epi->ws, NULL);
  1074. /*
  1075. * wait for ep_pm_stay_awake_rcu to finish, synchronize_rcu is
  1076. * used internally by wakeup_source_remove, too (called by
  1077. * wakeup_source_unregister), so we cannot use call_rcu
  1078. */
  1079. synchronize_rcu();
  1080. wakeup_source_unregister(ws);
  1081. }
  1082. /*
  1083. * Must be called with "mtx" held.
  1084. */
  1085. static int ep_insert(struct eventpoll *ep, struct epoll_event *event,
  1086. struct file *tfile, int fd, int full_check)
  1087. {
  1088. int error, revents, pwake = 0;
  1089. unsigned long flags;
  1090. long user_watches;
  1091. struct epitem *epi;
  1092. struct ep_pqueue epq;
  1093. user_watches = atomic_long_read(&ep->user->epoll_watches);
  1094. if (unlikely(user_watches >= max_user_watches))
  1095. return -ENOSPC;
  1096. if (!(epi = kmem_cache_alloc(epi_cache, GFP_KERNEL)))
  1097. return -ENOMEM;
  1098. /* Item initialization follow here ... */
  1099. INIT_LIST_HEAD(&epi->rdllink);
  1100. INIT_LIST_HEAD(&epi->fllink);
  1101. INIT_LIST_HEAD(&epi->pwqlist);
  1102. epi->ep = ep;
  1103. ep_set_ffd(&epi->ffd, tfile, fd);
  1104. epi->event = *event;
  1105. epi->nwait = 0;
  1106. epi->next = EP_UNACTIVE_PTR;
  1107. if (epi->event.events & EPOLLWAKEUP) {
  1108. error = ep_create_wakeup_source(epi);
  1109. if (error)
  1110. goto error_create_wakeup_source;
  1111. } else {
  1112. RCU_INIT_POINTER(epi->ws, NULL);
  1113. }
  1114. /* Initialize the poll table using the queue callback */
  1115. epq.epi = epi;
  1116. init_poll_funcptr(&epq.pt, ep_ptable_queue_proc);
  1117. /*
  1118. * Attach the item to the poll hooks and get current event bits.
  1119. * We can safely use the file* here because its usage count has
  1120. * been increased by the caller of this function. Note that after
  1121. * this operation completes, the poll callback can start hitting
  1122. * the new item.
  1123. */
  1124. revents = ep_item_poll(epi, &epq.pt);
  1125. /*
  1126. * We have to check if something went wrong during the poll wait queue
  1127. * install process. Namely an allocation for a wait queue failed due
  1128. * high memory pressure.
  1129. */
  1130. error = -ENOMEM;
  1131. if (epi->nwait < 0)
  1132. goto error_unregister;
  1133. /* Add the current item to the list of active epoll hook for this file */
  1134. spin_lock(&tfile->f_lock);
  1135. list_add_tail_rcu(&epi->fllink, &tfile->f_ep_links);
  1136. spin_unlock(&tfile->f_lock);
  1137. /*
  1138. * Add the current item to the RB tree. All RB tree operations are
  1139. * protected by "mtx", and ep_insert() is called with "mtx" held.
  1140. */
  1141. ep_rbtree_insert(ep, epi);
  1142. /* now check if we've created too many backpaths */
  1143. error = -EINVAL;
  1144. if (full_check && reverse_path_check())
  1145. goto error_remove_epi;
  1146. /* We have to drop the new item inside our item list to keep track of it */
  1147. spin_lock_irqsave(&ep->lock, flags);
  1148. /* If the file is already "ready" we drop it inside the ready list */
  1149. if ((revents & event->events) && !ep_is_linked(&epi->rdllink)) {
  1150. list_add_tail(&epi->rdllink, &ep->rdllist);
  1151. ep_pm_stay_awake(epi);
  1152. /* Notify waiting tasks that events are available */
  1153. if (waitqueue_active(&ep->wq))
  1154. wake_up_locked(&ep->wq);
  1155. if (waitqueue_active(&ep->poll_wait))
  1156. pwake++;
  1157. }
  1158. spin_unlock_irqrestore(&ep->lock, flags);
  1159. atomic_long_inc(&ep->user->epoll_watches);
  1160. /* We have to call this outside the lock */
  1161. if (pwake)
  1162. ep_poll_safewake(&ep->poll_wait);
  1163. return 0;
  1164. error_remove_epi:
  1165. spin_lock(&tfile->f_lock);
  1166. list_del_rcu(&epi->fllink);
  1167. spin_unlock(&tfile->f_lock);
  1168. rb_erase(&epi->rbn, &ep->rbr);
  1169. error_unregister:
  1170. ep_unregister_pollwait(ep, epi);
  1171. /*
  1172. * We need to do this because an event could have been arrived on some
  1173. * allocated wait queue. Note that we don't care about the ep->ovflist
  1174. * list, since that is used/cleaned only inside a section bound by "mtx".
  1175. * And ep_insert() is called with "mtx" held.
  1176. */
  1177. spin_lock_irqsave(&ep->lock, flags);
  1178. if (ep_is_linked(&epi->rdllink))
  1179. list_del_init(&epi->rdllink);
  1180. spin_unlock_irqrestore(&ep->lock, flags);
  1181. wakeup_source_unregister(ep_wakeup_source(epi));
  1182. error_create_wakeup_source:
  1183. kmem_cache_free(epi_cache, epi);
  1184. return error;
  1185. }
  1186. /*
  1187. * Modify the interest event mask by dropping an event if the new mask
  1188. * has a match in the current file status. Must be called with "mtx" held.
  1189. */
  1190. static int ep_modify(struct eventpoll *ep, struct epitem *epi, struct epoll_event *event)
  1191. {
  1192. int pwake = 0;
  1193. unsigned int revents;
  1194. poll_table pt;
  1195. init_poll_funcptr(&pt, NULL);
  1196. /*
  1197. * Set the new event interest mask before calling f_op->poll();
  1198. * otherwise we might miss an event that happens between the
  1199. * f_op->poll() call and the new event set registering.
  1200. */
  1201. epi->event.events = event->events; /* need barrier below */
  1202. epi->event.data = event->data; /* protected by mtx */
  1203. if (epi->event.events & EPOLLWAKEUP) {
  1204. if (!ep_has_wakeup_source(epi))
  1205. ep_create_wakeup_source(epi);
  1206. } else if (ep_has_wakeup_source(epi)) {
  1207. ep_destroy_wakeup_source(epi);
  1208. }
  1209. /*
  1210. * The following barrier has two effects:
  1211. *
  1212. * 1) Flush epi changes above to other CPUs. This ensures
  1213. * we do not miss events from ep_poll_callback if an
  1214. * event occurs immediately after we call f_op->poll().
  1215. * We need this because we did not take ep->lock while
  1216. * changing epi above (but ep_poll_callback does take
  1217. * ep->lock).
  1218. *
  1219. * 2) We also need to ensure we do not miss _past_ events
  1220. * when calling f_op->poll(). This barrier also
  1221. * pairs with the barrier in wq_has_sleeper (see
  1222. * comments for wq_has_sleeper).
  1223. *
  1224. * This barrier will now guarantee ep_poll_callback or f_op->poll
  1225. * (or both) will notice the readiness of an item.
  1226. */
  1227. smp_mb();
  1228. /*
  1229. * Get current event bits. We can safely use the file* here because
  1230. * its usage count has been increased by the caller of this function.
  1231. */
  1232. revents = ep_item_poll(epi, &pt);
  1233. /*
  1234. * If the item is "hot" and it is not registered inside the ready
  1235. * list, push it inside.
  1236. */
  1237. if (revents & event->events) {
  1238. spin_lock_irq(&ep->lock);
  1239. if (!ep_is_linked(&epi->rdllink)) {
  1240. list_add_tail(&epi->rdllink, &ep->rdllist);
  1241. ep_pm_stay_awake(epi);
  1242. /* Notify waiting tasks that events are available */
  1243. if (waitqueue_active(&ep->wq))
  1244. wake_up_locked(&ep->wq);
  1245. if (waitqueue_active(&ep->poll_wait))
  1246. pwake++;
  1247. }
  1248. spin_unlock_irq(&ep->lock);
  1249. }
  1250. /* We have to call this outside the lock */
  1251. if (pwake)
  1252. ep_poll_safewake(&ep->poll_wait);
  1253. return 0;
  1254. }
  1255. static int ep_send_events_proc(struct eventpoll *ep, struct list_head *head,
  1256. void *priv)
  1257. {
  1258. struct ep_send_events_data *esed = priv;
  1259. int eventcnt;
  1260. unsigned int revents;
  1261. struct epitem *epi;
  1262. struct epoll_event __user *uevent;
  1263. struct wakeup_source *ws;
  1264. poll_table pt;
  1265. init_poll_funcptr(&pt, NULL);
  1266. /*
  1267. * We can loop without lock because we are passed a task private list.
  1268. * Items cannot vanish during the loop because ep_scan_ready_list() is
  1269. * holding "mtx" during this call.
  1270. */
  1271. for (eventcnt = 0, uevent = esed->events;
  1272. !list_empty(head) && eventcnt < esed->maxevents;) {
  1273. epi = list_first_entry(head, struct epitem, rdllink);
  1274. /*
  1275. * Activate ep->ws before deactivating epi->ws to prevent
  1276. * triggering auto-suspend here (in case we reactive epi->ws
  1277. * below).
  1278. *
  1279. * This could be rearranged to delay the deactivation of epi->ws
  1280. * instead, but then epi->ws would temporarily be out of sync
  1281. * with ep_is_linked().
  1282. */
  1283. ws = ep_wakeup_source(epi);
  1284. if (ws) {
  1285. if (ws->active)
  1286. __pm_stay_awake(ep->ws);
  1287. __pm_relax(ws);
  1288. }
  1289. list_del_init(&epi->rdllink);
  1290. revents = ep_item_poll(epi, &pt);
  1291. /*
  1292. * If the event mask intersect the caller-requested one,
  1293. * deliver the event to userspace. Again, ep_scan_ready_list()
  1294. * is holding "mtx", so no operations coming from userspace
  1295. * can change the item.
  1296. */
  1297. if (revents) {
  1298. if (__put_user(revents, &uevent->events) ||
  1299. __put_user(epi->event.data, &uevent->data)) {
  1300. list_add(&epi->rdllink, head);
  1301. ep_pm_stay_awake(epi);
  1302. return eventcnt ? eventcnt : -EFAULT;
  1303. }
  1304. eventcnt++;
  1305. uevent++;
  1306. if (epi->event.events & EPOLLONESHOT)
  1307. epi->event.events &= EP_PRIVATE_BITS;
  1308. else if (!(epi->event.events & EPOLLET)) {
  1309. /*
  1310. * If this file has been added with Level
  1311. * Trigger mode, we need to insert back inside
  1312. * the ready list, so that the next call to
  1313. * epoll_wait() will check again the events
  1314. * availability. At this point, no one can insert
  1315. * into ep->rdllist besides us. The epoll_ctl()
  1316. * callers are locked out by
  1317. * ep_scan_ready_list() holding "mtx" and the
  1318. * poll callback will queue them in ep->ovflist.
  1319. */
  1320. list_add_tail(&epi->rdllink, &ep->rdllist);
  1321. ep_pm_stay_awake(epi);
  1322. }
  1323. }
  1324. }
  1325. return eventcnt;
  1326. }
  1327. static int ep_send_events(struct eventpoll *ep,
  1328. struct epoll_event __user *events, int maxevents)
  1329. {
  1330. struct ep_send_events_data esed;
  1331. esed.maxevents = maxevents;
  1332. esed.events = events;
  1333. return ep_scan_ready_list(ep, ep_send_events_proc, &esed, 0, false);
  1334. }
  1335. static inline struct timespec ep_set_mstimeout(long ms)
  1336. {
  1337. struct timespec now, ts = {
  1338. .tv_sec = ms / MSEC_PER_SEC,
  1339. .tv_nsec = NSEC_PER_MSEC * (ms % MSEC_PER_SEC),
  1340. };
  1341. ktime_get_ts(&now);
  1342. return timespec_add_safe(now, ts);
  1343. }
  1344. /**
  1345. * ep_poll - Retrieves ready events, and delivers them to the caller supplied
  1346. * event buffer.
  1347. *
  1348. * @ep: Pointer to the eventpoll context.
  1349. * @events: Pointer to the userspace buffer where the ready events should be
  1350. * stored.
  1351. * @maxevents: Size (in terms of number of events) of the caller event buffer.
  1352. * @timeout: Maximum timeout for the ready events fetch operation, in
  1353. * milliseconds. If the @timeout is zero, the function will not block,
  1354. * while if the @timeout is less than zero, the function will block
  1355. * until at least one event has been retrieved (or an error
  1356. * occurred).
  1357. *
  1358. * Returns: Returns the number of ready events which have been fetched, or an
  1359. * error code, in case of error.
  1360. */
  1361. static int ep_poll(struct eventpoll *ep, struct epoll_event __user *events,
  1362. int maxevents, long timeout)
  1363. {
  1364. int res = 0, eavail, timed_out = 0;
  1365. unsigned long flags;
  1366. long slack = 0;
  1367. wait_queue_t wait;
  1368. ktime_t expires, *to = NULL;
  1369. if (timeout > 0) {
  1370. struct timespec end_time = ep_set_mstimeout(timeout);
  1371. slack = select_estimate_accuracy(&end_time);
  1372. to = &expires;
  1373. *to = timespec_to_ktime(end_time);
  1374. } else if (timeout == 0) {
  1375. /*
  1376. * Avoid the unnecessary trip to the wait queue loop, if the
  1377. * caller specified a non blocking operation.
  1378. */
  1379. timed_out = 1;
  1380. spin_lock_irqsave(&ep->lock, flags);
  1381. goto check_events;
  1382. }
  1383. fetch_events:
  1384. spin_lock_irqsave(&ep->lock, flags);
  1385. if (!ep_events_available(ep)) {
  1386. /*
  1387. * We don't have any available event to return to the caller.
  1388. * We need to sleep here, and we will be wake up by
  1389. * ep_poll_callback() when events will become available.
  1390. */
  1391. init_waitqueue_entry(&wait, current);
  1392. __add_wait_queue_exclusive(&ep->wq, &wait);
  1393. for (;;) {
  1394. /*
  1395. * We don't want to sleep if the ep_poll_callback() sends us
  1396. * a wakeup in between. That's why we set the task state
  1397. * to TASK_INTERRUPTIBLE before doing the checks.
  1398. */
  1399. set_current_state(TASK_INTERRUPTIBLE);
  1400. if (ep_events_available(ep) || timed_out)
  1401. break;
  1402. if (signal_pending(current)) {
  1403. res = -EINTR;
  1404. break;
  1405. }
  1406. spin_unlock_irqrestore(&ep->lock, flags);
  1407. if (!freezable_schedule_hrtimeout_range(to, slack,
  1408. HRTIMER_MODE_ABS))
  1409. timed_out = 1;
  1410. spin_lock_irqsave(&ep->lock, flags);
  1411. }
  1412. __remove_wait_queue(&ep->wq, &wait);
  1413. set_current_state(TASK_RUNNING);
  1414. }
  1415. check_events:
  1416. /* Is it worth to try to dig for events ? */
  1417. eavail = ep_events_available(ep);
  1418. spin_unlock_irqrestore(&ep->lock, flags);
  1419. /*
  1420. * Try to transfer events to user space. In case we get 0 events and
  1421. * there's still timeout left over, we go trying again in search of
  1422. * more luck.
  1423. */
  1424. if (!res && eavail &&
  1425. !(res = ep_send_events(ep, events, maxevents)) && !timed_out)
  1426. goto fetch_events;
  1427. return res;
  1428. }
  1429. /**
  1430. * ep_loop_check_proc - Callback function to be passed to the @ep_call_nested()
  1431. * API, to verify that adding an epoll file inside another
  1432. * epoll structure, does not violate the constraints, in
  1433. * terms of closed loops, or too deep chains (which can
  1434. * result in excessive stack usage).
  1435. *
  1436. * @priv: Pointer to the epoll file to be currently checked.
  1437. * @cookie: Original cookie for this call. This is the top-of-the-chain epoll
  1438. * data structure pointer.
  1439. * @call_nests: Current dept of the @ep_call_nested() call stack.
  1440. *
  1441. * Returns: Returns zero if adding the epoll @file inside current epoll
  1442. * structure @ep does not violate the constraints, or -1 otherwise.
  1443. */
  1444. static int ep_loop_check_proc(void *priv, void *cookie, int call_nests)
  1445. {
  1446. int error = 0;
  1447. struct file *file = priv;
  1448. struct eventpoll *ep = file->private_data;
  1449. struct eventpoll *ep_tovisit;
  1450. struct rb_node *rbp;
  1451. struct epitem *epi;
  1452. mutex_lock_nested(&ep->mtx, call_nests + 1);
  1453. ep->visited = 1;
  1454. list_add(&ep->visited_list_link, &visited_list);
  1455. for (rbp = rb_first(&ep->rbr); rbp; rbp = rb_next(rbp)) {
  1456. epi = rb_entry(rbp, struct epitem, rbn);
  1457. if (unlikely(is_file_epoll(epi->ffd.file))) {
  1458. ep_tovisit = epi->ffd.file->private_data;
  1459. if (ep_tovisit->visited)
  1460. continue;
  1461. error = ep_call_nested(&poll_loop_ncalls, EP_MAX_NESTS,
  1462. ep_loop_check_proc, epi->ffd.file,
  1463. ep_tovisit, current);
  1464. if (error != 0)
  1465. break;
  1466. } else {
  1467. /*
  1468. * If we've reached a file that is not associated with
  1469. * an ep, then we need to check if the newly added
  1470. * links are going to add too many wakeup paths. We do
  1471. * this by adding it to the tfile_check_list, if it's
  1472. * not already there, and calling reverse_path_check()
  1473. * during ep_insert().
  1474. */
  1475. if (list_empty(&epi->ffd.file->f_tfile_llink))
  1476. list_add(&epi->ffd.file->f_tfile_llink,
  1477. &tfile_check_list);
  1478. }
  1479. }
  1480. mutex_unlock(&ep->mtx);
  1481. return error;
  1482. }
  1483. /**
  1484. * ep_loop_check - Performs a check to verify that adding an epoll file (@file)
  1485. * another epoll file (represented by @ep) does not create
  1486. * closed loops or too deep chains.
  1487. *
  1488. * @ep: Pointer to the epoll private data structure.
  1489. * @file: Pointer to the epoll file to be checked.
  1490. *
  1491. * Returns: Returns zero if adding the epoll @file inside current epoll
  1492. * structure @ep does not violate the constraints, or -1 otherwise.
  1493. */
  1494. static int ep_loop_check(struct eventpoll *ep, struct file *file)
  1495. {
  1496. int ret;
  1497. struct eventpoll *ep_cur, *ep_next;
  1498. ret = ep_call_nested(&poll_loop_ncalls, EP_MAX_NESTS,
  1499. ep_loop_check_proc, file, ep, current);
  1500. /* clear visited list */
  1501. list_for_each_entry_safe(ep_cur, ep_next, &visited_list,
  1502. visited_list_link) {
  1503. ep_cur->visited = 0;
  1504. list_del(&ep_cur->visited_list_link);
  1505. }
  1506. return ret;
  1507. }
  1508. static void clear_tfile_check_list(void)
  1509. {
  1510. struct file *file;
  1511. /* first clear the tfile_check_list */
  1512. while (!list_empty(&tfile_check_list)) {
  1513. file = list_first_entry(&tfile_check_list, struct file,
  1514. f_tfile_llink);
  1515. list_del_init(&file->f_tfile_llink);
  1516. }
  1517. INIT_LIST_HEAD(&tfile_check_list);
  1518. }
  1519. /*
  1520. * Open an eventpoll file descriptor.
  1521. */
  1522. SYSCALL_DEFINE1(epoll_create1, int, flags)
  1523. {
  1524. int error, fd;
  1525. struct eventpoll *ep = NULL;
  1526. struct file *file;
  1527. /* Check the EPOLL_* constant for consistency. */
  1528. BUILD_BUG_ON(EPOLL_CLOEXEC != O_CLOEXEC);
  1529. if (flags & ~EPOLL_CLOEXEC)
  1530. return -EINVAL;
  1531. /*
  1532. * Create the internal data structure ("struct eventpoll").
  1533. */
  1534. error = ep_alloc(&ep);
  1535. if (error < 0)
  1536. return error;
  1537. /*
  1538. * Creates all the items needed to setup an eventpoll file. That is,
  1539. * a file structure and a free file descriptor.
  1540. */
  1541. fd = get_unused_fd_flags(O_RDWR | (flags & O_CLOEXEC));
  1542. if (fd < 0) {
  1543. error = fd;
  1544. goto out_free_ep;
  1545. }
  1546. file = anon_inode_getfile("[eventpoll]", &eventpoll_fops, ep,
  1547. O_RDWR | (flags & O_CLOEXEC));
  1548. if (IS_ERR(file)) {
  1549. error = PTR_ERR(file);
  1550. goto out_free_fd;
  1551. }
  1552. ep->file = file;
  1553. fd_install(fd, file);
  1554. return fd;
  1555. out_free_fd:
  1556. put_unused_fd(fd);
  1557. out_free_ep:
  1558. ep_free(ep);
  1559. return error;
  1560. }
  1561. SYSCALL_DEFINE1(epoll_create, int, size)
  1562. {
  1563. if (size <= 0)
  1564. return -EINVAL;
  1565. return sys_epoll_create1(0);
  1566. }
  1567. /*
  1568. * The following function implements the controller interface for
  1569. * the eventpoll file that enables the insertion/removal/change of
  1570. * file descriptors inside the interest set.
  1571. */
  1572. SYSCALL_DEFINE4(epoll_ctl, int, epfd, int, op, int, fd,
  1573. struct epoll_event __user *, event)
  1574. {
  1575. int error;
  1576. int full_check = 0;
  1577. struct fd f, tf;
  1578. struct eventpoll *ep;
  1579. struct epitem *epi;
  1580. struct epoll_event epds;
  1581. struct eventpoll *tep = NULL;
  1582. error = -EFAULT;
  1583. if (ep_op_has_event(op) &&
  1584. copy_from_user(&epds, event, sizeof(struct epoll_event)))
  1585. goto error_return;
  1586. error = -EBADF;
  1587. f = fdget(epfd);
  1588. if (!f.file)
  1589. goto error_return;
  1590. /* Get the "struct file *" for the target file */
  1591. tf = fdget(fd);
  1592. if (!tf.file)
  1593. goto error_fput;
  1594. /* The target file descriptor must support poll */
  1595. error = -EPERM;
  1596. if (!tf.file->f_op->poll)
  1597. goto error_tgt_fput;
  1598. /* Check if EPOLLWAKEUP is allowed */
  1599. if (ep_op_has_event(op))
  1600. ep_take_care_of_epollwakeup(&epds);
  1601. /*
  1602. * We have to check that the file structure underneath the file descriptor
  1603. * the user passed to us _is_ an eventpoll file. And also we do not permit
  1604. * adding an epoll file descriptor inside itself.
  1605. */
  1606. error = -EINVAL;
  1607. if (f.file == tf.file || !is_file_epoll(f.file))
  1608. goto error_tgt_fput;
  1609. /*
  1610. * At this point it is safe to assume that the "private_data" contains
  1611. * our own data structure.
  1612. */
  1613. ep = f.file->private_data;
  1614. /*
  1615. * When we insert an epoll file descriptor, inside another epoll file
  1616. * descriptor, there is the change of creating closed loops, which are
  1617. * better be handled here, than in more critical paths. While we are
  1618. * checking for loops we also determine the list of files reachable
  1619. * and hang them on the tfile_check_list, so we can check that we
  1620. * haven't created too many possible wakeup paths.
  1621. *
  1622. * We do not need to take the global 'epumutex' on EPOLL_CTL_ADD when
  1623. * the epoll file descriptor is attaching directly to a wakeup source,
  1624. * unless the epoll file descriptor is nested. The purpose of taking the
  1625. * 'epmutex' on add is to prevent complex toplogies such as loops and
  1626. * deep wakeup paths from forming in parallel through multiple
  1627. * EPOLL_CTL_ADD operations.
  1628. */
  1629. mutex_lock_nested(&ep->mtx, 0);
  1630. if (op == EPOLL_CTL_ADD) {
  1631. if (!list_empty(&f.file->f_ep_links) ||
  1632. is_file_epoll(tf.file)) {
  1633. full_check = 1;
  1634. mutex_unlock(&ep->mtx);
  1635. mutex_lock(&epmutex);
  1636. if (is_file_epoll(tf.file)) {
  1637. error = -ELOOP;
  1638. if (ep_loop_check(ep, tf.file) != 0) {
  1639. clear_tfile_check_list();
  1640. goto error_tgt_fput;
  1641. }
  1642. } else
  1643. list_add(&tf.file->f_tfile_llink,
  1644. &tfile_check_list);
  1645. mutex_lock_nested(&ep->mtx, 0);
  1646. if (is_file_epoll(tf.file)) {
  1647. tep = tf.file->private_data;
  1648. mutex_lock_nested(&tep->mtx, 1);
  1649. }
  1650. }
  1651. }
  1652. /*
  1653. * Try to lookup the file inside our RB tree, Since we grabbed "mtx"
  1654. * above, we can be sure to be able to use the item looked up by
  1655. * ep_find() till we release the mutex.
  1656. */
  1657. epi = ep_find(ep, tf.file, fd);
  1658. error = -EINVAL;
  1659. switch (op) {
  1660. case EPOLL_CTL_ADD:
  1661. if (!epi) {
  1662. epds.events |= POLLERR | POLLHUP;
  1663. error = ep_insert(ep, &epds, tf.file, fd, full_check);
  1664. } else
  1665. error = -EEXIST;
  1666. if (full_check)
  1667. clear_tfile_check_list();
  1668. break;
  1669. case EPOLL_CTL_DEL:
  1670. if (epi)
  1671. error = ep_remove(ep, epi);
  1672. else
  1673. error = -ENOENT;
  1674. break;
  1675. case EPOLL_CTL_MOD:
  1676. if (epi) {
  1677. epds.events |= POLLERR | POLLHUP;
  1678. error = ep_modify(ep, epi, &epds);
  1679. } else
  1680. error = -ENOENT;
  1681. break;
  1682. }
  1683. if (tep != NULL)
  1684. mutex_unlock(&tep->mtx);
  1685. mutex_unlock(&ep->mtx);
  1686. error_tgt_fput:
  1687. if (full_check)
  1688. mutex_unlock(&epmutex);
  1689. fdput(tf);
  1690. error_fput:
  1691. fdput(f);
  1692. error_return:
  1693. return error;
  1694. }
  1695. /*
  1696. * Implement the event wait interface for the eventpoll file. It is the kernel
  1697. * part of the user space epoll_wait(2).
  1698. */
  1699. SYSCALL_DEFINE4(epoll_wait, int, epfd, struct epoll_event __user *, events,
  1700. int, maxevents, int, timeout)
  1701. {
  1702. int error;
  1703. struct fd f;
  1704. struct eventpoll *ep;
  1705. /* The maximum number of event must be greater than zero */
  1706. if (maxevents <= 0 || maxevents > EP_MAX_EVENTS)
  1707. return -EINVAL;
  1708. /* Verify that the area passed by the user is writeable */
  1709. if (!access_ok(VERIFY_WRITE, events, maxevents * sizeof(struct epoll_event)))
  1710. return -EFAULT;
  1711. /* Get the "struct file *" for the eventpoll file */
  1712. f = fdget(epfd);
  1713. if (!f.file)
  1714. return -EBADF;
  1715. /*
  1716. * We have to check that the file structure underneath the fd
  1717. * the user passed to us _is_ an eventpoll file.
  1718. */
  1719. error = -EINVAL;
  1720. if (!is_file_epoll(f.file))
  1721. goto error_fput;
  1722. /*
  1723. * At this point it is safe to assume that the "private_data" contains
  1724. * our own data structure.
  1725. */
  1726. ep = f.file->private_data;
  1727. /* Time to fish for events ... */
  1728. error = ep_poll(ep, events, maxevents, timeout);
  1729. error_fput:
  1730. fdput(f);
  1731. return error;
  1732. }
  1733. /*
  1734. * Implement the event wait interface for the eventpoll file. It is the kernel
  1735. * part of the user space epoll_pwait(2).
  1736. */
  1737. SYSCALL_DEFINE6(epoll_pwait, int, epfd, struct epoll_event __user *, events,
  1738. int, maxevents, int, timeout, const sigset_t __user *, sigmask,
  1739. size_t, sigsetsize)
  1740. {
  1741. int error;
  1742. sigset_t ksigmask, sigsaved;
  1743. /*
  1744. * If the caller wants a certain signal mask to be set during the wait,
  1745. * we apply it here.
  1746. */
  1747. if (sigmask) {
  1748. if (sigsetsize != sizeof(sigset_t))
  1749. return -EINVAL;
  1750. if (copy_from_user(&ksigmask, sigmask, sizeof(ksigmask)))
  1751. return -EFAULT;
  1752. sigsaved = current->blocked;
  1753. set_current_blocked(&ksigmask);
  1754. }
  1755. error = sys_epoll_wait(epfd, events, maxevents, timeout);
  1756. /*
  1757. * If we changed the signal mask, we need to restore the original one.
  1758. * In case we've got a signal while waiting, we do not restore the
  1759. * signal mask yet, and we allow do_signal() to deliver the signal on
  1760. * the way back to userspace, before the signal mask is restored.
  1761. */
  1762. if (sigmask) {
  1763. if (error == -EINTR) {
  1764. memcpy(&current->saved_sigmask, &sigsaved,
  1765. sizeof(sigsaved));
  1766. set_restore_sigmask();
  1767. } else
  1768. set_current_blocked(&sigsaved);
  1769. }
  1770. return error;
  1771. }
  1772. #ifdef CONFIG_COMPAT
  1773. COMPAT_SYSCALL_DEFINE6(epoll_pwait, int, epfd,
  1774. struct epoll_event __user *, events,
  1775. int, maxevents, int, timeout,
  1776. const compat_sigset_t __user *, sigmask,
  1777. compat_size_t, sigsetsize)
  1778. {
  1779. long err;
  1780. compat_sigset_t csigmask;
  1781. sigset_t ksigmask, sigsaved;
  1782. /*
  1783. * If the caller wants a certain signal mask to be set during the wait,
  1784. * we apply it here.
  1785. */
  1786. if (sigmask) {
  1787. if (sigsetsize != sizeof(compat_sigset_t))
  1788. return -EINVAL;
  1789. if (copy_from_user(&csigmask, sigmask, sizeof(csigmask)))
  1790. return -EFAULT;
  1791. sigset_from_compat(&ksigmask, &csigmask);
  1792. sigsaved = current->blocked;
  1793. set_current_blocked(&ksigmask);
  1794. }
  1795. err = sys_epoll_wait(epfd, events, maxevents, timeout);
  1796. /*
  1797. * If we changed the signal mask, we need to restore the original one.
  1798. * In case we've got a signal while waiting, we do not restore the
  1799. * signal mask yet, and we allow do_signal() to deliver the signal on
  1800. * the way back to userspace, before the signal mask is restored.
  1801. */
  1802. if (sigmask) {
  1803. if (err == -EINTR) {
  1804. memcpy(&current->saved_sigmask, &sigsaved,
  1805. sizeof(sigsaved));
  1806. set_restore_sigmask();
  1807. } else
  1808. set_current_blocked(&sigsaved);
  1809. }
  1810. return err;
  1811. }
  1812. #endif
  1813. static int __init eventpoll_init(void)
  1814. {
  1815. struct sysinfo si;
  1816. si_meminfo(&si);
  1817. /*
  1818. * Allows top 4% of lomem to be allocated for epoll watches (per user).
  1819. */
  1820. max_user_watches = (((si.totalram - si.totalhigh) / 25) << PAGE_SHIFT) /
  1821. EP_ITEM_COST;
  1822. BUG_ON(max_user_watches < 0);
  1823. /*
  1824. * Initialize the structure used to perform epoll file descriptor
  1825. * inclusion loops checks.
  1826. */
  1827. ep_nested_calls_init(&poll_loop_ncalls);
  1828. /* Initialize the structure used to perform safe poll wait head wake ups */
  1829. ep_nested_calls_init(&poll_safewake_ncalls);
  1830. /* Initialize the structure used to perform file's f_op->poll() calls */
  1831. ep_nested_calls_init(&poll_readywalk_ncalls);
  1832. /*
  1833. * We can have many thousands of epitems, so prevent this from
  1834. * using an extra cache line on 64-bit (and smaller) CPUs
  1835. */
  1836. BUILD_BUG_ON(sizeof(void *) <= 8 && sizeof(struct epitem) > 128);
  1837. /* Allocates slab cache used to allocate "struct epitem" items */
  1838. epi_cache = kmem_cache_create("eventpoll_epi", sizeof(struct epitem),
  1839. 0, SLAB_HWCACHE_ALIGN | SLAB_PANIC, NULL);
  1840. /* Allocates slab cache used to allocate "struct eppoll_entry" */
  1841. pwq_cache = kmem_cache_create("eventpoll_pwq",
  1842. sizeof(struct eppoll_entry), 0, SLAB_PANIC, NULL);
  1843. return 0;
  1844. }
  1845. fs_initcall(eventpoll_init);