eventpoll.c 58 KB

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