eventpoll.c 60 KB

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