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