Repository navigation
Expand file tree
/
Copy pathevent_poller.cpp
More file actions
628 lines (501 loc) · 14 KB
/
Copy pathevent_poller.cpp
File metadata and controls
628 lines (501 loc) · 14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
/*
This source file is part of KBEngine
For the latest info, see http://www.kbengine.org/
Copyright (c) 2008-2012 KBEngine.
KBEngine is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
KBEngine is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with KBEngine. If not, see <http://www.gnu.org/licenses/>.
*/
#include "event_poller.hpp"
#include "helper/profile.hpp"
namespace KBEngine {
ProfileVal g_idleProfile("Idle");
namespace Mercury
{
#ifndef _WIN32
#define HAS_EPOLL
#endif
//-------------------------------------------------------------------------------------
EventPoller::EventPoller() :
fdReadHandlers_(),
fdWriteHandlers_(),
spareTime_(0)
{
}
//-------------------------------------------------------------------------------------
EventPoller::~EventPoller()
{
}
//-------------------------------------------------------------------------------------
bool EventPoller::registerForRead(int fd,
InputNotificationHandler * handler)
{
if (!this->doRegisterForRead(fd))
{
return false;
}
fdReadHandlers_[ fd ] = handler;
return true;
}
//-------------------------------------------------------------------------------------
bool EventPoller::registerForWrite(int fd,
InputNotificationHandler * handler)
{
if (!this->doRegisterForWrite(fd))
{
return false;
}
fdWriteHandlers_[ fd ] = handler;
return true;
}
//-------------------------------------------------------------------------------------
bool EventPoller::deregisterForRead(int fd)
{
fdReadHandlers_.erase(fd);
return this->doDeregisterForRead(fd);
}
//-------------------------------------------------------------------------------------
bool EventPoller::deregisterForWrite(int fd)
{
fdWriteHandlers_.erase(fd);
return this->doDeregisterForWrite(fd);
}
//-------------------------------------------------------------------------------------
bool EventPoller::trigger(int fd, FDHandlers & handlers)
{
FDHandlers::iterator iter = handlers.find(fd);
if (iter == handlers.end())
{
return false;
}
iter->second->handleInputNotification(fd);
return true;
}
//-------------------------------------------------------------------------------------
bool EventPoller::triggerError(int fd)
{
if (!this->triggerRead(fd))
{
return this->triggerWrite(fd);
}
return true;
}
//-------------------------------------------------------------------------------------
bool EventPoller::isRegistered(int fd, bool isForRead) const
{
const FDHandlers & handlers =
isForRead ? fdReadHandlers_ : fdWriteHandlers_;
return handlers.find(fd) != handlers.end();
}
//-------------------------------------------------------------------------------------
InputNotificationHandler* EventPoller::find(int fd, bool isForRead)
{
FDHandlers & handlers =
isForRead ? fdReadHandlers_ : fdWriteHandlers_;
FDHandlers::iterator iter = handlers.find(fd);
if(iter == handlers.end())
return NULL;
return iter->second;
}
//-------------------------------------------------------------------------------------
int EventPoller::handleInputNotification(int fd)
{
this->processPendingEvents(0.0);
return 0;
}
//-------------------------------------------------------------------------------------
int EventPoller::getFileDescriptor() const
{
return -1;
}
//-------------------------------------------------------------------------------------
int EventPoller::maxFD() const
{
int readMaxFD = EventPoller::maxFD(fdReadHandlers_);
int writeMaxFD = EventPoller::maxFD(fdWriteHandlers_);
return std::max(readMaxFD, writeMaxFD);
}
//-------------------------------------------------------------------------------------
int EventPoller::maxFD(const FDHandlers & handlerMap)
{
int maxFD = -1;
FDHandlers::const_iterator iFDHandler = handlerMap.begin();
while (iFDHandler != handlerMap.end())
{
if (iFDHandler->first > maxFD)
{
maxFD = iFDHandler->first;
}
++iFDHandler;
}
return maxFD;
}
//-------------------------------------------------------------------------------------
class SelectPoller : public EventPoller
{
public:
SelectPoller();
protected:
virtual bool doRegisterForRead(int fd);
virtual bool doRegisterForWrite(int fd);
virtual bool doDeregisterForRead(int fd);
virtual bool doDeregisterForWrite(int fd);
virtual int processPendingEvents(double maxWait);
private:
void handleInputNotifications(int &countReady,
fd_set &readFDs, fd_set &writeFDs);
void updateLargestFileDescriptor();
// The file descriptor sets used in the select call.
fd_set fdReadSet_;
fd_set fdWriteSet_;
// This is the largest registered file descriptor (read or write). It's used
// in the call to select.
int fdLargest_;
// This is the number of file descriptors registered for the write event.
int fdWriteCount_;
};
//-------------------------------------------------------------------------------------
SelectPoller::SelectPoller() :
EventPoller(),
fdReadSet_(),
fdWriteSet_(),
fdLargest_(-1),
fdWriteCount_(0)
{
// set up our list of file descriptors
FD_ZERO(&fdReadSet_);
FD_ZERO(&fdWriteSet_);
}
//-------------------------------------------------------------------------------------
void SelectPoller::updateLargestFileDescriptor()
{
fdLargest_ = this->maxFD();
}
//-------------------------------------------------------------------------------------
void SelectPoller::handleInputNotifications(int &countReady,
fd_set &readFDs, fd_set &writeFDs)
{
#ifdef _WIN32
// X360 fd_sets don't look like POSIX ones, we know exactly what they are
// and can just iterate over the provided FD arrays
for (unsigned i=0; i < readFDs.fd_count; i++)
{
int fd = readFDs.fd_array[ i ];
--countReady;
this->triggerRead(fd);
}
for (unsigned i=0; i < writeFDs.fd_count; i++)
{
int fd = writeFDs.fd_array[ i ];
--countReady;
this->triggerWrite(fd);
}
#else
// POSIX fd_sets are more opaque and we just have to count up blindly until
// we hit valid FD's with FD_ISSET
for (int fd = 0; fd <= fdLargest_ && countReady > 0; ++fd)
{
if (FD_ISSET(fd, &readFDs))
{
--countReady;
this->triggerRead(fd);
}
if (FD_ISSET(fd, &writeFDs))
{
--countReady;
this->triggerWrite(fd);
}
}
#endif
}
//-------------------------------------------------------------------------------------
int SelectPoller::processPendingEvents(double maxWait)
{
fd_set readFDs;
fd_set writeFDs;
struct timeval nextTimeout;
FD_ZERO(&readFDs);
FD_ZERO(&writeFDs);
readFDs = fdReadSet_;
writeFDs = fdWriteSet_;
nextTimeout.tv_sec = (int)maxWait;
nextTimeout.tv_usec =
(int)((maxWait - (double)nextTimeout.tv_sec) * 1000000.0);
#if ENABLE_WATCHERS
g_idleProfile.start();
#else
uint64 startTime = timestamp();
#endif
KBEConcurrency::startMainThreadIdling();
int countReady = 0;
#ifdef _WIN32
if (fdLargest_ == -1)
{
// Windows can't handle it if we don't have any FDs to select on, but
// we have a non-NULL timeout.
Sleep(int(maxWait * 1000.0));
}
else
#endif
{
countReady = select(fdLargest_+1, &readFDs,
fdWriteCount_ ? &writeFDs : NULL, NULL, &nextTimeout);
}
KBEConcurrency::endMainThreadIdling();
#if ENABLE_WATCHERS
g_idleProfile.stop();
spareTime_ += g_idleProfile.lastTime_;
#else
spareTime_ += timestamp() - startTime;
#endif
if (countReady > 0)
{
this->handleInputNotifications(countReady, readFDs, writeFDs);
}
else if (countReady == -1)
{
// TODO: Clean this up on shutdown
// if (!breakProcessing_)
{
WARNING_MSG(boost::format("EventDispatcher::processContinuously: "
"error in select(): %1%\n") % kbe_strerror());
}
}
return countReady;
}
//-------------------------------------------------------------------------------------
bool SelectPoller::doRegisterForRead(int fd)
{
#ifndef _WIN32
if ((fd < 0) || (FD_SETSIZE <= fd))
{
ERROR_MSG(boost::format("EventDispatcher::registerFileDescriptor: "
"Tried to register invalid fd %1%. FD_SETSIZE (%2%)\n") %
fd % FD_SETSIZE);
return false;
}
#endif
// Bail early if it's already in the read set
if (FD_ISSET(fd, &fdReadSet_))
return false;
FD_SET(fd, &fdReadSet_);
if (fd > fdLargest_)
{
fdLargest_ = fd;
}
return true;
}
//-------------------------------------------------------------------------------------
bool SelectPoller::doRegisterForWrite(int fd)
{
#ifndef _WIN32
if ((fd < 0) || (FD_SETSIZE <= fd))
{
ERROR_MSG(boost::format("EventDispatcher::registerWriteFileDescriptor: "
"Tried to register invalid fd %1%. FD_SETSIZE (%2%)\n") %
fd % FD_SETSIZE);
return false;
}
#endif
if (FD_ISSET(fd, &fdWriteSet_))
{
return false;
}
FD_SET(fd, &fdWriteSet_);
if (fd > fdLargest_)
{
fdLargest_ = fd;
}
++fdWriteCount_;
return true;
}
//-------------------------------------------------------------------------------------
bool SelectPoller::doDeregisterForRead(int fd)
{
#ifndef _WIN32
if ((fd < 0) || (FD_SETSIZE <= fd))
{
return false;
}
#endif
if (!FD_ISSET(fd, &fdReadSet_))
{
return false;
}
FD_CLR(fd, &fdReadSet_);
if (fd == fdLargest_)
{
this->updateLargestFileDescriptor();
}
return true;
}
//-------------------------------------------------------------------------------------
bool SelectPoller::doDeregisterForWrite(int fd)
{
#ifndef _WIN32
if ((fd < 0) || (FD_SETSIZE <= fd))
{
return false;
}
#endif
if (!FD_ISSET(fd, &fdWriteSet_))
{
return false;
}
FD_CLR(fd, &fdWriteSet_);
if (fd == fdLargest_)
{
this->updateLargestFileDescriptor();
}
--fdWriteCount_;
return true;
}
//-------------------------------------------------------------------------------------
#ifdef HAS_EPOLL
#include <sys/epoll.h>
/**
* This class is an EventPoller that uses epoll.
*/
class EPoller : public EventPoller
{
public:
EPoller(int expectedSize = 10);
virtual ~EPoller();
int getFileDescriptor() const { return epfd_; }
protected:
virtual bool doRegisterForRead(int fd)
{ return this->doRegister(fd, true, true); }
virtual bool doRegisterForWrite(int fd)
{ return this->doRegister(fd, false, true); }
virtual bool doDeregisterForRead(int fd)
{ return this->doRegister(fd, true, false); }
virtual bool doDeregisterForWrite(int fd)
{ return this->doRegister(fd, false, false); }
virtual int processPendingEvents(double maxWait);
bool doRegister(int fd, bool isRead, bool isRegister);
private:
// epoll file descriptor
int epfd_;
};
//-------------------------------------------------------------------------------------
EPoller::EPoller(int expectedSize) :
epfd_(epoll_create(expectedSize))
{
if (epfd_ == -1)
{
ERROR_MSG(boost::format("EPoller::EPoller: epoll_create failed: %1%\n") %
kbe_strerror());
}
};
//-------------------------------------------------------------------------------------
EPoller::~EPoller()
{
if (epfd_ != -1)
{
close(epfd_);
}
}
//-------------------------------------------------------------------------------------
bool EPoller::doRegister(int fd, bool isRead, bool isRegister)
{
struct epoll_event ev;
memset(&ev, 0, sizeof(ev)); // stop valgrind warning
int op;
ev.data.fd = fd;
// Handle the case where the file is already registered for the opposite
// action.
if (this->isRegistered(fd, !isRead))
{
op = EPOLL_CTL_MOD;
ev.events = isRegister ? EPOLLIN|EPOLLOUT :
isRead ? EPOLLOUT : EPOLLIN;
}
else
{
// TODO: Could be good to use EPOLLET (leave like select for now).
ev.events = isRead ? EPOLLIN : EPOLLOUT;
op = isRegister ? EPOLL_CTL_ADD : EPOLL_CTL_DEL;
}
if (epoll_ctl(epfd_, op, fd, &ev) < 0)
{
const char* MESSAGE = "EPoller::doRegister: Failed to %s %s file "
"descriptor %d (%s)\n";
if (errno == EBADF)
{
WARNING_MSG(boost::format(MESSAGE) %
(isRegister ? "add" : "remove") %
(isRead ? "read" : "write") %
fd %
kbe_strerror());
}
else
{
ERROR_MSG(boost::format(MESSAGE) %
(isRegister ? "add" : "remove") %
(isRead ? "read" : "write") %
fd %
kbe_strerror());
}
return false;
}
return true;
}
//-------------------------------------------------------------------------------------
int EPoller::processPendingEvents(double maxWait)
{
const int MAX_EVENTS = 10;
struct epoll_event events[ MAX_EVENTS ];
int maxWaitInMilliseconds = int(ceil(maxWait * 1000));
#if ENABLE_WATCHERS
g_idleProfile.start();
#else
uint64 startTime = timestamp();
#endif
KBEConcurrency::startMainThreadIdling();
int nfds = epoll_wait(epfd_, events, MAX_EVENTS, maxWaitInMilliseconds);
KBEConcurrency::endMainThreadIdling();
#if ENABLE_WATCHERS
g_idleProfile.stop();
spareTime_ += g_idleProfile.lastTime_;
#else
spareTime_ += timestamp() - startTime;
#endif
for (int i = 0; i < nfds; ++i)
{
if (events[i].events & (EPOLLERR|EPOLLHUP))
{
this->triggerError(events[i].data.fd);
}
else
{
if (events[i].events & EPOLLIN)
{
this->triggerRead(events[i].data.fd);
}
if (events[i].events & EPOLLOUT)
{
this->triggerWrite(events[i].data.fd);
}
}
}
return nfds;
}
#endif // HAS_EPOLL
//-------------------------------------------------------------------------------------
EventPoller * EventPoller::create()
{
#ifdef HAS_EPOLL
return new EPoller();
#else
return new SelectPoller();
#endif // HAS_EPOLL
}
}
}