0dcd1652896999a69fc6edf4dfacc68b91f0dc70
[platform/upstream/gstreamer.git] / gst / cothreads.c
1 /* GStreamer
2  * Copyright (C) 1999,2000 Erik Walthinsen <omega@cse.ogi.edu>
3  *                    2000 Wim Taymans <wtay@chello.be>
4  *
5  * cothreads.c: Cothreading routines
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Library 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  * Library General Public License for more details.
16  *
17  * You should have received a copy of the GNU Library General Public
18  * 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
23 #include <glib.h>
24
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <signal.h>
28 #include <setjmp.h>
29 #include <unistd.h>
30 #include <errno.h>
31 #include <sys/mman.h>
32
33 #include "gst_private.h"
34
35 #include "cothreads.h"
36 #include "gstarch.h"
37 #include "gstlog.h"
38 #include "gstutils.h"
39
40 /* older glibc's have MAP_ANON instead of MAP_ANONYMOUS */
41 #ifndef MAP_ANONYMOUS
42 #define MAP_ANONYMOUS MAP_ANON
43 #endif
44
45 #define STACK_SIZE 0x200000
46
47 #define COTHREAD_MAGIC_NUMBER 0xabcdef
48
49 #define COTHREAD_MAXTHREADS 16
50 #define COTHREAD_STACKSIZE (STACK_SIZE/COTHREAD_MAXTHREADS)
51
52 static void     cothread_destroy        (cothread_state *thread);
53
54 struct _cothread_context
55 {
56   cothread_state *cothreads[COTHREAD_MAXTHREADS]; /* array of cothread states */
57   int ncothreads;
58   int current;
59   GHashTable *data;
60 };
61
62
63 /* this _cothread_ctx_key is used as a GThread key to the thread's context
64  * a GThread key is a "pointer" to memory space that is/can be different
65  * (ie. private) for each thread.  The key itself is shared among threads,
66  * so it only needs to be initialized once.
67  */
68 static GPrivate *_cothread_ctx_key;
69
70 /* Disabling this define allows you to shut off a few checks in
71  * cothread_switch.  This likely will speed things up fractionally */
72 /* #define COTHREAD_PARANOID */
73
74 /**
75  * cothread_context_init:
76  *
77  * Create and initialize a new cothread context 
78  *
79  * Returns: the new cothread context
80  */
81 cothread_context *
82 cothread_context_init (void)
83 {
84   cothread_context *ctx;
85
86   /* if there already is a cotread context for this thread,
87    * just return it */
88   ctx = g_private_get (_cothread_ctx_key);
89   if (ctx) 
90     return ctx;
91
92   /*
93    * initalize the whole of the cothreads context 
94    */
95   ctx = (cothread_context *) g_malloc (sizeof (cothread_context));
96
97   /* we consider the initiating process to be cothread 0 */
98   ctx->ncothreads = 1;
99   ctx->current = 0;
100   ctx->data = g_hash_table_new (g_str_hash, g_str_equal);
101
102   GST_INFO (GST_CAT_COTHREADS, "initializing cothreads");
103
104   /* initialize the cothread key (for GThread space) if not done yet */
105   /* FIXME this should be done in cothread_init() */
106   if (_cothread_ctx_key == NULL) {
107     _cothread_ctx_key = g_private_new (NULL);
108     if (_cothread_ctx_key == NULL) {
109       perror ("g_private_new");
110       return NULL;
111     }
112   }
113
114   /* set this thread's context pointer */
115   g_private_set (_cothread_ctx_key, ctx);
116
117   /* clear the cothread data */
118
119   memset (ctx->cothreads, 0, sizeof (ctx->cothreads));
120
121   /*
122    * initialize the 0th cothread
123    */
124   ctx->cothreads[0] = (cothread_state *) g_malloc0 (sizeof (cothread_state));
125   ctx->cothreads[0]->ctx = ctx;
126   ctx->cothreads[0]->cothreadnum = 0;
127   ctx->cothreads[0]->func = NULL;
128   ctx->cothreads[0]->argc = 0;
129   ctx->cothreads[0]->argv = NULL;
130   ctx->cothreads[0]->priv = NULL;
131   ctx->cothreads[0]->flags = COTHREAD_STARTED;
132   ctx->cothreads[0]->sp = (void *) CURRENT_STACK_FRAME;
133   ctx->cothreads[0]->pc = 0;
134
135   GST_INFO (GST_CAT_COTHREADS, "0th cothread is %p at sp:%p", 
136             ctx->cothreads[0], ctx->cothreads[0]->sp);
137
138   return ctx;
139 }
140
141 /**
142  * cothread_context_free:
143  * @ctx: the cothread context to free
144  *
145  * Free the cothread context.
146  */
147 void
148 cothread_context_free (cothread_context *ctx)
149 {
150   gint i;
151
152   g_return_if_fail (ctx != NULL);
153
154   GST_INFO (GST_CAT_COTHREADS, "free cothread context");
155
156   for (i = 0; i < COTHREAD_MAXTHREADS; i++) {
157     if (ctx->cothreads[i]) {
158       cothread_destroy (ctx->cothreads[i]);
159     }
160   }
161   g_hash_table_destroy (ctx->data);
162   g_free (ctx);
163 }
164
165 /**
166  * cothread_create:
167  * @ctx: the cothread context
168  *
169  * Create a new cothread state in the given context
170  *
171  * Returns: the new cothread state or NULL on error
172  */
173 cothread_state*
174 cothread_create (cothread_context *ctx)
175 {
176   cothread_state *cothread;
177   void *sp;
178   void *mmaped = 0;
179   guchar *stack_end;
180   gint slot = 0;
181
182   g_return_val_if_fail (ctx != NULL, NULL);
183
184   if (ctx->ncothreads == COTHREAD_MAXTHREADS) {
185     /* this is pretty fatal */
186     g_warning ("cothread_create: attempt to create > COTHREAD_MAXTHREADS\n");
187     return NULL;
188   }
189   /* find a free spot in the stack, note slot 0 has the main thread */
190   for (slot = 1; slot < ctx->ncothreads; slot++) {
191     if (ctx->cothreads[slot] == NULL)
192       break;
193     else if (ctx->cothreads[slot]->flags & COTHREAD_DESTROYED &&
194                     slot != ctx->current) {
195       cothread_destroy (ctx->cothreads[slot]);
196       break;
197     }
198   }
199
200   GST_DEBUG (GST_CAT_COTHREADS, "Found free cothread slot %d", slot);
201
202   sp = CURRENT_STACK_FRAME;
203   /* FIXME this may not be 64bit clean
204    *       could use casts to uintptr_t from inttypes.h
205    *       if only all platforms had inttypes.h
206    */
207   /* FIXME: a little explanation on what this REALLY means would be nice ;) */
208   stack_end = (guchar *) ((gulong) sp & ~(STACK_SIZE - 1));
209
210   /* cothread stack space of the thread is mapped in reverse, with cothread 0
211    * stack space at the top */
212   cothread = (cothread_state *) (stack_end + ((slot - 1) * COTHREAD_STACKSIZE));
213   GST_DEBUG (GST_CAT_COTHREADS, 
214              "mmap   cothread slot stack from %p to %p (size 0x%lx)", 
215              cothread, cothread + COTHREAD_STACKSIZE, 
216              (long) COTHREAD_STACKSIZE);
217
218   GST_DEBUG (GST_CAT_COTHREADS, "going into mmap");
219   /* the mmap is used to reserve part of the stack
220    * ie. we state explicitly that we are going to use it */
221   mmaped = mmap ((void *) cothread, COTHREAD_STACKSIZE,
222                   PROT_READ | PROT_WRITE | PROT_EXEC, 
223                   MAP_FIXED | MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
224   GST_DEBUG (GST_CAT_COTHREADS, "coming out of mmap");
225   if (mmaped == MAP_FAILED) {
226     perror ("mmap'ing cothread stack space");
227     return NULL;
228   }
229   if (mmaped != cothread) {
230     g_warning ("could not mmap requested memory for cothread");
231     return NULL;
232   }
233
234   cothread->magic_number = COTHREAD_MAGIC_NUMBER;
235   GST_DEBUG (GST_CAT_COTHREADS, "create  cothread %d with magic number 0x%x",
236              slot, cothread->magic_number);
237   cothread->ctx = ctx;
238   cothread->cothreadnum = slot;
239   cothread->flags = 0;
240   cothread->priv = NULL;
241   cothread->sp = ((guchar *) cothread + COTHREAD_STACKSIZE);
242   cothread->top_sp = cothread->sp; /* for debugging purposes 
243                                       to detect stack overruns */
244
245   GST_INFO (GST_CAT_COTHREADS, 
246             "created cothread #%d in slot %d: %p at sp:%p", 
247             ctx->ncothreads, slot, cothread, cothread->sp);
248
249   ctx->cothreads[slot] = cothread;
250   ctx->ncothreads++;
251
252   return cothread;
253 }
254
255 /**
256  * cothread_free:
257  * @cothread: the cothread state
258  *
259  * Free the given cothread state
260  */
261 void
262 cothread_free (cothread_state *cothread)
263 {
264   g_return_if_fail (cothread != NULL);
265
266   GST_INFO (GST_CAT_COTHREADS, "flag cothread %d for destruction", 
267             cothread->cothreadnum);
268
269   /* we simply flag the cothread for destruction here */
270   cothread->flags |= COTHREAD_DESTROYED;
271 }
272
273 static void
274 cothread_destroy (cothread_state *cothread)
275 {
276   cothread_context *ctx;
277   gint cothreadnum;
278
279   g_return_if_fail (cothread != NULL);
280
281   cothreadnum = cothread->cothreadnum;
282   ctx = cothread->ctx;
283
284   GST_INFO (GST_CAT_COTHREADS, "destroy cothread %d %p %d", 
285             cothreadnum, cothread, ctx->current);
286
287   /* we have to unlock here because we might be switched out 
288    * with the lock held */
289   cothread_unlock (cothread);
290
291   if (cothreadnum == 0) 
292   {
293     GST_INFO (GST_CAT_COTHREADS,
294               "trying to destroy cothread 0 with %d cothreads left", 
295              ctx->ncothreads);
296     if (ctx->ncothreads > 1)
297     {
298       /* we're trying to destroy cothread 0 when there are still cothreads
299        * active, so kill those first */
300       int i;
301
302       for (i = 1; i < COTHREAD_MAXTHREADS; ++i)
303       {
304         if (ctx->cothreads[i] != NULL)
305         {
306           cothread_destroy (ctx->cothreads[i]);
307           GST_INFO (GST_CAT_COTHREADS,
308                     "destroyed cothread %d, %d cothreads left\n", 
309                     i, ctx->ncothreads);
310         }
311       }
312     }
313     g_assert (ctx->ncothreads == 1);
314     g_free (cothread);
315   }
316   else {
317   /*  int res; 
318    *  Replaced with version below until cothreads issues solved */
319    int res = 0;
320     
321     /* doing cleanups of the cothread create */
322     GST_DEBUG (GST_CAT_COTHREADS, "destroy cothread %d with magic number 0x%x",
323              cothreadnum, cothread->magic_number);
324     g_assert (cothread->magic_number == COTHREAD_MAGIC_NUMBER);
325
326     g_assert (cothread->priv == NULL);
327
328     GST_DEBUG (GST_CAT_COTHREADS, 
329                "munmap cothread slot stack from %p to %p (size 0x%lx)", 
330                cothread, cothread + COTHREAD_STACKSIZE, 
331                (long) COTHREAD_STACKSIZE);
332 /*    res = munmap (thread, COTHREAD_STACKSIZE);
333  *    Commented out waiting for resolution for cothread issue */
334     if (res != 0)
335     {
336       switch (res)
337       {
338         case EINVAL:
339           g_warning ("munmap doesn't like start %p or length %d\n",
340                      cothread, COTHREAD_STACKSIZE);
341           break;
342         default:
343           g_warning ("Thomas was too lazy to check for all errors, "
344                      "so I can't tell you what is wrong.\n");
345           break;
346       }
347     }
348   }
349   GST_DEBUG (GST_CAT_COTHREADS, "munmap done\n");
350
351   ctx->cothreads[cothreadnum] = NULL;
352   ctx->ncothreads--;
353 }
354
355 /**
356  * cothread_setfunc:
357  * @thread: the cothread state
358  * @func: the function to call
359  * @argc: argument count for the cothread function
360  * @argv: arguments for the cothread function
361  *
362  * Set the cothread function
363  */
364 void
365 cothread_setfunc (cothread_state * thread, cothread_func func, int argc, char **argv)
366 {
367   thread->func = func;
368   thread->argc = argc;
369   thread->argv = argv;
370   thread->pc = (void *) func;
371 }
372
373 /**
374  * cothread_stop:
375  * @thread: the cothread to stop
376  *
377  * Stop the cothread and reset the stack and program counter.
378  */
379 void
380 cothread_stop (cothread_state * thread)
381 {
382   thread->flags &= ~COTHREAD_STARTED;
383   thread->pc = 0;
384   thread->sp = thread->top_sp;
385 }
386
387 /**
388  * cothread_main:
389  * @ctx: cothread context to find main cothread of.
390  *
391  * Gets the main thread.
392  *
393  * Returns: the #cothread_state of the main (0th) cothread.
394  */
395 cothread_state *
396 cothread_main (cothread_context * ctx)
397 {
398   GST_DEBUG (GST_CAT_COTHREADS, "returning %p, the 0th cothread", 
399              ctx->cothreads[0]);
400   return ctx->cothreads[0];
401 }
402
403 /**
404  * cothread_current_main:
405  *
406  * Get the main thread in the current GThread.
407  *
408  * Returns: the #cothread_state of the main (0th) thread in the current GThread
409  */
410 cothread_state *
411 cothread_current_main (void)
412 {
413   cothread_context *ctx = g_private_get (_cothread_ctx_key);
414
415   return ctx->cothreads[0];
416 }
417
418 /**
419  * cothread_current:
420  *
421  * Get the currenttly executing cothread
422  *
423  * Returns: the #cothread_state of the current cothread
424  */
425 cothread_state *
426 cothread_current (void)
427 {
428   cothread_context *ctx = g_private_get (_cothread_ctx_key);
429
430   return ctx->cothreads[ctx->current];
431 }
432
433 static void
434 cothread_stub (void)
435 {
436   cothread_context *ctx = g_private_get (_cothread_ctx_key);
437   register cothread_state *thread = ctx->cothreads[ctx->current];
438
439   GST_DEBUG_ENTER ("");
440
441   thread->flags |= COTHREAD_STARTED;
442
443   while (TRUE) {
444     thread->func (thread->argc, thread->argv);
445     /* we do this to avoid ever returning, we just switch to 0th thread */
446     cothread_switch (cothread_main (ctx));
447   }
448   GST_DEBUG_LEAVE ("");
449 }
450
451 /**
452  * cothread_getcurrent:
453  *
454  * Get the current cothread id
455  *
456  * Returns: the current cothread id
457  */
458 int cothread_getcurrent (void) __attribute__ ((no_instrument_function));
459 int
460 cothread_getcurrent (void)
461 {
462   cothread_context *ctx = g_private_get (_cothread_ctx_key);
463
464   if (!ctx)
465     return -1;
466   return ctx->current;
467 }
468
469 /**
470  * cothread_set_private:
471  * @thread: the cothread state
472  * @data: the data
473  *
474  * set private data for the cothread.
475  */
476 void
477 cothread_set_private (cothread_state *thread, gpointer data)
478 {
479   thread->priv = data;
480 }
481
482 /**
483  * cothread_context_set_data:
484  * @thread: the cothread state
485  * @key: a key for the data
486  * @data: the data
487  *
488  * adds data to a cothread
489  */
490 void
491 cothread_context_set_data (cothread_state *thread, gchar *key, gpointer data)
492 {
493   cothread_context *ctx = g_private_get (_cothread_ctx_key);
494
495   g_hash_table_insert (ctx->data, key, data);
496 }
497
498 /**
499  * cothread_get_private:
500  * @thread: the cothread state
501  *
502  * get the private data from the cothread
503  *
504  * Returns: the private data of the cothread
505  */
506 gpointer
507 cothread_get_private (cothread_state *thread)
508 {
509   return thread->priv;
510 }
511
512 /**
513  * cothread_context_get_data:
514  * @thread: the cothread state
515  * @key: a key for the data
516  *
517  * get data from the cothread
518  *
519  * Returns: the data associated with the key
520  */
521 gpointer
522 cothread_context_get_data (cothread_state * thread, gchar * key)
523 {
524   cothread_context *ctx = g_private_get (_cothread_ctx_key);
525
526   return g_hash_table_lookup (ctx->data, key);
527 }
528
529 /**
530  * cothreads_stackquery:
531  * @stack: Will be set to point to the allocated stack location
532  * @stacksize: Will be set to the size of the allocated stack
533  *
534  *  Returns: #TRUE on success, #FALSE otherwise.
535  */
536 gboolean
537 cothread_stackquery (void **stack, glong* stacksize)
538 {
539   /* use either
540    * - posix_memalign to allocate a 2M-aligned, 2M stack 
541    * or
542    * - valloc 
543    *
544    * memory allocated by either of these two can be freed using free () 
545    * FIXME: define how the stack grows */
546
547 #ifdef HAVE_POSIX_MEMALIGN
548   int retval = posix_memalign (stack, STACK_SIZE, STACK_SIZE);
549   if (retval != 0)
550   {
551     g_warning ("Could not posix_memalign stack !\n");
552     if (retval == EINVAL)
553       g_warning ("The alignment parameter %d was not a power of two !\n",
554                  STACK_SIZE);
555     if (retval == ENOMEM)
556       g_warning ("Insufficient memory to allocate the request of %d !\n",
557                  STACK_SIZE);
558     *stacksize = 0;
559     return FALSE;
560   }
561   GST_DEBUG (GST_CAT_THREAD, "have  posix_memalign at %p of size %d",
562              (void *) *stack, STACK_SIZE);
563 #else
564   if ((*stack = valloc (STACK_SIZE)) != 0)
565   {
566     g_warning ("Could not valloc stack !\n");
567     return FALSE;
568   }
569   GST_DEBUG (GST_CAT_THREAD, "have  valloc at %p of size %d",
570              (void *) *stack, STACK_SIZE);
571 #endif
572
573   GST_DEBUG (GST_CAT_COTHREADS, 
574              "Got new cothread stack from %p to %p (size %ld)",
575              *stack, *stack + STACK_SIZE - 1, (long) STACK_SIZE);
576   *stacksize = STACK_SIZE;
577   return TRUE;
578 }
579
580 /**
581  * cothread_switch:
582  * @thread: cothread state to switch to
583  *
584  * Switches to the given cothread state
585  */
586 void
587 cothread_switch (cothread_state * thread)
588 {
589   cothread_context *ctx;
590   cothread_state *current;
591   int enter;
592
593 #ifdef COTHREAD_PARANOID
594   if (thread == NULL)
595     goto nothread;
596 #endif
597   ctx = thread->ctx;
598 #ifdef COTHREAD_PARANOID
599   if (ctx == NULL)
600     goto nocontext;
601 #endif
602
603   current = ctx->cothreads[ctx->current];
604 #ifdef COTHREAD_PARANOID
605   if (current == NULL)
606     goto nocurrent;
607 #endif
608   if (current == thread)
609     goto selfswitch;
610
611
612   /* find the number of the thread to switch to */
613   GST_INFO (GST_CAT_COTHREAD_SWITCH, 
614             "switching from cothread #%d to cothread #%d",
615             ctx->current, thread->cothreadnum);
616   ctx->current = thread->cothreadnum;
617
618   /* save the current stack pointer, frame pointer, and pc */
619 #ifdef GST_ARCH_PRESETJMP
620   GST_ARCH_PRESETJMP ();
621 #endif
622   enter = setjmp (current->jmp);
623   if (enter != 0) {
624     GST_DEBUG (GST_CAT_COTHREADS, 
625                "enter cothread #%d %d %p<->%p (%d) %p", 
626                current->cothreadnum, enter, current->sp, current->top_sp, 
627                (char*) current->top_sp - (char*) current->sp, current->jmp);
628     return;
629   }
630   GST_DEBUG (GST_CAT_COTHREADS, "exit cothread #%d %d %p<->%p (%d) %p", 
631              current->cothreadnum, enter, current->sp, current->top_sp, 
632              (char *) current->top_sp - (char *) current->sp, current->jmp);
633   enter = 1;
634
635   if (current->flags & COTHREAD_DESTROYED) {
636     cothread_destroy (current);
637   }
638
639   GST_DEBUG (GST_CAT_COTHREADS, "set stack to %p", thread->sp);
640   /* restore stack pointer and other stuff of new cothread */
641   if (thread->flags & COTHREAD_STARTED) {
642     GST_DEBUG (GST_CAT_COTHREADS, "in thread %p", thread->jmp);
643     /* switch to it */
644     longjmp (thread->jmp, 1);
645   }
646   else {
647     GST_ARCH_SETUP_STACK ((char*)thread->sp);
648     GST_ARCH_SET_SP (thread->sp);
649     /* start it */
650     GST_ARCH_CALL (cothread_stub);
651     GST_DEBUG (GST_CAT_COTHREADS, "exit thread ");
652     ctx->current = 0;
653   }
654
655   return;
656
657 #ifdef COTHREAD_PARANOID
658 nothread:
659   g_warning ("cothread: can't switch to NULL cothread!\n");
660   return;
661 nocontext:
662   g_warning ("cothread: there's no context, help!\n");
663   exit (2);
664 nocurrent:
665   g_warning ("cothread: there's no current thread, help!\n");
666   exit (2);
667 #endif /* COTHREAD_PARANOID */
668 selfswitch:
669   g_warning ("cothread: trying to switch to same thread, legal but not necessary\n");
670   return;
671 }
672
673 /**
674  * cothread_lock:
675  * @thread: cothread state to lock
676  *
677  * Locks the cothread state.
678  */
679 void
680 cothread_lock (cothread_state * thread)
681 {
682 }
683
684 /**
685  * cothread_trylock:
686  * @thread: cothread state to try to lock
687  *
688  * Try to lock the cothread state
689  *
690  * Returns: TRUE if the cothread could be locked.
691  */
692 gboolean
693 cothread_trylock (cothread_state * thread)
694 {
695   return TRUE;
696 }
697
698 /**
699  * cothread_unlock:
700  * @thread: cothread state to unlock
701  *
702  * Unlock the cothread state.
703  */
704 void
705 cothread_unlock (cothread_state * thread)
706 {
707 }