eventpoll.c 70 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625
  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 (rwlock)
  48. *
  49. * The acquire order is the one listed above, from 1 to 3.
  50. * We need a rwlock (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. rwlock_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. /*
  187. * usage count, used together with epitem->dying to
  188. * orchestrate the disposal of this struct
  189. */
  190. refcount_t refcount;
  191. #ifdef CONFIG_NET_RX_BUSY_POLL
  192. /* used to track busy poll napi_id */
  193. unsigned int napi_id;
  194. /* busy poll timeout */
  195. u32 busy_poll_usecs;
  196. /* busy poll packet budget */
  197. u16 busy_poll_budget;
  198. bool prefer_busy_poll;
  199. #endif
  200. #ifdef CONFIG_DEBUG_LOCK_ALLOC
  201. /* tracks wakeup nests for lockdep validation */
  202. u8 nests;
  203. #endif
  204. };
  205. /* Wrapper struct used by poll queueing */
  206. struct ep_pqueue {
  207. poll_table pt;
  208. struct epitem *epi;
  209. };
  210. /*
  211. * Configuration options available inside /proc/sys/fs/epoll/
  212. */
  213. /* Maximum number of epoll watched descriptors, per user */
  214. static long max_user_watches __read_mostly;
  215. /* Used for cycles detection */
  216. static DEFINE_MUTEX(epnested_mutex);
  217. static u64 loop_check_gen = 0;
  218. /* Used to check for epoll file descriptor inclusion loops */
  219. static struct eventpoll *inserting_into;
  220. /* Slab cache used to allocate "struct epitem" */
  221. static struct kmem_cache *epi_cache __ro_after_init;
  222. /* Slab cache used to allocate "struct eppoll_entry" */
  223. static struct kmem_cache *pwq_cache __ro_after_init;
  224. /*
  225. * List of files with newly added links, where we may need to limit the number
  226. * of emanating paths. Protected by the epnested_mutex.
  227. */
  228. struct epitems_head {
  229. struct hlist_head epitems;
  230. struct epitems_head *next;
  231. };
  232. static struct epitems_head *tfile_check_list = EP_UNACTIVE_PTR;
  233. static struct kmem_cache *ephead_cache __ro_after_init;
  234. static inline void free_ephead(struct epitems_head *head)
  235. {
  236. if (head)
  237. kmem_cache_free(ephead_cache, head);
  238. }
  239. static void list_file(struct file *file)
  240. {
  241. struct epitems_head *head;
  242. head = container_of(file->f_ep, struct epitems_head, epitems);
  243. if (!head->next) {
  244. head->next = tfile_check_list;
  245. tfile_check_list = head;
  246. }
  247. }
  248. static void unlist_file(struct epitems_head *head)
  249. {
  250. struct epitems_head *to_free = head;
  251. struct hlist_node *p = rcu_dereference(hlist_first_rcu(&head->epitems));
  252. if (p) {
  253. struct epitem *epi= container_of(p, struct epitem, fllink);
  254. spin_lock(&epi->ffd.file->f_lock);
  255. if (!hlist_empty(&head->epitems))
  256. to_free = NULL;
  257. head->next = NULL;
  258. spin_unlock(&epi->ffd.file->f_lock);
  259. }
  260. free_ephead(to_free);
  261. }
  262. #ifdef CONFIG_SYSCTL
  263. #include <linux/sysctl.h>
  264. static long long_zero;
  265. static long long_max = LONG_MAX;
  266. static struct ctl_table epoll_table[] = {
  267. {
  268. .procname = "max_user_watches",
  269. .data = &max_user_watches,
  270. .maxlen = sizeof(max_user_watches),
  271. .mode = 0644,
  272. .proc_handler = proc_doulongvec_minmax,
  273. .extra1 = &long_zero,
  274. .extra2 = &long_max,
  275. },
  276. };
  277. static void __init epoll_sysctls_init(void)
  278. {
  279. register_sysctl("fs/epoll", epoll_table);
  280. }
  281. #else
  282. #define epoll_sysctls_init() do { } while (0)
  283. #endif /* CONFIG_SYSCTL */
  284. static const struct file_operations eventpoll_fops;
  285. static inline int is_file_epoll(struct file *f)
  286. {
  287. return f->f_op == &eventpoll_fops;
  288. }
  289. /* Setup the structure that is used as key for the RB tree */
  290. static inline void ep_set_ffd(struct epoll_filefd *ffd,
  291. struct file *file, int fd)
  292. {
  293. ffd->file = file;
  294. ffd->fd = fd;
  295. }
  296. /* Compare RB tree keys */
  297. static inline int ep_cmp_ffd(struct epoll_filefd *p1,
  298. struct epoll_filefd *p2)
  299. {
  300. return (p1->file > p2->file ? +1:
  301. (p1->file < p2->file ? -1 : p1->fd - p2->fd));
  302. }
  303. /* Tells us if the item is currently linked */
  304. static inline int ep_is_linked(struct epitem *epi)
  305. {
  306. return !list_empty(&epi->rdllink);
  307. }
  308. static inline struct eppoll_entry *ep_pwq_from_wait(wait_queue_entry_t *p)
  309. {
  310. return container_of(p, struct eppoll_entry, wait);
  311. }
  312. /* Get the "struct epitem" from a wait queue pointer */
  313. static inline struct epitem *ep_item_from_wait(wait_queue_entry_t *p)
  314. {
  315. return container_of(p, struct eppoll_entry, wait)->base;
  316. }
  317. /**
  318. * ep_events_available - Checks if ready events might be available.
  319. *
  320. * @ep: Pointer to the eventpoll context.
  321. *
  322. * Return: a value different than %zero if ready events are available,
  323. * or %zero otherwise.
  324. */
  325. static inline int ep_events_available(struct eventpoll *ep)
  326. {
  327. return !list_empty_careful(&ep->rdllist) ||
  328. READ_ONCE(ep->ovflist) != EP_UNACTIVE_PTR;
  329. }
  330. #ifdef CONFIG_NET_RX_BUSY_POLL
  331. /**
  332. * busy_loop_ep_timeout - check if busy poll has timed out. The timeout value
  333. * from the epoll instance ep is preferred, but if it is not set fallback to
  334. * the system-wide global via busy_loop_timeout.
  335. *
  336. * @start_time: The start time used to compute the remaining time until timeout.
  337. * @ep: Pointer to the eventpoll context.
  338. *
  339. * Return: true if the timeout has expired, false otherwise.
  340. */
  341. static bool busy_loop_ep_timeout(unsigned long start_time,
  342. struct eventpoll *ep)
  343. {
  344. unsigned long bp_usec = READ_ONCE(ep->busy_poll_usecs);
  345. if (bp_usec) {
  346. unsigned long end_time = start_time + bp_usec;
  347. unsigned long now = busy_loop_current_time();
  348. return time_after(now, end_time);
  349. } else {
  350. return busy_loop_timeout(start_time);
  351. }
  352. }
  353. static bool ep_busy_loop_on(struct eventpoll *ep)
  354. {
  355. return !!READ_ONCE(ep->busy_poll_usecs) || net_busy_loop_on();
  356. }
  357. static bool ep_busy_loop_end(void *p, unsigned long start_time)
  358. {
  359. struct eventpoll *ep = p;
  360. return ep_events_available(ep) || busy_loop_ep_timeout(start_time, ep);
  361. }
  362. /*
  363. * Busy poll if globally on and supporting sockets found && no events,
  364. * busy loop will return if need_resched or ep_events_available.
  365. *
  366. * we must do our busy polling with irqs enabled
  367. */
  368. static bool ep_busy_loop(struct eventpoll *ep, int nonblock)
  369. {
  370. unsigned int napi_id = READ_ONCE(ep->napi_id);
  371. u16 budget = READ_ONCE(ep->busy_poll_budget);
  372. bool prefer_busy_poll = READ_ONCE(ep->prefer_busy_poll);
  373. if (!budget)
  374. budget = BUSY_POLL_BUDGET;
  375. if (napi_id >= MIN_NAPI_ID && ep_busy_loop_on(ep)) {
  376. napi_busy_loop(napi_id, nonblock ? NULL : ep_busy_loop_end,
  377. ep, prefer_busy_poll, budget);
  378. if (ep_events_available(ep))
  379. return true;
  380. /*
  381. * Busy poll timed out. Drop NAPI ID for now, we can add
  382. * it back in when we have moved a socket with a valid NAPI
  383. * ID onto the ready list.
  384. */
  385. ep->napi_id = 0;
  386. return false;
  387. }
  388. return false;
  389. }
  390. /*
  391. * Set epoll busy poll NAPI ID from sk.
  392. */
  393. static inline void ep_set_busy_poll_napi_id(struct epitem *epi)
  394. {
  395. struct eventpoll *ep = epi->ep;
  396. unsigned int napi_id;
  397. struct socket *sock;
  398. struct sock *sk;
  399. if (!ep_busy_loop_on(ep))
  400. return;
  401. sock = sock_from_file(epi->ffd.file);
  402. if (!sock)
  403. return;
  404. sk = sock->sk;
  405. if (!sk)
  406. return;
  407. napi_id = READ_ONCE(sk->sk_napi_id);
  408. /* Non-NAPI IDs can be rejected
  409. * or
  410. * Nothing to do if we already have this ID
  411. */
  412. if (napi_id < MIN_NAPI_ID || napi_id == ep->napi_id)
  413. return;
  414. /* record NAPI ID for use in next busy poll */
  415. ep->napi_id = napi_id;
  416. }
  417. static long ep_eventpoll_bp_ioctl(struct file *file, unsigned int cmd,
  418. unsigned long arg)
  419. {
  420. struct eventpoll *ep = file->private_data;
  421. void __user *uarg = (void __user *)arg;
  422. struct epoll_params epoll_params;
  423. switch (cmd) {
  424. case EPIOCSPARAMS:
  425. if (copy_from_user(&epoll_params, uarg, sizeof(epoll_params)))
  426. return -EFAULT;
  427. /* pad byte must be zero */
  428. if (epoll_params.__pad)
  429. return -EINVAL;
  430. if (epoll_params.busy_poll_usecs > S32_MAX)
  431. return -EINVAL;
  432. if (epoll_params.prefer_busy_poll > 1)
  433. return -EINVAL;
  434. if (epoll_params.busy_poll_budget > NAPI_POLL_WEIGHT &&
  435. !capable(CAP_NET_ADMIN))
  436. return -EPERM;
  437. WRITE_ONCE(ep->busy_poll_usecs, epoll_params.busy_poll_usecs);
  438. WRITE_ONCE(ep->busy_poll_budget, epoll_params.busy_poll_budget);
  439. WRITE_ONCE(ep->prefer_busy_poll, epoll_params.prefer_busy_poll);
  440. return 0;
  441. case EPIOCGPARAMS:
  442. memset(&epoll_params, 0, sizeof(epoll_params));
  443. epoll_params.busy_poll_usecs = READ_ONCE(ep->busy_poll_usecs);
  444. epoll_params.busy_poll_budget = READ_ONCE(ep->busy_poll_budget);
  445. epoll_params.prefer_busy_poll = READ_ONCE(ep->prefer_busy_poll);
  446. if (copy_to_user(uarg, &epoll_params, sizeof(epoll_params)))
  447. return -EFAULT;
  448. return 0;
  449. default:
  450. return -ENOIOCTLCMD;
  451. }
  452. }
  453. #else
  454. static inline bool ep_busy_loop(struct eventpoll *ep, int nonblock)
  455. {
  456. return false;
  457. }
  458. static inline void ep_set_busy_poll_napi_id(struct epitem *epi)
  459. {
  460. }
  461. static long ep_eventpoll_bp_ioctl(struct file *file, unsigned int cmd,
  462. unsigned long arg)
  463. {
  464. return -EOPNOTSUPP;
  465. }
  466. #endif /* CONFIG_NET_RX_BUSY_POLL */
  467. /*
  468. * As described in commit 0ccf831cb lockdep: annotate epoll
  469. * the use of wait queues used by epoll is done in a very controlled
  470. * manner. Wake ups can nest inside each other, but are never done
  471. * with the same locking. For example:
  472. *
  473. * dfd = socket(...);
  474. * efd1 = epoll_create();
  475. * efd2 = epoll_create();
  476. * epoll_ctl(efd1, EPOLL_CTL_ADD, dfd, ...);
  477. * epoll_ctl(efd2, EPOLL_CTL_ADD, efd1, ...);
  478. *
  479. * When a packet arrives to the device underneath "dfd", the net code will
  480. * issue a wake_up() on its poll wake list. Epoll (efd1) has installed a
  481. * callback wakeup entry on that queue, and the wake_up() performed by the
  482. * "dfd" net code will end up in ep_poll_callback(). At this point epoll
  483. * (efd1) notices that it may have some event ready, so it needs to wake up
  484. * the waiters on its poll wait list (efd2). So it calls ep_poll_safewake()
  485. * that ends up in another wake_up(), after having checked about the
  486. * recursion constraints. That are, no more than EP_MAX_NESTS, to avoid
  487. * stack blasting.
  488. *
  489. * When CONFIG_DEBUG_LOCK_ALLOC is enabled, make sure lockdep can handle
  490. * this special case of epoll.
  491. */
  492. #ifdef CONFIG_DEBUG_LOCK_ALLOC
  493. static void ep_poll_safewake(struct eventpoll *ep, struct epitem *epi,
  494. unsigned pollflags)
  495. {
  496. struct eventpoll *ep_src;
  497. unsigned long flags;
  498. u8 nests = 0;
  499. /*
  500. * To set the subclass or nesting level for spin_lock_irqsave_nested()
  501. * it might be natural to create a per-cpu nest count. However, since
  502. * we can recurse on ep->poll_wait.lock, and a non-raw spinlock can
  503. * schedule() in the -rt kernel, the per-cpu variable are no longer
  504. * protected. Thus, we are introducing a per eventpoll nest field.
  505. * If we are not being call from ep_poll_callback(), epi is NULL and
  506. * we are at the first level of nesting, 0. Otherwise, we are being
  507. * called from ep_poll_callback() and if a previous wakeup source is
  508. * not an epoll file itself, we are at depth 1 since the wakeup source
  509. * is depth 0. If the wakeup source is a previous epoll file in the
  510. * wakeup chain then we use its nests value and record ours as
  511. * nests + 1. The previous epoll file nests value is stable since its
  512. * already holding its own poll_wait.lock.
  513. */
  514. if (epi) {
  515. if ((is_file_epoll(epi->ffd.file))) {
  516. ep_src = epi->ffd.file->private_data;
  517. nests = ep_src->nests;
  518. } else {
  519. nests = 1;
  520. }
  521. }
  522. spin_lock_irqsave_nested(&ep->poll_wait.lock, flags, nests);
  523. ep->nests = nests + 1;
  524. wake_up_locked_poll(&ep->poll_wait, EPOLLIN | pollflags);
  525. ep->nests = 0;
  526. spin_unlock_irqrestore(&ep->poll_wait.lock, flags);
  527. }
  528. #else
  529. static void ep_poll_safewake(struct eventpoll *ep, struct epitem *epi,
  530. __poll_t pollflags)
  531. {
  532. wake_up_poll(&ep->poll_wait, EPOLLIN | pollflags);
  533. }
  534. #endif
  535. static void ep_remove_wait_queue(struct eppoll_entry *pwq)
  536. {
  537. wait_queue_head_t *whead;
  538. rcu_read_lock();
  539. /*
  540. * If it is cleared by POLLFREE, it should be rcu-safe.
  541. * If we read NULL we need a barrier paired with
  542. * smp_store_release() in ep_poll_callback(), otherwise
  543. * we rely on whead->lock.
  544. */
  545. whead = smp_load_acquire(&pwq->whead);
  546. if (whead)
  547. remove_wait_queue(whead, &pwq->wait);
  548. rcu_read_unlock();
  549. }
  550. /*
  551. * This function unregisters poll callbacks from the associated file
  552. * descriptor. Must be called with "mtx" held.
  553. */
  554. static void ep_unregister_pollwait(struct eventpoll *ep, struct epitem *epi)
  555. {
  556. struct eppoll_entry **p = &epi->pwqlist;
  557. struct eppoll_entry *pwq;
  558. while ((pwq = *p) != NULL) {
  559. *p = pwq->next;
  560. ep_remove_wait_queue(pwq);
  561. kmem_cache_free(pwq_cache, pwq);
  562. }
  563. }
  564. /* call only when ep->mtx is held */
  565. static inline struct wakeup_source *ep_wakeup_source(struct epitem *epi)
  566. {
  567. return rcu_dereference_check(epi->ws, lockdep_is_held(&epi->ep->mtx));
  568. }
  569. /* call only when ep->mtx is held */
  570. static inline void ep_pm_stay_awake(struct epitem *epi)
  571. {
  572. struct wakeup_source *ws = ep_wakeup_source(epi);
  573. if (ws)
  574. __pm_stay_awake(ws);
  575. }
  576. static inline bool ep_has_wakeup_source(struct epitem *epi)
  577. {
  578. return rcu_access_pointer(epi->ws) ? true : false;
  579. }
  580. /* call when ep->mtx cannot be held (ep_poll_callback) */
  581. static inline void ep_pm_stay_awake_rcu(struct epitem *epi)
  582. {
  583. struct wakeup_source *ws;
  584. rcu_read_lock();
  585. ws = rcu_dereference(epi->ws);
  586. if (ws)
  587. __pm_stay_awake(ws);
  588. rcu_read_unlock();
  589. }
  590. /*
  591. * ep->mutex needs to be held because we could be hit by
  592. * eventpoll_release_file() and epoll_ctl().
  593. */
  594. static void ep_start_scan(struct eventpoll *ep, struct list_head *txlist)
  595. {
  596. /*
  597. * Steal the ready list, and re-init the original one to the
  598. * empty list. Also, set ep->ovflist to NULL so that events
  599. * happening while looping w/out locks, are not lost. We cannot
  600. * have the poll callback to queue directly on ep->rdllist,
  601. * because we want the "sproc" callback to be able to do it
  602. * in a lockless way.
  603. */
  604. lockdep_assert_irqs_enabled();
  605. write_lock_irq(&ep->lock);
  606. list_splice_init(&ep->rdllist, txlist);
  607. WRITE_ONCE(ep->ovflist, NULL);
  608. write_unlock_irq(&ep->lock);
  609. }
  610. static void ep_done_scan(struct eventpoll *ep,
  611. struct list_head *txlist)
  612. {
  613. struct epitem *epi, *nepi;
  614. write_lock_irq(&ep->lock);
  615. /*
  616. * During the time we spent inside the "sproc" callback, some
  617. * other events might have been queued by the poll callback.
  618. * We re-insert them inside the main ready-list here.
  619. */
  620. for (nepi = READ_ONCE(ep->ovflist); (epi = nepi) != NULL;
  621. nepi = epi->next, epi->next = EP_UNACTIVE_PTR) {
  622. /*
  623. * We need to check if the item is already in the list.
  624. * During the "sproc" callback execution time, items are
  625. * queued into ->ovflist but the "txlist" might already
  626. * contain them, and the list_splice() below takes care of them.
  627. */
  628. if (!ep_is_linked(epi)) {
  629. /*
  630. * ->ovflist is LIFO, so we have to reverse it in order
  631. * to keep in FIFO.
  632. */
  633. list_add(&epi->rdllink, &ep->rdllist);
  634. ep_pm_stay_awake(epi);
  635. }
  636. }
  637. /*
  638. * We need to set back ep->ovflist to EP_UNACTIVE_PTR, so that after
  639. * releasing the lock, events will be queued in the normal way inside
  640. * ep->rdllist.
  641. */
  642. WRITE_ONCE(ep->ovflist, EP_UNACTIVE_PTR);
  643. /*
  644. * Quickly re-inject items left on "txlist".
  645. */
  646. list_splice(txlist, &ep->rdllist);
  647. __pm_relax(ep->ws);
  648. if (!list_empty(&ep->rdllist)) {
  649. if (waitqueue_active(&ep->wq))
  650. wake_up(&ep->wq);
  651. }
  652. write_unlock_irq(&ep->lock);
  653. }
  654. static void ep_get(struct eventpoll *ep)
  655. {
  656. refcount_inc(&ep->refcount);
  657. }
  658. /*
  659. * Returns true if the event poll can be disposed
  660. */
  661. static bool ep_refcount_dec_and_test(struct eventpoll *ep)
  662. {
  663. if (!refcount_dec_and_test(&ep->refcount))
  664. return false;
  665. WARN_ON_ONCE(!RB_EMPTY_ROOT(&ep->rbr.rb_root));
  666. return true;
  667. }
  668. static void ep_free(struct eventpoll *ep)
  669. {
  670. mutex_destroy(&ep->mtx);
  671. free_uid(ep->user);
  672. wakeup_source_unregister(ep->ws);
  673. kfree(ep);
  674. }
  675. /*
  676. * Removes a "struct epitem" from the eventpoll RB tree and deallocates
  677. * all the associated resources. Must be called with "mtx" held.
  678. * If the dying flag is set, do the removal only if force is true.
  679. * This prevents ep_clear_and_put() from dropping all the ep references
  680. * while running concurrently with eventpoll_release_file().
  681. * Returns true if the eventpoll can be disposed.
  682. */
  683. static bool __ep_remove(struct eventpoll *ep, struct epitem *epi, bool force)
  684. {
  685. struct file *file = epi->ffd.file;
  686. struct epitems_head *to_free;
  687. struct hlist_head *head;
  688. lockdep_assert_irqs_enabled();
  689. /*
  690. * Removes poll wait queue hooks.
  691. */
  692. ep_unregister_pollwait(ep, epi);
  693. /* Remove the current item from the list of epoll hooks */
  694. spin_lock(&file->f_lock);
  695. if (epi->dying && !force) {
  696. spin_unlock(&file->f_lock);
  697. return false;
  698. }
  699. to_free = NULL;
  700. head = file->f_ep;
  701. if (head->first == &epi->fllink && !epi->fllink.next) {
  702. /* See eventpoll_release() for details. */
  703. WRITE_ONCE(file->f_ep, NULL);
  704. if (!is_file_epoll(file)) {
  705. struct epitems_head *v;
  706. v = container_of(head, struct epitems_head, epitems);
  707. if (!smp_load_acquire(&v->next))
  708. to_free = v;
  709. }
  710. }
  711. hlist_del_rcu(&epi->fllink);
  712. spin_unlock(&file->f_lock);
  713. free_ephead(to_free);
  714. rb_erase_cached(&epi->rbn, &ep->rbr);
  715. write_lock_irq(&ep->lock);
  716. if (ep_is_linked(epi))
  717. list_del_init(&epi->rdllink);
  718. write_unlock_irq(&ep->lock);
  719. wakeup_source_unregister(ep_wakeup_source(epi));
  720. /*
  721. * At this point it is safe to free the eventpoll item. Use the union
  722. * field epi->rcu, since we are trying to minimize the size of
  723. * 'struct epitem'. The 'rbn' field is no longer in use. Protected by
  724. * ep->mtx. The rcu read side, reverse_path_check_proc(), does not make
  725. * use of the rbn field.
  726. */
  727. kfree_rcu(epi, rcu);
  728. percpu_counter_dec(&ep->user->epoll_watches);
  729. return ep_refcount_dec_and_test(ep);
  730. }
  731. /*
  732. * ep_remove variant for callers owing an additional reference to the ep
  733. */
  734. static void ep_remove_safe(struct eventpoll *ep, struct epitem *epi)
  735. {
  736. WARN_ON_ONCE(__ep_remove(ep, epi, false));
  737. }
  738. static void ep_clear_and_put(struct eventpoll *ep)
  739. {
  740. struct rb_node *rbp, *next;
  741. struct epitem *epi;
  742. bool dispose;
  743. /* We need to release all tasks waiting for these file */
  744. if (waitqueue_active(&ep->poll_wait))
  745. ep_poll_safewake(ep, NULL, 0);
  746. mutex_lock(&ep->mtx);
  747. /*
  748. * Walks through the whole tree by unregistering poll callbacks.
  749. */
  750. for (rbp = rb_first_cached(&ep->rbr); rbp; rbp = rb_next(rbp)) {
  751. epi = rb_entry(rbp, struct epitem, rbn);
  752. ep_unregister_pollwait(ep, epi);
  753. cond_resched();
  754. }
  755. /*
  756. * Walks through the whole tree and try to free each "struct epitem".
  757. * Note that ep_remove_safe() will not remove the epitem in case of a
  758. * racing eventpoll_release_file(); the latter will do the removal.
  759. * At this point we are sure no poll callbacks will be lingering around.
  760. * Since we still own a reference to the eventpoll struct, the loop can't
  761. * dispose it.
  762. */
  763. for (rbp = rb_first_cached(&ep->rbr); rbp; rbp = next) {
  764. next = rb_next(rbp);
  765. epi = rb_entry(rbp, struct epitem, rbn);
  766. ep_remove_safe(ep, epi);
  767. cond_resched();
  768. }
  769. dispose = ep_refcount_dec_and_test(ep);
  770. mutex_unlock(&ep->mtx);
  771. if (dispose)
  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)
  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. rwlock_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. * Adds a new entry to the tail of the list in a lockless way, i.e.
  1036. * multiple CPUs are allowed to call this function concurrently.
  1037. *
  1038. * Beware: it is necessary to prevent any other modifications of the
  1039. * existing list until all changes are completed, in other words
  1040. * concurrent list_add_tail_lockless() calls should be protected
  1041. * with a read lock, where write lock acts as a barrier which
  1042. * makes sure all list_add_tail_lockless() calls are fully
  1043. * completed.
  1044. *
  1045. * Also an element can be locklessly added to the list only in one
  1046. * direction i.e. either to the tail or to the head, otherwise
  1047. * concurrent access will corrupt the list.
  1048. *
  1049. * Return: %false if element has been already added to the list, %true
  1050. * otherwise.
  1051. */
  1052. static inline bool list_add_tail_lockless(struct list_head *new,
  1053. struct list_head *head)
  1054. {
  1055. struct list_head *prev;
  1056. /*
  1057. * This is simple 'new->next = head' operation, but cmpxchg()
  1058. * is used in order to detect that same element has been just
  1059. * added to the list from another CPU: the winner observes
  1060. * new->next == new.
  1061. */
  1062. if (!try_cmpxchg(&new->next, &new, head))
  1063. return false;
  1064. /*
  1065. * Initially ->next of a new element must be updated with the head
  1066. * (we are inserting to the tail) and only then pointers are atomically
  1067. * exchanged. XCHG guarantees memory ordering, thus ->next should be
  1068. * updated before pointers are actually swapped and pointers are
  1069. * swapped before prev->next is updated.
  1070. */
  1071. prev = xchg(&head->prev, new);
  1072. /*
  1073. * It is safe to modify prev->next and new->prev, because a new element
  1074. * is added only to the tail and new->next is updated before XCHG.
  1075. */
  1076. prev->next = new;
  1077. new->prev = prev;
  1078. return true;
  1079. }
  1080. /*
  1081. * Chains a new epi entry to the tail of the ep->ovflist in a lockless way,
  1082. * i.e. multiple CPUs are allowed to call this function concurrently.
  1083. *
  1084. * Return: %false if epi element has been already chained, %true otherwise.
  1085. */
  1086. static inline bool chain_epi_lockless(struct epitem *epi)
  1087. {
  1088. struct eventpoll *ep = epi->ep;
  1089. /* Fast preliminary check */
  1090. if (epi->next != EP_UNACTIVE_PTR)
  1091. return false;
  1092. /* Check that the same epi has not been just chained from another CPU */
  1093. if (cmpxchg(&epi->next, EP_UNACTIVE_PTR, NULL) != EP_UNACTIVE_PTR)
  1094. return false;
  1095. /* Atomically exchange tail */
  1096. epi->next = xchg(&ep->ovflist, epi);
  1097. return true;
  1098. }
  1099. /*
  1100. * This is the callback that is passed to the wait queue wakeup
  1101. * mechanism. It is called by the stored file descriptors when they
  1102. * have events to report.
  1103. *
  1104. * This callback takes a read lock in order not to contend with concurrent
  1105. * events from another file descriptor, thus all modifications to ->rdllist
  1106. * or ->ovflist are lockless. Read lock is paired with the write lock from
  1107. * ep_start/done_scan(), which stops all list modifications and guarantees
  1108. * that lists state is seen correctly.
  1109. *
  1110. * Another thing worth to mention is that ep_poll_callback() can be called
  1111. * concurrently for the same @epi from different CPUs if poll table was inited
  1112. * with several wait queues entries. Plural wakeup from different CPUs of a
  1113. * single wait queue is serialized by wq.lock, but the case when multiple wait
  1114. * queues are used should be detected accordingly. This is detected using
  1115. * cmpxchg() operation.
  1116. */
  1117. static int ep_poll_callback(wait_queue_entry_t *wait, unsigned mode, int sync, void *key)
  1118. {
  1119. int pwake = 0;
  1120. struct epitem *epi = ep_item_from_wait(wait);
  1121. struct eventpoll *ep = epi->ep;
  1122. __poll_t pollflags = key_to_poll(key);
  1123. unsigned long flags;
  1124. int ewake = 0;
  1125. read_lock_irqsave(&ep->lock, flags);
  1126. ep_set_busy_poll_napi_id(epi);
  1127. /*
  1128. * If the event mask does not contain any poll(2) event, we consider the
  1129. * descriptor to be disabled. This condition is likely the effect of the
  1130. * EPOLLONESHOT bit that disables the descriptor when an event is received,
  1131. * until the next EPOLL_CTL_MOD will be issued.
  1132. */
  1133. if (!(epi->event.events & ~EP_PRIVATE_BITS))
  1134. goto out_unlock;
  1135. /*
  1136. * Check the events coming with the callback. At this stage, not
  1137. * every device reports the events in the "key" parameter of the
  1138. * callback. We need to be able to handle both cases here, hence the
  1139. * test for "key" != NULL before the event match test.
  1140. */
  1141. if (pollflags && !(pollflags & epi->event.events))
  1142. goto out_unlock;
  1143. /*
  1144. * If we are transferring events to userspace, we can hold no locks
  1145. * (because we're accessing user memory, and because of linux f_op->poll()
  1146. * semantics). All the events that happen during that period of time are
  1147. * chained in ep->ovflist and requeued later on.
  1148. */
  1149. if (READ_ONCE(ep->ovflist) != EP_UNACTIVE_PTR) {
  1150. if (chain_epi_lockless(epi))
  1151. ep_pm_stay_awake_rcu(epi);
  1152. } else if (!ep_is_linked(epi)) {
  1153. /* In the usual case, add event to ready list. */
  1154. if (list_add_tail_lockless(&epi->rdllink, &ep->rdllist))
  1155. ep_pm_stay_awake_rcu(epi);
  1156. }
  1157. /*
  1158. * Wake up ( if active ) both the eventpoll wait list and the ->poll()
  1159. * wait list.
  1160. */
  1161. if (waitqueue_active(&ep->wq)) {
  1162. if ((epi->event.events & EPOLLEXCLUSIVE) &&
  1163. !(pollflags & POLLFREE)) {
  1164. switch (pollflags & EPOLLINOUT_BITS) {
  1165. case EPOLLIN:
  1166. if (epi->event.events & EPOLLIN)
  1167. ewake = 1;
  1168. break;
  1169. case EPOLLOUT:
  1170. if (epi->event.events & EPOLLOUT)
  1171. ewake = 1;
  1172. break;
  1173. case 0:
  1174. ewake = 1;
  1175. break;
  1176. }
  1177. }
  1178. if (sync)
  1179. wake_up_sync(&ep->wq);
  1180. else
  1181. wake_up(&ep->wq);
  1182. }
  1183. if (waitqueue_active(&ep->poll_wait))
  1184. pwake++;
  1185. out_unlock:
  1186. read_unlock_irqrestore(&ep->lock, flags);
  1187. /* We have to call this outside the lock */
  1188. if (pwake)
  1189. ep_poll_safewake(ep, epi, pollflags & EPOLL_URING_WAKE);
  1190. if (!(epi->event.events & EPOLLEXCLUSIVE))
  1191. ewake = 1;
  1192. if (pollflags & POLLFREE) {
  1193. /*
  1194. * If we race with ep_remove_wait_queue() it can miss
  1195. * ->whead = NULL and do another remove_wait_queue() after
  1196. * us, so we can't use __remove_wait_queue().
  1197. */
  1198. list_del_init(&wait->entry);
  1199. /*
  1200. * ->whead != NULL protects us from the race with
  1201. * ep_clear_and_put() or ep_remove(), ep_remove_wait_queue()
  1202. * takes whead->lock held by the caller. Once we nullify it,
  1203. * nothing protects ep/epi or even wait.
  1204. */
  1205. smp_store_release(&ep_pwq_from_wait(wait)->whead, NULL);
  1206. }
  1207. return ewake;
  1208. }
  1209. /*
  1210. * This is the callback that is used to add our wait queue to the
  1211. * target file wakeup lists.
  1212. */
  1213. static void ep_ptable_queue_proc(struct file *file, wait_queue_head_t *whead,
  1214. poll_table *pt)
  1215. {
  1216. struct ep_pqueue *epq = container_of(pt, struct ep_pqueue, pt);
  1217. struct epitem *epi = epq->epi;
  1218. struct eppoll_entry *pwq;
  1219. if (unlikely(!epi)) // an earlier allocation has failed
  1220. return;
  1221. pwq = kmem_cache_alloc(pwq_cache, GFP_KERNEL);
  1222. if (unlikely(!pwq)) {
  1223. epq->epi = NULL;
  1224. return;
  1225. }
  1226. init_waitqueue_func_entry(&pwq->wait, ep_poll_callback);
  1227. pwq->whead = whead;
  1228. pwq->base = epi;
  1229. if (epi->event.events & EPOLLEXCLUSIVE)
  1230. add_wait_queue_exclusive(whead, &pwq->wait);
  1231. else
  1232. add_wait_queue(whead, &pwq->wait);
  1233. pwq->next = epi->pwqlist;
  1234. epi->pwqlist = pwq;
  1235. }
  1236. static void ep_rbtree_insert(struct eventpoll *ep, struct epitem *epi)
  1237. {
  1238. int kcmp;
  1239. struct rb_node **p = &ep->rbr.rb_root.rb_node, *parent = NULL;
  1240. struct epitem *epic;
  1241. bool leftmost = true;
  1242. while (*p) {
  1243. parent = *p;
  1244. epic = rb_entry(parent, struct epitem, rbn);
  1245. kcmp = ep_cmp_ffd(&epi->ffd, &epic->ffd);
  1246. if (kcmp > 0) {
  1247. p = &parent->rb_right;
  1248. leftmost = false;
  1249. } else
  1250. p = &parent->rb_left;
  1251. }
  1252. rb_link_node(&epi->rbn, parent, p);
  1253. rb_insert_color_cached(&epi->rbn, &ep->rbr, leftmost);
  1254. }
  1255. #define PATH_ARR_SIZE 5
  1256. /*
  1257. * These are the number paths of length 1 to 5, that we are allowing to emanate
  1258. * from a single file of interest. For example, we allow 1000 paths of length
  1259. * 1, to emanate from each file of interest. This essentially represents the
  1260. * potential wakeup paths, which need to be limited in order to avoid massive
  1261. * uncontrolled wakeup storms. The common use case should be a single ep which
  1262. * is connected to n file sources. In this case each file source has 1 path
  1263. * of length 1. Thus, the numbers below should be more than sufficient. These
  1264. * path limits are enforced during an EPOLL_CTL_ADD operation, since a modify
  1265. * and delete can't add additional paths. Protected by the epnested_mutex.
  1266. */
  1267. static const int path_limits[PATH_ARR_SIZE] = { 1000, 500, 100, 50, 10 };
  1268. static int path_count[PATH_ARR_SIZE];
  1269. static int path_count_inc(int nests)
  1270. {
  1271. /* Allow an arbitrary number of depth 1 paths */
  1272. if (nests == 0)
  1273. return 0;
  1274. if (++path_count[nests] > path_limits[nests])
  1275. return -1;
  1276. return 0;
  1277. }
  1278. static void path_count_init(void)
  1279. {
  1280. int i;
  1281. for (i = 0; i < PATH_ARR_SIZE; i++)
  1282. path_count[i] = 0;
  1283. }
  1284. static int reverse_path_check_proc(struct hlist_head *refs, int depth)
  1285. {
  1286. int error = 0;
  1287. struct epitem *epi;
  1288. if (depth > EP_MAX_NESTS) /* too deep nesting */
  1289. return -1;
  1290. /* CTL_DEL can remove links here, but that can't increase our count */
  1291. hlist_for_each_entry_rcu(epi, refs, fllink) {
  1292. struct hlist_head *refs = &epi->ep->refs;
  1293. if (hlist_empty(refs))
  1294. error = path_count_inc(depth);
  1295. else
  1296. error = reverse_path_check_proc(refs, depth + 1);
  1297. if (error != 0)
  1298. break;
  1299. }
  1300. return error;
  1301. }
  1302. /**
  1303. * reverse_path_check - The tfile_check_list is list of epitem_head, which have
  1304. * links that are proposed to be newly added. We need to
  1305. * make sure that those added links don't add too many
  1306. * paths such that we will spend all our time waking up
  1307. * eventpoll objects.
  1308. *
  1309. * Return: %zero if the proposed links don't create too many paths,
  1310. * %-1 otherwise.
  1311. */
  1312. static int reverse_path_check(void)
  1313. {
  1314. struct epitems_head *p;
  1315. for (p = tfile_check_list; p != EP_UNACTIVE_PTR; p = p->next) {
  1316. int error;
  1317. path_count_init();
  1318. rcu_read_lock();
  1319. error = reverse_path_check_proc(&p->epitems, 0);
  1320. rcu_read_unlock();
  1321. if (error)
  1322. return error;
  1323. }
  1324. return 0;
  1325. }
  1326. static int ep_create_wakeup_source(struct epitem *epi)
  1327. {
  1328. struct name_snapshot n;
  1329. struct wakeup_source *ws;
  1330. if (!epi->ep->ws) {
  1331. epi->ep->ws = wakeup_source_register(NULL, "eventpoll");
  1332. if (!epi->ep->ws)
  1333. return -ENOMEM;
  1334. }
  1335. take_dentry_name_snapshot(&n, epi->ffd.file->f_path.dentry);
  1336. ws = wakeup_source_register(NULL, n.name.name);
  1337. release_dentry_name_snapshot(&n);
  1338. if (!ws)
  1339. return -ENOMEM;
  1340. rcu_assign_pointer(epi->ws, ws);
  1341. return 0;
  1342. }
  1343. /* rare code path, only used when EPOLL_CTL_MOD removes a wakeup source */
  1344. static noinline void ep_destroy_wakeup_source(struct epitem *epi)
  1345. {
  1346. struct wakeup_source *ws = ep_wakeup_source(epi);
  1347. RCU_INIT_POINTER(epi->ws, NULL);
  1348. /*
  1349. * wait for ep_pm_stay_awake_rcu to finish, synchronize_rcu is
  1350. * used internally by wakeup_source_remove, too (called by
  1351. * wakeup_source_unregister), so we cannot use call_rcu
  1352. */
  1353. synchronize_rcu();
  1354. wakeup_source_unregister(ws);
  1355. }
  1356. static int attach_epitem(struct file *file, struct epitem *epi)
  1357. {
  1358. struct epitems_head *to_free = NULL;
  1359. struct hlist_head *head = NULL;
  1360. struct eventpoll *ep = NULL;
  1361. if (is_file_epoll(file))
  1362. ep = file->private_data;
  1363. if (ep) {
  1364. head = &ep->refs;
  1365. } else if (!READ_ONCE(file->f_ep)) {
  1366. allocate:
  1367. to_free = kmem_cache_zalloc(ephead_cache, GFP_KERNEL);
  1368. if (!to_free)
  1369. return -ENOMEM;
  1370. head = &to_free->epitems;
  1371. }
  1372. spin_lock(&file->f_lock);
  1373. if (!file->f_ep) {
  1374. if (unlikely(!head)) {
  1375. spin_unlock(&file->f_lock);
  1376. goto allocate;
  1377. }
  1378. /* See eventpoll_release() for details. */
  1379. WRITE_ONCE(file->f_ep, head);
  1380. to_free = NULL;
  1381. }
  1382. hlist_add_head_rcu(&epi->fllink, file->f_ep);
  1383. spin_unlock(&file->f_lock);
  1384. free_ephead(to_free);
  1385. return 0;
  1386. }
  1387. /*
  1388. * Must be called with "mtx" held.
  1389. */
  1390. static int ep_insert(struct eventpoll *ep, const struct epoll_event *event,
  1391. struct file *tfile, int fd, int full_check)
  1392. {
  1393. int error, pwake = 0;
  1394. __poll_t revents;
  1395. struct epitem *epi;
  1396. struct ep_pqueue epq;
  1397. struct eventpoll *tep = NULL;
  1398. if (is_file_epoll(tfile))
  1399. tep = tfile->private_data;
  1400. lockdep_assert_irqs_enabled();
  1401. if (unlikely(percpu_counter_compare(&ep->user->epoll_watches,
  1402. max_user_watches) >= 0))
  1403. return -ENOSPC;
  1404. percpu_counter_inc(&ep->user->epoll_watches);
  1405. if (!(epi = kmem_cache_zalloc(epi_cache, GFP_KERNEL))) {
  1406. percpu_counter_dec(&ep->user->epoll_watches);
  1407. return -ENOMEM;
  1408. }
  1409. /* Item initialization follow here ... */
  1410. INIT_LIST_HEAD(&epi->rdllink);
  1411. epi->ep = ep;
  1412. ep_set_ffd(&epi->ffd, tfile, fd);
  1413. epi->event = *event;
  1414. epi->next = EP_UNACTIVE_PTR;
  1415. if (tep)
  1416. mutex_lock_nested(&tep->mtx, 1);
  1417. /* Add the current item to the list of active epoll hook for this file */
  1418. if (unlikely(attach_epitem(tfile, epi) < 0)) {
  1419. if (tep)
  1420. mutex_unlock(&tep->mtx);
  1421. kmem_cache_free(epi_cache, epi);
  1422. percpu_counter_dec(&ep->user->epoll_watches);
  1423. return -ENOMEM;
  1424. }
  1425. if (full_check && !tep)
  1426. list_file(tfile);
  1427. /*
  1428. * Add the current item to the RB tree. All RB tree operations are
  1429. * protected by "mtx", and ep_insert() is called with "mtx" held.
  1430. */
  1431. ep_rbtree_insert(ep, epi);
  1432. if (tep)
  1433. mutex_unlock(&tep->mtx);
  1434. /*
  1435. * ep_remove_safe() calls in the later error paths can't lead to
  1436. * ep_free() as the ep file itself still holds an ep reference.
  1437. */
  1438. ep_get(ep);
  1439. /* now check if we've created too many backpaths */
  1440. if (unlikely(full_check && reverse_path_check())) {
  1441. ep_remove_safe(ep, epi);
  1442. return -EINVAL;
  1443. }
  1444. if (epi->event.events & EPOLLWAKEUP) {
  1445. error = ep_create_wakeup_source(epi);
  1446. if (error) {
  1447. ep_remove_safe(ep, epi);
  1448. return error;
  1449. }
  1450. }
  1451. /* Initialize the poll table using the queue callback */
  1452. epq.epi = epi;
  1453. init_poll_funcptr(&epq.pt, ep_ptable_queue_proc);
  1454. /*
  1455. * Attach the item to the poll hooks and get current event bits.
  1456. * We can safely use the file* here because its usage count has
  1457. * been increased by the caller of this function. Note that after
  1458. * this operation completes, the poll callback can start hitting
  1459. * the new item.
  1460. */
  1461. revents = ep_item_poll(epi, &epq.pt, 1);
  1462. /*
  1463. * We have to check if something went wrong during the poll wait queue
  1464. * install process. Namely an allocation for a wait queue failed due
  1465. * high memory pressure.
  1466. */
  1467. if (unlikely(!epq.epi)) {
  1468. ep_remove_safe(ep, epi);
  1469. return -ENOMEM;
  1470. }
  1471. /* We have to drop the new item inside our item list to keep track of it */
  1472. write_lock_irq(&ep->lock);
  1473. /* record NAPI ID of new item if present */
  1474. ep_set_busy_poll_napi_id(epi);
  1475. /* If the file is already "ready" we drop it inside the ready list */
  1476. if (revents && !ep_is_linked(epi)) {
  1477. list_add_tail(&epi->rdllink, &ep->rdllist);
  1478. ep_pm_stay_awake(epi);
  1479. /* Notify waiting tasks that events are available */
  1480. if (waitqueue_active(&ep->wq))
  1481. wake_up(&ep->wq);
  1482. if (waitqueue_active(&ep->poll_wait))
  1483. pwake++;
  1484. }
  1485. write_unlock_irq(&ep->lock);
  1486. /* We have to call this outside the lock */
  1487. if (pwake)
  1488. ep_poll_safewake(ep, NULL, 0);
  1489. return 0;
  1490. }
  1491. /*
  1492. * Modify the interest event mask by dropping an event if the new mask
  1493. * has a match in the current file status. Must be called with "mtx" held.
  1494. */
  1495. static int ep_modify(struct eventpoll *ep, struct epitem *epi,
  1496. const struct epoll_event *event)
  1497. {
  1498. int pwake = 0;
  1499. poll_table pt;
  1500. lockdep_assert_irqs_enabled();
  1501. init_poll_funcptr(&pt, NULL);
  1502. /*
  1503. * Set the new event interest mask before calling f_op->poll();
  1504. * otherwise we might miss an event that happens between the
  1505. * f_op->poll() call and the new event set registering.
  1506. */
  1507. epi->event.events = event->events; /* need barrier below */
  1508. epi->event.data = event->data; /* protected by mtx */
  1509. if (epi->event.events & EPOLLWAKEUP) {
  1510. if (!ep_has_wakeup_source(epi))
  1511. ep_create_wakeup_source(epi);
  1512. } else if (ep_has_wakeup_source(epi)) {
  1513. ep_destroy_wakeup_source(epi);
  1514. }
  1515. /*
  1516. * The following barrier has two effects:
  1517. *
  1518. * 1) Flush epi changes above to other CPUs. This ensures
  1519. * we do not miss events from ep_poll_callback if an
  1520. * event occurs immediately after we call f_op->poll().
  1521. * We need this because we did not take ep->lock while
  1522. * changing epi above (but ep_poll_callback does take
  1523. * ep->lock).
  1524. *
  1525. * 2) We also need to ensure we do not miss _past_ events
  1526. * when calling f_op->poll(). This barrier also
  1527. * pairs with the barrier in wq_has_sleeper (see
  1528. * comments for wq_has_sleeper).
  1529. *
  1530. * This barrier will now guarantee ep_poll_callback or f_op->poll
  1531. * (or both) will notice the readiness of an item.
  1532. */
  1533. smp_mb();
  1534. /*
  1535. * Get current event bits. We can safely use the file* here because
  1536. * its usage count has been increased by the caller of this function.
  1537. * If the item is "hot" and it is not registered inside the ready
  1538. * list, push it inside.
  1539. */
  1540. if (ep_item_poll(epi, &pt, 1)) {
  1541. write_lock_irq(&ep->lock);
  1542. if (!ep_is_linked(epi)) {
  1543. list_add_tail(&epi->rdllink, &ep->rdllist);
  1544. ep_pm_stay_awake(epi);
  1545. /* Notify waiting tasks that events are available */
  1546. if (waitqueue_active(&ep->wq))
  1547. wake_up(&ep->wq);
  1548. if (waitqueue_active(&ep->poll_wait))
  1549. pwake++;
  1550. }
  1551. write_unlock_irq(&ep->lock);
  1552. }
  1553. /* We have to call this outside the lock */
  1554. if (pwake)
  1555. ep_poll_safewake(ep, NULL, 0);
  1556. return 0;
  1557. }
  1558. static int ep_send_events(struct eventpoll *ep,
  1559. struct epoll_event __user *events, int maxevents)
  1560. {
  1561. struct epitem *epi, *tmp;
  1562. LIST_HEAD(txlist);
  1563. poll_table pt;
  1564. int res = 0;
  1565. /*
  1566. * Always short-circuit for fatal signals to allow threads to make a
  1567. * timely exit without the chance of finding more events available and
  1568. * fetching repeatedly.
  1569. */
  1570. if (fatal_signal_pending(current))
  1571. return -EINTR;
  1572. init_poll_funcptr(&pt, NULL);
  1573. mutex_lock(&ep->mtx);
  1574. ep_start_scan(ep, &txlist);
  1575. /*
  1576. * We can loop without lock because we are passed a task private list.
  1577. * Items cannot vanish during the loop we are holding ep->mtx.
  1578. */
  1579. list_for_each_entry_safe(epi, tmp, &txlist, rdllink) {
  1580. struct wakeup_source *ws;
  1581. __poll_t revents;
  1582. if (res >= maxevents)
  1583. break;
  1584. /*
  1585. * Activate ep->ws before deactivating epi->ws to prevent
  1586. * triggering auto-suspend here (in case we reactive epi->ws
  1587. * below).
  1588. *
  1589. * This could be rearranged to delay the deactivation of epi->ws
  1590. * instead, but then epi->ws would temporarily be out of sync
  1591. * with ep_is_linked().
  1592. */
  1593. ws = ep_wakeup_source(epi);
  1594. if (ws) {
  1595. if (ws->active)
  1596. __pm_stay_awake(ep->ws);
  1597. __pm_relax(ws);
  1598. }
  1599. list_del_init(&epi->rdllink);
  1600. /*
  1601. * If the event mask intersect the caller-requested one,
  1602. * deliver the event to userspace. Again, we are holding ep->mtx,
  1603. * so no operations coming from userspace can change the item.
  1604. */
  1605. revents = ep_item_poll(epi, &pt, 1);
  1606. if (!revents)
  1607. continue;
  1608. events = epoll_put_uevent(revents, epi->event.data, events);
  1609. if (!events) {
  1610. list_add(&epi->rdllink, &txlist);
  1611. ep_pm_stay_awake(epi);
  1612. if (!res)
  1613. res = -EFAULT;
  1614. break;
  1615. }
  1616. res++;
  1617. if (epi->event.events & EPOLLONESHOT)
  1618. epi->event.events &= EP_PRIVATE_BITS;
  1619. else if (!(epi->event.events & EPOLLET)) {
  1620. /*
  1621. * If this file has been added with Level
  1622. * Trigger mode, we need to insert back inside
  1623. * the ready list, so that the next call to
  1624. * epoll_wait() will check again the events
  1625. * availability. At this point, no one can insert
  1626. * into ep->rdllist besides us. The epoll_ctl()
  1627. * callers are locked out by
  1628. * ep_send_events() holding "mtx" and the
  1629. * poll callback will queue them in ep->ovflist.
  1630. */
  1631. list_add_tail(&epi->rdllink, &ep->rdllist);
  1632. ep_pm_stay_awake(epi);
  1633. }
  1634. }
  1635. ep_done_scan(ep, &txlist);
  1636. mutex_unlock(&ep->mtx);
  1637. return res;
  1638. }
  1639. static struct timespec64 *ep_timeout_to_timespec(struct timespec64 *to, long ms)
  1640. {
  1641. struct timespec64 now;
  1642. if (ms < 0)
  1643. return NULL;
  1644. if (!ms) {
  1645. to->tv_sec = 0;
  1646. to->tv_nsec = 0;
  1647. return to;
  1648. }
  1649. to->tv_sec = ms / MSEC_PER_SEC;
  1650. to->tv_nsec = NSEC_PER_MSEC * (ms % MSEC_PER_SEC);
  1651. ktime_get_ts64(&now);
  1652. *to = timespec64_add_safe(now, *to);
  1653. return to;
  1654. }
  1655. /*
  1656. * autoremove_wake_function, but remove even on failure to wake up, because we
  1657. * know that default_wake_function/ttwu will only fail if the thread is already
  1658. * woken, and in that case the ep_poll loop will remove the entry anyways, not
  1659. * try to reuse it.
  1660. */
  1661. static int ep_autoremove_wake_function(struct wait_queue_entry *wq_entry,
  1662. unsigned int mode, int sync, void *key)
  1663. {
  1664. int ret = default_wake_function(wq_entry, mode, sync, key);
  1665. /*
  1666. * Pairs with list_empty_careful in ep_poll, and ensures future loop
  1667. * iterations see the cause of this wakeup.
  1668. */
  1669. list_del_init_careful(&wq_entry->entry);
  1670. return ret;
  1671. }
  1672. /**
  1673. * ep_poll - Retrieves ready events, and delivers them to the caller-supplied
  1674. * event buffer.
  1675. *
  1676. * @ep: Pointer to the eventpoll context.
  1677. * @events: Pointer to the userspace buffer where the ready events should be
  1678. * stored.
  1679. * @maxevents: Size (in terms of number of events) of the caller event buffer.
  1680. * @timeout: Maximum timeout for the ready events fetch operation, in
  1681. * timespec. If the timeout is zero, the function will not block,
  1682. * while if the @timeout ptr is NULL, the function will block
  1683. * until at least one event has been retrieved (or an error
  1684. * occurred).
  1685. *
  1686. * Return: the number of ready events which have been fetched, or an
  1687. * error code, in case of error.
  1688. */
  1689. static int ep_poll(struct eventpoll *ep, struct epoll_event __user *events,
  1690. int maxevents, struct timespec64 *timeout)
  1691. {
  1692. int res, eavail, timed_out = 0;
  1693. u64 slack = 0;
  1694. wait_queue_entry_t wait;
  1695. ktime_t expires, *to = NULL;
  1696. lockdep_assert_irqs_enabled();
  1697. if (timeout && (timeout->tv_sec | timeout->tv_nsec)) {
  1698. slack = select_estimate_accuracy(timeout);
  1699. to = &expires;
  1700. *to = timespec64_to_ktime(*timeout);
  1701. } else if (timeout) {
  1702. /*
  1703. * Avoid the unnecessary trip to the wait queue loop, if the
  1704. * caller specified a non blocking operation.
  1705. */
  1706. timed_out = 1;
  1707. }
  1708. /*
  1709. * This call is racy: We may or may not see events that are being added
  1710. * to the ready list under the lock (e.g., in IRQ callbacks). For cases
  1711. * with a non-zero timeout, this thread will check the ready list under
  1712. * lock and will add to the wait queue. For cases with a zero
  1713. * timeout, the user by definition should not care and will have to
  1714. * recheck again.
  1715. */
  1716. eavail = ep_events_available(ep);
  1717. while (1) {
  1718. if (eavail) {
  1719. /*
  1720. * Try to transfer events to user space. In case we get
  1721. * 0 events and there's still timeout left over, we go
  1722. * trying again in search of more luck.
  1723. */
  1724. res = ep_send_events(ep, events, maxevents);
  1725. if (res)
  1726. return res;
  1727. }
  1728. if (timed_out)
  1729. return 0;
  1730. eavail = ep_busy_loop(ep, timed_out);
  1731. if (eavail)
  1732. continue;
  1733. if (signal_pending(current))
  1734. return -EINTR;
  1735. /*
  1736. * Internally init_wait() uses autoremove_wake_function(),
  1737. * thus wait entry is removed from the wait queue on each
  1738. * wakeup. Why it is important? In case of several waiters
  1739. * each new wakeup will hit the next waiter, giving it the
  1740. * chance to harvest new event. Otherwise wakeup can be
  1741. * lost. This is also good performance-wise, because on
  1742. * normal wakeup path no need to call __remove_wait_queue()
  1743. * explicitly, thus ep->lock is not taken, which halts the
  1744. * event delivery.
  1745. *
  1746. * In fact, we now use an even more aggressive function that
  1747. * unconditionally removes, because we don't reuse the wait
  1748. * entry between loop iterations. This lets us also avoid the
  1749. * performance issue if a process is killed, causing all of its
  1750. * threads to wake up without being removed normally.
  1751. */
  1752. init_wait(&wait);
  1753. wait.func = ep_autoremove_wake_function;
  1754. write_lock_irq(&ep->lock);
  1755. /*
  1756. * Barrierless variant, waitqueue_active() is called under
  1757. * the same lock on wakeup ep_poll_callback() side, so it
  1758. * is safe to avoid an explicit barrier.
  1759. */
  1760. __set_current_state(TASK_INTERRUPTIBLE);
  1761. /*
  1762. * Do the final check under the lock. ep_start/done_scan()
  1763. * plays with two lists (->rdllist and ->ovflist) and there
  1764. * is always a race when both lists are empty for short
  1765. * period of time although events are pending, so lock is
  1766. * important.
  1767. */
  1768. eavail = ep_events_available(ep);
  1769. if (!eavail)
  1770. __add_wait_queue_exclusive(&ep->wq, &wait);
  1771. write_unlock_irq(&ep->lock);
  1772. if (!eavail)
  1773. timed_out = !schedule_hrtimeout_range(to, slack,
  1774. HRTIMER_MODE_ABS);
  1775. __set_current_state(TASK_RUNNING);
  1776. /*
  1777. * We were woken up, thus go and try to harvest some events.
  1778. * If timed out and still on the wait queue, recheck eavail
  1779. * carefully under lock, below.
  1780. */
  1781. eavail = 1;
  1782. if (!list_empty_careful(&wait.entry)) {
  1783. write_lock_irq(&ep->lock);
  1784. /*
  1785. * If the thread timed out and is not on the wait queue,
  1786. * it means that the thread was woken up after its
  1787. * timeout expired before it could reacquire the lock.
  1788. * Thus, when wait.entry is empty, it needs to harvest
  1789. * events.
  1790. */
  1791. if (timed_out)
  1792. eavail = list_empty(&wait.entry);
  1793. __remove_wait_queue(&ep->wq, &wait);
  1794. write_unlock_irq(&ep->lock);
  1795. }
  1796. }
  1797. }
  1798. /**
  1799. * ep_loop_check_proc - verify that adding an epoll file inside another
  1800. * epoll structure does not violate the constraints, in
  1801. * terms of closed loops, or too deep chains (which can
  1802. * result in excessive stack usage).
  1803. *
  1804. * @ep: the &struct eventpoll to be currently checked.
  1805. * @depth: Current depth of the path being checked.
  1806. *
  1807. * Return: %zero if adding the epoll @file inside current epoll
  1808. * structure @ep does not violate the constraints, or %-1 otherwise.
  1809. */
  1810. static int ep_loop_check_proc(struct eventpoll *ep, int depth)
  1811. {
  1812. int error = 0;
  1813. struct rb_node *rbp;
  1814. struct epitem *epi;
  1815. mutex_lock_nested(&ep->mtx, depth + 1);
  1816. ep->gen = loop_check_gen;
  1817. for (rbp = rb_first_cached(&ep->rbr); rbp; rbp = rb_next(rbp)) {
  1818. epi = rb_entry(rbp, struct epitem, rbn);
  1819. if (unlikely(is_file_epoll(epi->ffd.file))) {
  1820. struct eventpoll *ep_tovisit;
  1821. ep_tovisit = epi->ffd.file->private_data;
  1822. if (ep_tovisit->gen == loop_check_gen)
  1823. continue;
  1824. if (ep_tovisit == inserting_into || depth > EP_MAX_NESTS)
  1825. error = -1;
  1826. else
  1827. error = ep_loop_check_proc(ep_tovisit, depth + 1);
  1828. if (error != 0)
  1829. break;
  1830. } else {
  1831. /*
  1832. * If we've reached a file that is not associated with
  1833. * an ep, then we need to check if the newly added
  1834. * links are going to add too many wakeup paths. We do
  1835. * this by adding it to the tfile_check_list, if it's
  1836. * not already there, and calling reverse_path_check()
  1837. * during ep_insert().
  1838. */
  1839. list_file(epi->ffd.file);
  1840. }
  1841. }
  1842. mutex_unlock(&ep->mtx);
  1843. return error;
  1844. }
  1845. /**
  1846. * ep_loop_check - Performs a check to verify that adding an epoll file (@to)
  1847. * into another epoll file (represented by @ep) does not create
  1848. * closed loops or too deep chains.
  1849. *
  1850. * @ep: Pointer to the epoll we are inserting into.
  1851. * @to: Pointer to the epoll to be inserted.
  1852. *
  1853. * Return: %zero if adding the epoll @to inside the epoll @from
  1854. * does not violate the constraints, or %-1 otherwise.
  1855. */
  1856. static int ep_loop_check(struct eventpoll *ep, struct eventpoll *to)
  1857. {
  1858. inserting_into = ep;
  1859. return ep_loop_check_proc(to, 0);
  1860. }
  1861. static void clear_tfile_check_list(void)
  1862. {
  1863. rcu_read_lock();
  1864. while (tfile_check_list != EP_UNACTIVE_PTR) {
  1865. struct epitems_head *head = tfile_check_list;
  1866. tfile_check_list = head->next;
  1867. unlist_file(head);
  1868. }
  1869. rcu_read_unlock();
  1870. }
  1871. /*
  1872. * Open an eventpoll file descriptor.
  1873. */
  1874. static int do_epoll_create(int flags)
  1875. {
  1876. int error, fd;
  1877. struct eventpoll *ep = NULL;
  1878. struct file *file;
  1879. /* Check the EPOLL_* constant for consistency. */
  1880. BUILD_BUG_ON(EPOLL_CLOEXEC != O_CLOEXEC);
  1881. if (flags & ~EPOLL_CLOEXEC)
  1882. return -EINVAL;
  1883. /*
  1884. * Create the internal data structure ("struct eventpoll").
  1885. */
  1886. error = ep_alloc(&ep);
  1887. if (error < 0)
  1888. return error;
  1889. /*
  1890. * Creates all the items needed to setup an eventpoll file. That is,
  1891. * a file structure and a free file descriptor.
  1892. */
  1893. fd = get_unused_fd_flags(O_RDWR | (flags & O_CLOEXEC));
  1894. if (fd < 0) {
  1895. error = fd;
  1896. goto out_free_ep;
  1897. }
  1898. file = anon_inode_getfile("[eventpoll]", &eventpoll_fops, ep,
  1899. O_RDWR | (flags & O_CLOEXEC));
  1900. if (IS_ERR(file)) {
  1901. error = PTR_ERR(file);
  1902. goto out_free_fd;
  1903. }
  1904. ep->file = file;
  1905. fd_install(fd, file);
  1906. return fd;
  1907. out_free_fd:
  1908. put_unused_fd(fd);
  1909. out_free_ep:
  1910. ep_clear_and_put(ep);
  1911. return error;
  1912. }
  1913. SYSCALL_DEFINE1(epoll_create1, int, flags)
  1914. {
  1915. return do_epoll_create(flags);
  1916. }
  1917. SYSCALL_DEFINE1(epoll_create, int, size)
  1918. {
  1919. if (size <= 0)
  1920. return -EINVAL;
  1921. return do_epoll_create(0);
  1922. }
  1923. #ifdef CONFIG_PM_SLEEP
  1924. static inline void ep_take_care_of_epollwakeup(struct epoll_event *epev)
  1925. {
  1926. if ((epev->events & EPOLLWAKEUP) && !capable(CAP_BLOCK_SUSPEND))
  1927. epev->events &= ~EPOLLWAKEUP;
  1928. }
  1929. #else
  1930. static inline void ep_take_care_of_epollwakeup(struct epoll_event *epev)
  1931. {
  1932. epev->events &= ~EPOLLWAKEUP;
  1933. }
  1934. #endif
  1935. static inline int epoll_mutex_lock(struct mutex *mutex, int depth,
  1936. bool nonblock)
  1937. {
  1938. if (!nonblock) {
  1939. mutex_lock_nested(mutex, depth);
  1940. return 0;
  1941. }
  1942. if (mutex_trylock(mutex))
  1943. return 0;
  1944. return -EAGAIN;
  1945. }
  1946. int do_epoll_ctl(int epfd, int op, int fd, struct epoll_event *epds,
  1947. bool nonblock)
  1948. {
  1949. int error;
  1950. int full_check = 0;
  1951. struct fd f, tf;
  1952. struct eventpoll *ep;
  1953. struct epitem *epi;
  1954. struct eventpoll *tep = NULL;
  1955. error = -EBADF;
  1956. f = fdget(epfd);
  1957. if (!fd_file(f))
  1958. goto error_return;
  1959. /* Get the "struct file *" for the target file */
  1960. tf = fdget(fd);
  1961. if (!fd_file(tf))
  1962. goto error_fput;
  1963. /* The target file descriptor must support poll */
  1964. error = -EPERM;
  1965. if (!file_can_poll(fd_file(tf)))
  1966. goto error_tgt_fput;
  1967. /* Check if EPOLLWAKEUP is allowed */
  1968. if (ep_op_has_event(op))
  1969. ep_take_care_of_epollwakeup(epds);
  1970. /*
  1971. * We have to check that the file structure underneath the file descriptor
  1972. * the user passed to us _is_ an eventpoll file. And also we do not permit
  1973. * adding an epoll file descriptor inside itself.
  1974. */
  1975. error = -EINVAL;
  1976. if (fd_file(f) == fd_file(tf) || !is_file_epoll(fd_file(f)))
  1977. goto error_tgt_fput;
  1978. /*
  1979. * epoll adds to the wakeup queue at EPOLL_CTL_ADD time only,
  1980. * so EPOLLEXCLUSIVE is not allowed for a EPOLL_CTL_MOD operation.
  1981. * Also, we do not currently supported nested exclusive wakeups.
  1982. */
  1983. if (ep_op_has_event(op) && (epds->events & EPOLLEXCLUSIVE)) {
  1984. if (op == EPOLL_CTL_MOD)
  1985. goto error_tgt_fput;
  1986. if (op == EPOLL_CTL_ADD && (is_file_epoll(fd_file(tf)) ||
  1987. (epds->events & ~EPOLLEXCLUSIVE_OK_BITS)))
  1988. goto error_tgt_fput;
  1989. }
  1990. /*
  1991. * At this point it is safe to assume that the "private_data" contains
  1992. * our own data structure.
  1993. */
  1994. ep = fd_file(f)->private_data;
  1995. /*
  1996. * When we insert an epoll file descriptor inside another epoll file
  1997. * descriptor, there is the chance of creating closed loops, which are
  1998. * better be handled here, than in more critical paths. While we are
  1999. * checking for loops we also determine the list of files reachable
  2000. * and hang them on the tfile_check_list, so we can check that we
  2001. * haven't created too many possible wakeup paths.
  2002. *
  2003. * We do not need to take the global 'epumutex' on EPOLL_CTL_ADD when
  2004. * the epoll file descriptor is attaching directly to a wakeup source,
  2005. * unless the epoll file descriptor is nested. The purpose of taking the
  2006. * 'epnested_mutex' on add is to prevent complex toplogies such as loops and
  2007. * deep wakeup paths from forming in parallel through multiple
  2008. * EPOLL_CTL_ADD operations.
  2009. */
  2010. error = epoll_mutex_lock(&ep->mtx, 0, nonblock);
  2011. if (error)
  2012. goto error_tgt_fput;
  2013. if (op == EPOLL_CTL_ADD) {
  2014. if (READ_ONCE(fd_file(f)->f_ep) || ep->gen == loop_check_gen ||
  2015. is_file_epoll(fd_file(tf))) {
  2016. mutex_unlock(&ep->mtx);
  2017. error = epoll_mutex_lock(&epnested_mutex, 0, nonblock);
  2018. if (error)
  2019. goto error_tgt_fput;
  2020. loop_check_gen++;
  2021. full_check = 1;
  2022. if (is_file_epoll(fd_file(tf))) {
  2023. tep = fd_file(tf)->private_data;
  2024. error = -ELOOP;
  2025. if (ep_loop_check(ep, tep) != 0)
  2026. goto error_tgt_fput;
  2027. }
  2028. error = epoll_mutex_lock(&ep->mtx, 0, nonblock);
  2029. if (error)
  2030. goto error_tgt_fput;
  2031. }
  2032. }
  2033. /*
  2034. * Try to lookup the file inside our RB tree. Since we grabbed "mtx"
  2035. * above, we can be sure to be able to use the item looked up by
  2036. * ep_find() till we release the mutex.
  2037. */
  2038. epi = ep_find(ep, fd_file(tf), fd);
  2039. error = -EINVAL;
  2040. switch (op) {
  2041. case EPOLL_CTL_ADD:
  2042. if (!epi) {
  2043. epds->events |= EPOLLERR | EPOLLHUP;
  2044. error = ep_insert(ep, epds, fd_file(tf), fd, full_check);
  2045. } else
  2046. error = -EEXIST;
  2047. break;
  2048. case EPOLL_CTL_DEL:
  2049. if (epi) {
  2050. /*
  2051. * The eventpoll itself is still alive: the refcount
  2052. * can't go to zero here.
  2053. */
  2054. ep_remove_safe(ep, epi);
  2055. error = 0;
  2056. } else {
  2057. error = -ENOENT;
  2058. }
  2059. break;
  2060. case EPOLL_CTL_MOD:
  2061. if (epi) {
  2062. if (!(epi->event.events & EPOLLEXCLUSIVE)) {
  2063. epds->events |= EPOLLERR | EPOLLHUP;
  2064. error = ep_modify(ep, epi, epds);
  2065. }
  2066. } else
  2067. error = -ENOENT;
  2068. break;
  2069. }
  2070. mutex_unlock(&ep->mtx);
  2071. error_tgt_fput:
  2072. if (full_check) {
  2073. clear_tfile_check_list();
  2074. loop_check_gen++;
  2075. mutex_unlock(&epnested_mutex);
  2076. }
  2077. fdput(tf);
  2078. error_fput:
  2079. fdput(f);
  2080. error_return:
  2081. return error;
  2082. }
  2083. /*
  2084. * The following function implements the controller interface for
  2085. * the eventpoll file that enables the insertion/removal/change of
  2086. * file descriptors inside the interest set.
  2087. */
  2088. SYSCALL_DEFINE4(epoll_ctl, int, epfd, int, op, int, fd,
  2089. struct epoll_event __user *, event)
  2090. {
  2091. struct epoll_event epds;
  2092. if (ep_op_has_event(op) &&
  2093. copy_from_user(&epds, event, sizeof(struct epoll_event)))
  2094. return -EFAULT;
  2095. return do_epoll_ctl(epfd, op, fd, &epds, false);
  2096. }
  2097. /*
  2098. * Implement the event wait interface for the eventpoll file. It is the kernel
  2099. * part of the user space epoll_wait(2).
  2100. */
  2101. static int do_epoll_wait(int epfd, struct epoll_event __user *events,
  2102. int maxevents, struct timespec64 *to)
  2103. {
  2104. int error;
  2105. struct fd f;
  2106. struct eventpoll *ep;
  2107. /* The maximum number of event must be greater than zero */
  2108. if (maxevents <= 0 || maxevents > EP_MAX_EVENTS)
  2109. return -EINVAL;
  2110. /* Verify that the area passed by the user is writeable */
  2111. if (!access_ok(events, maxevents * sizeof(struct epoll_event)))
  2112. return -EFAULT;
  2113. /* Get the "struct file *" for the eventpoll file */
  2114. f = fdget(epfd);
  2115. if (!fd_file(f))
  2116. return -EBADF;
  2117. /*
  2118. * We have to check that the file structure underneath the fd
  2119. * the user passed to us _is_ an eventpoll file.
  2120. */
  2121. error = -EINVAL;
  2122. if (!is_file_epoll(fd_file(f)))
  2123. goto error_fput;
  2124. /*
  2125. * At this point it is safe to assume that the "private_data" contains
  2126. * our own data structure.
  2127. */
  2128. ep = fd_file(f)->private_data;
  2129. /* Time to fish for events ... */
  2130. error = ep_poll(ep, events, maxevents, to);
  2131. error_fput:
  2132. fdput(f);
  2133. return error;
  2134. }
  2135. SYSCALL_DEFINE4(epoll_wait, int, epfd, struct epoll_event __user *, events,
  2136. int, maxevents, int, timeout)
  2137. {
  2138. struct timespec64 to;
  2139. return do_epoll_wait(epfd, events, maxevents,
  2140. ep_timeout_to_timespec(&to, timeout));
  2141. }
  2142. /*
  2143. * Implement the event wait interface for the eventpoll file. It is the kernel
  2144. * part of the user space epoll_pwait(2).
  2145. */
  2146. static int do_epoll_pwait(int epfd, struct epoll_event __user *events,
  2147. int maxevents, struct timespec64 *to,
  2148. const sigset_t __user *sigmask, size_t sigsetsize)
  2149. {
  2150. int error;
  2151. /*
  2152. * If the caller wants a certain signal mask to be set during the wait,
  2153. * we apply it here.
  2154. */
  2155. error = set_user_sigmask(sigmask, sigsetsize);
  2156. if (error)
  2157. return error;
  2158. error = do_epoll_wait(epfd, events, maxevents, to);
  2159. restore_saved_sigmask_unless(error == -EINTR);
  2160. return error;
  2161. }
  2162. SYSCALL_DEFINE6(epoll_pwait, int, epfd, struct epoll_event __user *, events,
  2163. int, maxevents, int, timeout, const sigset_t __user *, sigmask,
  2164. size_t, sigsetsize)
  2165. {
  2166. struct timespec64 to;
  2167. return do_epoll_pwait(epfd, events, maxevents,
  2168. ep_timeout_to_timespec(&to, timeout),
  2169. sigmask, sigsetsize);
  2170. }
  2171. SYSCALL_DEFINE6(epoll_pwait2, int, epfd, struct epoll_event __user *, events,
  2172. int, maxevents, const struct __kernel_timespec __user *, timeout,
  2173. const sigset_t __user *, sigmask, size_t, sigsetsize)
  2174. {
  2175. struct timespec64 ts, *to = NULL;
  2176. if (timeout) {
  2177. if (get_timespec64(&ts, timeout))
  2178. return -EFAULT;
  2179. to = &ts;
  2180. if (poll_select_set_timeout(to, ts.tv_sec, ts.tv_nsec))
  2181. return -EINVAL;
  2182. }
  2183. return do_epoll_pwait(epfd, events, maxevents, to,
  2184. sigmask, sigsetsize);
  2185. }
  2186. #ifdef CONFIG_COMPAT
  2187. static int do_compat_epoll_pwait(int epfd, struct epoll_event __user *events,
  2188. int maxevents, struct timespec64 *timeout,
  2189. const compat_sigset_t __user *sigmask,
  2190. compat_size_t sigsetsize)
  2191. {
  2192. long err;
  2193. /*
  2194. * If the caller wants a certain signal mask to be set during the wait,
  2195. * we apply it here.
  2196. */
  2197. err = set_compat_user_sigmask(sigmask, sigsetsize);
  2198. if (err)
  2199. return err;
  2200. err = do_epoll_wait(epfd, events, maxevents, timeout);
  2201. restore_saved_sigmask_unless(err == -EINTR);
  2202. return err;
  2203. }
  2204. COMPAT_SYSCALL_DEFINE6(epoll_pwait, int, epfd,
  2205. struct epoll_event __user *, events,
  2206. int, maxevents, int, timeout,
  2207. const compat_sigset_t __user *, sigmask,
  2208. compat_size_t, sigsetsize)
  2209. {
  2210. struct timespec64 to;
  2211. return do_compat_epoll_pwait(epfd, events, maxevents,
  2212. ep_timeout_to_timespec(&to, timeout),
  2213. sigmask, sigsetsize);
  2214. }
  2215. COMPAT_SYSCALL_DEFINE6(epoll_pwait2, int, epfd,
  2216. struct epoll_event __user *, events,
  2217. int, maxevents,
  2218. const struct __kernel_timespec __user *, timeout,
  2219. const compat_sigset_t __user *, sigmask,
  2220. compat_size_t, sigsetsize)
  2221. {
  2222. struct timespec64 ts, *to = NULL;
  2223. if (timeout) {
  2224. if (get_timespec64(&ts, timeout))
  2225. return -EFAULT;
  2226. to = &ts;
  2227. if (poll_select_set_timeout(to, ts.tv_sec, ts.tv_nsec))
  2228. return -EINVAL;
  2229. }
  2230. return do_compat_epoll_pwait(epfd, events, maxevents, to,
  2231. sigmask, sigsetsize);
  2232. }
  2233. #endif
  2234. static int __init eventpoll_init(void)
  2235. {
  2236. struct sysinfo si;
  2237. si_meminfo(&si);
  2238. /*
  2239. * Allows top 4% of lomem to be allocated for epoll watches (per user).
  2240. */
  2241. max_user_watches = (((si.totalram - si.totalhigh) / 25) << PAGE_SHIFT) /
  2242. EP_ITEM_COST;
  2243. BUG_ON(max_user_watches < 0);
  2244. /*
  2245. * We can have many thousands of epitems, so prevent this from
  2246. * using an extra cache line on 64-bit (and smaller) CPUs
  2247. */
  2248. BUILD_BUG_ON(sizeof(void *) <= 8 && sizeof(struct epitem) > 128);
  2249. /* Allocates slab cache used to allocate "struct epitem" items */
  2250. epi_cache = kmem_cache_create("eventpoll_epi", sizeof(struct epitem),
  2251. 0, SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_ACCOUNT, NULL);
  2252. /* Allocates slab cache used to allocate "struct eppoll_entry" */
  2253. pwq_cache = kmem_cache_create("eventpoll_pwq",
  2254. sizeof(struct eppoll_entry), 0, SLAB_PANIC|SLAB_ACCOUNT, NULL);
  2255. epoll_sysctls_init();
  2256. ephead_cache = kmem_cache_create("ep_head",
  2257. sizeof(struct epitems_head), 0, SLAB_PANIC|SLAB_ACCOUNT, NULL);
  2258. return 0;
  2259. }
  2260. fs_initcall(eventpoll_init);