eventpoll.c 68 KB

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