Merge remote branch 'gvdb/master'
[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 if (errno == ENOTSUP) {
361         /* FS is not supported. Currently we think it no longer make sense to
362          * monitor it, so clean the stat info and return 0 to ignore this
363          * node. If there are requirement, we can consider to add polling
364          * method.
365          */
366         NODE_CLE_FLAG(f, NODE_FLAG_STAT_UPDATED);
367         return 0;
368     } else {
369         FK_W ("PORT_ASSOCIATE 0x%p %s\n", f, g_strerror (errno));
370     }
371
372     /* No matter if associated successfully, stat info is out-of-date, so clean it. */
373     NODE_CLE_FLAG(f, NODE_FLAG_STAT_UPDATED);
374     return errno;
375 }
376
377 /*
378  * port_remove
379  *
380  * < private >
381  * Unsafe, need lock fen_lock.
382  */
383 void
384 port_remove (node_t *f)
385 {
386     /* g_assert(f->source); */
387
388     if (NODE_HAS_STATE(f, NODE_STATE_ASSOCIATED)) {
389         /* Mark unregisted. */
390         if (port_dissociate(PGPFD(f->source)->fd, PORT_SOURCE_FILE, (uintptr_t)FILE_OBJECT(f)) == 0) {
391             /*
392              * Note, we can run foode_delete if dissociating is failed,
393              * because there may be some pending events (mostly like
394              * FILE_DELETE) in the port_get. If we delete the foode
395              * the fnode may be deleted, then port_get will run on an invalid
396              * address.
397              */
398             NODE_CLE_STATE(f, NODE_STATE_ASSOCIATED);
399             FK_W ("PORT_DISSOCIATE 0x%p OK\n", f);
400         } else if (errno == ENOENT) {
401             /* The file has been removed from port, after port_get or before
402              * port_get but DELETED event has been generated.
403              * Ignored. */
404         } else {
405             FK_W ("PORT_DISSOCIATE 0x%p %s\n", f, g_strerror (errno));
406             g_return_if_reached();
407         }
408     }
409 }
410
411 /*
412  * Get Solaris resouce values.
413  *
414  */
415
416 extern gboolean
417 port_class_init (void (*user_process_events_callback) (gpointer, node_event_t*))
418 {
419         rctlblk_t *rblk;
420
421         if ((rblk = malloc (rctlblk_size ())) == NULL) {
422         FK_W ("[kernel] rblk malloc %s\n", g_strerror (errno));
423                 return FALSE;
424         }
425         if (getrctl ("process.max-port-events", NULL, rblk, RCTL_FIRST) == -1) {
426         FK_W ("[kernel] getrctl %s\n", g_strerror (errno));
427         free (rblk);
428         return FALSE;
429         } else {
430         max_port_events = rctlblk_get_value(rblk);
431                 FK_W ("max_port_events = %u\n", max_port_events);
432         free (rblk);
433         }
434     renamed_hash = g_hash_table_new_full(g_direct_hash, g_direct_equal,
435       NULL, NULL);
436     if (renamed_hash == NULL) {
437                 FK_W ("[kernel] FEN global renamed queue initializing faild\n");
438         return FALSE;
439     }
440     if ((g_eventq = g_queue_new ()) == NULL) {
441                 FK_W ("[kernel] FEN global event queue initializing faild\n");
442         return FALSE;
443     }
444     if (user_process_events_callback == NULL) {
445                 FK_W ("[kernel] FEN global no user_process_events_callback\n");
446         return FALSE;
447     }
448     user_process_events_cb = user_process_events_callback;
449     memset (&zero_wait, 0, sizeof (timespec_t));
450
451     pevents = g_malloc(PE_ALLOC * sizeof(port_event_t));
452     if (pevents == NULL) {
453                 FK_W ("[kernel] FEN global alloc pevents failed\n");
454         return FALSE;
455     }
456
457         return TRUE;
458 }
459
460 static gchar*
461 printevent (const char *pname, int event, const char *tag)
462 {
463     static gchar        *event_string = NULL;
464     GString                     *str;
465
466     if (event_string) {
467         g_free(event_string);
468     }
469
470     str = g_string_new ("");
471     g_string_printf (str, "[%s] [%-20s]", tag, pname);
472     if (event & FILE_ACCESS) {
473         str = g_string_append (str, " ACCESS");
474     }
475     if (event & FILE_MODIFIED) {
476         str = g_string_append (str, " MODIFIED");
477     }
478     if (event & FILE_ATTRIB) {
479         str = g_string_append (str, " ATTRIB");
480     }
481     if (event & FILE_DELETE) {
482         str = g_string_append (str, " DELETE");
483     }
484     if (event & FILE_RENAME_TO) {
485         str = g_string_append (str, " RENAME_TO");
486     }
487     if (event & FILE_RENAME_FROM) {
488         str = g_string_append (str, " RENAME_FROM");
489     }
490     if (event & UNMOUNTED) {
491         str = g_string_append (str, " UNMOUNTED");
492     }
493     if (event & MOUNTEDOVER) {
494         str = g_string_append (str, " MOUNTEDOVER");
495     }
496     event_string = str->str;
497     g_string_free (str, FALSE);
498     return event_string;
499 }
500
501 static gchar *
502 _event_strings(int event)
503 {
504     GString *str = g_string_sized_new(80);
505
506     if (event & FILE_DELETE)
507         g_string_append(str, " FILE_DELETE");
508
509     if (event & FILE_RENAME_FROM)
510         g_string_append(str, " FILE_RENAME_FROM");
511
512     if (event & FILE_MODIFIED)
513         g_string_append(str, " FILE_MODIFIED");
514
515     if (event & FILE_RENAME_TO)
516         g_string_append(str, " FILE_RENAME_TO");
517
518     if (event & MOUNTEDOVER)
519         g_string_append(str, " MOUNTEDOVER");
520
521     if (event & FILE_ATTRIB)
522         g_string_append(str, " FILE_ATTRIB");
523
524     if (event & UNMOUNTED)
525         g_string_append(str, " UNMOUNTED");
526
527     if (event & FILE_ACCESS)
528         g_string_append(str, " FILE_ACCESS");
529
530     return g_string_free(str, FALSE);
531 }
532
533 static const gchar *
534 _event_string (int event)
535 {
536     switch (event) {
537     case FILE_DELETE:
538         return "FILE_DELETE";
539     case FILE_RENAME_FROM:
540         return "FILE_RENAME_FROM";
541     case FILE_MODIFIED:
542         return "FILE_MODIFIED";
543     case FILE_RENAME_TO:
544         return "FILE_RENAME_TO";
545     case MOUNTEDOVER:
546         return "MOUNTEDOVER";
547     case FILE_ATTRIB:
548         return "FILE_ATTRIB";
549     case UNMOUNTED:
550         return "UNMOUNTED";
551     case FILE_ACCESS:
552         return "FILE_ACCESS";
553     default:
554         return "EVENT_UNKNOWN";
555     }
556 }