root/trunk/libffado/src/libieee1394/IsoHandlerManager.cpp

Revision 1348, 38.3 kB (checked in by ppalmers, 12 years ago)

merge 2.0 branch changes to trunk. svn merge -r 1337:HEAD svn+ssh://ffadosvn@ffado.org/ffado/branches/libffado-2.0

Line 
1 /*
2  * Copyright (C) 2005-2008 by Pieter Palmers
3  *
4  * This file is part of FFADO
5  * FFADO = Free Firewire (pro-)audio drivers for linux
6  *
7  * FFADO is based upon FreeBoB.
8  *
9  * This program is free software: you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation, either version 2 of the License, or
12  * (at your option) version 3 of the License.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
21  *
22  */
23
24 #include "config.h"
25
26 #include "IsoHandlerManager.h"
27 #include "ieee1394service.h"
28 #include "cycletimer.h"
29 #include "libstreaming/generic/StreamProcessor.h"
30
31 #include "libutil/Atomic.h"
32 #include "libutil/PosixThread.h"
33 #include "libutil/SystemTimeSource.h"
34 #include "libutil/Watchdog.h"
35
36 #include <cstring>
37 #include <assert.h>
38
39 IMPL_DEBUG_MODULE( IsoHandlerManager, IsoHandlerManager, DEBUG_LEVEL_NORMAL );
40 IMPL_DEBUG_MODULE( IsoTask, IsoTask, DEBUG_LEVEL_NORMAL );
41
42 using namespace Streaming;
43
44 // --- ISO Thread --- //
45
46 IsoTask::IsoTask(IsoHandlerManager& manager, enum IsoHandler::EHandlerType t)
47     : m_manager( manager )
48     , m_SyncIsoHandler ( NULL )
49     , m_handlerType( t )
50     , m_running( false )
51     , m_in_busreset( false )
52 {
53 }
54
55 IsoTask::~IsoTask()
56 {
57     sem_destroy(&m_activity_semaphore);
58 }
59
60 bool
61 IsoTask::Init()
62 {
63     request_update = 0;
64
65     int i;
66     for (i=0; i < ISOHANDLERMANAGER_MAX_ISO_HANDLERS_PER_PORT; i++) {
67         m_IsoHandler_map_shadow[i] = NULL;
68         m_poll_fds_shadow[i].events = 0;
69     }
70     m_poll_nfds_shadow = 0;
71
72     #ifdef DEBUG
73     m_last_loop_entry = 0;
74     m_successive_short_loops = 0;
75     #endif
76
77     sem_init(&m_activity_semaphore, 0, 0);
78     m_running = true;
79     return true;
80 }
81
82 bool
83 IsoTask::requestShadowMapUpdate()
84 {
85     debugOutput(DEBUG_LEVEL_VERBOSE, "(%p) enter\n", this);
86     INC_ATOMIC(&request_update);
87
88     // get the thread going again
89     signalActivity();
90
91     if (m_running) {
92         int timeout = 1000;
93         while(request_update && timeout--) {
94             Util::SystemTimeSource::SleepUsecRelative(1000);
95         }
96         if(timeout == 0) {
97             debugError("timeout waiting for shadow map update\n");
98         }
99     }
100     debugOutput(DEBUG_LEVEL_VERBOSE, "(%p) exit\n", this);
101     return true;
102 }
103
104 bool
105 IsoTask::handleBusReset()
106 {
107     bool retval = true;
108     m_in_busreset = true;
109     requestShadowMapUpdate();
110     if(request_update) {
111         debugError("shadow map update request not honored\n");
112         return false;
113     }
114
115     unsigned int i, max;
116     max = m_manager.m_IsoHandlers.size();
117     for (i = 0; i < max; i++) {
118         IsoHandler *h = m_manager.m_IsoHandlers.at(i);
119         assert(h);
120
121         // skip the handlers not intended for us
122         if(h->getType() != m_handlerType) continue;
123
124         if (!h->handleBusReset()) {
125             debugWarning("Failed to handle busreset on %p\n");
126             retval = false;
127         }
128     }
129
130     // re-enable processing
131     m_in_busreset = false;
132     requestShadowMapUpdate();
133     if(request_update) {
134         debugError("shadow map update request not honored\n");
135         return false;
136     }
137     return retval;
138 }
139
140 // updates the internal stream map
141 // note that this should be executed with the guarantee that
142 // nobody will modify the parent data structures
143 void
144 IsoTask::updateShadowMapHelper()
145 {
146     debugOutput( DEBUG_LEVEL_VERBOSE, "(%p) updating shadow vars...\n", this);
147     // we are handling a busreset
148     if(m_in_busreset) {
149         m_poll_nfds_shadow = 0;
150         return;
151     }
152     unsigned int i, cnt, max;
153     max = m_manager.m_IsoHandlers.size();
154     m_SyncIsoHandler = NULL;
155     for (i = 0, cnt = 0; i < max; i++) {
156         IsoHandler *h = m_manager.m_IsoHandlers.at(i);
157         assert(h);
158
159         // skip the handlers not intended for us
160         if(h->getType() != m_handlerType) continue;
161
162         if (h->isEnabled()) {
163             m_IsoHandler_map_shadow[cnt] = h;
164             m_poll_fds_shadow[cnt].fd = h->getFileDescriptor();
165             m_poll_fds_shadow[cnt].revents = 0;
166             m_poll_fds_shadow[cnt].events = POLLIN;
167             cnt++;
168             // FIXME: need a more generic approach here
169             if(   m_SyncIsoHandler == NULL
170                && h->getType() == IsoHandler::eHT_Transmit) {
171                 m_SyncIsoHandler = h;
172             }
173
174             debugOutput( DEBUG_LEVEL_VERBOSE, "(%p) %s handler %p added\n",
175                                               this, h->getTypeString(), h);
176         } else {
177             debugOutput( DEBUG_LEVEL_VERBOSE, "(%p) %s handler %p skipped (disabled)\n",
178                                               this, h->getTypeString(), h);
179         }
180         if(cnt > ISOHANDLERMANAGER_MAX_ISO_HANDLERS_PER_PORT) {
181             debugWarning("Too much ISO Handlers in thread...\n");
182             break;
183         }
184     }
185
186     // FIXME: need a more generic approach here
187     // if there are no active transmit handlers,
188     // use the first receive handler
189     if(   m_SyncIsoHandler == NULL
190        && m_poll_nfds_shadow) {
191         m_SyncIsoHandler = m_IsoHandler_map_shadow[0];
192     }
193     m_poll_nfds_shadow = cnt;
194     debugOutput( DEBUG_LEVEL_VERBOSE, "(%p) updated shadow vars...\n", this);
195 }
196
197 bool
198 IsoTask::Execute()
199 {
200     debugOutput(DEBUG_LEVEL_ULTRA_VERBOSE,
201                 "(%p, %s) Execute\n",
202                 this, (m_handlerType == IsoHandler::eHT_Transmit? "Transmit": "Receive"));
203     int err;
204     unsigned int i;
205     unsigned int m_poll_timeout = 10;
206
207     #ifdef DEBUG
208     uint64_t now = Util::SystemTimeSource::getCurrentTimeAsUsecs();
209     int diff = now - m_last_loop_entry;
210     if(diff < 100) {
211         debugOutputExtreme(DEBUG_LEVEL_VERY_VERBOSE,
212                            "(%p, %s) short loop detected (%d usec), cnt: %d\n",
213                            this, (m_handlerType == IsoHandler::eHT_Transmit? "Transmit": "Receive"),
214                            diff, m_successive_short_loops);
215         m_successive_short_loops++;
216         if(m_successive_short_loops > 10000) {
217             debugError("Shutting down runaway thread\n");
218             m_running = false;
219             return false;
220         }
221     } else {
222         // reset the counter
223         m_successive_short_loops = 0;
224     }
225     m_last_loop_entry = now;
226     #endif
227
228     // if some other thread requested a shadow map update, do it
229     if(request_update) {
230         updateShadowMapHelper();
231         DEC_ATOMIC(&request_update); // ack the update
232         assert(request_update >= 0);
233     }
234
235     // bypass if no handlers are registered
236     if (m_poll_nfds_shadow == 0) {
237         debugOutputExtreme(DEBUG_LEVEL_VERY_VERBOSE,
238                            "(%p, %s) bypass iterate since no handlers to poll\n",
239                            this, (m_handlerType == IsoHandler::eHT_Transmit? "Transmit": "Receive"));
240         usleep(m_poll_timeout * 1000);
241         return true;
242     }
243
244     // FIXME: what can happen is that poll() returns, but not all clients are
245     // ready. there might be some busy waiting behavior that still has to be solved.
246
247     // setup the poll here
248     // we should prevent a poll() where no events are specified, since that will only time-out
249     bool no_one_to_poll = true;
250     while(no_one_to_poll) {
251         for (i = 0; i < m_poll_nfds_shadow; i++) {
252             short events = 0;
253             IsoHandler *h = m_IsoHandler_map_shadow[i];
254             // we should only poll on a transmit handler
255             // that has a client that is ready to send
256             // something. Otherwise it will end up in
257             // busy wait looping since the packet function
258             // will defer processing (also avoids the
259             // AGAIN problem)
260             if (h->canIterateClient()) {
261                 events = POLLIN | POLLPRI;
262                 no_one_to_poll = false;
263                 // if we are going to poll() it, let's ensure
264                 // it can run until someone wants it to exit
265                 h->allowIterateLoop();
266             }
267             m_poll_fds_shadow[i].events = events;
268         }
269
270         if(no_one_to_poll) {
271             debugOutput(DEBUG_LEVEL_ULTRA_VERBOSE,
272                         "(%p, %s) No one to poll, waiting for something to happen\n",
273                         this, (m_handlerType == IsoHandler::eHT_Transmit? "Transmit": "Receive"));
274             // wait for something to happen
275             switch(waitForActivity()) {
276                 case IsoTask::eAR_Error:
277                     debugError("Error while waiting for activity\n");
278                     return false;
279                 case IsoTask::eAR_Interrupted:
280                     // FIXME: what to do here?
281                     debugWarning("Interrupted while waiting for activity\n");
282                     break;
283                 case IsoTask::eAR_Timeout:
284                     // FIXME: what to do here?
285                     debugWarning("Timeout while waiting for activity\n");
286                     no_one_to_poll = false; // exit the loop to be able to detect failing handlers
287                     break;
288                 case IsoTask::eAR_Activity:
289                     // do nothing
290                     debugOutputExtreme(DEBUG_LEVEL_VERBOSE,
291                                        "(%p, %s) something happened\n",
292                                        this, (m_handlerType == IsoHandler::eHT_Transmit? "Transmit": "Receive"));
293                     break;
294             }
295         }
296     }
297
298     // Use a shadow map of the fd's such that we don't have to update
299     // the fd map everytime we run poll().
300     err = poll (m_poll_fds_shadow, m_poll_nfds_shadow, m_poll_timeout);
301     uint32_t ctr_at_poll_return = m_manager.get1394Service().getCycleTimer();
302
303     if (err < 0) {
304         if (errno == EINTR) {
305             debugOutput(DEBUG_LEVEL_VERBOSE, "Ignoring poll return due to signal\n");
306             return true;
307         }
308         debugFatal("poll error: %s\n", strerror (errno));
309         m_running = false;
310         return false;
311     }
312
313     // find handlers that have died
314     uint64_t ctr_at_poll_return_ticks = CYCLE_TIMER_TO_TICKS(ctr_at_poll_return);
315     bool handler_died = false;
316     for (i = 0; i < m_poll_nfds_shadow; i++) {
317         // figure out if a handler has died
318
319         // this is the time of the last packet we saw in the iterate() handler
320         uint32_t last_packet_seen = m_IsoHandler_map_shadow[i]->getLastPacketTime();
321         if (last_packet_seen == 0xFFFFFFFF) {
322             // this was not iterated yet, so can't be dead
323             debugOutput(DEBUG_LEVEL_VERY_VERBOSE,
324                         "(%p, %s) handler %d didn't see any packets yet\n",
325                         this, (m_handlerType == IsoHandler::eHT_Transmit? "Transmit": "Receive"), i);
326             continue;
327         }
328
329         uint64_t last_packet_seen_ticks = CYCLE_TIMER_TO_TICKS(last_packet_seen);
330         // we use a relatively large value to distinguish between "death" and xrun
331         int64_t max_diff_ticks = TICKS_PER_SECOND * 2;
332         int64_t measured_diff_ticks = diffTicks(ctr_at_poll_return_ticks, last_packet_seen_ticks);
333
334         debugOutputExtreme(DEBUG_LEVEL_VERBOSE,
335                            "(%p, %s) check handler %d: diff = %lld, max = %lld, now: %08lX, last: %08lX\n",
336                            this, (m_handlerType == IsoHandler::eHT_Transmit? "Transmit": "Receive"),
337                            i, measured_diff_ticks, max_diff_ticks, ctr_at_poll_return, last_packet_seen);
338         if(measured_diff_ticks > max_diff_ticks) {
339             debugFatal("(%p, %s) Handler died: now: %08lX, last: %08lX, diff: %lld (max: %lld)\n",
340                        this, (m_handlerType == IsoHandler::eHT_Transmit? "Transmit": "Receive"),
341                        ctr_at_poll_return, last_packet_seen, measured_diff_ticks, max_diff_ticks);
342             m_IsoHandler_map_shadow[i]->notifyOfDeath();
343             handler_died = true;
344         }
345     }
346     if(handler_died) {
347         m_running = false;
348         return false; // one or more handlers have died
349     }
350
351     // iterate the handlers
352     for (i = 0; i < m_poll_nfds_shadow; i++) {
353         #ifdef DEBUG
354         if(m_poll_fds_shadow[i].revents) {
355             debugOutputExtreme(DEBUG_LEVEL_VERBOSE,
356                         "(%p, %s) received events: %08X for (%d/%d, %p, %s)\n",
357                         this, (m_handlerType == IsoHandler::eHT_Transmit? "Transmit": "Receive"),
358                         m_poll_fds_shadow[i].revents,
359                         i, m_poll_nfds_shadow,
360                         m_IsoHandler_map_shadow[i],
361                         m_IsoHandler_map_shadow[i]->getTypeString());
362         }
363         #endif
364
365         // if we get here, it means two things:
366         // 1) the kernel can accept or provide packets (poll returned POLLIN)
367         // 2) the client can provide or accept packets (since we enabled polling)
368         if(m_poll_fds_shadow[i].revents & (POLLIN)) {
369             m_IsoHandler_map_shadow[i]->iterate(ctr_at_poll_return);
370         } else {
371             // there might be some error condition
372             if (m_poll_fds_shadow[i].revents & POLLERR) {
373                 debugWarning("(%p) error on fd for %d\n", this, i);
374             }
375             if (m_poll_fds_shadow[i].revents & POLLHUP) {
376                 debugWarning("(%p) hangup on fd for %d\n", this, i);
377             }
378         }
379     }
380     return true;
381 }
382
383 enum IsoTask::eActivityResult
384 IsoTask::waitForActivity()
385 {
386     debugOutputExtreme(DEBUG_LEVEL_VERBOSE,
387                        "(%p, %s) waiting for activity\n",
388                        this, (m_handlerType == IsoHandler::eHT_Transmit? "Transmit": "Receive"));
389     struct timespec ts;
390     int result;
391     long long int timeout_nsec = ISOHANDLERMANAGER_ISO_TASK_WAIT_TIMEOUT_USECS * 1000LL;
392
393     if (clock_gettime(CLOCK_REALTIME, &ts) == -1) {
394         debugError("clock_gettime failed\n");
395         return eAR_Error;
396     }
397
398     ts.tv_nsec += timeout_nsec;
399     while(ts.tv_nsec >= 1000000000LL) {
400         ts.tv_sec += 1;
401         ts.tv_nsec -= 1000000000LL;
402     }
403
404     result = sem_timedwait(&m_activity_semaphore, &ts);
405
406     if(result != 0) {
407         if (errno == ETIMEDOUT) {
408             debugOutput(DEBUG_LEVEL_VERBOSE,
409                         "(%p) sem_timedwait() timed out (result=%d)\n",
410                         this, result);
411             return eAR_Timeout;
412         } else if (errno == EINTR) {
413             debugOutput(DEBUG_LEVEL_VERBOSE,
414                         "(%p) sem_timedwait() interrupted by signal (result=%d)\n",
415                         this, result);
416             return eAR_Interrupted;
417         } else if (errno == EINVAL) {
418             debugError("(%p) sem_timedwait error (result=%d errno=EINVAL)\n",
419                         this, result);
420             debugError("(%p) timeout_nsec=%lld ts.sec=%d ts.nsec=%lld\n",
421                        this, timeout_nsec, ts.tv_sec, ts.tv_nsec);
422             return eAR_Error;
423         } else {
424             debugError("(%p) sem_timedwait error (result=%d errno=%d)\n",
425                         this, result, errno);
426             debugError("(%p) timeout_nsec=%lld ts.sec=%d ts.nsec=%lld\n",
427                        this, timeout_nsec, ts.tv_sec, ts.tv_nsec);
428             return eAR_Error;
429         }
430     }
431
432     debugOutput(DEBUG_LEVEL_ULTRA_VERBOSE,
433                 "(%p, %s) got activity\n",
434                 this, (m_handlerType == IsoHandler::eHT_Transmit? "Transmit": "Receive"));
435     return eAR_Activity;
436 }
437
438 void
439 IsoTask::signalActivity()
440 {
441     // signal the activity cond var
442     sem_post(&m_activity_semaphore);
443     debugOutput(DEBUG_LEVEL_ULTRA_VERBOSE,
444                 "(%p, %s) activity\n",
445                 this, (m_handlerType == IsoHandler::eHT_Transmit? "Transmit": "Receive"));
446 }
447
448 void IsoTask::setVerboseLevel(int i) {
449     setDebugLevel(i);
450     debugOutput( DEBUG_LEVEL_VERBOSE, "Setting verbose level to %d...\n", i );
451 }
452
453 // -- the ISO handler manager -- //
454 IsoHandlerManager::IsoHandlerManager(Ieee1394Service& service)
455    : m_State(E_Created)
456    , m_service( service )
457    , m_realtime(false), m_priority(0)
458    , m_IsoThreadTransmit ( NULL )
459    , m_IsoTaskTransmit ( NULL )
460    , m_IsoThreadReceive ( NULL )
461    , m_IsoTaskReceive ( NULL )
462 {
463 }
464
465 IsoHandlerManager::IsoHandlerManager(Ieee1394Service& service, bool run_rt, int rt_prio)
466    : m_State(E_Created)
467    , m_service( service )
468    , m_realtime(run_rt), m_priority(rt_prio)
469    , m_IsoThreadTransmit ( NULL )
470    , m_IsoTaskTransmit ( NULL )
471    , m_IsoThreadReceive ( NULL )
472    , m_IsoTaskReceive ( NULL )
473 {
474 }
475
476 IsoHandlerManager::~IsoHandlerManager()
477 {
478     stopHandlers();
479     pruneHandlers();
480     if(m_IsoHandlers.size() > 0) {
481         debugError("Still some handlers in use\n");
482     }
483     if (m_IsoThreadTransmit) {
484         m_IsoThreadTransmit->Stop();
485         delete m_IsoThreadTransmit;
486     }
487     if (m_IsoThreadReceive) {
488         m_IsoThreadReceive->Stop();
489         delete m_IsoThreadReceive;
490     }
491     if (m_IsoTaskTransmit) {
492         delete m_IsoTaskTransmit;
493     }
494     if (m_IsoTaskReceive) {
495         delete m_IsoTaskReceive;
496     }
497 }
498
499 bool
500 IsoHandlerManager::handleBusReset()
501 {
502     debugOutput( DEBUG_LEVEL_NORMAL, "bus reset...\n");
503     // A few things can happen on bus reset:
504     // 1) no devices added/removed => streams are still valid, but might have to be restarted
505     // 2) a device was removed => some streams become invalid
506     // 3) a device was added => same as 1, new device is ignored
507     if (!m_IsoTaskTransmit) {
508         debugError("No xmit task\n");
509         return false;
510     }
511     if (!m_IsoTaskReceive) {
512         debugError("No receive task\n");
513         return false;
514     }
515     if (!m_IsoTaskTransmit->handleBusReset()) {
516         debugWarning("could no handle busreset on xmit\n");
517     }
518     if (!m_IsoTaskReceive->handleBusReset()) {
519         debugWarning("could no handle busreset on recv\n");
520     }
521     return true;
522 }
523
524 void
525 IsoHandlerManager::requestShadowMapUpdate()
526 {
527     if(m_IsoTaskTransmit) m_IsoTaskTransmit->requestShadowMapUpdate();
528     if(m_IsoTaskReceive) m_IsoTaskReceive->requestShadowMapUpdate();
529 }
530
531 bool
532 IsoHandlerManager::setThreadParameters(bool rt, int priority) {
533     debugOutput( DEBUG_LEVEL_VERBOSE, "(%p) switch to: (rt=%d, prio=%d)...\n", this, rt, priority);
534     if (priority > THREAD_MAX_RTPRIO) priority = THREAD_MAX_RTPRIO; // cap the priority
535     m_realtime = rt;
536     m_priority = priority;
537
538     if (m_IsoThreadTransmit) {
539         if (m_realtime) {
540             m_IsoThreadTransmit->AcquireRealTime(m_priority
541                                                  + ISOHANDLERMANAGER_ISO_PRIO_INCREASE
542                                                  + ISOHANDLERMANAGER_ISO_PRIO_INCREASE_XMIT);
543         } else {
544             m_IsoThreadTransmit->DropRealTime();
545         }
546     }
547     if (m_IsoThreadReceive) {
548         if (m_realtime) {
549             m_IsoThreadReceive->AcquireRealTime(m_priority
550                                                 + ISOHANDLERMANAGER_ISO_PRIO_INCREASE
551                                                 + ISOHANDLERMANAGER_ISO_PRIO_INCREASE_RECV);
552         } else {
553             m_IsoThreadReceive->DropRealTime();
554         }
555     }
556
557     return true;
558 }
559
560 bool IsoHandlerManager::init()
561 {
562     debugOutput( DEBUG_LEVEL_VERBOSE, "Initializing ISO manager %p...\n", this);
563     // check state
564     if(m_State != E_Created) {
565         debugError("Manager already initialized...\n");
566         return false;
567     }
568
569     // create threads to iterate our ISO handlers
570     debugOutput( DEBUG_LEVEL_VERBOSE, "Create iso thread for %p transmit...\n", this);
571     m_IsoTaskTransmit = new IsoTask( *this, IsoHandler::eHT_Transmit );
572     if(!m_IsoTaskTransmit) {
573         debugFatal("No task\n");
574         return false;
575     }
576     m_IsoTaskTransmit->setVerboseLevel(getDebugLevel());
577     m_IsoThreadTransmit = new Util::PosixThread(m_IsoTaskTransmit, "ISOXMT", m_realtime,
578                                                 m_priority + ISOHANDLERMANAGER_ISO_PRIO_INCREASE
579                                                 + ISOHANDLERMANAGER_ISO_PRIO_INCREASE_XMIT,
580                                                 PTHREAD_CANCEL_DEFERRED);
581
582     if(!m_IsoThreadTransmit) {
583         debugFatal("No thread\n");
584         return false;
585     }
586     m_IsoThreadTransmit->setVerboseLevel(getDebugLevel());
587
588     debugOutput( DEBUG_LEVEL_VERBOSE, "Create iso thread for %p receive...\n", this);
589     m_IsoTaskReceive = new IsoTask( *this, IsoHandler::eHT_Receive );
590     if(!m_IsoTaskReceive) {
591         debugFatal("No task\n");
592         return false;
593     }
594     m_IsoTaskReceive->setVerboseLevel(getDebugLevel());
595     m_IsoThreadReceive = new Util::PosixThread(m_IsoTaskReceive, "ISORCV", m_realtime,
596                                                m_priority + ISOHANDLERMANAGER_ISO_PRIO_INCREASE
597                                                + ISOHANDLERMANAGER_ISO_PRIO_INCREASE_RECV,
598                                                PTHREAD_CANCEL_DEFERRED);
599
600     if(!m_IsoThreadReceive) {
601         debugFatal("No thread\n");
602         return false;
603     }
604     m_IsoThreadReceive->setVerboseLevel(getDebugLevel());
605     // register the thread with the RT watchdog
606     Util::Watchdog *watchdog = m_service.getWatchdog();
607     if(watchdog) {
608         if(!watchdog->registerThread(m_IsoThreadTransmit)) {
609             debugWarning("could not register iso transmit thread with watchdog\n");
610         }
611         if(!watchdog->registerThread(m_IsoThreadReceive)) {
612             debugWarning("could not register iso receive thread with watchdog\n");
613         }
614     } else {
615         debugWarning("could not find valid watchdog\n");
616     }
617
618     if (m_IsoThreadTransmit->Start() != 0) {
619         debugFatal("Could not start ISO Transmit thread\n");
620         return false;
621     }
622     if (m_IsoThreadReceive->Start() != 0) {
623         debugFatal("Could not start ISO Receive thread\n");
624         return false;
625     }
626
627     m_State=E_Running;
628     return true;
629 }
630
631 bool
632 IsoHandlerManager::disable(IsoHandler *h) {
633     bool result;
634     int i=0;
635     debugOutput(DEBUG_LEVEL_VERBOSE, "Disable on IsoHandler %p\n", h);
636     for ( IsoHandlerVectorIterator it = m_IsoHandlers.begin();
637         it != m_IsoHandlers.end();
638         ++it )
639     {
640         if ((*it) == h) {
641             result = h->disable();
642             if(h->getType() == IsoHandler::eHT_Transmit) {
643                 result &= m_IsoTaskTransmit->requestShadowMapUpdate();
644             } else {
645                 result &= m_IsoTaskReceive->requestShadowMapUpdate();
646             }
647             debugOutput(DEBUG_LEVEL_VERY_VERBOSE, " disabled\n");
648             return result;
649         }
650         i++;
651     }
652     debugError("Handler not found\n");
653     return false;
654 }
655
656 bool
657 IsoHandlerManager::enable(IsoHandler *h) {
658     bool result;
659     int i=0;
660     debugOutput(DEBUG_LEVEL_VERBOSE, "Enable on IsoHandler %p\n", h);
661     for ( IsoHandlerVectorIterator it = m_IsoHandlers.begin();
662         it != m_IsoHandlers.end();
663         ++it )
664     {
665         if ((*it) == h) {
666             result = h->enable();
667             if(h->getType() == IsoHandler::eHT_Transmit) {
668                 result &= m_IsoTaskTransmit->requestShadowMapUpdate();
669             } else {
670                 result &= m_IsoTaskReceive->requestShadowMapUpdate();
671             }
672             debugOutput(DEBUG_LEVEL_VERY_VERBOSE, " enabled\n");
673             return result;
674         }
675         i++;
676     }
677     debugError("Handler not found\n");
678     return false;
679 }
680
681 void
682 IsoHandlerManager::signalActivityTransmit()
683 {
684     assert(m_IsoTaskTransmit);
685     m_IsoTaskTransmit->signalActivity();
686 }
687
688 void
689 IsoHandlerManager::signalActivityReceive()
690 {
691     assert(m_IsoTaskReceive);
692     m_IsoTaskReceive->signalActivity();
693 }
694
695 bool IsoHandlerManager::registerHandler(IsoHandler *handler)
696 {
697     debugOutput( DEBUG_LEVEL_VERBOSE, "enter...\n");
698     assert(handler);
699     handler->setVerboseLevel(getDebugLevel());
700     m_IsoHandlers.push_back(handler);
701     requestShadowMapUpdate();
702     return true;
703 }
704
705 bool IsoHandlerManager::unregisterHandler(IsoHandler *handler)
706 {
707     debugOutput( DEBUG_LEVEL_VERBOSE, "enter...\n");
708     assert(handler);
709
710     for ( IsoHandlerVectorIterator it = m_IsoHandlers.begin();
711       it != m_IsoHandlers.end();
712       ++it )
713     {
714         if ( *it == handler ) {
715             m_IsoHandlers.erase(it);
716             requestShadowMapUpdate();
717             return true;
718         }
719     }
720     debugFatal("Could not find handler (%p)\n", handler);
721     return false; //not found
722 }
723
724 /**
725  * Registers an StreamProcessor with the IsoHandlerManager.
726  *
727  * If nescessary, an IsoHandler is created to handle this stream.
728  * Once an StreamProcessor is registered to the handler, it will be included
729  * in the ISO streaming cycle (i.e. receive/transmit of it will occur).
730  *
731  * @param stream the stream to register
732  * @return true if registration succeeds
733  *
734  * \todo : currently there is a one-to-one mapping
735  *        between streams and handlers, this is not ok for
736  *        multichannel receive
737  */
738 bool IsoHandlerManager::registerStream(StreamProcessor *stream)
739 {
740     debugOutput( DEBUG_LEVEL_VERBOSE, "Registering %s stream %p\n", stream->getTypeString(), stream);
741     assert(stream);
742
743     IsoHandler* h = NULL;
744
745     // make sure the stream isn't already attached to a handler
746     for ( IsoHandlerVectorIterator it = m_IsoHandlers.begin();
747       it != m_IsoHandlers.end();
748       ++it )
749     {
750         if((*it)->isStreamRegistered(stream)) {
751             debugError( "stream already registered!\n");
752             return false;
753         }
754     }
755
756     // clean up all handlers that aren't used
757     pruneHandlers();
758
759     // allocate a handler for this stream
760     if (stream->getType()==StreamProcessor::ePT_Receive) {
761         // setup the optimal parameters for the raw1394 ISO buffering
762         unsigned int packets_per_period = stream->getPacketsPerPeriod();
763         unsigned int max_packet_size = stream->getMaxPacketSize() + 8; // bufferfill takes another 8 bytes for headers
764         unsigned int page_size = getpagesize();
765
766         // Ensure we don't request a packet size bigger than the
767         // kernel-enforced maximum which is currently 1 page.
768         // NOTE: PP: this is not really true AFAICT
769         if (max_packet_size > page_size) {
770             debugError("max packet size (%u) > page size (%u)\n", max_packet_size, page_size);
771             return false;
772         }
773
774         // the interrupt/wakeup interval prediction of raw1394 is a mess...
775         int irq_interval = (packets_per_period-1) / MINIMUM_INTERRUPTS_PER_PERIOD;
776         if(irq_interval <= 0) irq_interval=1;
777
778         // the receive buffer size doesn't matter for the latency,
779         // but it has a minimal value in order for libraw to operate correctly (300)
780         int buffers=400;
781
782         // create the actual handler
783         h = new IsoHandler(*this, IsoHandler::eHT_Receive,
784                            buffers, max_packet_size, irq_interval);
785
786         debugOutput( DEBUG_LEVEL_VERBOSE, " creating IsoRecvHandler\n");
787
788         if(!h) {
789             debugFatal("Could not create IsoRecvHandler\n");
790             return false;
791         }
792
793     } else if (stream->getType()==StreamProcessor::ePT_Transmit) {
794         // setup the optimal parameters for the raw1394 ISO buffering
795 //        unsigned int packets_per_period = stream->getPacketsPerPeriod();
796         unsigned int max_packet_size = stream->getMaxPacketSize();
797 //         unsigned int page_size = getpagesize();
798
799         // Ensure we don't request a packet size bigger than the
800         // kernel-enforced maximum which is currently 1 page.
801 //         if (max_packet_size > page_size) {
802 //             debugError("max packet size (%u) > page size (%u)\n", max_packet_size, page_size);
803 //             return false;
804 //         }
805         if (max_packet_size > MAX_XMIT_PACKET_SIZE) {
806             debugError("max packet size (%u) > MAX_XMIT_PACKET_SIZE (%u)\n",
807                        max_packet_size, MAX_XMIT_PACKET_SIZE);
808             return false;
809         }
810
811         // the SP specifies how many packets to ISO-buffer
812         int buffers = stream->getNbPacketsIsoXmitBuffer();
813         if (buffers > MAX_XMIT_NB_BUFFERS) {
814             debugOutput(DEBUG_LEVEL_VERBOSE,
815                         "nb buffers (%u) > MAX_XMIT_NB_BUFFERS (%u)\n",
816                         buffers, MAX_XMIT_NB_BUFFERS);
817             buffers = MAX_XMIT_NB_BUFFERS;
818         }
819         unsigned int irq_interval = buffers / MINIMUM_INTERRUPTS_PER_PERIOD;
820         if(irq_interval <= 0) irq_interval=1;
821
822         debugOutput( DEBUG_LEVEL_VERBOSE, " creating IsoXmitHandler\n");
823
824         // create the actual handler
825         h = new IsoHandler(*this, IsoHandler::eHT_Transmit,
826                            buffers, max_packet_size, irq_interval);
827
828         if(!h) {
829             debugFatal("Could not create IsoXmitHandler\n");
830             return false;
831         }
832
833     } else {
834         debugFatal("Bad stream type\n");
835         return false;
836     }
837
838     h->setVerboseLevel(getDebugLevel());
839
840     // init the handler
841     if(!h->init()) {
842         debugFatal("Could not initialize receive handler\n");
843         return false;
844     }
845
846     // register the stream with the handler
847     if(!h->registerStream(stream)) {
848         debugFatal("Could not register receive stream with handler\n");
849         return false;
850     }
851
852     // register the handler with the manager
853     if(!registerHandler(h)) {
854         debugFatal("Could not register receive handler with manager\n");
855         return false;
856     }
857     debugOutput( DEBUG_LEVEL_VERBOSE, " registered stream (%p) with handler (%p)\n", stream, h);
858
859     m_StreamProcessors.push_back(stream);
860     debugOutput( DEBUG_LEVEL_VERBOSE, " %d streams, %d handlers registered\n",
861                                       m_StreamProcessors.size(), m_IsoHandlers.size());
862     return true;
863 }
864
865 bool IsoHandlerManager::unregisterStream(StreamProcessor *stream)
866 {
867     debugOutput( DEBUG_LEVEL_VERBOSE, "Unregistering %s stream %p\n", stream->getTypeString(), stream);
868     assert(stream);
869
870     // make sure the stream isn't attached to a handler anymore
871     for ( IsoHandlerVectorIterator it = m_IsoHandlers.begin();
872       it != m_IsoHandlers.end();
873       ++it )
874     {
875         if((*it)->isStreamRegistered(stream)) {
876             if(!(*it)->unregisterStream(stream)) {
877                 debugOutput( DEBUG_LEVEL_VERBOSE, " could not unregister stream (%p) from handler (%p)...\n",stream,*it);
878                 return false;
879             }
880             debugOutput( DEBUG_LEVEL_VERBOSE, " unregistered stream (%p) from handler (%p)...\n",stream,*it);
881         }
882     }
883
884     // clean up all handlers that aren't used
885     pruneHandlers();
886
887     // remove the stream from the registered streams list
888     for ( StreamProcessorVectorIterator it = m_StreamProcessors.begin();
889       it != m_StreamProcessors.end();
890       ++it )
891     {
892         if ( *it == stream ) {
893             m_StreamProcessors.erase(it);
894             debugOutput( DEBUG_LEVEL_VERBOSE, " deleted stream (%p) from list...\n", *it);
895             return true;
896         }
897     }
898     return false; //not found
899 }
900
901 /**
902  * @brief unregister a handler from the manager
903  * @note called without the lock held.
904  */
905 void IsoHandlerManager::pruneHandlers() {
906     debugOutput( DEBUG_LEVEL_VERBOSE, "enter...\n");
907     IsoHandlerVector toUnregister;
908
909     // find all handlers that are not in use
910     for ( IsoHandlerVectorIterator it = m_IsoHandlers.begin();
911           it != m_IsoHandlers.end();
912           ++it )
913     {
914         if(!((*it)->inUse())) {
915             debugOutput( DEBUG_LEVEL_VERBOSE, " handler (%p) not in use\n",*it);
916             toUnregister.push_back(*it);
917         }
918     }
919     // delete them
920     for ( IsoHandlerVectorIterator it = toUnregister.begin();
921           it != toUnregister.end();
922           ++it )
923     {
924         unregisterHandler(*it);
925
926         debugOutput( DEBUG_LEVEL_VERBOSE, " deleting handler (%p)\n",*it);
927
928         // Now the handler's been unregistered it won't be reused
929         // again.  Therefore it really needs to be formally deleted
930         // to free up the raw1394 handle.  Otherwise things fall
931         // apart after several xrun recoveries as the system runs
932         // out of resources to support all the disused but still
933         // allocated raw1394 handles.  At least this is the current
934         // theory as to why we end up with "memory allocation"
935         // failures after several Xrun recoveries.
936         delete *it;
937     }
938 }
939
940 bool
941 IsoHandlerManager::stopHandlerForStream(Streaming::StreamProcessor *stream) {
942     // check state
943     if(m_State != E_Running) {
944         debugError("Incorrect state, expected E_Running, got %s\n", eHSToString(m_State));
945         return false;
946     }
947     for ( IsoHandlerVectorIterator it = m_IsoHandlers.begin();
948       it != m_IsoHandlers.end();
949       ++it )
950     {
951         if((*it)->isStreamRegistered(stream)) {
952             debugOutput( DEBUG_LEVEL_VERBOSE, " stopping handler %p for stream %p\n", *it, stream);
953             if(!(*it)->disable()) {
954                 debugOutput( DEBUG_LEVEL_VERBOSE, " could not disable handler (%p)\n",*it);
955                 return false;
956             }
957             bool result;
958             if((*it)->getType() == IsoHandler::eHT_Transmit) {
959                 result = m_IsoTaskTransmit->requestShadowMapUpdate();
960             } else {
961                 result = m_IsoTaskReceive->requestShadowMapUpdate();
962             }
963             if(!result) {
964                 debugOutput( DEBUG_LEVEL_VERBOSE, " could not update shadow map for handler (%p)\n",*it);
965                 return false;
966             }
967             return true;
968         }
969     }
970     debugError("Stream %p has no attached handler\n", stream);
971     return false;
972 }
973
974 int
975 IsoHandlerManager::getPacketLatencyForStream(Streaming::StreamProcessor *stream) {
976     for ( IsoHandlerVectorIterator it = m_IsoHandlers.begin();
977       it != m_IsoHandlers.end();
978       ++it )
979     {
980         if((*it)->isStreamRegistered(stream)) {
981             return (*it)->getIrqInterval();
982         }
983     }
984     debugError("Stream %p has no attached handler\n", stream);
985     return 0;
986 }
987
988 void
989 IsoHandlerManager::flushHandlerForStream(Streaming::StreamProcessor *stream) {
990     for ( IsoHandlerVectorIterator it = m_IsoHandlers.begin();
991       it != m_IsoHandlers.end();
992       ++it )
993     {
994         if((*it)->isStreamRegistered(stream)) {
995             (*it)->flush();
996         }
997     }
998     debugError("Stream %p has no attached handler\n", stream);
999     return;
1000 }
1001
1002 IsoHandler *
1003 IsoHandlerManager::getHandlerForStream(Streaming::StreamProcessor *stream) {
1004     for ( IsoHandlerVectorIterator it = m_IsoHandlers.begin();
1005       it != m_IsoHandlers.end();
1006       ++it )
1007     {
1008         if((*it)->isStreamRegistered(stream)) {
1009             return (*it);
1010         }
1011     }
1012     debugError("Stream %p has no attached handler\n", stream);
1013     return NULL;
1014 }
1015
1016 bool
1017 IsoHandlerManager::startHandlerForStream(Streaming::StreamProcessor *stream) {
1018     return startHandlerForStream(stream, -1);
1019 }
1020
1021 bool
1022 IsoHandlerManager::startHandlerForStream(Streaming::StreamProcessor *stream, int cycle) {
1023     // check state
1024     if(m_State != E_Running) {
1025         debugError("Incorrect state, expected E_Running, got %s\n", eHSToString(m_State));
1026         return false;
1027     }
1028     for ( IsoHandlerVectorIterator it = m_IsoHandlers.begin();
1029       it != m_IsoHandlers.end();
1030       ++it )
1031     {
1032         if((*it)->isStreamRegistered(stream)) {
1033             debugOutput( DEBUG_LEVEL_VERBOSE, " starting handler %p for stream %p\n", *it, stream);
1034             if(!(*it)->enable(cycle)) {
1035                 debugOutput( DEBUG_LEVEL_VERBOSE, " could not enable handler (%p)\n",*it);
1036                 return false;
1037             }
1038             bool result;
1039             if((*it)->getType() == IsoHandler::eHT_Transmit) {
1040                 result = m_IsoTaskTransmit->requestShadowMapUpdate();
1041             } else {
1042                 result = m_IsoTaskReceive->requestShadowMapUpdate();
1043             }
1044             if(!result) {
1045                 debugOutput( DEBUG_LEVEL_VERBOSE, " could not update shadow map for handler (%p)\n",*it);
1046                 return false;
1047             }
1048             return true;
1049         }
1050     }
1051     debugError("Stream %p has no attached handler\n", stream);
1052     return false;
1053 }
1054
1055 bool IsoHandlerManager::stopHandlers() {
1056     debugOutput( DEBUG_LEVEL_VERBOSE, "enter...\n");
1057
1058     // check state
1059     if(m_State != E_Running) {
1060         debugError("Incorrect state, expected E_Running, got %s\n", eHSToString(m_State));
1061         return false;
1062     }
1063
1064     bool retval=true;
1065
1066     for ( IsoHandlerVectorIterator it = m_IsoHandlers.begin();
1067         it != m_IsoHandlers.end();
1068         ++it )
1069     {
1070         debugOutput( DEBUG_LEVEL_VERBOSE, "Stopping handler (%p)\n",*it);
1071         if(!(*it)->disable()){
1072             debugOutput( DEBUG_LEVEL_VERBOSE, " could not stop handler (%p)\n",*it);
1073             retval=false;
1074         }
1075         bool result;
1076         if((*it)->getType() == IsoHandler::eHT_Transmit) {
1077             result = m_IsoTaskTransmit->requestShadowMapUpdate();
1078         } else {
1079             result = m_IsoTaskReceive->requestShadowMapUpdate();
1080         }
1081         if(!result) {
1082             debugOutput( DEBUG_LEVEL_VERBOSE, " could not update shadow map for handler (%p)\n",*it);
1083             return false;
1084         }
1085     }
1086
1087     if (retval) {
1088         m_State=E_Prepared;
1089     } else {
1090         m_State=E_Error;
1091     }
1092     return retval;
1093 }
1094
1095 bool IsoHandlerManager::reset() {
1096     debugOutput( DEBUG_LEVEL_VERBOSE, "enter...\n");
1097     // check state
1098     if(m_State == E_Error) {
1099         debugFatal("Resetting from error condition not yet supported...\n");
1100         return false;
1101     }
1102     // if not in an error condition, reset means stop the handlers
1103     return stopHandlers();
1104 }
1105
1106 void IsoHandlerManager::setVerboseLevel(int i) {
1107     setDebugLevel(i);
1108     // propagate the debug level
1109     for ( IsoHandlerVectorIterator it = m_IsoHandlers.begin();
1110           it != m_IsoHandlers.end();
1111           ++it )
1112     {
1113         (*it)->setVerboseLevel(i);
1114     }
1115     if(m_IsoThreadTransmit) m_IsoThreadTransmit->setVerboseLevel(i);
1116     if(m_IsoTaskTransmit)   m_IsoTaskTransmit->setVerboseLevel(i);
1117     if(m_IsoThreadReceive)  m_IsoThreadReceive->setVerboseLevel(i);
1118     if(m_IsoTaskReceive)    m_IsoTaskReceive->setVerboseLevel(i);
1119     setDebugLevel(i);
1120     debugOutput( DEBUG_LEVEL_VERBOSE, "Setting verbose level to %d...\n", i );
1121 }
1122
1123 void IsoHandlerManager::dumpInfo() {
1124     #ifdef DEBUG
1125     unsigned int i=0;
1126     debugOutputShort( DEBUG_LEVEL_NORMAL, "Dumping IsoHandlerManager Stream handler information...\n");
1127     debugOutputShort( DEBUG_LEVEL_NORMAL, " State: %d\n",(int)m_State);
1128
1129     for ( IsoHandlerVectorIterator it = m_IsoHandlers.begin();
1130           it != m_IsoHandlers.end();
1131           ++it )
1132     {
1133         debugOutputShort( DEBUG_LEVEL_NORMAL, " IsoHandler %d (%p)\n",i++,*it);
1134         (*it)->dumpInfo();
1135     }
1136     #endif
1137 }
1138
1139 const char *
1140 IsoHandlerManager::eHSToString(enum eHandlerStates s) {
1141     switch (s) {
1142         default: return "Invalid";
1143         case E_Created: return "Created";
1144         case E_Prepared: return "Prepared";
1145         case E_Running: return "Running";
1146         case E_Error: return "Error";
1147     }
1148 }
Note: See TracBrowser for help on using the browser.