eventpoll.c 43 KB

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