File: kqueue-thread.c

package info (click to toggle)
glib2.0 2.42.1-1
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-backports, jessie-kfreebsd, jessie-kfreebsd-proposed-updates
  • size: 82,084 kB
  • sloc: ansic: 411,692; xml: 15,280; sh: 12,977; python: 5,145; makefile: 3,567; perl: 1,422; cpp: 9
file content (304 lines) | stat: -rw-r--r-- 8,879 bytes parent folder | download | duplicates (4)
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
/*******************************************************************************
  Copyright (c) 2011, 2012 Dmitry Matveev <me@dmitrymatveev.co.uk>

  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files (the "Software"), to deal
  in the Software without restriction, including without limitation the rights
  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  copies of the Software, and to permit persons to whom the Software is
  furnished to do so, subject to the following conditions:

  The above copyright notice and this permission notice shall be included in
  all copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  THE SOFTWARE.
*******************************************************************************/

#include "config.h"
#include <sys/types.h>
#include <sys/event.h>
#include <sys/time.h>
#include <unistd.h>
#include <errno.h>
#include <glib.h>

#include "kqueue-thread.h"
#include "kqueue-sub.h"
#include "kqueue-utils.h"

static gboolean kt_debug_enabled = FALSE;
#define KT_W if (kt_debug_enabled) g_warning

static GQueue pick_up_fds_queue = G_QUEUE_INIT;
G_LOCK_DEFINE_STATIC (pick_up_lock);

static GSList *remove_fds_list = NULL;
G_LOCK_DEFINE_STATIC (remove_lock);

/* GIO does not have analogues for NOTE_LINK and(?) NOTE_REVOKE, so
 * we do not ask kqueue() to watch for these events for now. */
const uint32_t KQUEUE_VNODE_FLAGS =
  NOTE_DELETE | NOTE_WRITE | NOTE_EXTEND | NOTE_ATTRIB | NOTE_RENAME;

extern int get_kqueue_descriptor(void);

/**
 * _kqueue_thread_collect_fds:
 * @events: a #kevents - the list of events to monitor. Will be extended
 *     with new items.
 *
 * Picks up new file descriptors for monitoring from a global queue.
 *
 * To add new items to the list, use _kqueue_thread_push_fd().
 */
static void
_kqueue_thread_collect_fds (kevents *events)
{
  g_assert (events != NULL);
  gint length = 0;

  G_LOCK (pick_up_lock);
  if ((length = g_queue_get_length (&pick_up_fds_queue)) != 0)
    {
      gpointer fdp = NULL;
      kevents_extend_sz (events, length);

      while ((fdp = g_queue_pop_head (&pick_up_fds_queue)) != NULL)
        {
          struct kevent *pevent = &events->memory[events->kq_size++];
          EV_SET (pevent,
                  GPOINTER_TO_INT (fdp),
                  EVFILT_VNODE,
                  EV_ADD | EV_ENABLE | EV_ONESHOT,
                  KQUEUE_VNODE_FLAGS,
                  0,
                  0);
        }
    }
  G_UNLOCK (pick_up_lock);
}


/**
 * _kqueue_thread_cleanup_fds:
 * @events: a #kevents -- list of events to monitor. Cancelled
 *     subscriptions will be removed from it, and its size
 *     probably will be reduced.
 *
 * Removes file descriptors from monitoring.
 *
 * This function will pick up file descriptors from a global list
 * to cancel monitoring on them. The list will be freed then.
 *
 * To add new items to the list, use _kqueue_thread_remove_fd().
 */
static void
_kqueue_thread_cleanup_fds (kevents *events)
{
  g_assert (events != NULL);

  G_LOCK (remove_lock);
  if (remove_fds_list)
    {
      size_t oldsize = events->kq_size;
      int i, j;

      for (i = 1, j = 1; i < oldsize; i++)
        {
          int fd = events->memory[i].ident;
          GSList *elem = g_slist_find (remove_fds_list, GINT_TO_POINTER (fd));
          if (elem == NULL)
            {
              if (i != j)
                events->memory[j] = events->memory[i];
              ++j;
            }
          else if (close (fd) == -1)
            KT_W ("Failed to close fd %d, error %d", fd, errno);
        }

      KT_W ("FD Clean up complete, kq_size now %d\n", j);
      events->kq_size = j;
      kevents_reduce (events);
      g_slist_free (remove_fds_list);
      remove_fds_list = NULL;
    }
  G_UNLOCK (remove_lock);
}


/**
 * _kqueue_thread_drop_fd:
 * @events: a #kevents -- list of events to monitor. Cancelled
 *     subscriptions will be removed from it, and its size
 *     probably will be reduced.
 *
 * Removes a concrete file descriptor from monitoring.
 */
