eventpoll.c 64 KB

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