eventpoll.c 58 KB

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