static void
_kqueue_thread_drop_fd (kevents *events, int fd)
{
  g_assert (events != NULL);

  int i;
  for (i = 1; i < events->kq_size; i++)
    {
      if (events->memory[i].ident == fd)
        {
          if (close (fd) == -1)
            KT_W ("Failed to close fd %d, error %d", fd, errno);

          events->memory[i] = events->memory[--events->kq_size];
          return;
        }
    } 
}

/**
 * _kqueue_thread_func:
 * @arg: a pointer to int -- control file descriptor.
 *
 * The thread communicates with the outside world through a so-called
 * command file descriptor. The thread reads control commands from it
 * and writes the notifications into it.
 *
 * Control commands are single-byte characters:
 * - 'A' - pick up new file descriptors to monitor
 * - 'R' - remove some descriptors from monitoring.
 *
 * For details, see _kqueue_thread_collect_fds() and
 * _kqueue_thread_cleanup_fds().
 *
 * Notifications, that thread writes into the command file descriptor,
 * are represented with #kqueue_notification objects.
 *
 * Returns: %NULL
 */
void*
_kqueue_thread_func (void *arg)
{
  int fd, kqueue_descriptor;
  kevents waiting;

  g_assert (arg != NULL);
  kevents_init_sz (&waiting, 1);

  fd = *(int *) arg;

  kqueue_descriptor = get_kqueue_descriptor();
  if (kqueue_descriptor == -1)
    {
      KT_W ("fatal: kqueue is not initialized!\n");
      return NULL;
    }

  EV_SET (&waiting.memory[0],
          fd,
          EVFILT_READ,
          EV_ADD | EV_ENABLE | EV_ONESHOT,
          NOTE_LOWAT,
          1,
          0);
  waiting.kq_size = 1;

  for (;;)
    {
      /* TODO: Provide more items in the 'eventlist' to kqueue(2).
       * Currently the backend takes notifications from the kernel one
       * by one, i.e. there will be a lot of system calls and context
       * switches when the application will monitor a lot of files with
       * high filesystem activity on each. */
     
      struct kevent received;
      KT_W ("Watching for %zi items", waiting.kq_size);
      int ret = kevent (kqueue_descriptor, waiting.memory, waiting.kq_size, &received, 1, NULL);
      int kevent_errno = errno;
      KT_W ("Awoken.");

      if (ret == -1)
        {
          KT_W ("kevent failed: %d", kevent_errno);
          if (kevent_errno == EINTR)
            continue;
          else
            return NULL;
        }

      if (received.ident == fd)
        {
          char c;
            if (!_ku_read (fd, &c, 1))
              {
                KT_W ("Failed to read command, error %d", errno);
                continue;
              }
          if (c == 'A')
            _kqueue_thread_collect_fds (&waiting);
          else if (c == 'R')
            _kqueue_thread_cleanup_fds (&waiting);
        }
      else 
        {
          struct kqueue_notification kn;
          kn.fd = received.ident;

          if (received.flags & EV_ERROR)
            {
              kn.flags = NOTE_REVOKE;
              _kqueue_thread_drop_fd (&waiting, received.ident);
            }
          else
            kn.flags = (received.fflags & ~NOTE_REVOKE);

          if (!_ku_write (fd, &kn, sizeof (struct kqueue_notification)))
            KT_W ("Failed to write a kqueue notification, error %d", errno);
        }
    }
  kevents_free (&waiting);
  return NULL;
}


/**
 * _kqueue_thread_push_fd:
 * @fd: a file descriptor
 *
 * Puts a new file descriptor into the pick up list for monitroing.
 *
 * The kqueue thread will not start monitoring on it immediately, it
 * should be bumped via its command file descriptor manually.
 * See kqueue_thread() and _kqueue_thread_collect_fds() for details.
 */
void
_kqueue_thread_push_fd (int fd)
{
  G_LOCK (pick_up_lock);
  g_queue_push_tail (&pick_up_fds_queue, GINT_TO_POINTER (fd));
  G_UNLOCK (pick_up_lock);
}


/**
 * _kqueue_thread_remove_fd:
 * @fd: a file descriptor
 *
 * Puts a new file descriptor into the remove list to cancel monitoring
 * on it.
 *
 * The kqueue thread will not stop monitoring on it immediately, it
 * should be bumped via its command file descriptor manually.
 * See kqueue_thread() and _kqueue_thread_collect_fds() for details.
 */
void
_kqueue_thread_remove_fd (int fd)
{
  G_LOCK (remove_lock);
  remove_fds_list = g_slist_prepend (remove_fds_list, GINT_TO_POINTER (fd));
  G_UNLOCK (remove_lock);
}