3 * Copyright 2007,2008,2009 Free Software Foundation, Inc.
5 * This file is part of GNU Radio
7 * GNU Radio is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 3, or (at your option)
12 * GNU Radio 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
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License along
18 * with this program; if not, write to the Free Software Foundation, Inc.,
19 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
25 #include "gc_job_manager_impl.h"
26 #include <gcell/gc_mbox.h>
27 #include <gcell/gc_aligned_alloc.h>
28 #include <gcell/memory_barrier.h>
29 #include <gc_proc_def_utils.h>
30 #include <atomic_dec_if_positive.h>
36 #include <sys/types.h>
43 #define __nop() __asm__ volatile ("ori 0,0,0" : : : "memory")
44 #define __cctpl() __asm__ volatile ("or 1,1,1" : : : "memory")
45 #define __cctpm() __asm__ volatile ("or 2,2,2" : : : "memory")
46 #define __cctph() __asm__ volatile ("or 3,3,3" : : : "memory")
47 #define __db8cyc() __asm__ volatile ("or 28,28,28" : : : "memory")
48 #define __db10cyc() __asm__ volatile ("or 29,29,29" : : : "memory")
49 #define __db12cyc() __asm__ volatile ("or 30,30,30" : : : "memory")
50 #define __db16cyc() __asm__ volatile ("or 31,31,31" : : : "memory")
54 #define CCTPL() __cctpl()
55 #define CCTPM() __cctpm()
57 #define CCTPL() (void) 0
58 #define CCTPM() (void) 0
61 static const size_t CACHE_LINE_SIZE = 128;
63 static const unsigned int DEFAULT_MAX_JOBS = 128;
64 static const unsigned int DEFAULT_MAX_CLIENT_THREADS = 64;
66 // FIXME this really depends on the SPU code...
67 static const unsigned int MAX_TOTAL_INDIRECT_LENGTH = 16 * 1024;
70 static bool s_key_initialized = false;
71 static pthread_key_t s_client_key;
73 static int s_worker_debug = 0;
75 // custom deleter of gang_contexts for use with boost::shared_ptr
78 void operator()(spe_gang_context_ptr_t ctx) {
80 int r = spe_gang_context_destroy(ctx);
82 perror("spe_gang_context_destroy");
89 // custom deleter of anything that can be freed with "free"
92 void operator()(void *p) {
99 * Called when client thread is destroyed.
100 * We mark our client info free.
103 client_key_destructor(void *p)
105 ((gc_client_thread_info *) p)->d_free = 1;
109 is_power_of_2(uint32_t x)
111 return (x != 0) && !(x & (x - 1));
114 ////////////////////////////////////////////////////////////////////////
117 gc_job_manager_impl::gc_job_manager_impl(const gc_jm_options *options)
118 : d_debug(0), d_spu_args(0),
119 d_eh_cond(&d_eh_mutex), d_eh_thread(0), d_eh_state(EHS_INIT),
120 d_shutdown_requested(false),
121 d_jc_cond(&d_jc_mutex), d_jc_thread(0), d_jc_state(JCS_INIT), d_jc_njobs_active(0),
122 d_ntell(0), d_tell_start(0),
123 d_client_thread(0), d_ea_args_maxsize(0),
124 d_proc_def(0), d_proc_def_ls_addr(0), d_nproc_defs(0)
126 if (!s_key_initialized){
127 int r = pthread_key_create(&s_client_key, client_key_destructor);
129 throw std::runtime_error("pthread_key_create");
130 s_key_initialized = true;
134 pthread_setspecific(s_client_key, 0);
137 d_options = *options;
139 // provide the real default for those indicated with a zero
140 if (d_options.max_jobs == 0)
141 d_options.max_jobs = DEFAULT_MAX_JOBS;
142 if (d_options.max_client_threads == 0)
143 d_options.max_client_threads = DEFAULT_MAX_CLIENT_THREADS;
145 if (!d_options.program_handle){
146 fprintf(stderr, "gc_job_manager: options->program_handle must be non-zero\n");
147 throw std::runtime_error("gc_job_manager: options->program_handle must be non-zero");
150 int ncpu_nodes = spe_cpu_info_get(SPE_COUNT_PHYSICAL_CPU_NODES, -1);
151 int nusable_spes = spe_cpu_info_get(SPE_COUNT_USABLE_SPES, -1);
154 printf("cpu_nodes = %d\n", ncpu_nodes);
155 for (int i = 0; i < ncpu_nodes; i++){
156 printf("node[%d].physical_spes = %2d\n", i,
157 spe_cpu_info_get(SPE_COUNT_PHYSICAL_SPES, i));
158 printf("node[%d].usable_spes = %2d\n", i,
159 spe_cpu_info_get(SPE_COUNT_USABLE_SPES, i));
164 d_options.nspes = std::min(d_options.nspes, (unsigned int) MAX_SPES);
165 nusable_spes = std::min(nusable_spes, (int) MAX_SPES);
168 // sanity check requested number of spes.
170 if (d_options.nspes == 0) // use all of them
171 d_options.nspes = nusable_spes;
173 if (d_options.nspes > (unsigned int) nusable_spes){
175 "gc_job_manager: warning: caller requested %d spes. There are only %d available.\n",
176 d_options.nspes, nusable_spes);
177 if (d_options.gang_schedule){
178 // If we're gang scheduling we'll never get scheduled if we
179 // ask for more than are available.
180 throw std::out_of_range("gang_scheduling: not enough spes available");
182 else { // FIXME clamp to usable. problem on PS3 when overcommited
183 fprintf(stderr, "gc_job_manager: clamping nspes to %d\n", nusable_spes);
184 d_options.nspes = nusable_spes;
189 if (d_options.use_affinity){
190 printf("gc_job_manager: warning: affinity request was ignored\n");
193 if (d_options.gang_schedule){
194 d_gang = spe_gang_context_sptr(spe_gang_context_create(0), gang_deleter());
196 perror("gc_job_manager_impl[spe_gang_context_create]");
197 throw std::runtime_error("spe_gang_context_create");
201 d_ntell = std::min(d_options.nspes, 2U);
203 // ----------------------------------------------------------------
204 // initalize the job queue
206 d_queue = (gc_jd_queue_t *) gc_aligned_alloc(sizeof(gc_jd_queue_t), CACHE_LINE_SIZE);
208 boost::shared_ptr<void>((void *) d_queue, free_deleter());
209 gc_jd_queue_init(d_queue);
212 // ----------------------------------------------------------------
213 // create the spe contexts
215 // 1 spu_arg struct for each SPE
216 assert(sizeof(gc_spu_args_t) % 16 == 0);
218 (gc_spu_args_t *) gc_aligned_alloc(MAX_SPES * sizeof(gc_spu_args_t), 16);
220 boost::shared_ptr<void>((void *) d_spu_args, free_deleter());
222 // 2 completion info structs for each SPE (we double buffer them)
223 assert(sizeof(gc_comp_info_t) % CACHE_LINE_SIZE == 0);
225 (gc_comp_info_t *) gc_aligned_alloc(2 * MAX_SPES * sizeof(gc_comp_info_t),
228 boost::shared_ptr<void>((void *) d_comp_info, free_deleter());
231 // get a handle to the spe program
233 spe_program_handle_t *spe_image = d_options.program_handle.get();
235 // fish proc_def table out of SPE ELF file
237 if (!gcpd_find_table(spe_image, &d_proc_def, &d_nproc_defs, &d_proc_def_ls_addr)){
238 fprintf(stderr, "gc_job_manager_impl: couldn't find gc_proc_defs in SPE ELF file.\n");
239 throw std::runtime_error("no gc_proc_defs");
241 // fprintf(stderr, "d_proc_def_ls_addr = 0x%0x\n", d_proc_def_ls_addr);
243 int spe_flags = (SPE_EVENTS_ENABLE
245 | SPE_CFG_SIGNOTIFY1_OR
246 | SPE_CFG_SIGNOTIFY2_OR);
248 for (unsigned int i = 0; i < d_options.nspes; i++){
249 // FIXME affinity stuff goes here
250 d_worker[i].spe_ctx = spe_context_create(spe_flags, d_gang.get());;
251 if (d_worker[i].spe_ctx == 0){
252 perror("spe_context_create");
253 throw std::runtime_error("spe_context_create");
256 d_worker[i].spe_ctrl =
257 (spe_spu_control_area_t *)spe_ps_area_get(d_worker[i].spe_ctx, SPE_CONTROL_AREA);
258 if (d_worker[i].spe_ctrl == 0){
259 perror("spe_ps_area_get(SPE_CONTROL_AREA)");
260 throw std::runtime_error("spe_ps_area_get(SPE_CONTROL_AREA)");
263 d_worker[i].spe_idx = i;
264 d_worker[i].spu_args = &d_spu_args[i];
265 d_worker[i].spu_args->queue = ptr_to_ea(d_queue);
266 d_worker[i].spu_args->comp_info[0] = ptr_to_ea(&d_comp_info[2*i+0]);
267 d_worker[i].spu_args->comp_info[1] = ptr_to_ea(&d_comp_info[2*i+1]);
268 d_worker[i].spu_args->spu_idx = i;
269 d_worker[i].spu_args->nspus = d_options.nspes;
270 d_worker[i].spu_args->proc_def_ls_addr = d_proc_def_ls_addr;
271 d_worker[i].spu_args->nproc_defs = d_nproc_defs;
272 d_worker[i].spu_args->log.base = 0;
273 d_worker[i].spu_args->log.nentries = 0;
274 d_worker[i].state = WS_INIT;
276 int r = spe_program_load(d_worker[i].spe_ctx, spe_image);
278 perror("spe_program_load");
279 throw std::runtime_error("spe_program_load");
285 // ----------------------------------------------------------------
286 // initalize the free list of job descriptors
288 d_free_list = (gc_jd_stack_t *) gc_aligned_alloc(sizeof(gc_jd_stack_t), CACHE_LINE_SIZE);
289 // This ensures that the memory associated with d_free_list is
290 // automatically freed in the destructor or if an exception occurs
291 // here in the constructor.
293 boost::shared_ptr<void>((void *) d_free_list, free_deleter());
294 gc_jd_stack_init(d_free_list);
297 printf("sizeof(d_jd[0]) = %d (0x%x)\n", sizeof(d_jd[0]), sizeof(d_jd[0]));
298 printf("max_jobs = %u\n", d_options.max_jobs);
301 // Initialize the array of job descriptors.
302 d_jd = (gc_job_desc_t *) gc_aligned_alloc(sizeof(d_jd[0]) * d_options.max_jobs, CACHE_LINE_SIZE);
303 _d_jd_boost = boost::shared_ptr<void>((void *) d_jd, free_deleter());
307 for (int i = 0; i < (int) d_options.max_jobs; i++)
308 d_jd[i].sys.job_id = i;
310 // push them onto the free list
311 for (int i = d_options.max_jobs - 1; i >= 0; i--)
312 free_job_desc(&d_jd[i]);
314 // ----------------------------------------------------------------
315 // initialize d_client_thread
318 gc_client_thread_info_sa cti(
319 new gc_client_thread_info[d_options.max_client_threads]);
321 d_client_thread.swap(cti);
323 for (unsigned int i = 0; i < d_options.max_client_threads; i++)
324 d_client_thread[i].d_client_id = i;
327 // ----------------------------------------------------------------
328 // initialize bitvectors
330 // initialize d_bvlen, the number of longs in job related bitvectors.
331 int bits_per_long = sizeof(unsigned long) * 8;
332 d_bvlen = (d_options.max_jobs + bits_per_long - 1) / bits_per_long;
334 // allocate all bitvectors in a single cache-aligned chunk
335 size_t nlongs = d_bvlen * d_options.max_client_threads;
336 void *p = gc_aligned_alloc(nlongs * sizeof(unsigned long), CACHE_LINE_SIZE);
337 _d_all_bitvectors = boost::shared_ptr<void>(p, free_deleter());
339 // Now point the gc_client_thread_info bitvectors into this storage
340 unsigned long *v = (unsigned long *) p;
342 for (unsigned int i = 0; i < d_options.max_client_threads; i++, v += d_bvlen)
343 d_client_thread[i].d_jobs_done = v;
346 // ----------------------------------------------------------------
347 // create the spe event handler & worker (SPE) threads
349 create_event_handler();
352 ////////////////////////////////////////////////////////////////////////
354 gc_job_manager_impl::~gc_job_manager_impl()
358 d_jd = 0; // handled via _d_jd_boost
359 d_free_list = 0; // handled via _d_free_list_boost
360 d_queue = 0; // handled via _d_queue_boost
362 // clear cti, since we've deleted the underlying data
363 pthread_setspecific(s_client_key, 0);
369 gc_job_manager_impl::shutdown()
371 omni_mutex_lock l(d_eh_mutex);
374 omni_mutex_lock l2(d_jc_mutex);
375 d_shutdown_requested = true; // set flag for event handler thread
376 d_jc_cond.signal(); // wake up job completer
379 // should only happens during early QA code
380 if (d_eh_thread == 0 && d_eh_state == EHS_INIT)
383 while (d_eh_state != EHS_DEAD) // wait for it to finish
390 gc_job_manager_impl::nspes() const
392 return d_options.nspes;
395 ////////////////////////////////////////////////////////////////////////
398 gc_job_manager_impl::bv_zero(unsigned long *bv)
400 memset(bv, 0, sizeof(unsigned long) * d_bvlen);
404 gc_job_manager_impl::bv_clr(unsigned long *bv, unsigned int bitno)
406 unsigned int wi = bitno / (sizeof (unsigned long) * 8);
407 unsigned int bi = bitno & ((sizeof (unsigned long) * 8) - 1);
408 bv[wi] &= ~(1UL << bi);
412 gc_job_manager_impl::bv_set(unsigned long *bv, unsigned int bitno)
414 unsigned int wi = bitno / (sizeof (unsigned long) * 8);
415 unsigned int bi = bitno & ((sizeof (unsigned long) * 8) - 1);
416 bv[wi] |= (1UL << bi);
420 gc_job_manager_impl::bv_isset(unsigned long *bv, unsigned int bitno)
422 unsigned int wi = bitno / (sizeof (unsigned long) * 8);
423 unsigned int bi = bitno & ((sizeof (unsigned long) * 8) - 1);
424 return (bv[wi] & (1UL << bi)) != 0;
428 gc_job_manager_impl::bv_isclr(unsigned long *bv, unsigned int bitno)
430 unsigned int wi = bitno / (sizeof (unsigned long) * 8);
431 unsigned int bi = bitno & ((sizeof (unsigned long) * 8) - 1);
432 return (bv[wi] & (1UL << bi)) == 0;
435 ////////////////////////////////////////////////////////////////////////
438 gc_job_manager_impl::alloc_job_desc()
440 // stack is lock free, and safe to call from any thread
441 gc_job_desc *jd = gc_jd_stack_pop(d_free_list);
443 throw gc_bad_alloc("alloc_job_desc: none available");
449 gc_job_manager_impl::free_job_desc(gc_job_desc *jd)
451 // stack is lock free, thus safe to call from any thread
453 gc_jd_stack_push(d_free_list, jd);
456 ////////////////////////////////////////////////////////////////////////
460 gc_job_manager_impl::incr_njobs_active()
462 omni_mutex_lock l(d_jc_mutex);
464 if (d_shutdown_requested)
467 if (d_jc_njobs_active++ == 0) // signal on 0 to 1 transition
474 gc_job_manager_impl::decr_njobs_active(int n)
476 omni_mutex_lock l(d_jc_mutex);
477 d_jc_njobs_active -= n;
482 * We check as much as we can here on the PPE side, so that the SPE
486 check_direct_args(gc_job_desc *jd, gc_job_direct_args *args)
488 if (args->nargs > MAX_ARGS_DIRECT){
489 jd->status = JS_BAD_N_DIRECT;
497 check_ea_args(gc_job_desc *jd, gc_job_ea_args *p)
499 if (p->nargs > MAX_ARGS_EA){
500 jd->status = JS_BAD_N_EA;
504 uint32_t dir_union = 0;
506 for (unsigned int i = 0; i < p->nargs; i++){
507 dir_union |= p->arg[i].direction;
508 switch(p->arg[i].direction){
514 jd->status = JS_BAD_DIRECTION;
520 unsigned int common_eah = (p->arg[0].ea_addr) >> 32;
521 for (unsigned int i = 1; i < p->nargs; i++){
522 if ((p->arg[i].ea_addr >> 32) != common_eah){
523 jd->status = JS_BAD_EAH;
529 jd->sys.direction_union = dir_union;
534 gc_job_manager_impl::submit_job(gc_job_desc *jd)
536 // Ensure it's one of our job descriptors
538 if (jd < d_jd || jd >= &d_jd[d_options.max_jobs]){
539 jd->status = JS_BAD_JOB_DESC;
543 // Ensure we've got a client_thread_info assigned to this thread.
545 gc_client_thread_info *cti =
546 (gc_client_thread_info *) pthread_getspecific(s_client_key);
547 if (unlikely(cti == 0)){
548 if ((cti = alloc_cti()) == 0){
549 fprintf(stderr, "gc_job_manager_impl::submit_job: Too many client threads.\n");
550 jd->status = JS_TOO_MANY_CLIENTS;
553 int r = pthread_setspecific(s_client_key, cti);
555 jd->status = JS_BAD_JUJU;
556 fprintf(stderr, "pthread_setspecific failed (return = %d)\n", r);
561 if (jd->proc_id == GCP_UNKNOWN_PROC){
562 jd->status = JS_UNKNOWN_PROC;
566 if (!check_direct_args(jd, &jd->input))
569 if (!check_direct_args(jd, &jd->output))
572 if (!check_ea_args(jd, &jd->eaa))
576 jd->sys.client_id = cti->d_client_id;
578 if (!incr_njobs_active()){
579 jd->status = JS_SHUTTING_DOWN;
583 gc_jd_queue_enqueue(d_queue, jd);
584 // tell_spes_to_check_queue();
589 gc_job_manager_impl::wait_job(gc_job_desc *jd)
592 return wait_jobs(1, &jd, &done, GC_WAIT_ANY) == 1 && jd->status == JS_OK;
596 gc_job_manager_impl::wait_jobs(unsigned int njobs,
603 gc_client_thread_info *cti =
604 (gc_client_thread_info *) pthread_getspecific(s_client_key);
605 if (unlikely(cti == 0))
608 for (i = 0; i < njobs; i++){
610 if (unlikely(jd[i]->sys.client_id != cti->d_client_id)){
611 fprintf(stderr, "gc_job_manager_impl::wait_jobs: can't wait for a job you didn't submit\n");
617 omni_mutex_lock l(cti->d_mutex);
619 // setup info for event handler
620 cti->d_state = (mode == GC_WAIT_ANY) ? CT_WAIT_ANY : CT_WAIT_ALL;
621 cti->d_njobs_waiting_for = njobs;
622 cti->d_jobs_waiting_for = jd;
623 assert(cti->d_jobs_done != 0);
625 unsigned int ndone = 0;
627 // wait for jobs to complete
631 for (i= 0; i < njobs; i++){
634 else if (bv_isset(cti->d_jobs_done, jd[i]->sys.job_id)){
635 bv_clr(cti->d_jobs_done, jd[i]->sys.job_id);
641 if (mode == GC_WAIT_ANY && ndone > 0)
644 if (mode == GC_WAIT_ALL && ndone == njobs)
647 // FIXME what happens when somebody calls shutdown?
649 cti->d_cond.wait(); // wait for event handler to wake us up
652 cti->d_state = CT_NOT_WAITING;
653 cti->d_njobs_waiting_for = 0; // tidy up (not reqd)
654 cti->d_jobs_waiting_for = 0; // tidy up (not reqd)
659 ////////////////////////////////////////////////////////////////////////
662 gc_job_manager_impl::send_all_spes(uint32_t msg)
666 for (unsigned int i = 0; i < d_options.nspes; i++)
667 ok &= send_spe(i, msg);
673 gc_job_manager_impl::send_spe(unsigned int spe, uint32_t msg)
675 if (spe >= d_options.nspes)
678 int r = spe_in_mbox_write(d_worker[spe].spe_ctx, &msg, 1,
679 SPE_MBOX_ALL_BLOCKING);
681 perror("spe_in_mbox_write");
689 gc_job_manager_impl::tell_spes_to_check_queue()
691 int nspes = d_options.nspes;
693 for (int i = 0, ntold = 0; ntold < d_ntell && i < nspes ; ++i){
694 volatile spe_spu_control_area_t *spe_ctrl = d_worker[d_tell_start].spe_ctrl;
695 int nfree = (spe_ctrl->SPU_Mbox_Stat >> 8) & 0xFF;
697 spe_ctrl->SPU_In_Mbox = MK_MBOX_MSG(OP_CHECK_QUEUE, 0);
701 unsigned int t = d_tell_start + 1;
702 if (t >= d_options.nspes)
709 ////////////////////////////////////////////////////////////////////////
712 pthread_create_failure_msg(int r, const char *which)
718 case EAGAIN: s = "EAGAIN"; break;
719 case EINVAL: s = "EINVAL"; break;
720 case EPERM: s = "EPERM"; break;
722 snprintf(buf, sizeof(buf), "Unknown error %d", r);
726 fprintf(stderr, "pthread_create[%s] failed: %s\n", which, s);
731 start_thread(pthread_t *thread,
732 void *(*start_routine)(void *), void *arg,
736 pthread_attr_init(&attr);
737 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
739 // FIXME save sigprocmask
740 // FIXME set sigprocmask
742 int r = pthread_create(thread, &attr, start_routine, arg);
744 // FIXME restore sigprocmask
747 pthread_create_failure_msg(r, msg);
754 ////////////////////////////////////////////////////////////////////////
756 static void *start_worker(void *arg);
759 start_event_handler(void *arg)
761 gc_job_manager_impl *p = (gc_job_manager_impl *) arg;
762 p->event_handler_loop();
767 start_job_completer(void *arg)
769 gc_job_manager_impl *p = (gc_job_manager_impl *) arg;
770 p->job_completer_loop();
775 gc_job_manager_impl::create_event_handler()
777 // create the SPE event handler and register our interest in events
779 d_spe_event_handler.ptr = spe_event_handler_create();
780 if (d_spe_event_handler.ptr == 0){
781 perror("spe_event_handler_create");
782 throw std::runtime_error("spe_event_handler_create");
785 for (unsigned int i = 0; i < d_options.nspes; i++){
787 memset(&eu, 0, sizeof(eu));
788 eu.events = SPE_EVENT_OUT_INTR_MBOX | SPE_EVENT_SPE_STOPPED;
789 eu.spe = d_worker[i].spe_ctx;
790 eu.data.u32 = i; // set in events returned by spe_event_wait
792 if (spe_event_handler_register(d_spe_event_handler.ptr, &eu) != 0){
793 perror("spe_event_handler_register");
794 throw std::runtime_error("spe_event_handler_register");
798 // create the event handling thread
800 if (!start_thread(&d_eh_thread, start_event_handler, this, "event_handler")){
801 throw std::runtime_error("pthread_create");
804 // create the job completion thread
806 if (!start_thread(&d_jc_thread, start_job_completer, this, "job_completer")){
807 throw std::runtime_error("pthread_create");
810 // create the SPE worker threads
813 for (unsigned int i = 0; ok && i < d_options.nspes; i++){
815 snprintf(name, sizeof(name), "worker[%d]", i);
816 ok &= start_thread(&d_worker[i].thread, start_worker,
822 // FIXME Clean up the mess. Need to terminate event handler and all workers.
824 // this should cause the workers to exit, unless they're seriously broken
825 send_all_spes(MK_MBOX_MSG(OP_EXIT, 0));
829 throw std::runtime_error("pthread_create");
833 ////////////////////////////////////////////////////////////////////////
836 gc_job_manager_impl::set_eh_state(evt_handler_state s)
838 omni_mutex_lock l(d_eh_mutex);
840 d_eh_cond.broadcast();
844 gc_job_manager_impl::set_ea_args_maxsize(int maxsize)
846 omni_mutex_lock l(d_eh_mutex);
847 d_ea_args_maxsize = maxsize;
848 d_eh_cond.broadcast();
852 gc_job_manager_impl::print_event(spe_event_unit_t *evt)
854 printf("evt: spe = %d events = (0x%x)", evt->data.u32, evt->events);
856 if (evt->events & SPE_EVENT_OUT_INTR_MBOX)
857 printf(" OUT_INTR_MBOX");
859 if (evt->events & SPE_EVENT_IN_MBOX)
862 if (evt->events & SPE_EVENT_TAG_GROUP)
863 printf(" TAG_GROUP");
865 if (evt->events & SPE_EVENT_SPE_STOPPED)
866 printf(" SPE_STOPPED");
871 struct job_client_info {
877 compare_jci_clients(const void *va, const void *vb)
879 const job_client_info *a = (job_client_info *) va;
880 const job_client_info *b = (job_client_info *) vb;
882 return a->client_id - b->client_id;
886 gc_job_manager_impl::notify_clients_jobs_are_done(unsigned int spe_num,
887 unsigned int completion_info_idx)
889 const char *msg = "gc_job_manager_impl::notify_client_job_is_done (INTERNAL ERROR)";
891 smp_rmb(); // order reads so we know that data sent from SPE is here
893 gc_comp_info_t *ci = &d_comp_info[2 * spe_num + (completion_info_idx & 0x1)];
895 if (ci->ncomplete == 0){ // never happens, but ensures code below is correct
900 decr_njobs_active(ci->ncomplete);
903 static int total_jobs;
904 static int total_msgs;
906 total_jobs += ci->ncomplete;
907 printf("ppe: tj = %6d tm = %6d\n", total_jobs, total_msgs);
910 job_client_info gci[GC_CI_NJOBS];
913 * Make one pass through and sanity check everything while filling in gci
915 for (unsigned int i = 0; i < ci->ncomplete; i++){
916 unsigned int job_id = ci->job_id[i];
918 if (job_id >= d_options.max_jobs){
919 // internal error, shouldn't happen
920 fprintf(stderr,"%s: invalid job_id = %d\n", msg, job_id);
921 ci->in_use = 0; // clear flag so SPE knows we're done with it
924 gc_job_desc *jd = &d_jd[job_id];
926 if (jd->sys.client_id >= d_options.max_client_threads){
927 // internal error, shouldn't happen
928 fprintf(stderr, "%s: invalid client_id = %d\n", msg, jd->sys.client_id);
929 ci->in_use = 0; // clear flag so SPE knows we're done with it
933 gci[i].job_id = job_id;
934 gci[i].client_id = jd->sys.client_id;
937 // sort by client_id so we only have to lock & signal once / client
939 if (ci->ncomplete > 1)
940 qsort(gci, ci->ncomplete, sizeof(gci[0]), compare_jci_clients);
944 gc_client_thread_info *last_cti = &d_client_thread[gci[0].client_id];
945 last_cti->d_mutex.lock();
946 bv_set(last_cti->d_jobs_done, gci[0].job_id); // mark job done
948 for (unsigned int i = 1; i < ci->ncomplete; i++){
950 gc_client_thread_info *cti = &d_client_thread[gci[i].client_id];
952 if (cti != last_cti){ // new client?
954 // yes. signal old client, unlock old, lock new
956 // FIXME we could distinguish between CT_WAIT_ALL & CT_WAIT_ANY
958 if (last_cti->d_state == CT_WAIT_ANY || last_cti->d_state == CT_WAIT_ALL)
959 last_cti->d_cond.signal(); // wake client thread up
961 last_cti->d_mutex.unlock();
967 bv_set(cti->d_jobs_done, gci[i].job_id);
972 if (last_cti->d_state == CT_WAIT_ANY || last_cti->d_state == CT_WAIT_ALL)
973 last_cti->d_cond.signal(); // wake client thread up
974 last_cti->d_mutex.unlock();
976 ci->in_use = 0; // clear flag so SPE knows we're done with it
980 gc_job_manager_impl::handle_event(spe_event_unit_t *evt)
984 int spe_num = evt->data.u32;
986 // only a single event type can be signaled at a time
988 if (evt->events == SPE_EVENT_OUT_INTR_MBOX) { // SPE sent us 1 or more msgs
989 static const int NMSGS = 32;
990 unsigned int msg[NMSGS];
991 int n = spe_out_intr_mbox_read(evt->spe, msg, NMSGS, SPE_MBOX_ANY_BLOCKING);
992 // printf("spe_out_intr_mbox_read = %d\n", n);
994 perror("spe_out_intr_mbox_read");
997 for (int i = 0; i < n; i++){
998 switch(MBOX_MSG_OP(msg[i])){
1002 printf("eh: job_done (0x%08x) from spu[%d]\n", msg[i], spe_num);
1003 notify_clients_jobs_are_done(spe_num, MBOX_MSG_ARG(msg[i]));
1006 case OP_SPU_BUFSIZE:
1007 set_ea_args_maxsize(MBOX_MSG_ARG(msg[i]));
1012 printf("eh: Unexpected msg (0x%08x) from spu[%d]\n", msg[i], spe_num);
1018 else if (evt->events == SPE_EVENT_SPE_STOPPED){ // the SPE stopped
1020 int r = spe_stop_info_read(evt->spe, &si);
1022 perror("spe_stop_info_read");
1025 switch (si.stop_reason){
1028 printf("eh: spu[%d] SPE_EXIT w/ exit_code = %d\n",
1029 spe_num, si.result.spe_exit_code);
1032 case SPE_STOP_AND_SIGNAL:
1033 printf("eh: spu[%d] SPE_STOP_AND_SIGNAL w/ spe_signal_code = 0x%x\n",
1034 spe_num, si.result.spe_signal_code);
1036 case SPE_RUNTIME_ERROR:
1037 printf("eh: spu[%d] SPE_RUNTIME_ERROR w/ spe_runtime_error = 0x%x\n",
1038 spe_num, si.result.spe_runtime_error);
1040 case SPE_RUNTIME_EXCEPTION:
1041 printf("eh: spu[%d] SPE_RUNTIME_EXCEPTION w/ spe_runtime_exception = 0x%x\n",
1042 spe_num, si.result.spe_runtime_exception);
1044 case SPE_RUNTIME_FATAL:
1045 printf("eh: spu[%d] SPE_RUNTIME_FATAL w/ spe_runtime_fatal = 0x%x\n",
1046 spe_num, si.result.spe_runtime_fatal);
1048 case SPE_CALLBACK_ERROR:
1049 printf("eh: spu[%d] SPE_CALLBACK_ERROR w/ spe_callback_error = 0x%x\n",
1050 spe_num, si.result.spe_callback_error);
1052 case SPE_ISOLATION_ERROR:
1053 printf("eh: spu[%d] SPE_ISOLATION_ERROR w/ spe_isolation_error = 0x%x\n",
1054 spe_num, si.result.spe_isolation_error);
1057 printf("eh: spu[%d] UNKNOWN STOP REASON (%d) w/ spu_status = 0x%x\n",
1058 spe_num, si.stop_reason, si.spu_status);
1063 #if 0 // not enabled
1064 else if (evt->events == SPE_EVENT_IN_MBOX){ // there's room to write to SPE
1065 // spe_in_mbox_write (ignore)
1067 else if (evt->events == SPE_EVENT_TAG_GROUP){ // our DMA completed
1068 // spe_mfcio_tag_status_read
1072 fprintf(stderr, "handle_event: unexpected evt->events = 0x%x\n", evt->events);
1078 // This is the "main program" of the event handling thread
1081 gc_job_manager_impl::event_handler_loop()
1083 static const int MAX_EVENTS = 16;
1084 static const int TIMEOUT = 20; // how long to block in milliseconds
1086 spe_event_unit_t events[MAX_EVENTS];
1089 printf("event_handler_loop: starting\n");
1091 set_eh_state(EHS_RUNNING);
1093 // ask the first spe for its max bufsize
1094 send_spe(0, MK_MBOX_MSG(OP_GET_SPU_BUFSIZE, 0));
1099 case EHS_RUNNING: // normal stuff
1100 if (d_shutdown_requested) {
1101 set_eh_state(EHS_SHUTTING_DOWN);
1105 case EHS_SHUTTING_DOWN:
1106 if (d_jc_state == JCS_DEAD){
1107 send_all_spes(MK_MBOX_MSG(OP_EXIT, 0));
1108 set_eh_state(EHS_WAITING_FOR_WORKERS_TO_DIE);
1112 case EHS_WAITING_FOR_WORKERS_TO_DIE:
1114 bool all_dead = true;
1115 for (unsigned int i = 0; i < d_options.nspes; i++)
1116 all_dead &= d_worker[i].state == WS_DEAD;
1119 set_eh_state(EHS_DEAD);
1121 printf("event_handler_loop: exiting\n");
1128 set_eh_state(EHS_DEAD);
1129 printf("event_handler_loop(default): exiting\n");
1133 // block waiting for events...
1134 int nevents = spe_event_wait(d_spe_event_handler.ptr,
1135 events, MAX_EVENTS, TIMEOUT);
1137 perror("spe_wait_event");
1140 for (int i = 0; i < nevents; i++){
1141 handle_event(&events[i]);
1146 ////////////////////////////////////////////////////////////////////////
1149 gc_job_manager_impl::poll_for_job_completion()
1151 static const int niter = 10000;
1153 CCTPL(); // change current (h/w) thread priority to low
1155 for (int n = 0; n < niter; n++){
1157 for (unsigned int spe_num = 0; spe_num < d_options.nspes; spe_num++){
1158 volatile spe_spu_control_area_t *spe_ctrl = d_worker[spe_num].spe_ctrl;
1159 int nentries = spe_ctrl->SPU_Mbox_Stat & 0xFF;
1160 while (nentries-- > 0){
1161 unsigned int msg = spe_ctrl->SPU_Out_Mbox;
1162 switch(MBOX_MSG_OP(msg)){
1165 printf("jc: job_done (0x%08x) from spu[%d]\n", msg, spe_num);
1167 CCTPM(); // change current thread priority to medium
1168 notify_clients_jobs_are_done(spe_num, MBOX_MSG_ARG(msg));
1173 printf("jc: Unexpected msg (0x%08x) from spu[%d]\n", msg, spe_num);
1183 // This is the "main program" of the job completer thread
1186 gc_job_manager_impl::job_completer_loop()
1188 d_jc_state = JCS_RUNNING;
1192 omni_mutex_lock l(d_jc_mutex);
1193 if (d_jc_njobs_active == 0){
1194 if (d_shutdown_requested){
1195 d_jc_state = JCS_DEAD;
1202 poll_for_job_completion();
1206 ////////////////////////////////////////////////////////////////////////
1207 // this is the top of the SPE worker threads
1210 start_worker(void *arg)
1212 worker_ctx *w = (worker_ctx *) arg;
1215 w->state = WS_RUNNING;
1217 printf("worker[%d]: WS_RUNNING\n", w->spe_idx);
1219 unsigned int entry = SPE_DEFAULT_ENTRY;
1220 int r = spe_context_run(w->spe_ctx, &entry, 0, w->spu_args, 0, &si);
1222 if (r < 0){ // error
1224 snprintf(buf, sizeof(buf), "worker[%d]: spe_context_run", w->spe_idx);
1228 // spe program called exit.
1230 printf("worker[%d]: SPE_EXIT w/ exit_code = %d\n",
1231 w->spe_idx, si.result.spe_exit_code);
1234 // called stop_and_signal
1236 // I'm not sure we'll ever get here. I think the event
1237 // handler will catch this...
1238 printf("worker[%d]: SPE_STOP_AND_SIGNAL w/ spe_signal_code = 0x%x\n",
1239 w->spe_idx, si.result.spe_signal_code);
1242 // in any event, we're committing suicide now ;)
1244 printf("worker[%d]: WS_DEAD\n", w->spe_idx);
1250 ////////////////////////////////////////////////////////////////////////
1252 gc_client_thread_info *
1253 gc_job_manager_impl::alloc_cti()
1255 for (unsigned int i = 0; i < d_options.max_client_threads; i++){
1256 if (d_client_thread[i].d_free){
1257 // try to atomically grab it
1258 if (_atomic_dec_if_positive(ptr_to_ea(&d_client_thread[i].d_free)) == 0){
1260 gc_client_thread_info *cti = &d_client_thread[i];
1261 cti->d_state = CT_NOT_WAITING;
1262 bv_zero(cti->d_jobs_done);
1263 cti->d_njobs_waiting_for = 0;
1264 cti->d_jobs_waiting_for = 0;
1274 gc_job_manager_impl::free_cti(gc_client_thread_info *cti)
1276 assert((size_t) (cti - d_client_thread.get()) < d_options.max_client_threads);
1281 gc_job_manager_impl::ea_args_maxsize()
1283 omni_mutex_lock l(d_eh_mutex);
1285 while (d_ea_args_maxsize == 0) // wait for it to be initialized
1288 return d_ea_args_maxsize;
1292 gc_job_manager_impl::set_debug(int debug)
1295 s_worker_debug = debug;
1299 gc_job_manager_impl::debug()
1304 ////////////////////////////////////////////////////////////////////////
1307 gc_job_manager_impl::setup_logfiles()
1309 if (!d_options.enable_logging)
1312 if (d_options.log2_nlog_entries == 0)
1313 d_options.log2_nlog_entries = 12;
1315 // must end up a multiple of the page size
1317 size_t pagesize = getpagesize();
1318 size_t s = (1 << d_options.log2_nlog_entries) * sizeof(gc_log_entry_t);
1319 s = ((s + pagesize - 1) / pagesize) * pagesize;
1320 size_t nentries = s / sizeof(gc_log_entry_t);
1321 assert(is_power_of_2(nentries));
1323 for (unsigned int i = 0; i < d_options.nspes; i++){
1325 snprintf(filename, sizeof(filename), "spu_log.%02d", i);
1326 int fd = open(filename, O_CREAT|O_TRUNC|O_RDWR, 0664);
1331 lseek(fd, s - 1, SEEK_SET);
1333 void *p = mmap(0, s, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
1334 if (p == MAP_FAILED){
1335 perror("gc_job_manager_impl::setup_logfiles: mmap");
1341 d_spu_args[i].log.base = ptr_to_ea(p);
1342 d_spu_args[i].log.nentries = nentries;
1347 gc_job_manager_impl::sync_logfiles()
1349 for (unsigned int i = 0; i < d_options.nspes; i++){
1350 if (d_spu_args[i].log.base)
1351 msync(ea_to_ptr(d_spu_args[i].log.base),
1352 d_spu_args[i].log.nentries * sizeof(gc_log_entry_t),
1358 gc_job_manager_impl::unmap_logfiles()
1360 for (unsigned int i = 0; i < d_options.nspes; i++){
1361 if (d_spu_args[i].log.base)
1362 munmap(ea_to_ptr(d_spu_args[i].log.base),
1363 d_spu_args[i].log.nentries * sizeof(gc_log_entry_t));
1367 ////////////////////////////////////////////////////////////////////////
1369 // lookup proc names in d_proc_def table
1372 gc_job_manager_impl::lookup_proc(const std::string &proc_name)
1374 for (int i = 0; i < d_nproc_defs; i++)
1375 if (proc_name == d_proc_def[i].name)
1378 throw gc_unknown_proc(proc_name);
1381 std::vector<std::string>
1382 gc_job_manager_impl::proc_names()
1384 std::vector<std::string> r;
1385 for (int i = 0; i < d_nproc_defs; i++)
1386 r.push_back(d_proc_def[i].name);
1391 ////////////////////////////////////////////////////////////////////////
1393 worker_ctx::~worker_ctx()
1396 int r = spe_context_destroy(spe_ctx);
1398 perror("spe_context_destroy");