eventpoll.c 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591
  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 <asm/uaccess.h>
  36. #include <asm/system.h>
  37. #include <asm/io.h>
  38. #include <asm/mman.h>
  39. #include <linux/atomic.h>
  40. /*
  41. * LOCKING:
  42. * There are three level of locking required by epoll :
  43. *
  44. * 1) epmutex (mutex)
  45. * 2) ep->mtx (mutex)
  46. * 3) ep->lock (spinlock)
  47. *
  48. * The acquire order is the one listed above, from 1 to 3.
  49. * We need a spinlock (ep->lock) because we manipulate objects
  50. * from inside the poll callback, that might be triggered from
  51. * a wake_up() that in turn might be called from IRQ context.
  52. * So we can't sleep inside the poll callback and hence we need
  53. * a spinlock. During the event transfer loop (from kernel to
  54. * user space) we could end up sleeping due a copy_to_user(), so
  55. * we need a lock that will allow us to sleep. This lock is a
  56. * mutex (ep->mtx). It is acquired during the event transfer loop,
  57. * during epoll_ctl(EPOLL_CTL_DEL) and during eventpoll_release_file().
  58. * Then we also need a global mutex to serialize eventpoll_release_file()
  59. * and ep_free().
  60. * This mutex is acquired by ep_free() during the epoll file
  61. * cleanup path and it is also acquired by eventpoll_release_file()
  62. * if a file has been pushed inside an epoll set and it is then
  63. * close()d without a previous call to epoll_ctl(EPOLL_CTL_DEL).
  64. * It is also acquired when inserting an epoll fd onto another epoll
  65. * fd. We do this so that we walk the epoll tree and ensure that this
  66. * insertion does not create a cycle of epoll file descriptors, which
  67. * could lead to deadlock. We need a global mutex to prevent two
  68. * simultaneous inserts (A into B and B into A) from racing and
  69. * constructing a cycle without either insert observing that it is
  70. * going to.
  71. * It is possible to drop the "ep->mtx" and to use the global
  72. * mutex "epmutex" (together with "ep->lock") to have it working,
  73. * but having "ep->mtx" will make the interface more scalable.
  74. * Events that require holding "epmutex" are very rare, while for
  75. * normal operations the epoll private "ep->mtx" will guarantee
  76. * a better scalability.
  77. */
  78. /* Epoll private bits inside the event mask */
  79. #define EP_PRIVATE_BITS (EPOLLONESHOT | EPOLLET)
  80. /* Maximum number of nesting allowed inside epoll sets */
  81. #define EP_MAX_NESTS 4
  82. #define EP_MAX_EVENTS (INT_MAX / sizeof(struct epoll_event))
  83. #define EP_UNACTIVE_PTR ((void *) -1L)
  84. #define EP_ITEM_COST (sizeof(struct epitem) + sizeof(struct eppoll_entry))
  85. struct epoll_filefd {
  86. struct file *file;
  87. int fd;
  88. };
  89. /*
  90. * Structure used to track possible nested calls, for too deep recursions
  91. * and loop cycles.
  92. */
  93. struct nested_call_node {
  94. struct list_head llink;
  95. void *cookie;
  96. void *ctx;
  97. };
  98. /*
  99. * This structure is used as collector for nested calls, to check for
  100. * maximum recursion dept and loop cycles.
  101. */
  102. struct nested_calls {
  103. struct list_head tasks_call_list;
  104. spinlock_t lock;
  105. };
  106. /*
  107. * Each file descriptor added to the eventpoll interface will
  108. * have an entry of this type linked to the "rbr" RB tree.
  109. */
  110. struct epitem {
  111. /* RB tree node used to link this structure to the eventpoll RB tree */
  112. struct rb_node rbn;
  113. /* List header used to link this structure to the eventpoll ready list */
  114. struct list_head rdllink;
  115. /*
  116. * Works together "struct eventpoll"->ovflist in keeping the
  117. * single linked chain of items.
  118. */
  119. struct epitem *next;
  120. /* The file descriptor information this item refers to */
  121. struct epoll_filefd ffd;
  122. /* Number of active wait queue attached to poll operations */
  123. int nwait;
  124. /* List containing poll wait queues */
  125. struct list_head pwqlist;
  126. /* The "container" of this item */
  127. struct eventpoll *ep;
  128. /* List header used to link this item to the "struct file" items list */
  129. struct list_head fllink;
  130. /* The structure that describe the interested events and the source fd */
  131. struct epoll_event event;
  132. };
  133. /*
  134. * This structure is stored inside the "private_data" member of the file
  135. * structure and represents the main data structure for the eventpoll
  136. * interface.
  137. */
  138. struct eventpoll {
  139. /* Protect the access to this structure */
  140. spinlock_t lock;
  141. /*
  142. * This mutex is used to ensure that files are not removed
  143. * while epoll is using them. This is held during the event
  144. * collection loop, the file cleanup path, the epoll file exit
  145. * code and the ctl operations.
  146. */
  147. struct mutex mtx;
  148. /* Wait queue used by sys_epoll_wait() */
  149. wait_queue_head_t wq;
  150. /* Wait queue used by file->poll() */
  151. wait_queue_head_t poll_wait;
  152. /* List of ready file descriptors */
  153. struct list_head rdllist;
  154. /* RB tree root used to store monitored fd structs */
  155. struct rb_root rbr;
  156. /*
  157. * This is a single linked list that chains all the "struct epitem" that
  158. * happened while transferring ready events to userspace w/out
  159. * holding ->lock.
  160. */
  161. struct epitem *ovflist;
  162. /* The user that created the eventpoll descriptor */
  163. struct user_struct *user;
  164. };
  165. /* Wait structure used by the poll hooks */
  166. struct eppoll_entry {
  167. /* List header used to link this structure to the "struct epitem" */
  168. struct list_head llink;
  169. /* The "base" pointer is set to the container "struct epitem" */
  170. struct epitem *base;
  171. /*
  172. * Wait queue item that will be linked to the target file wait
  173. * queue head.
  174. */
  175. wait_queue_t wait;
  176. /* The wait queue head that linked the "wait" wait queue item */
  177. wait_queue_head_t *whead;
  178. };
  179. /* Wrapper struct used by poll queueing */
  180. struct ep_pqueue {
  181. poll_table pt;
  182. struct epitem *epi;
  183. };
  184. /* Used by the ep_send_events() function as callback private data */
  185. struct ep_send_events_data {
  186. int maxevents;
  187. struct epoll_event __user *events;
  188. };
  189. /*
  190. * Configuration options available inside /proc/sys/fs/epoll/
  191. */
  192. /* Maximum number of epoll watched descriptors, per user */
  193. static long max_user_watches __read_mostly;
  194. /*
  195. * This mutex is used to serialize ep_free() and eventpoll_release_file().
  196. */
  197. static DEFINE_MUTEX(epmutex);
  198. /* Used to check for epoll file descriptor inclusion loops */
  199. static struct nested_calls poll_loop_ncalls;
  200. /* Used for safe wake up implementation */
  201. static struct nested_calls poll_safewake_ncalls;
  202. /* Used to call file's f_op->poll() under the nested calls boundaries */
  203. static struct nested_calls poll_readywalk_ncalls;
  204. /* Slab cache used to allocate "struct epitem" */
  205. static struct kmem_cache *epi_cache __read_mostly;
  206. /* Slab cache used to allocate "struct eppoll_entry" */
  207. static struct kmem_cache *pwq_cache __read_mostly;
  208. #ifdef CONFIG_SYSCTL
  209. #include <linux/sysctl.h>
  210. static long zero;
  211. static long long_max = LONG_MAX;
  212. ctl_table epoll_table[] = {
  213. {
  214. .procname = "max_user_watches",
  215. .data = &max_user_watches,
  216. .maxlen = sizeof(max_user_watches),
  217. .mode = 0644,
  218. .proc_handler = proc_doulongvec_minmax,
  219. .extra1 = &zero,
  220. .extra2 = &long_max,
  221. },
  222. { }
  223. };
  224. #endif /* CONFIG_SYSCTL */
  225. /* Setup the structure that is used as key for the RB tree */
  226. static inline void ep_set_ffd(struct epoll_filefd *ffd,
  227. struct file *file, int fd)
  228. {
  229. ffd->file = file;
  230. ffd->fd = fd;
  231. }
  232. /* Compare RB tree keys */
  233. static inline int ep_cmp_ffd(struct epoll_filefd *p1,
  234. struct epoll_filefd *p2)
  235. {
  236. return (p1->file > p2->file ? +1:
  237. (p1->file < p2->file ? -1 : p1->fd - p2->fd));
  238. }
  239. /* Tells us if the item is currently linked */
  240. static inline int ep_is_linked(struct list_head *p)
  241. {
  242. return !list_empty(p);
  243. }
  244. /* Get the "struct epitem" from a wait queue pointer */
  245. static inline struct epitem *ep_item_from_wait(wait_queue_t *p)
  246. {
  247. return container_of(p, struct eppoll_entry, wait)->base;
  248. }
  249. /* Get the "struct epitem" from an epoll queue wrapper */
  250. static inline struct epitem *ep_item_from_epqueue(poll_table *p)
  251. {
  252. return container_of(p, struct ep_pqueue, pt)->epi;
  253. }
  254. /* Tells if the epoll_ctl(2) operation needs an event copy from userspace */
  255. static inline int ep_op_has_event(int op)
  256. {
  257. return op != EPOLL_CTL_DEL;
  258. }
  259. /* Initialize the poll safe wake up structure */
  260. static void ep_nested_calls_init(struct nested_calls *ncalls)
  261. {
  262. INIT_LIST_HEAD(&ncalls->tasks_call_list);
  263. spin_lock_init(&ncalls->lock);
  264. }
  265. /**
  266. * ep_events_available - Checks if ready events might be available.
  267. *
  268. * @ep: Pointer to the eventpoll context.
  269. *
  270. * Returns: Returns a value different than zero if ready events are available,
  271. * or zero otherwise.
  272. */
  273. static inline int ep_events_available(struct eventpoll *ep)
  274. {
  275. return !list_empty(&ep->rdllist) || ep->ovflist != EP_UNACTIVE_PTR;
  276. }
  277. /**
  278. * ep_call_nested - Perform a bound (possibly) nested call, by checking
  279. * that the recursion limit is not exceeded, and that
  280. * the same nested call (by the meaning of same cookie) is
  281. * no re-entered.
  282. *
  283. * @ncalls: Pointer to the nested_calls structure to be used for this call.
  284. * @max_nests: Maximum number of allowed nesting calls.
  285. * @nproc: Nested call core function pointer.
  286. * @priv: Opaque data to be passed to the @nproc callback.
  287. * @cookie: Cookie to be used to identify this nested call.
  288. * @ctx: This instance context.
  289. *
  290. * Returns: Returns the code returned by the @nproc callback, or -1 if
  291. * the maximum recursion limit has been exceeded.
  292. */
  293. static int ep_call_nested(struct nested_calls *ncalls, int max_nests,
  294. int (*nproc)(void *, void *, int), void *priv,
  295. void *cookie, void *ctx)
  296. {
  297. int error, call_nests = 0;
  298. unsigned long flags;
  299. struct list_head *lsthead = &ncalls->tasks_call_list;
  300. struct nested_call_node *tncur;
  301. struct nested_call_node tnode;
  302. spin_lock_irqsave(&ncalls->lock, flags);
  303. /*
  304. * Try to see if the current task is already inside this wakeup call.
  305. * We use a list here, since the population inside this set is always
  306. * very much limited.
  307. */
  308. list_for_each_entry(tncur, lsthead, llink) {
  309. if (tncur->ctx == ctx &&
  310. (tncur->cookie == cookie || ++call_nests > max_nests)) {
  311. /*
  312. * Ops ... loop detected or maximum nest level reached.
  313. * We abort this wake by breaking the cycle itself.
  314. */
  315. error = -1;
  316. goto out_unlock;
  317. }
  318. }
  319. /* Add the current task and cookie to the list */
  320. tnode.ctx = ctx;
  321. tnode.cookie = cookie;
  322. list_add(&tnode.llink, lsthead);
  323. spin_unlock_irqrestore(&ncalls->lock, flags);
  324. /* Call the nested function */
  325. error = (*nproc)(priv, cookie, call_nests);
  326. /* Remove the current task from the list */
  327. spin_lock_irqsave(&ncalls->lock, flags);
  328. list_del(&tnode.llink);
  329. out_unlock:
  330. spin_unlock_irqrestore(&ncalls->lock, flags);
  331. return error;
  332. }
  333. #ifdef CONFIG_DEBUG_LOCK_ALLOC
  334. static inline void ep_wake_up_nested(wait_queue_head_t *wqueue,
  335. unsigned long events, int subclass)
  336. {
  337. unsigned long flags;
  338. spin_lock_irqsave_nested(&wqueue->lock, flags, subclass);
  339. wake_up_locked_poll(wqueue, events);
  340. spin_unlock_irqrestore(&wqueue->lock, flags);
  341. }
  342. #else
  343. static inline void ep_wake_up_nested(wait_queue_head_t *wqueue,
  344. unsigned long events, int subclass)
  345. {
  346. wake_up_poll(wqueue, events);
  347. }
  348. #endif
  349. static int ep_poll_wakeup_proc(void *priv, void *cookie, int call_nests)
  350. {
  351. ep_wake_up_nested((wait_queue_head_t *) cookie, POLLIN,
  352. 1 + call_nests);
  353. return 0;
  354. }
  355. /*
  356. * Perform a safe wake up of the poll wait list. The problem is that
  357. * with the new callback'd wake up system, it is possible that the
  358. * poll callback is reentered from inside the call to wake_up() done
  359. * on the poll wait queue head. The rule is that we cannot reenter the
  360. * wake up code from the same task more than EP_MAX_NESTS times,
  361. * and we cannot reenter the same wait queue head at all. This will
  362. * enable to have a hierarchy of epoll file descriptor of no more than
  363. * EP_MAX_NESTS deep.
  364. */
  365. static void ep_poll_safewake(wait_queue_head_t *wq)
  366. {
  367. int this_cpu = get_cpu();
  368. ep_call_nested(&poll_safewake_ncalls, EP_MAX_NESTS,
  369. ep_poll_wakeup_proc, NULL, wq, (void *) (long) this_cpu);
  370. put_cpu();
  371. }
  372. /*
  373. * This function unregisters poll callbacks from the associated file
  374. * descriptor. Must be called with "mtx" held (or "epmutex" if called from
  375. * ep_free).
  376. */
  377. static void ep_unregister_pollwait(struct eventpoll *ep, struct epitem *epi)
  378. {
  379. struct list_head *lsthead = &epi->pwqlist;
  380. struct eppoll_entry *pwq;
  381. while (!list_empty(lsthead)) {
  382. pwq = list_first_entry(lsthead, struct eppoll_entry, llink);
  383. list_del(&pwq->llink);
  384. remove_wait_queue(pwq->whead, &pwq->wait);
  385. kmem_cache_free(pwq_cache, pwq);
  386. }
  387. }
  388. /**
  389. * ep_scan_ready_list - Scans the ready list in a way that makes possible for
  390. * the scan code, to call f_op->poll(). Also allows for
  391. * O(NumReady) performance.
  392. *
  393. * @ep: Pointer to the epoll private data structure.
  394. * @sproc: Pointer to the scan callback.
  395. * @priv: Private opaque data passed to the @sproc callback.
  396. *
  397. * Returns: The same integer error code returned by the @sproc callback.
  398. */
  399. static int ep_scan_ready_list(struct eventpoll *ep,
  400. int (*sproc)(struct eventpoll *,
  401. struct list_head *, void *),
  402. void *priv)
  403. {
  404. int error, pwake = 0;
  405. unsigned long flags;
  406. struct epitem *epi, *nepi;
  407. LIST_HEAD(txlist);
  408. /*
  409. * We need to lock this because we could be hit by
  410. * eventpoll_release_file() and epoll_ctl().
  411. */
  412. mutex_lock(&ep->mtx);
  413. /*
  414. * Steal the ready list, and re-init the original one to the
  415. * empty list. Also, set ep->ovflist to NULL so that events
  416. * happening while looping w/out locks, are not lost. We cannot
  417. * have the poll callback to queue directly on ep->rdllist,
  418. * because we want the "sproc" callback to be able to do it
  419. * in a lockless way.
  420. */
  421. spin_lock_irqsave(&ep->lock, flags);
  422. list_splice_init(&ep->rdllist, &txlist);
  423. ep->ovflist = NULL;
  424. spin_unlock_irqrestore(&ep->lock, flags);
  425. /*
  426. * Now call the callback function.
  427. */
  428. error = (*sproc)(ep, &txlist, priv);
  429. spin_lock_irqsave(&ep->lock, flags);
  430. /*
  431. * During the time we spent inside the "sproc" callback, some
  432. * other events might have been queued by the poll callback.
  433. * We re-insert them inside the main ready-list here.
  434. */
  435. for (nepi = ep->ovflist; (epi = nepi) != NULL;
  436. nepi = epi->next, epi->next = EP_UNACTIVE_PTR) {
  437. /*
  438. * We need to check if the item is already in the list.
  439. * During the "sproc" callback execution time, items are
  440. * queued into ->ovflist but the "txlist" might already
  441. * contain them, and the list_splice() below takes care of them.
  442. */
  443. if (!ep_is_linked(&epi->rdllink))
  444. list_add_tail(&epi->rdllink, &ep->rdllist);
  445. }
  446. /*
  447. * We need to set back ep->ovflist to EP_UNACTIVE_PTR, so that after
  448. * releasing the lock, events will be queued in the normal way inside
  449. * ep->rdllist.
  450. */
  451. ep->ovflist = EP_UNACTIVE_PTR;
  452. /*
  453. * Quickly re-inject items left on "txlist".
  454. */
  455. list_splice(&txlist, &ep->rdllist);
  456. if (!list_empty(&ep->rdllist)) {
  457. /*
  458. * Wake up (if active) both the eventpoll wait list and
  459. * the ->poll() wait list (delayed after we release the lock).
  460. */
  461. if (waitqueue_active(&ep->wq))
  462. wake_up_locked(&ep->wq);
  463. if (waitqueue_active(&ep->poll_wait))
  464. pwake++;
  465. }
  466. spin_unlock_irqrestore(&ep->lock, flags);
  467. mutex_unlock(&ep->mtx);
  468. /* We have to call this outside the lock */
  469. if (pwake)
  470. ep_poll_safewake(&ep->poll_wait);
  471. return error;
  472. }
  473. /*
  474. * Removes a "struct epitem" from the eventpoll RB tree and deallocates
  475. * all the associated resources. Must be called with "mtx" held.
  476. */
  477. static int ep_remove(struct eventpoll *ep, struct epitem *epi)
  478. {
  479. unsigned long flags;
  480. struct file *file = epi->ffd.file;
  481. /*
  482. * Removes poll wait queue hooks. We _have_ to do this without holding
  483. * the "ep->lock" otherwise a deadlock might occur. This because of the
  484. * sequence of the lock acquisition. Here we do "ep->lock" then the wait
  485. * queue head lock when unregistering the wait queue. The wakeup callback
  486. * will run by holding the wait queue head lock and will call our callback
  487. * that will try to get "ep->lock".
  488. */
  489. ep_unregister_pollwait(ep, epi);
  490. /* Remove the current item from the list of epoll hooks */
  491. spin_lock(&file->f_lock);
  492. if (ep_is_linked(&epi->fllink))
  493. list_del_init(&epi->fllink);
  494. spin_unlock(&file->f_lock);
  495. rb_erase(&epi->rbn, &ep->rbr);
  496. spin_lock_irqsave(&ep->lock, flags);
  497. if (ep_is_linked(&epi->rdllink))
  498. list_del_init(&epi->rdllink);
  499. spin_unlock_irqrestore(&ep->lock, flags);
  500. /* At this point it is safe to free the eventpoll item */
  501. kmem_cache_free(epi_cache, epi);
  502. atomic_long_dec(&ep->user->epoll_watches);
  503. return 0;
  504. }
  505. static void ep_free(struct eventpoll *ep)
  506. {
  507. struct rb_node *rbp;
  508. struct epitem *epi;
  509. /* We need to release all tasks waiting for these file */
  510. if (waitqueue_active(&ep->poll_wait))
  511. ep_poll_safewake(&ep->poll_wait);
  512. /*
  513. * We need to lock this because we could be hit by
  514. * eventpoll_release_file() while we're freeing the "struct eventpoll".
  515. * We do not need to hold "ep->mtx" here because the epoll file
  516. * is on the way to be removed and no one has references to it
  517. * anymore. The only hit might come from eventpoll_release_file() but
  518. * holding "epmutex" is sufficient here.
  519. */
  520. mutex_lock(&epmutex);
  521. /*
  522. * Walks through the whole tree by unregistering poll callbacks.
  523. */
  524. for (rbp = rb_first(&ep->rbr); rbp; rbp = rb_next(rbp)) {
  525. epi = rb_entry(rbp, struct epitem, rbn);
  526. ep_unregister_pollwait(ep, epi);
  527. }
  528. /*
  529. * Walks through the whole tree by freeing each "struct epitem". At this
  530. * point we are sure no poll callbacks will be lingering around, and also by
  531. * holding "epmutex" we can be sure that no file cleanup code will hit
  532. * us during this operation. So we can avoid the lock on "ep->lock".
  533. */
  534. while ((rbp = rb_first(&ep->rbr)) != NULL) {
  535. epi = rb_entry(rbp, struct epitem, rbn);
  536. ep_remove(ep, epi);
  537. }
  538. mutex_unlock(&epmutex);
  539. mutex_destroy(&ep->mtx);
  540. free_uid(ep->user);
  541. kfree(ep);
  542. }
  543. static int ep_eventpoll_release(struct inode *inode, struct file *file)
  544. {
  545. struct eventpoll *ep = file->private_data;
  546. if (ep)
  547. ep_free(ep);
  548. return 0;
  549. }
  550. static int ep_read_events_proc(struct eventpoll *ep, struct list_head *head,
  551. void *priv)
  552. {
  553. struct epitem *epi, *tmp;
  554. list_for_each_entry_safe(epi, tmp, head, rdllink) {
  555. if (epi->ffd.file->f_op->poll(epi->ffd.file, NULL) &
  556. epi->event.events)
  557. return POLLIN | POLLRDNORM;
  558. else {
  559. /*
  560. * Item has been dropped into the ready list by the poll
  561. * callback, but it's not actually ready, as far as
  562. * caller requested events goes. We can remove it here.
  563. */
  564. list_del_init(&epi->rdllink);
  565. }
  566. }
  567. return 0;
  568. }
  569. static int ep_poll_readyevents_proc(void *priv, void *cookie, int call_nests)
  570. {
  571. return ep_scan_ready_list(priv, ep_read_events_proc, NULL);
  572. }
  573. static unsigned int ep_eventpoll_poll(struct file *file, poll_table *wait)
  574. {
  575. int pollflags;
  576. struct eventpoll *ep = file->private_data;
  577. /* Insert inside our poll wait queue */
  578. poll_wait(file, &ep->poll_wait, wait);
  579. /*
  580. * Proceed to find out if wanted events are really available inside
  581. * the ready list. This need to be done under ep_call_nested()
  582. * supervision, since the call to f_op->poll() done on listed files
  583. * could re-enter here.
  584. */
  585. pollflags = ep_call_nested(&poll_readywalk_ncalls, EP_MAX_NESTS,
  586. ep_poll_readyevents_proc, ep, ep, current);
  587. return pollflags != -1 ? pollflags : 0;
  588. }
  589. /* File callbacks that implement the eventpoll file behaviour */
  590. static const struct file_operations eventpoll_fops = {
  591. .release = ep_eventpoll_release,
  592. .poll = ep_eventpoll_poll,
  593. .llseek = noop_llseek,
  594. };
  595. /* Fast test to see if the file is an evenpoll file */
  596. static inline int is_file_epoll(struct file *f)
  597. {
  598. return f->f_op == &eventpoll_fops;
  599. }
  600. /*
  601. * This is called from eventpoll_release() to unlink files from the eventpoll
  602. * interface. We need to have this facility to cleanup correctly files that are
  603. * closed without being removed from the eventpoll interface.
  604. */
  605. void eventpoll_release_file(struct file *file)
  606. {
  607. struct list_head *lsthead = &file->f_ep_links;
  608. struct eventpoll *ep;
  609. struct epitem *epi;
  610. /*
  611. * We don't want to get "file->f_lock" because it is not
  612. * necessary. It is not necessary because we're in the "struct file"
  613. * cleanup path, and this means that no one is using this file anymore.
  614. * So, for example, epoll_ctl() cannot hit here since if we reach this
  615. * point, the file counter already went to zero and fget() would fail.
  616. * The only hit might come from ep_free() but by holding the mutex
  617. * will correctly serialize the operation. We do need to acquire
  618. * "ep->mtx" after "epmutex" because ep_remove() requires it when called
  619. * from anywhere but ep_free().
  620. *
  621. * Besides, ep_remove() acquires the lock, so we can't hold it here.
  622. */
  623. mutex_lock(&epmutex);
  624. while (!list_empty(lsthead)) {
  625. epi = list_first_entry(lsthead, struct epitem, fllink);
  626. ep = epi->ep;
  627. list_del_init(&epi->fllink);
  628. mutex_lock(&ep->mtx);
  629. ep_remove(ep, epi);
  630. mutex_unlock(&ep->mtx);
  631. }
  632. mutex_unlock(&epmutex);
  633. }
  634. static int ep_alloc(struct eventpoll **pep)
  635. {
  636. int error;
  637. struct user_struct *user;
  638. struct eventpoll *ep;
  639. user = get_current_user();
  640. error = -ENOMEM;
  641. ep = kzalloc(sizeof(*ep), GFP_KERNEL);
  642. if (unlikely(!ep))
  643. goto free_uid;
  644. spin_lock_init(&ep->lock);
  645. mutex_init(&ep->mtx);
  646. init_waitqueue_head(&ep->wq);
  647. init_waitqueue_head(&ep->poll_wait);
  648. INIT_LIST_HEAD(&ep->rdllist);
  649. ep->rbr = RB_ROOT;
  650. ep->ovflist = EP_UNACTIVE_PTR;
  651. ep->user = user;
  652. *pep = ep;
  653. return 0;
  654. free_uid:
  655. free_uid(user);
  656. return error;
  657. }
  658. /*
  659. * Search the file inside the eventpoll tree. The RB tree operations
  660. * are protected by the "mtx" mutex, and ep_find() must be called with
  661. * "mtx" held.
  662. */
  663. static struct epitem *ep_find(struct eventpoll *ep, struct file *file, int fd)
  664. {
  665. int kcmp;
  666. struct rb_node *rbp;
  667. struct epitem *epi, *epir = NULL;
  668. struct epoll_filefd ffd;
  669. ep_set_ffd(&ffd, file, fd);
  670. for (rbp = ep->rbr.rb_node; rbp; ) {
  671. epi = rb_entry(rbp, struct epitem, rbn);
  672. kcmp = ep_cmp_ffd(&ffd, &epi->ffd);
  673. if (kcmp > 0)
  674. rbp = rbp->rb_right;
  675. else if (kcmp < 0)
  676. rbp = rbp->rb_left;
  677. else {
  678. epir = epi;
  679. break;
  680. }
  681. }
  682. return epir;
  683. }
  684. /*
  685. * This is the callback that is passed to the wait queue wakeup
  686. * mechanism. It is called by the stored file descriptors when they
  687. * have events to report.
  688. */
  689. static int ep_poll_callback(wait_queue_t *wait, unsigned mode, int sync, void *key)
  690. {
  691. int pwake = 0;
  692. unsigned long flags;
  693. struct epitem *epi = ep_item_from_wait(wait);
  694. struct eventpoll *ep = epi->ep;
  695. spin_lock_irqsave(&ep->lock, flags);
  696. /*
  697. * If the event mask does not contain any poll(2) event, we consider the
  698. * descriptor to be disabled. This condition is likely the effect of the
  699. * EPOLLONESHOT bit that disables the descriptor when an event is received,
  700. * until the next EPOLL_CTL_MOD will be issued.
  701. */
  702. if (!(epi->event.events & ~EP_PRIVATE_BITS))
  703. goto out_unlock;
  704. /*
  705. * Check the events coming with the callback. At this stage, not
  706. * every device reports the events in the "key" parameter of the
  707. * callback. We need to be able to handle both cases here, hence the
  708. * test for "key" != NULL before the event match test.
  709. */
  710. if (key && !((unsigned long) key & epi->event.events))
  711. goto out_unlock;
  712. /*
  713. * If we are transferring events to userspace, we can hold no locks
  714. * (because we're accessing user memory, and because of linux f_op->poll()
  715. * semantics). All the events that happen during that period of time are
  716. * chained in ep->ovflist and requeued later on.
  717. */
  718. if (unlikely(ep->ovflist != EP_UNACTIVE_PTR)) {
  719. if (epi->next == EP_UNACTIVE_PTR) {
  720. epi->next = ep->ovflist;
  721. ep->ovflist = epi;
  722. }
  723. goto out_unlock;
  724. }
  725. /* If this file is already in the ready list we exit soon */
  726. if (!ep_is_linked(&epi->rdllink))
  727. list_add_tail(&epi->rdllink, &ep->rdllist);
  728. /*
  729. * Wake up ( if active ) both the eventpoll wait list and the ->poll()
  730. * wait list.
  731. */
  732. if (waitqueue_active(&ep->wq))
  733. wake_up_locked(&ep->wq);
  734. if (waitqueue_active(&ep->poll_wait))
  735. pwake++;
  736. out_unlock:
  737. spin_unlock_irqrestore(&ep->lock, flags);
  738. /* We have to call this outside the lock */
  739. if (pwake)
  740. ep_poll_safewake(&ep->poll_wait);
  741. return 1;
  742. }
  743. /*
  744. * This is the callback that is used to add our wait queue to the
  745. * target file wakeup lists.
  746. */
  747. static void ep_ptable_queue_proc(struct file *file, wait_queue_head_t *whead,
  748. poll_table *pt)
  749. {
  750. struct epitem *epi = ep_item_from_epqueue(pt);
  751. struct eppoll_entry *pwq;
  752. if (epi->nwait >= 0 && (pwq = kmem_cache_alloc(pwq_cache, GFP_KERNEL))) {
  753. init_waitqueue_func_entry(&pwq->wait, ep_poll_callback);
  754. pwq->whead = whead;
  755. pwq->base = epi;
  756. add_wait_queue(whead, &pwq->wait);
  757. list_add_tail(&pwq->llink, &epi->pwqlist);
  758. epi->nwait++;
  759. } else {
  760. /* We have to signal that an error occurred */
  761. epi->nwait = -1;
  762. }
  763. }
  764. static void ep_rbtree_insert(struct eventpoll *ep, struct epitem *epi)
  765. {
  766. int kcmp;
  767. struct rb_node **p = &ep->rbr.rb_node, *parent = NULL;
  768. struct epitem *epic;
  769. while (*p) {
  770. parent = *p;
  771. epic = rb_entry(parent, struct epitem, rbn);
  772. kcmp = ep_cmp_ffd(&epi->ffd, &epic->ffd);
  773. if (kcmp > 0)
  774. p = &parent->rb_right;
  775. else
  776. p = &parent->rb_left;
  777. }
  778. rb_link_node(&epi->rbn, parent, p);
  779. rb_insert_color(&epi->rbn, &ep->rbr);
  780. }
  781. /*
  782. * Must be called with "mtx" held.
  783. */
  784. static int ep_insert(struct eventpoll *ep, struct epoll_event *event,
  785. struct file *tfile, int fd)
  786. {
  787. int error, revents, pwake = 0;
  788. unsigned long flags;
  789. long user_watches;
  790. struct epitem *epi;
  791. struct ep_pqueue epq;
  792. user_watches = atomic_long_read(&ep->user->epoll_watches);
  793. if (unlikely(user_watches >= max_user_watches))
  794. return -ENOSPC;
  795. if (!(epi = kmem_cache_alloc(epi_cache, GFP_KERNEL)))
  796. return -ENOMEM;
  797. /* Item initialization follow here ... */
  798. INIT_LIST_HEAD(&epi->rdllink);
  799. INIT_LIST_HEAD(&epi->fllink);
  800. INIT_LIST_HEAD(&epi->pwqlist);
  801. epi->ep = ep;
  802. ep_set_ffd(&epi->ffd, tfile, fd);
  803. epi->event = *event;
  804. epi->nwait = 0;
  805. epi->next = EP_UNACTIVE_PTR;
  806. /* Initialize the poll table using the queue callback */
  807. epq.epi = epi;
  808. init_poll_funcptr(&epq.pt, ep_ptable_queue_proc);
  809. /*
  810. * Attach the item to the poll hooks and get current event bits.
  811. * We can safely use the file* here because its usage count has
  812. * been increased by the caller of this function. Note that after
  813. * this operation completes, the poll callback can start hitting
  814. * the new item.
  815. */
  816. revents = tfile->f_op->poll(tfile, &epq.pt);
  817. /*
  818. * We have to check if something went wrong during the poll wait queue
  819. * install process. Namely an allocation for a wait queue failed due
  820. * high memory pressure.
  821. */
  822. error = -ENOMEM;
  823. if (epi->nwait < 0)
  824. goto error_unregister;
  825. /* Add the current item to the list of active epoll hook for this file */
  826. spin_lock(&tfile->f_lock);
  827. list_add_tail(&epi->fllink, &tfile->f_ep_links);
  828. spin_unlock(&tfile->f_lock);
  829. /*
  830. * Add the current item to the RB tree. All RB tree operations are
  831. * protected by "mtx", and ep_insert() is called with "mtx" held.
  832. */
  833. ep_rbtree_insert(ep, epi);
  834. /* We have to drop the new item inside our item list to keep track of it */
  835. spin_lock_irqsave(&ep->lock, flags);
  836. /* If the file is already "ready" we drop it inside the ready list */
  837. if ((revents & event->events) && !ep_is_linked(&epi->rdllink)) {
  838. list_add_tail(&epi->rdllink, &ep->rdllist);
  839. /* Notify waiting tasks that events are available */
  840. if (waitqueue_active(&ep->wq))
  841. wake_up_locked(&ep->wq);
  842. if (waitqueue_active(&ep->poll_wait))
  843. pwake++;
  844. }
  845. spin_unlock_irqrestore(&ep->lock, flags);
  846. atomic_long_inc(&ep->user->epoll_watches);
  847. /* We have to call this outside the lock */
  848. if (pwake)
  849. ep_poll_safewake(&ep->poll_wait);
  850. return 0;
  851. error_unregister:
  852. ep_unregister_pollwait(ep, epi);
  853. /*
  854. * We need to do this because an event could have been arrived on some
  855. * allocated wait queue. Note that we don't care about the ep->ovflist
  856. * list, since that is used/cleaned only inside a section bound by "mtx".
  857. * And ep_insert() is called with "mtx" held.
  858. */
  859. spin_lock_irqsave(&ep->lock, flags);
  860. if (ep_is_linked(&epi->rdllink))
  861. list_del_init(&epi->rdllink);
  862. spin_unlock_irqrestore(&ep->lock, flags);
  863. kmem_cache_free(epi_cache, epi);
  864. return error;
  865. }
  866. /*
  867. * Modify the interest event mask by dropping an event if the new mask
  868. * has a match in the current file status. Must be called with "mtx" held.
  869. */
  870. static int ep_modify(struct eventpoll *ep, struct epitem *epi, struct epoll_event *event)
  871. {
  872. int pwake = 0;
  873. unsigned int revents;
  874. /*
  875. * Set the new event interest mask before calling f_op->poll();
  876. * otherwise we might miss an event that happens between the
  877. * f_op->poll() call and the new event set registering.
  878. */
  879. epi->event.events = event->events;
  880. epi->event.data = event->data; /* protected by mtx */
  881. /*
  882. * Get current event bits. We can safely use the file* here because
  883. * its usage count has been increased by the caller of this function.
  884. */
  885. revents = epi->ffd.file->f_op->poll(epi->ffd.file, NULL);
  886. /*
  887. * If the item is "hot" and it is not registered inside the ready
  888. * list, push it inside.
  889. */
  890. if (revents & event->events) {
  891. spin_lock_irq(&ep->lock);
  892. if (!ep_is_linked(&epi->rdllink)) {
  893. list_add_tail(&epi->rdllink, &ep->rdllist);
  894. /* Notify waiting tasks that events are available */
  895. if (waitqueue_active(&ep->wq))
  896. wake_up_locked(&ep->wq);
  897. if (waitqueue_active(&ep->poll_wait))
  898. pwake++;
  899. }
  900. spin_unlock_irq(&ep->lock);
  901. }
  902. /* We have to call this outside the lock */
  903. if (pwake)
  904. ep_poll_safewake(&ep->poll_wait);
  905. return 0;
  906. }
  907. static int ep_send_events_proc(struct eventpoll *ep, struct list_head *head,
  908. void *priv)
  909. {
  910. struct ep_send_events_data *esed = priv;
  911. int eventcnt;
  912. unsigned int revents;
  913. struct epitem *epi;
  914. struct epoll_event __user *uevent;
  915. /*
  916. * We can loop without lock because we are passed a task private list.
  917. * Items cannot vanish during the loop because ep_scan_ready_list() is
  918. * holding "mtx" during this call.
  919. */
  920. for (eventcnt = 0, uevent = esed->events;
  921. !list_empty(head) && eventcnt < esed->maxevents;) {
  922. epi = list_first_entry(head, struct epitem, rdllink);
  923. list_del_init(&epi->rdllink);
  924. revents = epi->ffd.file->f_op->poll(epi->ffd.file, NULL) &
  925. epi->event.events;
  926. /*
  927. * If the event mask intersect the caller-requested one,
  928. * deliver the event to userspace. Again, ep_scan_ready_list()
  929. * is holding "mtx", so no operations coming from userspace
  930. * can change the item.
  931. */
  932. if (revents) {
  933. if (__put_user(revents, &uevent->events) ||
  934. __put_user(epi->event.data, &uevent->data)) {
  935. list_add(&epi->rdllink, head);
  936. return eventcnt ? eventcnt : -EFAULT;
  937. }
  938. eventcnt++;
  939. uevent++;
  940. if (epi->event.events & EPOLLONESHOT)
  941. epi->event.events &= EP_PRIVATE_BITS;
  942. else if (!(epi->event.events & EPOLLET)) {
  943. /*
  944. * If this file has been added with Level
  945. * Trigger mode, we need to insert back inside
  946. * the ready list, so that the next call to
  947. * epoll_wait() will check again the events
  948. * availability. At this point, no one can insert
  949. * into ep->rdllist besides us. The epoll_ctl()
  950. * callers are locked out by
  951. * ep_scan_ready_list() holding "mtx" and the
  952. * poll callback will queue them in ep->ovflist.
  953. */
  954. list_add_tail(&epi->rdllink, &ep->rdllist);
  955. }
  956. }
  957. }
  958. return eventcnt;
  959. }
  960. static int ep_send_events(struct eventpoll *ep,
  961. struct epoll_event __user *events, int maxevents)
  962. {
  963. struct ep_send_events_data esed;
  964. esed.maxevents = maxevents;
  965. esed.events = events;
  966. return ep_scan_ready_list(ep, ep_send_events_proc, &esed);
  967. }
  968. static inline struct timespec ep_set_mstimeout(long ms)
  969. {
  970. struct timespec now, ts = {
  971. .tv_sec = ms / MSEC_PER_SEC,
  972. .tv_nsec = NSEC_PER_MSEC * (ms % MSEC_PER_SEC),
  973. };
  974. ktime_get_ts(&now);
  975. return timespec_add_safe(now, ts);
  976. }
  977. /**
  978. * ep_poll - Retrieves ready events, and delivers them to the caller supplied
  979. * event buffer.
  980. *
  981. * @ep: Pointer to the eventpoll context.
  982. * @events: Pointer to the userspace buffer where the ready events should be
  983. * stored.
  984. * @maxevents: Size (in terms of number of events) of the caller event buffer.
  985. * @timeout: Maximum timeout for the ready events fetch operation, in
  986. * milliseconds. If the @timeout is zero, the function will not block,
  987. * while if the @timeout is less than zero, the function will block
  988. * until at least one event has been retrieved (or an error
  989. * occurred).
  990. *
  991. * Returns: Returns the number of ready events which have been fetched, or an
  992. * error code, in case of error.
  993. */
  994. static int ep_poll(struct eventpoll *ep, struct epoll_event __user *events,
  995. int maxevents, long timeout)
  996. {
  997. int res = 0, eavail, timed_out = 0;
  998. unsigned long flags;
  999. long slack = 0;
  1000. wait_queue_t wait;
  1001. ktime_t expires, *to = NULL;
  1002. if (timeout > 0) {
  1003. struct timespec end_time = ep_set_mstimeout(timeout);
  1004. slack = select_estimate_accuracy(&end_time);
  1005. to = &expires;
  1006. *to = timespec_to_ktime(end_time);
  1007. } else if (timeout == 0) {
  1008. /*
  1009. * Avoid the unnecessary trip to the wait queue loop, if the
  1010. * caller specified a non blocking operation.
  1011. */
  1012. timed_out = 1;
  1013. spin_lock_irqsave(&ep->lock, flags);
  1014. goto check_events;
  1015. }
  1016. fetch_events:
  1017. spin_lock_irqsave(&ep->lock, flags);
  1018. if (!ep_events_available(ep)) {
  1019. /*
  1020. * We don't have any available event to return to the caller.
  1021. * We need to sleep here, and we will be wake up by
  1022. * ep_poll_callback() when events will become available.
  1023. */
  1024. init_waitqueue_entry(&wait, current);
  1025. __add_wait_queue_exclusive(&ep->wq, &wait);
  1026. for (;;) {
  1027. /*
  1028. * We don't want to sleep if the ep_poll_callback() sends us
  1029. * a wakeup in between. That's why we set the task state
  1030. * to TASK_INTERRUPTIBLE before doing the checks.
  1031. */
  1032. set_current_state(TASK_INTERRUPTIBLE);
  1033. if (ep_events_available(ep) || timed_out)
  1034. break;
  1035. if (signal_pending(current)) {
  1036. res = -EINTR;
  1037. break;
  1038. }
  1039. spin_unlock_irqrestore(&ep->lock, flags);
  1040. if (!schedule_hrtimeout_range(to, slack, HRTIMER_MODE_ABS))
  1041. timed_out = 1;
  1042. spin_lock_irqsave(&ep->lock, flags);
  1043. }
  1044. __remove_wait_queue(&ep->wq, &wait);
  1045. set_current_state(TASK_RUNNING);
  1046. }
  1047. check_events:
  1048. /* Is it worth to try to dig for events ? */
  1049. eavail = ep_events_available(ep);
  1050. spin_unlock_irqrestore(&ep->lock, flags);
  1051. /*
  1052. * Try to transfer events to user space. In case we get 0 events and
  1053. * there's still timeout left over, we go trying again in search of
  1054. * more luck.
  1055. */
  1056. if (!res && eavail &&
  1057. !(res = ep_send_events(ep, events, maxevents)) && !timed_out)
  1058. goto fetch_events;
  1059. return res;
  1060. }
  1061. /**
  1062. * ep_loop_check_proc - Callback function to be passed to the @ep_call_nested()
  1063. * API, to verify that adding an epoll file inside another
  1064. * epoll structure, does not violate the constraints, in
  1065. * terms of closed loops, or too deep chains (which can
  1066. * result in excessive stack usage).
  1067. *
  1068. * @priv: Pointer to the epoll file to be currently checked.
  1069. * @cookie: Original cookie for this call. This is the top-of-the-chain epoll
  1070. * data structure pointer.
  1071. * @call_nests: Current dept of the @ep_call_nested() call stack.
  1072. *
  1073. * Returns: Returns zero if adding the epoll @file inside current epoll
  1074. * structure @ep does not violate the constraints, or -1 otherwise.
  1075. */
  1076. static int ep_loop_check_proc(void *priv, void *cookie, int call_nests)
  1077. {
  1078. int error = 0;
  1079. struct file *file = priv;
  1080. struct eventpoll *ep = file->private_data;
  1081. struct rb_node *rbp;
  1082. struct epitem *epi;
  1083. mutex_lock(&ep->mtx);
  1084. for (rbp = rb_first(&ep->rbr); rbp; rbp = rb_next(rbp)) {
  1085. epi = rb_entry(rbp, struct epitem, rbn);
  1086. if (unlikely(is_file_epoll(epi->ffd.file))) {
  1087. error = ep_call_nested(&poll_loop_ncalls, EP_MAX_NESTS,
  1088. ep_loop_check_proc, epi->ffd.file,
  1089. epi->ffd.file->private_data, current);
  1090. if (error != 0)
  1091. break;
  1092. }
  1093. }
  1094. mutex_unlock(&ep->mtx);
  1095. return error;
  1096. }
  1097. /**
  1098. * ep_loop_check - Performs a check to verify that adding an epoll file (@file)
  1099. * another epoll file (represented by @ep) does not create
  1100. * closed loops or too deep chains.
  1101. *
  1102. * @ep: Pointer to the epoll private data structure.
  1103. * @file: Pointer to the epoll file to be checked.
  1104. *
  1105. * Returns: Returns zero if adding the epoll @file inside current epoll
  1106. * structure @ep does not violate the constraints, or -1 otherwise.
  1107. */
  1108. static int ep_loop_check(struct eventpoll *ep, struct file *file)
  1109. {
  1110. return ep_call_nested(&poll_loop_ncalls, EP_MAX_NESTS,
  1111. ep_loop_check_proc, file, ep, current);
  1112. }
  1113. /*
  1114. * Open an eventpoll file descriptor.
  1115. */
  1116. SYSCALL_DEFINE1(epoll_create1, int, flags)
  1117. {
  1118. int error;
  1119. struct eventpoll *ep = NULL;
  1120. /* Check the EPOLL_* constant for consistency. */
  1121. BUILD_BUG_ON(EPOLL_CLOEXEC != O_CLOEXEC);
  1122. if (flags & ~EPOLL_CLOEXEC)
  1123. return -EINVAL;
  1124. /*
  1125. * Create the internal data structure ("struct eventpoll").
  1126. */
  1127. error = ep_alloc(&ep);
  1128. if (error < 0)
  1129. return error;
  1130. /*
  1131. * Creates all the items needed to setup an eventpoll file. That is,
  1132. * a file structure and a free file descriptor.
  1133. */
  1134. error = anon_inode_getfd("[eventpoll]", &eventpoll_fops, ep,
  1135. O_RDWR | (flags & O_CLOEXEC));
  1136. if (error < 0)
  1137. ep_free(ep);
  1138. return error;
  1139. }
  1140. SYSCALL_DEFINE1(epoll_create, int, size)
  1141. {
  1142. if (size <= 0)
  1143. return -EINVAL;
  1144. return sys_epoll_create1(0);
  1145. }
  1146. /*
  1147. * The following function implements the controller interface for
  1148. * the eventpoll file that enables the insertion/removal/change of
  1149. * file descriptors inside the interest set.
  1150. */
  1151. SYSCALL_DEFINE4(epoll_ctl, int, epfd, int, op, int, fd,
  1152. struct epoll_event __user *, event)
  1153. {
  1154. int error;
  1155. int did_lock_epmutex = 0;
  1156. struct file *file, *tfile;
  1157. struct eventpoll *ep;
  1158. struct epitem *epi;
  1159. struct epoll_event epds;
  1160. error = -EFAULT;
  1161. if (ep_op_has_event(op) &&
  1162. copy_from_user(&epds, event, sizeof(struct epoll_event)))
  1163. goto error_return;
  1164. /* Get the "struct file *" for the eventpoll file */
  1165. error = -EBADF;
  1166. file = fget(epfd);
  1167. if (!file)
  1168. goto error_return;
  1169. /* Get the "struct file *" for the target file */
  1170. tfile = fget(fd);
  1171. if (!tfile)
  1172. goto error_fput;
  1173. /* The target file descriptor must support poll */
  1174. error = -EPERM;
  1175. if (!tfile->f_op || !tfile->f_op->poll)
  1176. goto error_tgt_fput;
  1177. /*
  1178. * We have to check that the file structure underneath the file descriptor
  1179. * the user passed to us _is_ an eventpoll file. And also we do not permit
  1180. * adding an epoll file descriptor inside itself.
  1181. */
  1182. error = -EINVAL;
  1183. if (file == tfile || !is_file_epoll(file))
  1184. goto error_tgt_fput;
  1185. /*
  1186. * At this point it is safe to assume that the "private_data" contains
  1187. * our own data structure.
  1188. */
  1189. ep = file->private_data;
  1190. /*
  1191. * When we insert an epoll file descriptor, inside another epoll file
  1192. * descriptor, there is the change of creating closed loops, which are
  1193. * better be handled here, than in more critical paths.
  1194. *
  1195. * We hold epmutex across the loop check and the insert in this case, in
  1196. * order to prevent two separate inserts from racing and each doing the
  1197. * insert "at the same time" such that ep_loop_check passes on both
  1198. * before either one does the insert, thereby creating a cycle.
  1199. */
  1200. if (unlikely(is_file_epoll(tfile) && op == EPOLL_CTL_ADD)) {
  1201. mutex_lock(&epmutex);
  1202. did_lock_epmutex = 1;
  1203. error = -ELOOP;
  1204. if (ep_loop_check(ep, tfile) != 0)
  1205. goto error_tgt_fput;
  1206. }
  1207. mutex_lock(&ep->mtx);
  1208. /*
  1209. * Try to lookup the file inside our RB tree, Since we grabbed "mtx"
  1210. * above, we can be sure to be able to use the item looked up by
  1211. * ep_find() till we release the mutex.
  1212. */
  1213. epi = ep_find(ep, tfile, fd);
  1214. error = -EINVAL;
  1215. switch (op) {
  1216. case EPOLL_CTL_ADD:
  1217. if (!epi) {
  1218. epds.events |= POLLERR | POLLHUP;
  1219. error = ep_insert(ep, &epds, tfile, fd);
  1220. } else
  1221. error = -EEXIST;
  1222. break;
  1223. case EPOLL_CTL_DEL:
  1224. if (epi)
  1225. error = ep_remove(ep, epi);
  1226. else
  1227. error = -ENOENT;
  1228. break;
  1229. case EPOLL_CTL_MOD:
  1230. if (epi) {
  1231. epds.events |= POLLERR | POLLHUP;
  1232. error = ep_modify(ep, epi, &epds);
  1233. } else
  1234. error = -ENOENT;
  1235. break;
  1236. }
  1237. mutex_unlock(&ep->mtx);
  1238. error_tgt_fput:
  1239. if (unlikely(did_lock_epmutex))
  1240. mutex_unlock(&epmutex);
  1241. fput(tfile);
  1242. error_fput:
  1243. fput(file);
  1244. error_return:
  1245. return error;
  1246. }
  1247. /*
  1248. * Implement the event wait interface for the eventpoll file. It is the kernel
  1249. * part of the user space epoll_wait(2).
  1250. */
  1251. SYSCALL_DEFINE4(epoll_wait, int, epfd, struct epoll_event __user *, events,
  1252. int, maxevents, int, timeout)
  1253. {
  1254. int error;
  1255. struct file *file;
  1256. struct eventpoll *ep;
  1257. /* The maximum number of event must be greater than zero */
  1258. if (maxevents <= 0 || maxevents > EP_MAX_EVENTS)
  1259. return -EINVAL;
  1260. /* Verify that the area passed by the user is writeable */
  1261. if (!access_ok(VERIFY_WRITE, events, maxevents * sizeof(struct epoll_event))) {
  1262. error = -EFAULT;
  1263. goto error_return;
  1264. }
  1265. /* Get the "struct file *" for the eventpoll file */
  1266. error = -EBADF;
  1267. file = fget(epfd);
  1268. if (!file)
  1269. goto error_return;
  1270. /*
  1271. * We have to check that the file structure underneath the fd
  1272. * the user passed to us _is_ an eventpoll file.
  1273. */
  1274. error = -EINVAL;
  1275. if (!is_file_epoll(file))
  1276. goto error_fput;
  1277. /*
  1278. * At this point it is safe to assume that the "private_data" contains
  1279. * our own data structure.
  1280. */
  1281. ep = file->private_data;
  1282. /* Time to fish for events ... */
  1283. error = ep_poll(ep, events, maxevents, timeout);
  1284. error_fput:
  1285. fput(file);
  1286. error_return:
  1287. return error;
  1288. }
  1289. #ifdef HAVE_SET_RESTORE_SIGMASK
  1290. /*
  1291. * Implement the event wait interface for the eventpoll file. It is the kernel
  1292. * part of the user space epoll_pwait(2).
  1293. */
  1294. SYSCALL_DEFINE6(epoll_pwait, int, epfd, struct epoll_event __user *, events,
  1295. int, maxevents, int, timeout, const sigset_t __user *, sigmask,
  1296. size_t, sigsetsize)
  1297. {
  1298. int error;
  1299. sigset_t ksigmask, sigsaved;
  1300. /*
  1301. * If the caller wants a certain signal mask to be set during the wait,
  1302. * we apply it here.
  1303. */
  1304. if (sigmask) {
  1305. if (sigsetsize != sizeof(sigset_t))
  1306. return -EINVAL;
  1307. if (copy_from_user(&ksigmask, sigmask, sizeof(ksigmask)))
  1308. return -EFAULT;
  1309. sigdelsetmask(&ksigmask, sigmask(SIGKILL) | sigmask(SIGSTOP));
  1310. sigprocmask(SIG_SETMASK, &ksigmask, &sigsaved);
  1311. }
  1312. error = sys_epoll_wait(epfd, events, maxevents, timeout);
  1313. /*
  1314. * If we changed the signal mask, we need to restore the original one.
  1315. * In case we've got a signal while waiting, we do not restore the
  1316. * signal mask yet, and we allow do_signal() to deliver the signal on
  1317. * the way back to userspace, before the signal mask is restored.
  1318. */
  1319. if (sigmask) {
  1320. if (error == -EINTR) {
  1321. memcpy(&current->saved_sigmask, &sigsaved,
  1322. sizeof(sigsaved));
  1323. set_restore_sigmask();
  1324. } else
  1325. sigprocmask(SIG_SETMASK, &sigsaved, NULL);
  1326. }
  1327. return error;
  1328. }
  1329. #endif /* HAVE_SET_RESTORE_SIGMASK */
  1330. static int __init eventpoll_init(void)
  1331. {
  1332. struct sysinfo si;
  1333. si_meminfo(&si);
  1334. /*
  1335. * Allows top 4% of lomem to be allocated for epoll watches (per user).
  1336. */
  1337. max_user_watches = (((si.totalram - si.totalhigh) / 25) << PAGE_SHIFT) /
  1338. EP_ITEM_COST;
  1339. BUG_ON(max_user_watches < 0);
  1340. /*
  1341. * Initialize the structure used to perform epoll file descriptor
  1342. * inclusion loops checks.
  1343. */
  1344. ep_nested_calls_init(&poll_loop_ncalls);
  1345. /* Initialize the structure used to perform safe poll wait head wake ups */
  1346. ep_nested_calls_init(&poll_safewake_ncalls);
  1347. /* Initialize the structure used to perform file's f_op->poll() calls */
  1348. ep_nested_calls_init(&poll_readywalk_ncalls);
  1349. /* Allocates slab cache used to allocate "struct epitem" items */
  1350. epi_cache = kmem_cache_create("eventpoll_epi", sizeof(struct epitem),
  1351. 0, SLAB_HWCACHE_ALIGN | SLAB_PANIC, NULL);
  1352. /* Allocates slab cache used to allocate "struct eppoll_entry" */
  1353. pwq_cache = kmem_cache_create("eventpoll_pwq",
  1354. sizeof(struct eppoll_entry), 0, SLAB_PANIC, NULL);
  1355. return 0;
  1356. }
  1357. fs_initcall(eventpoll_init);