Reworked Solaris file event notification for GIO. See
[platform/upstream/glib.git] / gio / fen / fen-kernel.c
1 /* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2 /* vim:set expandtab ts=4 shiftwidth=4: */
3 /* 
4  * Copyright (c) 2008, 2010 Oracle and/or its affiliates, Inc. All rights
5  * reserved.
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General
18  * Public License along with this library; if not, write to the
19  * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
20  * Boston, MA 02111-1307, USA.
21  *
22  * Authors: Lin Ma <lin.ma@sun.com>
23  */
24
25 #include "config.h"
26 #include <rctl.h>
27 #include <strings.h>
28 #include <stdio.h>
29 #include <stdlib.h>
30 #include <unistd.h>
31 #include <glib.h>
32 #include "fen-kernel.h"
33 #include "fen-dump.h"
34
35 #ifdef GIO_COMPILATION
36 #define FK_W if (fk_debug_enabled) g_debug
37 static gboolean fk_debug_enabled = FALSE;
38 #else
39 #include "gam_error.h"
40 #define FK_W(...) GAM_DEBUG(DEBUG_INFO, __VA_ARGS__)
41 #endif
42
43 G_GNUC_INTERNAL G_LOCK_DEFINE (fen_lock);
44
45 static ulong max_port_events = 512;
46 static GList *pn_visible_list;  /* the queue of ports which don't have the max objs */
47 static GQueue *g_eventq = NULL;
48 static timespec_t zero_wait;
49 static void (*user_process_events_cb) (gpointer, node_event_t*);
50 static port_event_t *pevents = NULL;
51 static gint PE_ALLOC = 2048;
52 static GHashTable *renamed_hash = NULL; /* <parent node, ev> */
53
54 typedef struct _PSource {
55     GSource  source;            /* Inherit from GSource, must be the first. */
56     GPollFD  gfd;
57     gboolean pending;
58     uint_t   event_growing_factor;
59     uint_t   pending_events;
60 } PSource;
61
62 #define PGPFD(s)             (&((PSource *)(s))->gfd)
63 #define SLEEP_BASE_TIME      10 /* in milliseconds */
64 #define EXPECT_INC_EVENTS(pn)  (1 << (pn->event_growing_factor))
65
66 #define RENAME_EVENTS_INTERVAL 500 /* in milliseconds */
67 #define PROCESS_PORT_EVENTS_TIME 1000 /* in milliseconds */
68 guint process_port_event_id = 0;
69
70 static gchar* _event_strings(int event);
71 static const gchar* _event_string (int event);
72 static GSource *psource_new();
73
74 static gboolean port_prepare(GSource *source, gint *timeout_);
75 static gboolean port_check(GSource *source);
76 static gboolean port_dispatch(GSource *source, GSourceFunc callback, gpointer user_data);
77 static GSourceFuncs fen_source_func = {
78     port_prepare,
79     port_check,
80     port_dispatch,
81     NULL
82 };
83
84 static gboolean
85 port_prepare(GSource *source, gint *timeout_)
86 {
87     return FALSE;
88 }
89
90 static gboolean
91 port_check(GSource *source)
92 {
93         PSource *pn = (PSource *)source;
94     uint_t nget;
95     
96     if (pn->pending) {
97         pn->pending = FALSE;
98         g_source_add_poll(source, PGPFD(source));
99         g_source_unref(source);
100         return FALSE;
101     }
102
103     if (!(PGPFD(pn)->revents & G_IO_IN))
104         return FALSE;
105
106     if (port_getn(PGPFD(source)->fd, NULL, 0, &nget, 0) == 0) {
107         if (nget - pn->pending_events > EXPECT_INC_EVENTS(pn)) {
108             /* Sleep for a while. */
109             pn->pending_events = nget;
110             pn->event_growing_factor ++;
111
112             pn->pending = TRUE;
113             g_source_ref(source);
114             g_source_remove_poll(source, PGPFD(source));
115             g_timeout_add(SLEEP_BASE_TIME,
116               (GSourceFunc)port_check,
117               (gpointer)pn);
118             return FALSE;
119         }
120     }
121
122     pn->pending_events = 0;
123     pn->event_growing_factor = 0;
124
125     return TRUE;
126 }
127
128 static gboolean
129 port_dispatch(GSource *source, GSourceFunc callback, gpointer user_data)
130 {
131     node_t *f;
132         uint_t nget = 0;
133         uint_t total = 0;
134
135     FK_W ("%s 0x%p fd %d\n", __func__, source, PGPFD(source)->fd);
136
137     G_LOCK (fen_lock);
138     do {
139         nget = 1;
140         if (port_getn(PGPFD(source)->fd, pevents, PE_ALLOC, &nget, &zero_wait) == 0) {
141             int i;
142             for (i = 0; i < nget; i++) {
143                 f = (node_t *)pevents[i].portev_user;
144
145                 if (pevents[i].portev_source == PORT_SOURCE_FILE) {
146
147                     NODE_CLE_STATE(f, NODE_STATE_ASSOCIATED);
148                     NODE_SET_STATE(f, NODE_STATE_HAS_EVENTS);
149
150                     if (HAS_NO_EXCEPTION_EVENTS(pevents[i].portev_events)) {
151                         /* If the events do not show it's deleted, update
152                          * file timestamp to avoid missing events next time.
153                          */
154                         if (node_lstat(f) != 0 /* || port_add(f) != 0 */) {
155                             /* Included deleted event. */
156                             pevents[i].portev_events |= FILE_DELETE;
157                         }
158                     }
159
160                     /* Queue it and waiting for processing. */
161                     g_queue_push_tail(g_eventq,
162                       node_event_new(pevents[i].portev_events, (gpointer)f));
163
164                 } else {
165                     FK_W ("[kernel] unknown portev_source %d\n", pevents[i].portev_source);
166                 }
167             }
168
169             total += nget;
170
171         } else {
172             FK_W ("[kernel] port_getn %s\n", g_strerror (errno));
173             break;
174         }
175     } while (nget == PE_ALLOC);
176
177     G_UNLOCK (fen_lock);
178
179     if (total > 0 && callback) {
180         FK_W ("[kernel] get total %ld events\n", total);
181         return callback (user_data);
182     }
183     return TRUE;
184 }
185
186 static gboolean
187 process_renamed_hash_cb(gpointer key, gpointer value, gpointer user_data)
188 {
189     node_event_t *ev = value;
190
191 #if 0
192     node_add_event(ev->user_data, ev);
193 #else
194     user_process_events_cb(ev->user_data, ev);
195 #endif
196     /* Always delete self from hash. */
197     return TRUE;
198 }
199
200 static gboolean
201 port_events_process_cb(gpointer user_data)
202 {
203     node_event_t *ev;
204     
205     G_LOCK (fen_lock);
206
207         /* Processing g_eventq */
208     while ((ev = (node_event_t*)g_queue_pop_head (g_eventq)) != NULL) {
209
210         /* FK_W ("[%s] 0x%p %s\n", __func__, ev, _event_string (ev->e)); */
211
212         {
213             gchar *log = _event_strings(ev->e);
214             FK_W ("%s %s %s\n", __func__, NODE_NAME(ev->user_data), log);
215             g_free(log);
216         }
217
218 #ifdef GIO_COMPILATION
219         /* Use the parent node as a hash, because only the dir_subs in the
220          * parent node should receive MOVE event.
221          */
222         if (NODE_PARENT(ev->user_data)) {
223             if (ev->e == FILE_RENAME_TO) {
224                 g_hash_table_insert(renamed_hash, NODE_PARENT(ev->user_data), ev);
225                 g_time_val_add(&ev->rename_tv, RENAME_EVENTS_INTERVAL);
226                 continue;
227             }
228             if (ev->e == FILE_RENAME_FROM) {
229                 node_event_t *pair_ev;
230
231                 pair_ev = g_hash_table_lookup(renamed_hash, NODE_PARENT(ev->user_data));
232                 if (pair_ev && node_timeval_lt(&ev->ctv, &pair_ev->rename_tv)) {
233                     g_hash_table_remove(renamed_hash, NODE_PARENT(ev->user_data));
234                     pair_ev->pair_data = ev->user_data;
235                     /* Free ev, exchange pair_ev and ev. */
236                     node_event_delete(ev);
237                     ev = pair_ev;
238                 }
239             }
240         }
241 #endif
242     
243 #if 0
244         node_add_event(ev->user_data, ev);
245 #else
246         user_process_events_cb(ev->user_data, ev);
247 #endif
248     }
249
250     /* Processing the events in renamed_hash. TODO we should delay it and wait
251      * for more possible pair.
252      */
253     g_hash_table_foreach_remove(renamed_hash, process_renamed_hash_cb, NULL);
254
255     G_UNLOCK (fen_lock);
256
257     process_port_event_id = 0;
258     return FALSE;
259 }
260
261 static gboolean
262 port_events_read_cb(gpointer user_data)
263 {
264
265     if (process_port_event_id == 0) {
266         process_port_event_id = g_timeout_add(PROCESS_PORT_EVENTS_TIME,
267           port_events_process_cb,
268           NULL);
269     }
270
271         return TRUE;
272 }
273
274 /*
275  * malloc PSource and port_create, start thread at pnode_ref.
276  * if psource_new succeeded, the PSource will never
277  * be freed. So PSource can be freed only in psource_new.
278  * Note pnode_monitor_remove_all can also free PSource, but currently no one
279  * invork it.
280  */
281 static GSource*
282 psource_new()
283 {
284     GSource *source = NULL;
285     int fd;
286
287     if ((fd = port_create()) >= 0) {
288         source = g_source_new(&fen_source_func, sizeof(PSource));
289         PGPFD(source)->fd = fd;
290         PGPFD(source)->events = G_IO_IN | G_IO_HUP | G_IO_ERR;
291         g_source_set_callback(source, port_events_read_cb, NULL, NULL);
292         g_source_attach(source, NULL);
293         g_source_unref(source);
294         g_source_add_poll(source, PGPFD(source));
295
296         FK_W ("%s 0x%p fd %d\n", __func__, source, PGPFD(source)->fd);
297     } else {
298         FK_W ("PORT_CREATE %s\n", g_strerror(errno));
299         g_return_val_if_reached(NULL);
300     }
301
302         return source;
303 }
304
305 /**
306  * port_add:
307  * @f:
308  *
309  * Unsafe, need lock fen_lock.
310  * port_add will associate a GSource to @f->source
311  */
312 gint
313 port_add(node_t *f)
314 {
315         GSource *source = f->source;
316
317     FK_W ("%s [0x%p] %s\n", __func__, f, NODE_NAME(f));
318
319     g_assert(f);
320     g_assert(NODE_HAS_FLAG(f, NODE_FLAG_STAT_UPDATED));
321
322     /* if (!NODE_HAS_FLAG(f, NODE_FLAG_STAT_DONE)) { */
323     /*     if (NODE_STAT(f) != 0) { */
324     /*         return errno; */
325     /*     } */
326     /* } */
327
328     /* Try re-use f->pn. f->pn may be used by other request, e.g. f is deleted
329      * for a long time. So if pn is full, we try to open a new one.
330      */
331     if (!source) {
332 start_over:
333         /* Try the next visible source. */
334         if (pn_visible_list) {
335             source = (GSource *)pn_visible_list->data;
336         } else {
337             if ((source = psource_new()) != NULL) {
338                 g_assert (g_list_find (pn_visible_list, source) == NULL);
339                 pn_visible_list = g_list_prepend (pn_visible_list, source);
340             }
341         }
342     }
343
344     if (port_associate(PGPFD(source)->fd, PORT_SOURCE_FILE, (uintptr_t)FILE_OBJECT(f),
345         CONCERNED_EVENTS,
346         (void *)f) == 0) {
347         f->source = source;
348         NODE_SET_STATE(f, NODE_STATE_ASSOCIATED);
349         NODE_CLE_FLAG(f, NODE_FLAG_STAT_UPDATED);
350         FK_W ("PORT_ASSOCIATE 0x%p OK\n", f);
351         return 0;
352     } else if (errno == EAGAIN) {
353         /* Full, remove it. */
354         pn_visible_list = g_list_remove (pn_visible_list, source);
355         /* Re-add to port */
356         goto start_over;
357
358     } else if (errno == ENOENT) {
359         /* File is not exist */
360     } else {
361         FK_W ("PORT_ASSOCIATE 0x%p %s\n", f, g_strerror (errno));
362     }
363
364     /* No matter if associated successfully, stat info is out-of-date, so clean it. */
365     NODE_CLE_FLAG(f, NODE_FLAG_STAT_UPDATED);
366     return errno;
367 }
368
369 /**
370  * port_remove
371  *
372  * < private >
373  * Unsafe, need lock fen_lock.
374  */
375 void
376 port_remove (node_t *f)
377 {
378     /* g_assert(f->source); */
379
380     if (NODE_HAS_STATE(f, NODE_STATE_ASSOCIATED)) {
381         /* Mark unregisted. */
382         if (port_dissociate(PGPFD(f->source)->fd, PORT_SOURCE_FILE, (uintptr_t)FILE_OBJECT(f)) == 0) {
383             /*
384              * Note, we can run foode_delete if dissociating is failed,
385              * because there may be some pending events (mostly like
386              * FILE_DELETE) in the port_get. If we delete the foode
387              * the fnode may be deleted, then port_get will run on an invalid
388              * address.
389              */
390             NODE_CLE_STATE(f, NODE_STATE_ASSOCIATED);
391             FK_W ("PORT_DISSOCIATE 0x%p OK\n", f);
392         } else if (errno == ENOENT) {
393             /* The file has been removed from port, after port_get or before
394              * port_get but DELETED event has been generated.
395              * Ignored. */
396         } else {
397             FK_W ("PORT_DISSOCIATE 0x%p %s\n", f, g_strerror (errno));
398             g_return_if_reached();
399         }
400     }
401 }
402
403 /**
404  * Get Solaris resouce values.
405  *
406  */
407
408 extern gboolean
409 port_class_init (void (*user_process_events_callback) (gpointer, node_event_t*))
410 {
411         rctlblk_t *rblk;
412
413         if ((rblk = malloc (rctlblk_size ())) == NULL) {
414         FK_W ("[kernel] rblk malloc %s\n", g_strerror (errno));
415                 return FALSE;
416         }
417         if (getrctl ("process.max-port-events", NULL, rblk, RCTL_FIRST) == -1) {
418         FK_W ("[kernel] getrctl %s\n", g_strerror (errno));
419         free (rblk);
420         return FALSE;
421         } else {
422         max_port_events = rctlblk_get_value(rblk);
423                 FK_W ("max_port_events = %u\n", max_port_events);
424         free (rblk);
425         }
426     renamed_hash = g_hash_table_new_full(g_direct_hash, g_direct_equal,
427       NULL, NULL);
428     if (renamed_hash == NULL) {
429                 FK_W ("[kernel] FEN global renamed queue initializing faild\n");
430         return FALSE;
431     }
432     if ((g_eventq = g_queue_new ()) == NULL) {
433                 FK_W ("[kernel] FEN global event queue initializing faild\n");
434         return FALSE;
435     }
436     if (user_process_events_callback == NULL) {
437                 FK_W ("[kernel] FEN global no user_process_events_callback\n");
438         return FALSE;
439     }
440     user_process_events_cb = user_process_events_callback;
441     memset (&zero_wait, 0, sizeof (timespec_t));
442
443     pevents = g_malloc(PE_ALLOC * sizeof(port_event_t));
444     if (pevents == NULL) {
445                 FK_W ("[kernel] FEN global alloc pevents failed\n");
446         return FALSE;
447     }
448
449         return TRUE;
450 }
451
452 static gchar*
453 printevent (const char *pname, int event, const char *tag)
454 {
455     static gchar        *event_string = NULL;
456     GString                     *str;
457
458     if (event_string) {
459         g_free(event_string);
460     }
461
462     str = g_string_new ("");
463     g_string_printf (str, "[%s] [%-20s]", tag, pname);
464     if (event & FILE_ACCESS) {
465         str = g_string_append (str, " ACCESS");
466     }
467     if (event & FILE_MODIFIED) {
468         str = g_string_append (str, " MODIFIED");
469     }
470     if (event & FILE_ATTRIB) {
471         str = g_string_append (str, " ATTRIB");
472     }
473     if (event & FILE_DELETE) {
474         str = g_string_append (str, " DELETE");
475     }
476     if (event & FILE_RENAME_TO) {
477         str = g_string_append (str, " RENAME_TO");
478     }
479     if (event & FILE_RENAME_FROM) {
480         str = g_string_append (str, " RENAME_FROM");
481     }
482     if (event & UNMOUNTED) {
483         str = g_string_append (str, " UNMOUNTED");
484     }
485     if (event & MOUNTEDOVER) {
486         str = g_string_append (str, " MOUNTEDOVER");
487     }
488     event_string = str->str;
489     g_string_free (str, FALSE);
490     return event_string;
491 }
492
493 static gchar *
494 _event_strings(int event)
495 {
496     GString *str = g_string_sized_new(80);
497
498     if (event & FILE_DELETE)
499         g_string_append(str, " FILE_DELETE");
500
501     if (event & FILE_RENAME_FROM)
502         g_string_append(str, " FILE_RENAME_FROM");
503
504     if (event & FILE_MODIFIED)
505         g_string_append(str, " FILE_MODIFIED");
506
507     if (event & FILE_RENAME_TO)
508         g_string_append(str, " FILE_RENAME_TO");
509
510     if (event & MOUNTEDOVER)
511         g_string_append(str, " MOUNTEDOVER");
512
513     if (event & FILE_ATTRIB)
514         g_string_append(str, " FILE_ATTRIB");
515
516     if (event & UNMOUNTED)
517         g_string_append(str, " UNMOUNTED");
518
519     if (event & FILE_ACCESS)
520         g_string_append(str, " FILE_ACCESS");
521
522     return g_string_free(str, FALSE);
523 }
524
525 static const gchar *
526 _event_string (int event)
527 {
528     switch (event) {
529     case FILE_DELETE:
530         return "FILE_DELETE";
531     case FILE_RENAME_FROM:
532         return "FILE_RENAME_FROM";
533     case FILE_MODIFIED:
534         return "FILE_MODIFIED";
535     case FILE_RENAME_TO:
536         return "FILE_RENAME_TO";
537     case MOUNTEDOVER:
538         return "MOUNTEDOVER";
539     case FILE_ATTRIB:
540         return "FILE_ATTRIB";
541     case UNMOUNTED:
542         return "UNMOUNTED";
543     case FILE_ACCESS:
544         return "FILE_ACCESS";
545     default:
546         return "EVENT_UNKNOWN";
547     }
548 }
549