Added setting of _gst_debug_cothread_index for debugging
[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   unsigned long stack_top;
60   GHashTable *data;
61   GThread *thread;
62 };
63
64 /* Disabling this define allows you to shut off a few checks in
65  * cothread_switch.  This likely will speed things up fractionally */
66 #define COTHREAD_PARANOID
67
68
69 /* this _cothread_ctx_key is used as a GThread key to the thread's context
70  * a GThread key is a "pointer" to memory space that is/can be different
71  * (ie. private) for each thread.  The key itself is shared among threads,
72  * so it only needs to be initialized once.
73  */
74 static GStaticPrivate _cothread_ctx_key = G_STATIC_PRIVATE_INIT;
75
76 /*
77  * This should only after context init, since we do checking.
78  */
79 static cothread_context *
80 cothread_get_current_context (void)
81 {
82   cothread_context *ctx;
83
84   ctx = g_static_private_get (&_cothread_ctx_key);
85   g_assert(ctx);
86
87 #ifdef COTHREAD_PARANOID
88   g_assert (ctx->thread == g_thread_self());
89 #endif
90
91   return ctx;
92 }
93
94 /**
95  * cothread_context_init:
96  *
97  * Create and initialize a new cothread context 
98  *
99  * Returns: the new cothread context
100  */
101 cothread_context *
102 cothread_context_init (void)
103 {
104   cothread_context *ctx;
105   void *sp;
106
107   /* if there already is a cotread context for this thread,
108    * just return it */
109   ctx = g_static_private_get (&_cothread_ctx_key);
110   if (ctx) {
111     GST_INFO (GST_CAT_COTHREADS, 
112               "returning private _cothread_ctx_key %p", ctx);
113     return ctx;
114   }
115
116   /*
117    * initalize the whole of the cothreads context 
118    */
119   ctx = (cothread_context *) g_malloc (sizeof (cothread_context));
120
121   /* we consider the initiating process to be cothread 0 */
122   ctx->ncothreads = 1;
123   ctx->current = 0;
124   ctx->data = g_hash_table_new (g_str_hash, g_str_equal);
125   ctx->thread = g_thread_self();
126
127   GST_INFO (GST_CAT_COTHREADS, "initializing cothreads");
128
129   /* set this thread's context pointer */
130   GST_INFO (GST_CAT_COTHREADS, "setting private _cothread_ctx_key to %p",
131             ctx);
132   g_static_private_set (&_cothread_ctx_key, ctx, NULL);
133
134   /* clear the cothread data */
135   memset (ctx->cothreads, 0, sizeof (ctx->cothreads));
136
137   sp = CURRENT_STACK_FRAME;
138   /* FIXME this may not be 64bit clean
139    *       could use casts to uintptr_t from inttypes.h
140    *       if only all platforms had inttypes.h
141    */
142   /* stack_top is the address of the first byte past our stack segment. */
143   /* FIXME: an assumption is made that the stack segment is STACK_SIZE
144    * aligned. */
145   ctx->stack_top = ((gulong) sp | (STACK_SIZE - 1)) + 1;
146   GST_DEBUG (GST_CAT_COTHREADS, "stack top is 0x%08lx", ctx->stack_top);
147
148   /*
149    * initialize the 0th cothread
150    */
151   ctx->cothreads[0] = (cothread_state *) g_malloc0 (sizeof (cothread_state));
152   ctx->cothreads[0]->ctx = ctx;
153   ctx->cothreads[0]->cothreadnum = 0;
154   ctx->cothreads[0]->func = NULL;
155   ctx->cothreads[0]->argc = 0;
156   ctx->cothreads[0]->argv = NULL;
157   ctx->cothreads[0]->priv = NULL;
158   ctx->cothreads[0]->flags = COTHREAD_STARTED;
159   ctx->cothreads[0]->sp = (void *) CURRENT_STACK_FRAME;
160
161   GST_INFO (GST_CAT_COTHREADS, "0th cothread is %p at sp:%p", 
162             ctx->cothreads[0], ctx->cothreads[0]->sp);
163
164   return ctx;
165 }
166
167 /**
168  * cothread_context_free:
169  * @ctx: the cothread context to free
170  *
171  * Free the cothread context.
172  */
173 void
174 cothread_context_free (cothread_context *ctx)
175 {
176   gint i;
177
178   g_return_if_fail (ctx != NULL);
179   g_assert (ctx->thread == g_thread_self());
180
181   GST_INFO (GST_CAT_COTHREADS, "free cothread context");
182
183   for (i = 0; i < COTHREAD_MAXTHREADS; i++) {
184     if (ctx->cothreads[i]) {
185       cothread_destroy (ctx->cothreads[i]);
186     }
187   }
188   g_hash_table_destroy (ctx->data);
189   /* make sure we free the private key for cothread context */
190   g_static_private_set (&_cothread_ctx_key, NULL, NULL);
191   g_free (ctx);
192 }
193
194 /**
195  * cothread_create:
196  * @ctx: the cothread context
197  *
198  * Create a new cothread state in the given context
199  *
200  * Returns: the new cothread state or NULL on error
201  */
202 cothread_state*
203 cothread_create (cothread_context *ctx)
204 {
205   cothread_state *cothread;
206   void *mmaped = 0;
207   gint slot = 0;
208   unsigned long page_size;
209
210   g_return_val_if_fail (ctx != NULL, NULL);
211   g_assert (ctx->thread == g_thread_self());
212
213   if (ctx->ncothreads == COTHREAD_MAXTHREADS) {
214     /* this is pretty fatal */
215     g_warning ("cothread_create: attempt to create > COTHREAD_MAXTHREADS\n");
216     return NULL;
217   }
218   /* find a free spot in the stack, note slot 0 has the main thread */
219   for (slot = 1; slot < ctx->ncothreads; slot++) {
220     if (ctx->cothreads[slot] == NULL)
221       break;
222     else if (ctx->cothreads[slot]->flags & COTHREAD_DESTROYED &&
223                     slot != ctx->current) {
224       cothread_destroy (ctx->cothreads[slot]);
225       break;
226     }
227   }
228
229   GST_DEBUG (GST_CAT_COTHREADS, "Found free cothread slot %d", slot);
230
231   /* cothread stack space of the thread is mapped in reverse, with cothread 0
232    * stack space at the top */
233   cothread = (cothread_state *) (ctx->stack_top - (slot + 1) * COTHREAD_STACKSIZE);
234   GST_DEBUG (GST_CAT_COTHREADS, "cothread pointer is %p", cothread);
235
236 #if 0
237   /* This tests to see whether or not we can grow down the stack */
238   {
239     unsigned long ptr;
240     for(ptr=ctx->stack_top - 4096; ptr > (unsigned long)cothread; ptr -= 4096){
241       GST_DEBUG (GST_CAT_COTHREADS, "touching location 0x%08lx", ptr);
242       *(volatile unsigned int *)ptr = *(volatile unsigned int *)ptr;
243       GST_DEBUG (GST_CAT_COTHREADS, "ok (0x%08x)", *(unsigned int *)ptr);
244     }
245   }
246 #endif
247
248 #ifdef _SC_PAGESIZE
249   page_size = sysconf(_SC_PAGESIZE);
250 #else
251   page_size = getpagesize();
252 #endif
253
254   /* The mmap is necessary on Linux/i386, and possibly others, since the
255    * kernel is picky about when we can expand our stack. */
256   GST_DEBUG (GST_CAT_COTHREADS, "mmaping %p, size 0x%08x", cothread,
257              COTHREAD_STACKSIZE);
258   /* Remap with a guard page. This decreases our stack size by 8 kB (for
259    * 4 kB pages) and also wastes almost 4 kB for the cothreads
260    * structure */
261   munmap((void *)cothread, COTHREAD_STACKSIZE);
262   mmaped = mmap ((void *) cothread, page_size,
263                  PROT_READ | PROT_WRITE,
264                  MAP_FIXED | MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
265   mmaped = mmap (((void *) cothread) + page_size * 2,
266                  COTHREAD_STACKSIZE - page_size * 2,
267                  PROT_READ | PROT_WRITE | PROT_EXEC,
268                  MAP_FIXED | MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
269   GST_DEBUG (GST_CAT_COTHREADS, "coming out of mmap");
270   if (mmaped == MAP_FAILED) {
271     perror ("mmap'ing cothread stack space");
272     return NULL;
273   }
274   if (mmaped != (void *)cothread + page_size * 2) {
275     g_warning ("could not mmap requested memory for cothread");
276     return NULL;
277   }
278
279   cothread->magic_number = COTHREAD_MAGIC_NUMBER;
280   GST_DEBUG (GST_CAT_COTHREADS, "create  cothread %d with magic number 0x%x",
281              slot, cothread->magic_number);
282   cothread->ctx = ctx;
283   cothread->cothreadnum = slot;
284   cothread->flags = 0;
285   cothread->priv = NULL;
286   cothread->sp = ((guchar *) cothread + COTHREAD_STACKSIZE);
287   cothread->stack_size = COTHREAD_STACKSIZE - page_size * 2;
288   cothread->stack_base = (void *)cothread + 2 * page_size;
289
290   GST_INFO (GST_CAT_COTHREADS, 
291             "created cothread #%d in slot %d: %p at sp:%p", 
292             ctx->ncothreads, slot, cothread, cothread->sp);
293
294   ctx->cothreads[slot] = cothread;
295   ctx->ncothreads++;
296
297   return cothread;
298 }
299
300 /**
301  * cothread_free:
302  * @cothread: the cothread state
303  *
304  * Free the given cothread state
305  */
306 void
307 cothread_free (cothread_state *cothread)
308 {
309   g_return_if_fail (cothread != NULL);
310
311   GST_INFO (GST_CAT_COTHREADS, "flag cothread %d for destruction", 
312             cothread->cothreadnum);
313
314   /* we simply flag the cothread for destruction here */
315   if (cothread)
316     cothread->flags |= COTHREAD_DESTROYED;
317   else
318     g_warning ("somebody set up us the bomb");
319 }
320
321 static void
322 cothread_destroy (cothread_state *cothread)
323 {
324   cothread_context *ctx;
325   gint cothreadnum;
326
327   g_return_if_fail (cothread != NULL);
328
329   cothreadnum = cothread->cothreadnum;
330   ctx = cothread->ctx;
331   g_assert (ctx->thread == g_thread_self());
332
333   GST_INFO (GST_CAT_COTHREADS, "destroy cothread %d %p %d", 
334             cothreadnum, cothread, ctx->current);
335
336   /* we have to unlock here because we might be switched out 
337    * with the lock held */
338   cothread_unlock (cothread);
339
340   if (cothreadnum == 0) 
341   {
342     GST_INFO (GST_CAT_COTHREADS,
343               "trying to destroy cothread 0 with %d cothreads left", 
344              ctx->ncothreads);
345     if (ctx->ncothreads > 1)
346     {
347       /* we're trying to destroy cothread 0 when there are still cothreads
348        * active, so kill those first */
349       int i;
350
351       for (i = 1; i < COTHREAD_MAXTHREADS; ++i)
352       {
353         if (ctx->cothreads[i] != NULL)
354         {
355           cothread_destroy (ctx->cothreads[i]);
356           GST_INFO (GST_CAT_COTHREADS,
357                     "destroyed cothread %d, %d cothreads left",
358                     i, ctx->ncothreads);
359         }
360       }
361     }
362     g_assert (ctx->ncothreads == 1);
363     GST_INFO (GST_CAT_COTHREADS, "freeing 0th cothread");
364     g_free (cothread);
365   }
366   else {
367   /*  int res; 
368    *  Replaced with version below until cothreads issues solved */
369    int res = 0;
370     
371     /* doing cleanups of the cothread create */
372     GST_DEBUG (GST_CAT_COTHREADS, "destroy cothread %d with magic number 0x%x",
373              cothreadnum, cothread->magic_number);
374     g_assert (cothread->magic_number == COTHREAD_MAGIC_NUMBER);
375
376     g_assert (cothread->priv == NULL);
377
378     GST_DEBUG (GST_CAT_COTHREADS, 
379                "munmap cothread slot stack from %p to %p (size 0x%lx)", 
380                cothread, cothread + COTHREAD_STACKSIZE, 
381                (long) COTHREAD_STACKSIZE);
382 /*    res = munmap (thread, COTHREAD_STACKSIZE);
383  *    Commented out waiting for resolution for cothread issue */
384     if (res != 0)
385     {
386       switch (res)
387       {
388         case EINVAL:
389           g_warning ("munmap doesn't like start %p or length %d\n",
390                      cothread, COTHREAD_STACKSIZE);
391           break;
392         default:
393           g_warning ("Thomas was too lazy to check for all errors, "
394                      "so I can't tell you what is wrong.\n");
395           break;
396       }
397     }
398   }
399   GST_DEBUG (GST_CAT_COTHREADS, "munmap done");
400
401   ctx->cothreads[cothreadnum] = NULL;
402   ctx->ncothreads--;
403 }
404
405 /**
406  * cothread_setfunc:
407  * @thread: the cothread state
408  * @func: the function to call
409  * @argc: argument count for the cothread function
410  * @argv: arguments for the cothread function
411  *
412  * Set the cothread function
413  */
414 void
415 cothread_setfunc (cothread_state * thread, cothread_func func, int argc, char **argv)
416 {
417   thread->func = func;
418   thread->argc = argc;
419   thread->argv = argv;
420 }
421
422 /**
423  * cothread_stop:
424  * @thread: the cothread to stop
425  *
426  * Stop the cothread and reset the stack and program counter.
427  */
428 void
429 cothread_stop (cothread_state * thread)
430 {
431   thread->flags &= ~COTHREAD_STARTED;
432 }
433
434 /**
435  * cothread_main:
436  * @ctx: cothread context to find main cothread of.
437  *
438  * Gets the main thread.
439  *
440  * Returns: the #cothread_state of the main (0th) cothread.
441  */
442 cothread_state *
443 cothread_main (cothread_context * ctx)
444 {
445   GST_DEBUG (GST_CAT_COTHREADS, "returning %p, the 0th cothread", 
446              ctx->cothreads[0]);
447   return ctx->cothreads[0];
448 }
449
450 /**
451  * cothread_current_main:
452  *
453  * Get the main thread in the current GThread.
454  *
455  * Returns: the #cothread_state of the main (0th) thread in the current GThread
456  */
457 cothread_state *
458 cothread_current_main (void)
459 {
460   cothread_context *ctx = cothread_get_current_context();
461
462   return ctx->cothreads[0];
463 }
464
465 /**
466  * cothread_current:
467  *
468  * Get the currenttly executing cothread
469  *
470  * Returns: the #cothread_state of the current cothread
471  */
472 cothread_state *
473 cothread_current (void)
474 {
475   cothread_context *ctx = cothread_get_current_context();
476
477   return ctx->cothreads[ctx->current];
478 }
479
480 static void
481 cothread_stub (void)
482 {
483   cothread_context *ctx = cothread_get_current_context();
484   register cothread_state *thread = ctx->cothreads[ctx->current];
485
486   GST_DEBUG_ENTER ("");
487
488   GST_DEBUG (GST_CAT_COTHREADS, "stack addr %p\n", &ctx);
489
490   thread->flags |= COTHREAD_STARTED;
491
492   while (TRUE) {
493     thread->func (thread->argc, thread->argv);
494     /* we do this to avoid ever returning, we just switch to 0th thread */
495     cothread_switch (cothread_main (ctx));
496   }
497   GST_DEBUG_LEAVE ("");
498 }
499
500 /**
501  * cothread_getcurrent:
502  *
503  * Get the current cothread id
504  *
505  * Returns: the current cothread id
506  */
507 int cothread_getcurrent (void) G_GNUC_NO_INSTRUMENT;
508
509 int
510 cothread_getcurrent (void)
511 {
512   cothread_context *ctx = cothread_get_current_context();
513
514   if (!ctx)
515     return -1;
516   return ctx->current;
517 }
518
519 /**
520  * cothread_set_private:
521  * @thread: the cothread state
522  * @data: the data
523  *
524  * set private data for the cothread.
525  */
526 void
527 cothread_set_private (cothread_state *thread, gpointer data)
528 {
529   thread->priv = data;
530 }
531
532 /**
533  * cothread_context_set_data:
534  * @thread: the cothread state
535  * @key: a key for the data
536  * @data: the data
537  *
538  * adds data to a cothread
539  */
540 void
541 cothread_context_set_data (cothread_state *thread, gchar *key, gpointer data)
542 {
543   cothread_context *ctx = cothread_get_current_context();
544
545   g_hash_table_insert (ctx->data, key, data);
546 }
547
548 /**
549  * cothread_get_private:
550  * @thread: the cothread state
551  *
552  * get the private data from the cothread
553  *
554  * Returns: the private data of the cothread
555  */
556 gpointer
557 cothread_get_private (cothread_state *thread)
558 {
559   return thread->priv;
560 }
561
562 /**
563  * cothread_context_get_data:
564  * @thread: the cothread state
565  * @key: a key for the data
566  *
567  * get data from the cothread
568  *
569  * Returns: the data associated with the key
570  */
571 gpointer
572 cothread_context_get_data (cothread_state * thread, gchar * key)
573 {
574   cothread_context *ctx = cothread_get_current_context();
575
576   return g_hash_table_lookup (ctx->data, key);
577 }
578
579 /**
580  * cothread_switch:
581  * @thread: cothread state to switch to
582  *
583  * Switches to the given cothread state
584  */
585 void
586 cothread_switch (cothread_state * thread)
587 {
588   cothread_context *ctx;
589   cothread_state *current;
590   int enter;
591
592 #ifdef COTHREAD_PARANOID
593   if (thread == NULL)
594     goto nothread;
595 #endif
596   ctx = thread->ctx;
597
598   /* paranoia check to make sure we're in the right thread */
599   g_assert (ctx->thread == g_thread_self());
600
601 #ifdef COTHREAD_PARANOID
602   if (ctx == NULL)
603     goto nocontext;
604 #endif
605
606   current = ctx->cothreads[ctx->current];
607 #ifdef COTHREAD_PARANOID
608   if (current == NULL)
609     goto nocurrent;
610 #endif
611   if (current == thread)
612     goto selfswitch;
613
614
615   /* find the number of the thread to switch to */
616   GST_INFO (GST_CAT_COTHREAD_SWITCH, 
617             "switching from cothread #%d to cothread #%d",
618             ctx->current, thread->cothreadnum);
619   ctx->current = thread->cothreadnum;
620
621   g_static_private_set (&_gst_debug_cothread_index, (void *)ctx->current, NULL);
622
623   /* save the current stack pointer, frame pointer, and pc */
624 #ifdef GST_ARCH_PRESETJMP
625   GST_ARCH_PRESETJMP ();
626 #endif
627   enter = setjmp (current->jmp);
628   if (enter != 0) {
629     GST_DEBUG (GST_CAT_COTHREADS, 
630                "enter cothread #%d %d sp=%p jmpbuf=%p", 
631                current->cothreadnum, enter, current->sp, current->jmp);
632     return;
633   }
634   GST_DEBUG (GST_CAT_COTHREADS, "exit cothread #%d %d sp=%p jmpbuf=%p", 
635              current->cothreadnum, enter, current->sp, current->jmp);
636   enter = 1;
637
638   if (current->flags & COTHREAD_DESTROYED) {
639     cothread_destroy (current);
640   }
641
642   GST_DEBUG (GST_CAT_COTHREADS, "set stack to %p", thread->sp);
643   /* restore stack pointer and other stuff of new cothread */
644   if (thread->flags & COTHREAD_STARTED) {
645     GST_DEBUG (GST_CAT_COTHREADS, "via longjmp() jmpbuf %p", thread->jmp);
646     /* switch to it */
647     longjmp (thread->jmp, 1);
648   }
649   else {
650 #ifdef HAVE_MAKECONTEXT
651     ucontext_t ucp;
652
653     GST_DEBUG (GST_CAT_COTHREADS, "making context");
654
655     g_assert(thread != cothread_main(ctx));
656
657     getcontext(&ucp);
658     ucp.uc_stack.ss_sp = (void *)thread->stack_base;
659     ucp.uc_stack.ss_size = thread->stack_size;
660     makecontext(&ucp, cothread_stub, 0);
661     setcontext(&ucp);
662 #else
663     GST_ARCH_SETUP_STACK ((char*)thread->sp);
664     GST_ARCH_SET_SP (thread->sp);
665     /* start it */
666     GST_ARCH_CALL (cothread_stub);
667 #endif
668
669     GST_DEBUG (GST_CAT_COTHREADS, "exit thread ");
670     ctx->current = 0;
671   }
672
673   return;
674
675 #ifdef COTHREAD_PARANOID
676 nothread:
677   g_warning ("cothread: can't switch to NULL cothread!\n");
678   return;
679 nocontext:
680   g_warning ("cothread: there's no context, help!\n");
681   exit (2);
682 nocurrent:
683   g_warning ("cothread: there's no current thread, help!\n");
684   exit (2);
685 #endif /* COTHREAD_PARANOID */
686 selfswitch:
687   g_warning ("cothread: trying to switch to same thread, legal but not necessary\n");
688   return;
689 }
690
691 /**
692  * cothread_lock:
693  * @thread: cothread state to lock
694  *
695  * Locks the cothread state.
696  */
697 void
698 cothread_lock (cothread_state * thread)
699 {
700 }
701
702 /**
703  * cothread_trylock:
704  * @thread: cothread state to try to lock
705  *
706  * Try to lock the cothread state
707  *
708  * Returns: TRUE if the cothread could be locked.
709  */
710 gboolean
711 cothread_trylock (cothread_state * thread)
712 {
713   return TRUE;
714 }
715
716 /**
717  * cothread_unlock:
718  * @thread: cothread state to unlock
719  *
720  * Unlock the cothread state.
721  */
722 void
723 cothread_unlock (cothread_state * thread)
724 {
725 }