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