root/branches/libffado-2.0/src/libieee1394/IsoHandlerManager.cpp

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

Host controller reliability changes:

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