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

Revision 1943, 67.4 kB (checked in by jwoithe, 10 years ago)

RME: fix for lengthy startup delay which prevented reliable startup in approximately 20% attempts. This may not be the approach adopted long-term since there seems to be something amiss with the way iso handlers are started in general (in short, the start cycle - m_switch_on_cycle in IsoHandler? - is never set to anything other than zero).

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 #include "libutil/Configuration.h"
36
37 #include <cstring>
38 #include <assert.h>
39
40 IMPL_DEBUG_MODULE( IsoHandlerManager, IsoHandlerManager, DEBUG_LEVEL_NORMAL );
41 IMPL_DEBUG_MODULE( IsoHandlerManager::IsoTask, IsoTask, DEBUG_LEVEL_NORMAL );
42 IMPL_DEBUG_MODULE( IsoHandlerManager::IsoHandler, IsoHandler, DEBUG_LEVEL_NORMAL );
43
44 using namespace Streaming;
45
46 // --- ISO Thread --- //
47
48 IsoHandlerManager::IsoTask::IsoTask(IsoHandlerManager& manager, enum IsoHandler::EHandlerType t)
49     : m_manager( manager )
50     , m_SyncIsoHandler ( NULL )
51     , m_handlerType( t )
52     , m_running( false )
53     , m_in_busreset( false )
54     , m_activity_wait_timeout_nsec (ISOHANDLERMANAGER_ISO_TASK_WAIT_TIMEOUT_USECS * 1000LL)
55 {
56 }
57
58 IsoHandlerManager::IsoTask::~IsoTask()
59 {
60     sem_destroy(&m_activity_semaphore);
61 }
62
63 bool
64 IsoHandlerManager::IsoTask::Init()
65 {
66     request_update = 0;
67
68     int i;
69     for (i=0; i < ISOHANDLERMANAGER_MAX_ISO_HANDLERS_PER_PORT; i++) {
70         m_IsoHandler_map_shadow[i] = NULL;
71         m_poll_fds_shadow[i].events = 0;
72     }
73     m_poll_nfds_shadow = 0;
74
75     #ifdef DEBUG
76     m_last_loop_entry = 0;
77     m_successive_short_loops = 0;
78     #endif
79
80     sem_init(&m_activity_semaphore, 0, 0);
81     m_running = true;
82     return true;
83 }
84
85 void
86 IsoHandlerManager::IsoTask::requestShadowMapUpdate()
87 {
88     debugOutput(DEBUG_LEVEL_VERBOSE, "(%p) enter\n", this);
89     INC_ATOMIC(&request_update);
90
91     // get the thread going again
92     signalActivity();
93     debugOutput(DEBUG_LEVEL_VERBOSE, "(%p) exit\n", this);
94 }
95
96 bool
97 IsoHandlerManager::IsoTask::handleBusReset()
98 {
99     bool retval = true;
100     if(!m_running) {
101         // nothing to do here
102         return true;
103     }
104     m_in_busreset = true;
105     requestShadowMapUpdate();
106
107     unsigned int i, max;
108     max = m_manager.m_IsoHandlers.size();
109     for (i = 0; i < max; i++) {
110         IsoHandler *h = m_manager.m_IsoHandlers.at(i);
111         assert(h);
112
113         // skip the handlers not intended for us
114         if(h->getType() != m_handlerType) continue;
115
116         if (!h->handleBusReset()) {
117             debugWarning("Failed to handle busreset on %p\n", h);
118             retval = false;
119         }
120     }
121
122     // re-enable processing
123     m_in_busreset = false;
124     requestShadowMapUpdate();
125     return retval;
126 }
127
128 // updates the internal stream map
129 // note that this should be executed with the guarantee that
130 // nobody will modify the parent data structures
131 void
132 IsoHandlerManager::IsoTask::updateShadowMapHelper()
133 {
134     debugOutput( DEBUG_LEVEL_VERBOSE, "(%p) updating shadow vars...\n", this);
135     // we are handling a busreset
136     if(m_in_busreset) {
137         m_poll_nfds_shadow = 0;
138         return;
139     }
140     unsigned int i, cnt, max;
141     max = m_manager.m_IsoHandlers.size();
142     m_SyncIsoHandler = NULL;
143     for (i = 0, cnt = 0; i < max; i++) {
144         IsoHandler *h = m_manager.m_IsoHandlers.at(i);
145         assert(h);
146
147         // skip the handlers not intended for us
148         if(h->getType() != m_handlerType) continue;
149
150         // update the state of the handler
151         // FIXME: maybe this is not the best place to do this
152         // it might be better to eliminate the 'requestShadowMapUpdate'
153         // entirely and replace it with a mechanism that implements all
154         // actions on the m_manager.m_IsoHandlers in the loop
155         h->updateState();
156
157         // rebuild the map
158         if (h->isEnabled()) {
159             m_IsoHandler_map_shadow[cnt] = h;
160             m_poll_fds_shadow[cnt].fd = h->getFileDescriptor();
161             m_poll_fds_shadow[cnt].revents = 0;
162             m_poll_fds_shadow[cnt].events = POLLIN;
163             cnt++;
164             // FIXME: need a more generic approach here
165             if(   m_SyncIsoHandler == NULL
166                && h->getType() == IsoHandler::eHT_Transmit) {
167                 m_SyncIsoHandler = h;
168             }
169
170             debugOutput( DEBUG_LEVEL_VERBOSE, "(%p) %s handler %p added\n",
171                                               this, h->getTypeString(), h);
172         } else {
173             debugOutput( DEBUG_LEVEL_VERBOSE, "(%p) %s handler %p skipped (disabled)\n",
174                                               this, h->getTypeString(), h);
175         }
176         if(cnt > ISOHANDLERMANAGER_MAX_ISO_HANDLERS_PER_PORT) {
177             debugWarning("Too much ISO Handlers in thread...\n");
178             break;
179         }
180     }
181
182     // FIXME: need a more generic approach here
183     // if there are no active transmit handlers,
184     // use the first receive handler
185     if(   m_SyncIsoHandler == NULL
186        && m_poll_nfds_shadow) {
187         m_SyncIsoHandler = m_IsoHandler_map_shadow[0];
188     }
189     m_poll_nfds_shadow = cnt;
190     debugOutput( DEBUG_LEVEL_VERBOSE, "(%p) updated shadow vars...\n", this);
191 }
192
193 bool
194 IsoHandlerManager::IsoTask::Execute()
195 {
196     debugOutput(DEBUG_LEVEL_ULTRA_VERBOSE,
197                 "(%p, %s) Execute\n",
198                 this, (m_handlerType == IsoHandler::eHT_Transmit? "Transmit": "Receive"));
199     int err;
200     unsigned int i;
201     unsigned int m_poll_timeout = 10;
202
203     #ifdef DEBUG
204     uint64_t now = Util::SystemTimeSource::getCurrentTimeAsUsecs();
205     int diff = now - m_last_loop_entry;
206     if(diff < 100) {
207         debugOutputExtreme(DEBUG_LEVEL_VERY_VERBOSE,
208                            "(%p, %s) short loop detected (%d usec), cnt: %d\n",
209                            this, (m_handlerType == IsoHandler::eHT_Transmit? "Transmit": "Receive"),
210                            diff, m_successive_short_loops);
211         m_successive_short_loops++;
212         if(m_successive_short_loops > 10000) {
213             debugError("Shutting down runaway thread\n");
214             m_running = false;
215             return false;
216         }
217     } else {
218         // reset the counter
219         m_successive_short_loops = 0;
220     }
221     m_last_loop_entry = now;
222     #endif
223
224     // if some other thread requested a shadow map update, do it
225     if(request_update) {
226         updateShadowMapHelper();
227         DEC_ATOMIC(&request_update); // ack the update
228         assert(request_update >= 0);
229     }
230
231     // bypass if no handlers are registered
232     if (m_poll_nfds_shadow == 0) {
233         debugOutputExtreme(DEBUG_LEVEL_VERY_VERBOSE,
234                            "(%p, %s) bypass iterate since no handlers to poll\n",
235                            this, (m_handlerType == IsoHandler::eHT_Transmit? "Transmit": "Receive"));
236         usleep(m_poll_timeout * 1000);
237         return true;
238     }
239
240     // FIXME: what can happen is that poll() returns, but not all clients are
241     // ready. there might be some busy waiting behavior that still has to be solved.
242
243     // setup the poll here
244     // we should prevent a poll() where no events are specified, since that will only time-out
245     bool no_one_to_poll = true;
246     while(no_one_to_poll) {
247         for (i = 0; i < m_poll_nfds_shadow; i++) {
248             short events = 0;
249             IsoHandler *h = m_IsoHandler_map_shadow[i];
250             // we should only poll on a transmit handler
251             // that has a client that is ready to send
252             // something. Otherwise it will end up in
253             // busy wait looping since the packet function
254             // will defer processing (also avoids the
255             // AGAIN problem)
256             if (h->canIterateClient()) {
257                 events = POLLIN | POLLPRI;
258                 no_one_to_poll = false;
259             }
260             m_poll_fds_shadow[i].events = events;
261         }
262
263         if(no_one_to_poll) {
264             debugOutputExtreme(DEBUG_LEVEL_VERBOSE,
265                         "(%p, %s) No one to poll, waiting for something to happen\n",
266                         this, (m_handlerType == IsoHandler::eHT_Transmit? "Transmit": "Receive"));
267             // wait for something to happen
268             switch(waitForActivity()) {
269                 case IsoHandlerManager::IsoTask::eAR_Error:
270                     debugError("Error while waiting for activity\n");
271                     return false;
272                 case IsoHandlerManager::IsoTask::eAR_Interrupted:
273                     // FIXME: what to do here?
274                     debugWarning("Interrupted while waiting for activity\n");
275                     break;
276                 case IsoHandlerManager::IsoTask::eAR_Timeout:
277                     // FIXME: what to do here?
278                     debugWarning("Timeout while waiting for activity\n");
279                     no_one_to_poll = false; // exit the loop to be able to detect failing handlers
280                     break;
281                 case IsoHandlerManager::IsoTask::eAR_Activity:
282                     // do nothing
283                     debugOutputExtreme(DEBUG_LEVEL_VERBOSE,
284                                        "(%p, %s) something happened\n",
285                                        this, (m_handlerType == IsoHandler::eHT_Transmit? "Transmit": "Receive"));
286                     break;
287             }
288         }
289     }
290
291     // Use a shadow map of the fd's such that we don't have to update
292     // the fd map everytime we run poll().
293     err = poll (m_poll_fds_shadow, m_poll_nfds_shadow, m_poll_timeout);
294     uint32_t ctr_at_poll_return = m_manager.get1394Service().getCycleTimer();
295
296     if (err < 0) {
297         if (errno == EINTR) {
298             debugOutput(DEBUG_LEVEL_VERBOSE, "Ignoring poll return due to signal\n");
299             return true;
300         }
301         debugFatal("poll error: %s\n", strerror (errno));
302         m_running = false;
303         return false;
304     }
305
306     // find handlers that have died
307     uint64_t ctr_at_poll_return_ticks = CYCLE_TIMER_TO_TICKS(ctr_at_poll_return);
308     bool handler_died = false;
309     for (i = 0; i < m_poll_nfds_shadow; i++) {
310         // figure out if a handler has died
311
312         // this is the time of the last packet we saw in the iterate() handler
313         uint32_t last_packet_seen = m_IsoHandler_map_shadow[i]->getLastPacketTime();
314         if (last_packet_seen == 0xFFFFFFFF) {
315             // this was not iterated yet, so can't be dead
316             debugOutput(DEBUG_LEVEL_VERY_VERBOSE,
317                         "(%p, %s) handler %d didn't see any packets yet\n",
318                         this, (m_handlerType == IsoHandler::eHT_Transmit? "Transmit": "Receive"), i);
319             continue;
320         }
321
322         uint64_t last_packet_seen_ticks = CYCLE_TIMER_TO_TICKS(last_packet_seen);
323         // we use a relatively large value to distinguish between "death" and xrun
324         int64_t max_diff_ticks = TICKS_PER_SECOND * 2;
325         int64_t measured_diff_ticks = diffTicks(ctr_at_poll_return_ticks, last_packet_seen_ticks);
326
327         debugOutputExtreme(DEBUG_LEVEL_VERBOSE,
328                            "(%p, %s) check handler %d: diff = %"PRId64", max = %"PRId64", now: %08X, last: %08X\n",
329                            this, (m_handlerType == IsoHandler::eHT_Transmit? "Transmit": "Receive"),
330                            i, measured_diff_ticks, max_diff_ticks, ctr_at_poll_return, last_packet_seen);
331         if(measured_diff_ticks > max_diff_ticks) {
332             debugFatal("(%p, %s) Handler died: now: %08X, last: %08X, diff: %"PRId64" (max: %"PRId64")\n",
333                        this, (m_handlerType == IsoHandler::eHT_Transmit? "Transmit": "Receive"),
334                        ctr_at_poll_return, last_packet_seen, measured_diff_ticks, max_diff_ticks);
335             m_IsoHandler_map_shadow[i]->notifyOfDeath();
336             handler_died = true;
337         }
338     }
339
340     if(handler_died) {
341         m_running = false;
342         return false; // one or more handlers have died
343     }
344
345     // iterate the handlers
346     for (i = 0; i < m_poll_nfds_shadow; i++) {
347         #ifdef DEBUG
348         if(m_poll_fds_shadow[i].revents) {
349             debugOutputExtreme(DEBUG_LEVEL_VERBOSE,
350                         "(%p, %s) received events: %08X for (%d/%d, %p, %s)\n",
351                         this, (m_handlerType == IsoHandler::eHT_Transmit? "Transmit": "Receive"),
352                         m_poll_fds_shadow[i].revents,
353                         i, m_poll_nfds_shadow,
354                         m_IsoHandler_map_shadow[i],
355                         m_IsoHandler_map_shadow[i]->getTypeString());
356         }
357         #endif
358
359         // if we get here, it means two things:
360         // 1) the kernel can accept or provide packets (poll returned POLLIN)
361         // 2) the client can provide or accept packets (since we enabled polling)
362         if(m_poll_fds_shadow[i].revents & (POLLIN)) {
363             m_IsoHandler_map_shadow[i]->iterate(ctr_at_poll_return);
364         } else {
365             // there might be some error condition
366             if (m_poll_fds_shadow[i].revents & POLLERR) {
367                 debugWarning("(%p) error on fd for %d\n", this, i);
368             }
369             if (m_poll_fds_shadow[i].revents & POLLHUP) {
370                 debugWarning("(%p) hangup on fd for %d\n", this, i);
371             }
372         }
373     }
374     return true;
375 }
376
377 enum IsoHandlerManager::IsoTask::eActivityResult
378 IsoHandlerManager::IsoTask::waitForActivity()
379 {
380     debugOutputExtreme(DEBUG_LEVEL_VERBOSE,
381                        "(%p, %s) waiting for activity\n",
382                        this, (m_handlerType == IsoHandler::eHT_Transmit? "Transmit": "Receive"));
383     struct timespec ts;
384     int result;
385
386     if (clock_gettime(CLOCK_REALTIME, &ts) == -1) {
387         debugError("clock_gettime failed\n");
388         return eAR_Error;
389     }
390
391     ts.tv_nsec += m_activity_wait_timeout_nsec;
392     while(ts.tv_nsec >= 1000000000LL) {
393         ts.tv_sec += 1;
394         ts.tv_nsec -= 1000000000LL;
395     }
396
397     result = sem_timedwait(&m_activity_semaphore, &ts);
398
399     if(result != 0) {
400         if (errno == ETIMEDOUT) {
401             debugOutput(DEBUG_LEVEL_VERBOSE,
402                         "(%p) sem_timedwait() timed out (result=%d)\n",
403                         this, result);
404             return eAR_Timeout;
405         } else if (errno == EINTR) {
406             debugOutput(DEBUG_LEVEL_VERBOSE,
407                         "(%p) sem_timedwait() interrupted by signal (result=%d)\n",
408                         this, result);
409             return eAR_Interrupted;
410         } else if (errno == EINVAL) {
411             debugError("(%p) sem_timedwait error (result=%d errno=EINVAL)\n",
412                         this, result);
413             debugError("(%p) timeout_nsec=%lld ts.sec=%"PRId64" ts.nsec=%"PRId64"\n",
414                        this, m_activity_wait_timeout_nsec,
415                        (int64_t)ts.tv_sec, (int64_t)ts.tv_nsec);
416             return eAR_Error;
417         } else {
418             debugError("(%p) sem_timedwait error (result=%d errno=%d)\n",
419                         this, result, errno);
420             debugError("(%p) timeout_nsec=%lld ts.sec=%"PRId64" ts.nsec=%"PRId64"\n",
421                        this, m_activity_wait_timeout_nsec,
422                        (int64_t)ts.tv_sec, (int64_t)ts.tv_nsec);
423             return eAR_Error;
424         }
425     }
426
427     debugOutput(DEBUG_LEVEL_ULTRA_VERBOSE,
428                 "(%p, %s) got activity\n",
429                 this, (m_handlerType == IsoHandler::eHT_Transmit? "Transmit": "Receive"));
430     return eAR_Activity;
431 }
432
433 void
434 IsoHandlerManager::IsoTask::signalActivity()
435 {
436     // signal the activity cond var
437     sem_post(&m_activity_semaphore);
438     debugOutput(DEBUG_LEVEL_ULTRA_VERBOSE,
439                 "(%p, %s) activity\n",
440                 this, (m_handlerType == IsoHandler::eHT_Transmit? "Transmit": "Receive"));
441 }
442
443 void IsoHandlerManager::IsoTask::setVerboseLevel(int i) {
444     setDebugLevel(i);
445     debugOutput( DEBUG_LEVEL_VERBOSE, "Setting verbose level to %d...\n", i );
446 }
447
448 // -- the ISO handler manager -- //
449 IsoHandlerManager::IsoHandlerManager(Ieee1394Service& service)
450    : m_State(E_Created)
451    , m_service( service )
452    , m_realtime(false), m_priority(0)
453    , m_IsoThreadTransmit ( NULL )
454    , m_IsoTaskTransmit ( NULL )
455    , m_IsoThreadReceive ( NULL )
456    , m_IsoTaskReceive ( NULL )
457 {
458 }
459
460 IsoHandlerManager::IsoHandlerManager(Ieee1394Service& service, bool run_rt, int rt_prio)
461    : m_State(E_Created)
462    , m_service( service )
463    , m_realtime(run_rt), m_priority(rt_prio)
464    , m_IsoThreadTransmit ( NULL )
465    , m_IsoTaskTransmit ( NULL )
466    , m_IsoThreadReceive ( NULL )
467    , m_IsoTaskReceive ( NULL )
468    , m_MissedCyclesOK ( false )
469 {
470 }
471
472 IsoHandlerManager::~IsoHandlerManager()
473 {
474     stopHandlers();
475     pruneHandlers();
476     if(m_IsoHandlers.size() > 0) {
477         debugError("Still some handlers in use\n");
478     }
479     if (m_IsoThreadTransmit) {
480         m_IsoThreadTransmit->Stop();
481         delete m_IsoThreadTransmit;
482     }
483     if (m_IsoThreadReceive) {
484         m_IsoThreadReceive->Stop();
485         delete m_IsoThreadReceive;
486     }
487     if (m_IsoTaskTransmit) {
488         delete m_IsoTaskTransmit;
489     }
490     if (m_IsoTaskReceive) {
491         delete m_IsoTaskReceive;
492     }
493 }
494
495 bool
496 IsoHandlerManager::handleBusReset()
497 {
498     debugOutput( DEBUG_LEVEL_NORMAL, "bus reset...\n");
499     // A few things can happen on bus reset:
500     // 1) no devices added/removed => streams are still valid, but might have to be restarted
501     // 2) a device was removed => some streams become invalid
502     // 3) a device was added => same as 1, new device is ignored
503     if (!m_IsoTaskTransmit) {
504         debugError("No xmit task\n");
505         return false;
506     }
507     if (!m_IsoTaskReceive) {
508         debugError("No receive task\n");
509         return false;
510     }
511     if (!m_IsoTaskTransmit->handleBusReset()) {
512         debugWarning("could no handle busreset on xmit\n");
513     }
514     if (!m_IsoTaskReceive->handleBusReset()) {
515         debugWarning("could no handle busreset on recv\n");
516     }
517     return true;
518 }
519
520 void
521 IsoHandlerManager::requestShadowMapUpdate()
522 {
523     if(m_IsoTaskTransmit) m_IsoTaskTransmit->requestShadowMapUpdate();
524     if(m_IsoTaskReceive) m_IsoTaskReceive->requestShadowMapUpdate();
525 }
526
527 bool
528 IsoHandlerManager::setThreadParameters(bool rt, int priority) {
529     debugOutput( DEBUG_LEVEL_VERBOSE, "(%p) switch to: (rt=%d, prio=%d)...\n", this, rt, priority);
530     if (priority > THREAD_MAX_RTPRIO) priority = THREAD_MAX_RTPRIO; // cap the priority
531     if (priority < THREAD_MIN_RTPRIO) priority = THREAD_MIN_RTPRIO; // cap the priority
532     m_realtime = rt;
533     m_priority = priority;
534
535     // grab the options from the parent
536     Util::Configuration *config = m_service.getConfiguration();
537     int ihm_iso_prio_increase = ISOHANDLERMANAGER_ISO_PRIO_INCREASE;
538     int ihm_iso_prio_increase_xmit = ISOHANDLERMANAGER_ISO_PRIO_INCREASE_XMIT;
539     int ihm_iso_prio_increase_recv = ISOHANDLERMANAGER_ISO_PRIO_INCREASE_RECV;
540     if(config) {
541         config->getValueForSetting("ieee1394.isomanager.prio_increase", ihm_iso_prio_increase);
542         config->getValueForSetting("ieee1394.isomanager.prio_increase_xmit", ihm_iso_prio_increase_xmit);
543         config->getValueForSetting("ieee1394.isomanager.prio_increase_recv", ihm_iso_prio_increase_recv);
544     }
545
546     if (m_IsoThreadTransmit) {
547         if (m_realtime) {
548             m_IsoThreadTransmit->AcquireRealTime(m_priority
549                                                  + ihm_iso_prio_increase
550                                                  + ihm_iso_prio_increase_xmit);
551         } else {
552             m_IsoThreadTransmit->DropRealTime();
553         }
554     }
555     if (m_IsoThreadReceive) {
556         if (m_realtime) {
557             m_IsoThreadReceive->AcquireRealTime(m_priority
558                                                 + ihm_iso_prio_increase
559                                                 + ihm_iso_prio_increase_recv);
560         } else {
561             m_IsoThreadReceive->DropRealTime();
562         }
563     }
564
565     return true;
566 }
567
568 bool IsoHandlerManager::init()
569 {
570     debugOutput( DEBUG_LEVEL_VERBOSE, "Initializing ISO manager %p...\n", this);
571     // check state
572     if(m_State != E_Created) {
573         debugError("Manager already initialized...\n");
574         return false;
575     }
576
577     // grab the options from the parent
578     Util::Configuration *config = m_service.getConfiguration();
579     int ihm_iso_prio_increase = ISOHANDLERMANAGER_ISO_PRIO_INCREASE;
580     int ihm_iso_prio_increase_xmit = ISOHANDLERMANAGER_ISO_PRIO_INCREASE_XMIT;
581     int ihm_iso_prio_increase_recv = ISOHANDLERMANAGER_ISO_PRIO_INCREASE_RECV;
582     int64_t isotask_activity_timeout_usecs = ISOHANDLERMANAGER_ISO_TASK_WAIT_TIMEOUT_USECS;
583     if(config) {
584         config->getValueForSetting("ieee1394.isomanager.prio_increase", ihm_iso_prio_increase);
585         config->getValueForSetting("ieee1394.isomanager.prio_increase_xmit", ihm_iso_prio_increase_xmit);
586         config->getValueForSetting("ieee1394.isomanager.prio_increase_recv", ihm_iso_prio_increase_recv);
587         config->getValueForSetting("ieee1394.isomanager.isotask_activity_timeout_usecs", isotask_activity_timeout_usecs);
588     }
589
590     // create threads to iterate our ISO handlers
591     debugOutput( DEBUG_LEVEL_VERBOSE, "Create iso thread for %p transmit...\n", this);
592     m_IsoTaskTransmit = new IsoTask( *this, IsoHandler::eHT_Transmit );
593     if(!m_IsoTaskTransmit) {
594         debugFatal("No task\n");
595         return false;
596     }
597     m_IsoTaskTransmit->setVerboseLevel(getDebugLevel());
598     m_IsoTaskTransmit->m_activity_wait_timeout_nsec = isotask_activity_timeout_usecs * 1000LL;
599     m_IsoThreadTransmit = new Util::PosixThread(m_IsoTaskTransmit, "ISOXMT", m_realtime,
600                                                 m_priority + ihm_iso_prio_increase
601                                                 + ihm_iso_prio_increase_xmit,
602                                                 PTHREAD_CANCEL_DEFERRED);
603
604     if(!m_IsoThreadTransmit) {
605         debugFatal("No thread\n");
606         return false;
607     }
608     m_IsoThreadTransmit->setVerboseLevel(getDebugLevel());
609
610     debugOutput( DEBUG_LEVEL_VERBOSE, "Create iso thread for %p receive...\n", this);
611     m_IsoTaskReceive = new IsoTask( *this, IsoHandler::eHT_Receive );
612     if(!m_IsoTaskReceive) {
613         debugFatal("No task\n");
614         return false;
615     }
616     m_IsoTaskReceive->setVerboseLevel(getDebugLevel());
617     m_IsoThreadReceive = new Util::PosixThread(m_IsoTaskReceive, "ISORCV", m_realtime,
618                                                m_priority + ihm_iso_prio_increase
619                                                + ihm_iso_prio_increase_recv,
620                                                PTHREAD_CANCEL_DEFERRED);
621
622     if(!m_IsoThreadReceive) {
623         debugFatal("No thread\n");
624         return false;
625     }
626     m_IsoThreadReceive->setVerboseLevel(getDebugLevel());
627     // register the thread with the RT watchdog
628     Util::Watchdog *watchdog = m_service.getWatchdog();
629     if(watchdog) {
630         if(!watchdog->registerThread(m_IsoThreadTransmit)) {
631             debugWarning("could not register iso transmit thread with watchdog\n");
632         }
633         if(!watchdog->registerThread(m_IsoThreadReceive)) {
634             debugWarning("could not register iso receive thread with watchdog\n");
635         }
636     } else {
637         debugWarning("could not find valid watchdog\n");
638     }
639
640     if (m_IsoThreadTransmit->Start() != 0) {
641         debugFatal("Could not start ISO Transmit thread\n");
642         return false;
643     }
644     if (m_IsoThreadReceive->Start() != 0) {
645         debugFatal("Could not start ISO Receive thread\n");
646         return false;
647     }
648
649     m_State=E_Running;
650     return true;
651 }
652
653 void
654 IsoHandlerManager::signalActivityTransmit()
655 {
656     assert(m_IsoTaskTransmit);
657     m_IsoTaskTransmit->signalActivity();
658 }
659
660 void
661 IsoHandlerManager::signalActivityReceive()
662 {
663     assert(m_IsoTaskReceive);
664     m_IsoTaskReceive->signalActivity();
665 }
666
667 bool IsoHandlerManager::registerHandler(IsoHandler *handler)
668 {
669     debugOutput( DEBUG_LEVEL_VERBOSE, "enter...\n");
670     assert(handler);
671     handler->setVerboseLevel(getDebugLevel());
672     m_IsoHandlers.push_back(handler);
673     requestShadowMapUpdate();
674     return true;
675 }
676
677 bool IsoHandlerManager::unregisterHandler(IsoHandler *handler)
678 {
679     debugOutput( DEBUG_LEVEL_VERBOSE, "enter...\n");
680     assert(handler);
681
682     for ( IsoHandlerVectorIterator it = m_IsoHandlers.begin();
683       it != m_IsoHandlers.end();
684       ++it )
685     {
686         if ( *it == handler ) {
687             m_IsoHandlers.erase(it);
688             requestShadowMapUpdate();
689             return true;
690         }
691     }
692     debugFatal("Could not find handler (%p)\n", handler);
693     return false; //not found
694 }
695
696 /**
697  * Registers an StreamProcessor with the IsoHandlerManager.
698  *
699  * If nescessary, an IsoHandler is created to handle this stream.
700  * Once an StreamProcessor is registered to the handler, it will be included
701  * in the ISO streaming cycle (i.e. receive/transmit of it will occur).
702  *
703  * @param stream the stream to register
704  * @return true if registration succeeds
705  *
706  * \todo : currently there is a one-to-one mapping
707  *        between streams and handlers, this is not ok for
708  *        multichannel receive
709  */
710 bool IsoHandlerManager::registerStream(StreamProcessor *stream)
711 {
712     debugOutput( DEBUG_LEVEL_VERBOSE, "Registering %s stream %p\n", stream->getTypeString(), stream);
713     assert(stream);
714
715     IsoHandler* h = NULL;
716
717     // make sure the stream isn't already attached to a handler
718     for ( IsoHandlerVectorIterator it = m_IsoHandlers.begin();
719       it != m_IsoHandlers.end();
720       ++it )
721     {
722         if((*it)->isStreamRegistered(stream)) {
723             debugError( "stream already registered!\n");
724             return false;
725         }
726     }
727
728     // clean up all handlers that aren't used
729     pruneHandlers();
730
731     // allocate a handler for this stream
732     if (stream->getType()==StreamProcessor::ePT_Receive) {
733         // grab the options from the parent
734         Util::Configuration *config = m_service.getConfiguration();
735         int receive_mode_setting = DEFAULT_ISO_RECEIVE_MODE;
736         int bufferfill_mode_threshold = BUFFERFILL_MODE_THRESHOLD;
737         int min_interrupts_per_period = MINIMUM_INTERRUPTS_PER_PERIOD;
738         int max_nb_buffers_recv = MAX_RECV_NB_BUFFERS;
739         int min_packetsize_recv = MIN_RECV_PACKET_SIZE;
740         if(config) {
741             config->getValueForSetting("ieee1394.isomanager.iso_receive_mode", receive_mode_setting);
742             config->getValueForSetting("ieee1394.isomanager.bufferfill_mode_threshold", bufferfill_mode_threshold);
743             config->getValueForSetting("ieee1394.isomanager.min_interrupts_per_period", min_interrupts_per_period);
744             config->getValueForSetting("ieee1394.isomanager.max_nb_buffers_recv", max_nb_buffers_recv);
745             config->getValueForSetting("ieee1394.isomanager.min_packetsize_recv", min_packetsize_recv);
746         }
747
748         // setup the optimal parameters for the raw1394 ISO buffering
749         unsigned int packets_per_period = stream->getPacketsPerPeriod();
750         // reserve space for the 1394 header too (might not be necessary)
751         unsigned int max_packet_size = stream->getMaxPacketSize() + 8;
752         unsigned int page_size = getpagesize();
753
754         enum raw1394_iso_dma_recv_mode receive_mode;
755         switch(receive_mode_setting) {
756             case 0:
757                 if(packets_per_period < (unsigned)bufferfill_mode_threshold) {
758                     debugOutput( DEBUG_LEVEL_VERBOSE, "Using packet-per-buffer mode (auto) [%d, %d]\n",
759                                  packets_per_period, bufferfill_mode_threshold);
760                     receive_mode = RAW1394_DMA_PACKET_PER_BUFFER;
761                 } else {
762                     debugOutput( DEBUG_LEVEL_VERBOSE, "Using bufferfill mode (auto) [%d, %d]\n",
763                                  packets_per_period, bufferfill_mode_threshold);
764                     receive_mode = RAW1394_DMA_BUFFERFILL;
765                 }
766                 break;
767             case 1:
768                 debugOutput( DEBUG_LEVEL_VERBOSE, "Using packet-per-buffer mode (config)\n");
769                 receive_mode = RAW1394_DMA_PACKET_PER_BUFFER;
770                 break;
771             case 2:
772                 debugOutput( DEBUG_LEVEL_VERBOSE, "Using bufferfill mode (config)\n");
773                 receive_mode = RAW1394_DMA_BUFFERFILL;
774                 break;
775             default: debugWarning("Bogus receive mode setting in config: %d\n", receive_mode_setting);
776         }
777
778         // Ensure we don't request a packet size bigger than the
779         // kernel-enforced maximum which is currently 1 page.
780         // NOTE: PP: this is not really true AFAICT
781         if (max_packet_size > page_size) {
782             debugError("max packet size (%u) > page size (%u)\n", max_packet_size, page_size);
783             return false;
784         }
785         if (max_packet_size < (unsigned)min_packetsize_recv) {
786             debugError("min packet size (%u) < MIN_RECV_PACKET_SIZE (%u), using min value\n",
787                        max_packet_size, min_packetsize_recv);
788             max_packet_size = min_packetsize_recv;
789         }
790
791         // apparently a too small value causes issues too
792         if(max_packet_size < 200) max_packet_size = 200;
793
794         // the interrupt/wakeup interval prediction of raw1394 is a mess...
795         int irq_interval = (packets_per_period-1) / min_interrupts_per_period;
796         if(irq_interval <= 0) irq_interval=1;
797
798         // the receive buffer size doesn't matter for the latency,
799         // it does seem to be confined to a certain region for correct
800         // operation. However it is not clear how many.
801         int buffers = max_nb_buffers_recv;
802
803         // ensure at least 2 hardware interrupts per ISO buffer wraparound
804         if(irq_interval > buffers/2) {
805             irq_interval = buffers/2;
806         }
807
808         // create the actual handler
809         debugOutput( DEBUG_LEVEL_VERBOSE, " creating IsoRecvHandler\n");
810         h = new IsoHandler(*this, IsoHandler::eHT_Receive,
811                            buffers, max_packet_size, irq_interval);
812
813         if(!h) {
814             debugFatal("Could not create IsoRecvHandler\n");
815             return false;
816         }
817
818         h->setReceiveMode(receive_mode);
819
820     } else if (stream->getType()==StreamProcessor::ePT_Transmit) {
821         // grab the options from the parent
822         Util::Configuration *config = m_service.getConfiguration();
823         int min_interrupts_per_period = MINIMUM_INTERRUPTS_PER_PERIOD;
824         int max_nb_buffers_xmit = MAX_XMIT_NB_BUFFERS;
825         int max_packetsize_xmit = MAX_XMIT_PACKET_SIZE;
826         int min_packetsize_xmit = MIN_XMIT_PACKET_SIZE;
827         if(config) {
828             config->getValueForSetting("ieee1394.isomanager.min_interrupts_per_period", min_interrupts_per_period);
829             config->getValueForSetting("ieee1394.isomanager.max_nb_buffers_xmit", max_nb_buffers_xmit);
830             config->getValueForSetting("ieee1394.isomanager.max_packetsize_xmit", max_packetsize_xmit);
831             config->getValueForSetting("ieee1394.isomanager.min_packetsize_xmit", min_packetsize_xmit);
832         }
833
834         // setup the optimal parameters for the raw1394 ISO buffering
835         // reserve space for the 1394 header too (might not be necessary)
836         unsigned int max_packet_size = stream->getMaxPacketSize() + 8;
837
838         if (max_packet_size > (unsigned)max_packetsize_xmit) {
839             debugError("max packet size (%u) > MAX_XMIT_PACKET_SIZE (%u)\n",
840                        max_packet_size, max_packetsize_xmit);
841             return false;
842         }
843         if (max_packet_size < (unsigned)min_packetsize_xmit) {
844             debugError("min packet size (%u) < MIN_XMIT_PACKET_SIZE (%u), using min value\n",
845                        max_packet_size, min_packetsize_xmit);
846             max_packet_size = min_packetsize_xmit;
847         }
848
849         int buffers = max_nb_buffers_xmit;
850         unsigned int packets_per_period = stream->getPacketsPerPeriod();
851
852         int irq_interval = (packets_per_period-1) / min_interrupts_per_period;
853         if(irq_interval <= 0) irq_interval=1;
854         // ensure at least 2 hardware interrupts per ISO buffer wraparound
855         if(irq_interval > buffers/2) {
856             irq_interval = buffers/2;
857         }
858
859         debugOutput( DEBUG_LEVEL_VERBOSE, " creating IsoXmitHandler\n");
860
861         // create the actual handler
862         h = new IsoHandler(*this, IsoHandler::eHT_Transmit,
863                            buffers, max_packet_size, irq_interval);
864
865         if(!h) {
866             debugFatal("Could not create IsoXmitHandler\n");
867             return false;
868         }
869
870     } else {
871         debugFatal("Bad stream type\n");
872         return false;
873     }
874
875     h->setVerboseLevel(getDebugLevel());
876
877     // register the stream with the handler
878     if(!h->registerStream(stream)) {
879         debugFatal("Could not register receive stream with handler\n");
880         return false;
881     }
882
883     // register the handler with the manager
884     if(!registerHandler(h)) {
885         debugFatal("Could not register receive handler with manager\n");
886         return false;
887     }
888     debugOutput( DEBUG_LEVEL_VERBOSE, " registered stream (%p) with handler (%p)\n", stream, h);
889
890     m_StreamProcessors.push_back(stream);
891     debugOutput( DEBUG_LEVEL_VERBOSE, " %zd streams, %zd handlers registered\n",
892                                       m_StreamProcessors.size(), m_IsoHandlers.size());
893     return true;
894 }
895
896 bool IsoHandlerManager::unregisterStream(StreamProcessor *stream)
897 {
898     debugOutput( DEBUG_LEVEL_VERBOSE, "Unregistering %s stream %p\n", stream->getTypeString(), stream);
899     assert(stream);
900
901     // make sure the stream isn't attached to a handler anymore
902     for ( IsoHandlerVectorIterator it = m_IsoHandlers.begin();
903       it != m_IsoHandlers.end();
904       ++it )
905     {
906         if((*it)->isStreamRegistered(stream)) {
907             if(!(*it)->unregisterStream(stream)) {
908                 debugOutput( DEBUG_LEVEL_VERBOSE, " could not unregister stream (%p) from handler (%p)...\n",stream,*it);
909                 return false;
910             }
911             debugOutput( DEBUG_LEVEL_VERBOSE, " unregistered stream (%p) from handler (%p)...\n",stream,*it);
912         }
913     }
914
915     // clean up all handlers that aren't used
916     pruneHandlers();
917
918     // remove the stream from the registered streams list
919     for ( StreamProcessorVectorIterator it = m_StreamProcessors.begin();
920       it != m_StreamProcessors.end();
921       ++it )
922     {
923         if ( *it == stream ) {
924             m_StreamProcessors.erase(it);
925             debugOutput( DEBUG_LEVEL_VERBOSE, " deleted stream (%p) from list...\n", *it);
926             return true;
927         }
928     }
929     return false; //not found
930 }
931
932 /**
933  * @brief unregister a handler from the manager
934  * @note called without the lock held.
935  */
936 void IsoHandlerManager::pruneHandlers() {
937     debugOutput( DEBUG_LEVEL_VERBOSE, "enter...\n");
938     IsoHandlerVector toUnregister;
939
940     // find all handlers that are not in use
941     for ( IsoHandlerVectorIterator it = m_IsoHandlers.begin();
942           it != m_IsoHandlers.end();
943           ++it )
944     {
945         if(!((*it)->inUse())) {
946             debugOutput( DEBUG_LEVEL_VERBOSE, " handler (%p) not in use\n",*it);
947             toUnregister.push_back(*it);
948         }
949     }
950     // delete them
951     for ( IsoHandlerVectorIterator it = toUnregister.begin();
952           it != toUnregister.end();
953           ++it )
954     {
955         unregisterHandler(*it);
956
957         debugOutput( DEBUG_LEVEL_VERBOSE, " deleting handler (%p)\n",*it);
958
959         // Now the handler's been unregistered it won't be reused
960         // again.  Therefore it really needs to be formally deleted
961         // to free up the raw1394 handle.  Otherwise things fall
962         // apart after several xrun recoveries as the system runs
963         // out of resources to support all the disused but still
964         // allocated raw1394 handles.  At least this is the current
965         // theory as to why we end up with "memory allocation"
966         // failures after several Xrun recoveries.
967         delete *it;
968     }
969 }
970
971 int
972 IsoHandlerManager::getPacketLatencyForStream(Streaming::StreamProcessor *stream) {
973     for ( IsoHandlerVectorIterator it = m_IsoHandlers.begin();
974       it != m_IsoHandlers.end();
975       ++it )
976     {
977         if((*it)->isStreamRegistered(stream)) {
978             return (*it)->getIrqInterval();
979         }
980     }
981     debugError("Stream %p has no attached handler\n", stream);
982     return 0;
983 }
984
985 IsoHandlerManager::IsoHandler *
986 IsoHandlerManager::getHandlerForStream(Streaming::StreamProcessor *stream) {
987     for ( IsoHandlerVectorIterator it = m_IsoHandlers.begin();
988       it != m_IsoHandlers.end();
989       ++it )
990     {
991         if((*it)->isStreamRegistered(stream)) {
992             return (*it);
993         }
994     }
995     debugError("Stream %p has no attached handler\n", stream);
996     return NULL;
997 }
998
999 void
1000 IsoHandlerManager::dumpInfoForStream(Streaming::StreamProcessor *stream)
1001 {
1002     IsoHandler *h = getHandlerForStream(stream);
1003     if (h) {
1004         debugOutputShort( DEBUG_LEVEL_NORMAL, "  Packets, Dropped, Skipped : %d, %d, %d\n",
1005                             h->m_packets, h->m_dropped, h->m_skipped);
1006     } else {
1007         debugError("No handler for stream %p??\n", stream);
1008     }
1009 }
1010
1011 void IsoHandlerManager::setIsoStartCycleForStream(Streaming::StreamProcessor *stream, signed int cycle) {
1012     // Permit the direct manipulation of the m_switch_on_cycle field from
1013     // the stream's handler.  This is usually used to set it to -1 so the
1014     // kernel (at least with the ieee1394 stack) starts the streaming as
1015     // soon as possible, something that is required for some interfaces (eg:
1016     // RME).  Note that as of 20 Dec 2010 it seems that ordinarily
1017     // m_switch_on_cycle remains fixed at 0 (its initialised value) because
1018     // requestEnable() doesn't set it.  This allows the override configured
1019     // by this function to take effect.
1020     IsoHandler *h = getHandlerForStream(stream);
1021     h->setIsoStartCycle(cycle);
1022 }
1023
1024 bool
1025 IsoHandlerManager::startHandlerForStream(Streaming::StreamProcessor *stream) {
1026     return startHandlerForStream(stream, -1);
1027 }
1028
1029 bool
1030 IsoHandlerManager::startHandlerForStream(Streaming::StreamProcessor *stream, int cycle) {
1031     // check state
1032     if(m_State != E_Running) {
1033         debugError("Incorrect state, expected E_Running, got %s\n", eHSToString(m_State));
1034         return false;
1035     }
1036     for ( IsoHandlerVectorIterator it = m_IsoHandlers.begin();
1037       it != m_IsoHandlers.end();
1038       ++it )
1039     {
1040         if((*it)->isStreamRegistered(stream)) {
1041             debugOutput( DEBUG_LEVEL_VERBOSE, " starting handler %p for stream %p\n", *it, stream);
1042             if(!(*it)->requestEnable(cycle)) {
1043                 debugOutput( DEBUG_LEVEL_VERBOSE, " could not request enable for handler %p)\n",*it);
1044                 return false;
1045             }
1046
1047             if((*it)->getType() == IsoHandler::eHT_Transmit) {
1048                 m_IsoTaskTransmit->requestShadowMapUpdate();
1049             } else {
1050                 m_IsoTaskReceive->requestShadowMapUpdate();
1051             }
1052
1053             debugOutput(DEBUG_LEVEL_VERY_VERBOSE, " requested enable for handler %p\n", *it);
1054             return true;
1055         }
1056     }
1057     debugError("Stream %p has no attached handler\n", stream);
1058     return false;
1059 }
1060
1061 bool
1062 IsoHandlerManager::stopHandlerForStream(Streaming::StreamProcessor *stream) {
1063     // check state
1064     if(m_State != E_Running) {
1065         debugError("Incorrect state, expected E_Running, got %s\n", eHSToString(m_State));
1066         return false;
1067     }
1068     for ( IsoHandlerVectorIterator it = m_IsoHandlers.begin();
1069       it != m_IsoHandlers.end();
1070       ++it )
1071     {
1072         if((*it)->isStreamRegistered(stream)) {
1073             debugOutput( DEBUG_LEVEL_VERBOSE, " stopping handler %p for stream %p\n", *it, stream);
1074             if(!(*it)->requestDisable()) {
1075                 debugOutput( DEBUG_LEVEL_VERBOSE, " could not request disable for handler %p\n",*it);
1076                 return false;
1077             }
1078
1079             if((*it)->getType() == IsoHandler::eHT_Transmit) {
1080                 m_IsoTaskTransmit->requestShadowMapUpdate();
1081             } else {
1082                 m_IsoTaskReceive->requestShadowMapUpdate();
1083             }
1084
1085             debugOutput(DEBUG_LEVEL_VERBOSE, " requested disable for handler %p\n", *it);
1086             return true;
1087         }
1088     }
1089     debugError("Stream %p has no attached handler\n", stream);
1090     return false;
1091 }
1092
1093 bool IsoHandlerManager::stopHandlers() {
1094     debugOutput( DEBUG_LEVEL_VERBOSE, "enter...\n");
1095
1096     // check state
1097     if(m_State != E_Running) {
1098         debugError("Incorrect state, expected E_Running, got %s\n", eHSToString(m_State));
1099         return false;
1100     }
1101
1102     bool retval=true;
1103
1104     for ( IsoHandlerVectorIterator it = m_IsoHandlers.begin();
1105         it != m_IsoHandlers.end();
1106         ++it )
1107     {
1108         debugOutput( DEBUG_LEVEL_VERBOSE, "Stopping handler (%p)\n",*it);
1109
1110         if(!(*it)->requestDisable()) {
1111             debugOutput( DEBUG_LEVEL_VERBOSE, " could not request disable for handler %p\n",*it);
1112             return false;
1113         }
1114
1115         if((*it)->getType() == IsoHandler::eHT_Transmit) {
1116             m_IsoTaskTransmit->requestShadowMapUpdate();
1117         } else {
1118             m_IsoTaskReceive->requestShadowMapUpdate();
1119         }
1120
1121         debugOutput(DEBUG_LEVEL_VERBOSE, " requested disable for handler %p\n", *it);
1122     }
1123
1124     if (retval) {
1125         m_State=E_Prepared;
1126     } else {
1127         m_State=E_Error;
1128     }
1129     return retval;
1130 }
1131
1132 bool IsoHandlerManager::reset() {
1133     debugOutput( DEBUG_LEVEL_VERBOSE, "enter...\n");
1134     // check state
1135     if(m_State == E_Error) {
1136         debugFatal("Resetting from error condition not yet supported...\n");
1137         return false;
1138     }
1139     // if not in an error condition, reset means stop the handlers
1140     return stopHandlers();
1141 }
1142
1143 void IsoHandlerManager::setVerboseLevel(int i) {
1144     setDebugLevel(i);
1145     // propagate the debug level
1146     for ( IsoHandlerVectorIterator it = m_IsoHandlers.begin();
1147           it != m_IsoHandlers.end();
1148           ++it )
1149     {
1150         (*it)->setVerboseLevel(i);
1151     }
1152     if(m_IsoThreadTransmit) m_IsoThreadTransmit->setVerboseLevel(i);
1153     if(m_IsoTaskTransmit)   m_IsoTaskTransmit->setVerboseLevel(i);
1154     if(m_IsoThreadReceive)  m_IsoThreadReceive->setVerboseLevel(i);
1155     if(m_IsoTaskReceive)    m_IsoTaskReceive->setVerboseLevel(i);
1156     setDebugLevel(i);
1157     debugOutput( DEBUG_LEVEL_VERBOSE, "Setting verbose level to %d...\n", i );
1158 }
1159
1160 void IsoHandlerManager::dumpInfo() {
1161     #ifdef DEBUG
1162     unsigned int i=0;
1163     debugOutputShort( DEBUG_LEVEL_NORMAL, "Dumping IsoHandlerManager Stream handler information...\n");
1164     debugOutputShort( DEBUG_LEVEL_NORMAL, " State: %d\n",(int)m_State);
1165
1166     for ( IsoHandlerVectorIterator it = m_IsoHandlers.begin();
1167           it != m_IsoHandlers.end();
1168           ++it )
1169     {
1170         debugOutputShort( DEBUG_LEVEL_NORMAL, " IsoHandler %d (%p)\n",i++,*it);
1171         (*it)->dumpInfo();
1172     }
1173     #endif
1174 }
1175
1176 const char *
1177 IsoHandlerManager::eHSToString(enum eHandlerStates s) {
1178     switch (s) {
1179         default: return "Invalid";
1180         case E_Created: return "Created";
1181         case E_Prepared: return "Prepared";
1182         case E_Running: return "Running";
1183         case E_Error: return "Error";
1184     }
1185 }
1186
1187
1188 // ISOHANDLER
1189
1190 /* the C callbacks */
1191 enum raw1394_iso_disposition
1192 IsoHandlerManager::IsoHandler::iso_transmit_handler(raw1394handle_t handle,
1193         unsigned char *data, unsigned int *length,
1194         unsigned char *tag, unsigned char *sy,
1195         int cycle, unsigned int dropped1) {
1196
1197     IsoHandler *xmitHandler = static_cast<IsoHandler *>(raw1394_get_userdata(handle));
1198     assert(xmitHandler);
1199     unsigned int skipped = (dropped1 & 0xFFFF0000) >> 16;
1200     unsigned int dropped = dropped1 & 0xFFFF;
1201     return xmitHandler->getPacket(data, length, tag, sy, cycle, dropped, skipped);
1202 }
1203
1204 enum raw1394_iso_disposition
1205 IsoHandlerManager::IsoHandler::iso_receive_handler(raw1394handle_t handle, unsigned char *data,
1206                         unsigned int length, unsigned char channel,
1207                         unsigned char tag, unsigned char sy, unsigned int cycle,
1208                         unsigned int dropped) {
1209
1210     IsoHandler *recvHandler = static_cast<IsoHandler *>(raw1394_get_userdata(handle));
1211     assert(recvHandler);
1212
1213     return recvHandler->putPacket(data, length, channel, tag, sy, cycle, dropped);
1214 }
1215
1216 IsoHandlerManager::IsoHandler::IsoHandler(IsoHandlerManager& manager, enum EHandlerType t)
1217    : m_manager( manager )
1218    , m_type ( t )
1219    , m_handle( NULL )
1220    , m_buf_packets( 400 )
1221    , m_max_packet_size( 1024 )
1222    , m_irq_interval( -1 )
1223    , m_last_cycle( -1 )
1224    , m_last_now( 0xFFFFFFFF )
1225    , m_last_packet_handled_at( 0xFFFFFFFF )
1226    , m_receive_mode ( RAW1394_DMA_PACKET_PER_BUFFER )
1227    , m_Client( 0 )
1228    , m_speed( RAW1394_ISO_SPEED_400 )
1229    , m_State( eHS_Stopped )
1230    , m_NextState( eHS_Stopped )
1231    , m_switch_on_cycle(0)
1232 #ifdef DEBUG
1233    , m_packets ( 0 )
1234    , m_dropped( 0 )
1235    , m_skipped( 0 )
1236    , m_min_ahead( 7999 )
1237 #endif
1238 {
1239 }
1240
1241 IsoHandlerManager::IsoHandler::IsoHandler(IsoHandlerManager& manager, enum EHandlerType t,
1242                        unsigned int buf_packets, unsigned int max_packet_size, int irq)
1243    : m_manager( manager )
1244    , m_type ( t )
1245    , m_handle( NULL )
1246    , m_buf_packets( buf_packets )
1247    , m_max_packet_size( max_packet_size )
1248    , m_irq_interval( irq )
1249    , m_last_cycle( -1 )
1250    , m_last_now( 0xFFFFFFFF )
1251    , m_last_packet_handled_at( 0xFFFFFFFF )
1252    , m_receive_mode ( RAW1394_DMA_PACKET_PER_BUFFER )
1253    , m_Client( 0 )
1254    , m_speed( RAW1394_ISO_SPEED_400 )
1255    , m_State( eHS_Stopped )
1256    , m_NextState( eHS_Stopped )
1257    , m_switch_on_cycle(0)
1258 #ifdef DEBUG
1259    , m_packets ( 0 )
1260    , m_dropped( 0 )
1261    , m_skipped( 0 )
1262    , m_min_ahead( 7999 )
1263 #endif
1264 {
1265 }
1266
1267 IsoHandlerManager::IsoHandler::IsoHandler(IsoHandlerManager& manager, enum EHandlerType t, unsigned int buf_packets,
1268                        unsigned int max_packet_size, int irq,
1269                        enum raw1394_iso_speed speed)
1270    : m_manager( manager )
1271    , m_type ( t )
1272    , m_handle( NULL )
1273    , m_buf_packets( buf_packets )
1274    , m_max_packet_size( max_packet_size )
1275    , m_irq_interval( irq )
1276    , m_last_cycle( -1 )
1277    , m_last_now( 0xFFFFFFFF )
1278    , m_last_packet_handled_at( 0xFFFFFFFF )
1279    , m_receive_mode ( RAW1394_DMA_PACKET_PER_BUFFER )
1280    , m_Client( 0 )
1281    , m_speed( speed )
1282    , m_State( eHS_Stopped )
1283    , m_NextState( eHS_Stopped )
1284    , m_switch_on_cycle(0)
1285 #ifdef DEBUG
1286    , m_packets( 0 )
1287    , m_dropped( 0 )
1288    , m_skipped( 0 )
1289    , m_min_ahead( 7999 )
1290 #endif
1291 {
1292 }
1293
1294 IsoHandlerManager::IsoHandler::~IsoHandler() {
1295 // Don't call until libraw1394's raw1394_new_handle() function has been
1296 // fixed to correctly initialise the iso_packet_infos field.  Bug is
1297 // confirmed present in libraw1394 1.2.1.  In any case,
1298 // raw1394_destroy_handle() will do any iso system shutdown required.
1299 //     raw1394_iso_shutdown(m_handle);
1300     if(m_handle) {
1301         if (m_State == eHS_Running) {
1302             debugError("BUG: Handler still running!\n");
1303             disable();
1304         }
1305     }
1306 }
1307
1308 bool
1309 IsoHandlerManager::IsoHandler::canIterateClient()
1310 {
1311     debugOutputExtreme(DEBUG_LEVEL_VERY_VERBOSE, "checking...\n");
1312     if(m_Client) {
1313         bool result;
1314
1315         if (m_type == eHT_Receive) {
1316             result = m_Client->canProducePacket();
1317         } else {
1318             result = m_Client->canConsumePacket();
1319         }
1320         debugOutputExtreme(DEBUG_LEVEL_VERY_VERBOSE, " returns %d\n", result);
1321         return result && (m_State != eHS_Error);
1322     } else {
1323         debugOutputExtreme(DEBUG_LEVEL_VERY_VERBOSE, " no client\n");
1324     }
1325     return false;
1326 }
1327
1328 bool
1329 IsoHandlerManager::IsoHandler::iterate() {
1330     return iterate(m_manager.get1394Service().getCycleTimer());
1331 }
1332
1333 bool
1334 IsoHandlerManager::IsoHandler::iterate(uint32_t cycle_timer_now) {
1335     debugOutputExtreme(DEBUG_LEVEL_VERY_VERBOSE, "(%p, %s) Iterating ISO handler at %08X...\n",
1336                        this, getTypeString(), cycle_timer_now);
1337     m_last_now = cycle_timer_now;
1338     if(m_State == eHS_Running) {
1339         assert(m_handle);
1340
1341         #if ISOHANDLER_FLUSH_BEFORE_ITERATE
1342         // this flushes all packets received since the poll() returned
1343         // from kernel to userspace such that they are processed by this
1344         // iterate. Doing so might result in lower latency capability
1345         // and/or better reliability
1346         if(m_type == eHT_Receive) {
1347             raw1394_iso_recv_flush(m_handle);
1348         }
1349         #endif
1350
1351         if(raw1394_loop_iterate(m_handle)) {
1352             debugError( "IsoHandler (%p): Failed to iterate handler: %s\n",
1353                         this, strerror(errno));
1354             return false;
1355         }
1356         debugOutputExtreme(DEBUG_LEVEL_VERY_VERBOSE, "(%p, %s) done interating ISO handler...\n",
1357                            this, getTypeString());
1358         return true;
1359     } else {
1360         debugOutput(DEBUG_LEVEL_VERBOSE, "(%p, %s) Not iterating a non-running handler...\n",
1361                     this, getTypeString());
1362         return false;
1363     }
1364 }
1365
1366 /**
1367  * Bus reset handler
1368  *
1369  * @return ?
1370  */
1371
1372 bool
1373 IsoHandlerManager::IsoHandler::handleBusReset()
1374 {
1375     debugOutput( DEBUG_LEVEL_NORMAL, "bus reset...\n");
1376     m_last_packet_handled_at = 0xFFFFFFFF;
1377
1378     #define CSR_CYCLE_TIME            0x200
1379     #define CSR_REGISTER_BASE  0xfffff0000000ULL
1380     // do a simple read on ourself in order to update the internal structures
1381     // this avoids read failures after a bus reset
1382     quadlet_t buf=0;
1383     raw1394_read(m_handle, raw1394_get_local_id(m_handle),
1384                  CSR_REGISTER_BASE | CSR_CYCLE_TIME, 4, &buf);
1385
1386     return m_Client->handleBusReset();
1387 }
1388
1389 /**
1390  * Call this if you find out that this handler has died for some
1391  * external reason.
1392  */
1393 void
1394 IsoHandlerManager::IsoHandler::notifyOfDeath()
1395 {
1396     m_State = eHS_Error;
1397     m_NextState = eHS_Error;
1398
1399     // notify the client of the fact that we have died
1400     m_Client->handlerDied();
1401
1402     // wake ourselves up
1403     if(m_handle) raw1394_wake_up(m_handle);
1404 }
1405
1406 void IsoHandlerManager::IsoHandler::dumpInfo()
1407 {
1408     int channel=-1;
1409     if (m_Client) channel=m_Client->getChannel();
1410
1411     debugOutputShort( DEBUG_LEVEL_NORMAL, "  Handler type................: %s\n",
1412             getTypeString());
1413     debugOutputShort( DEBUG_LEVEL_NORMAL, "  Port, Channel...............: %2d, %2d\n",
1414             m_manager.get1394Service().getPort(), channel);
1415     debugOutputShort( DEBUG_LEVEL_NORMAL, "  Buffer, MaxPacketSize, IRQ..: %4d, %4d, %4d\n",
1416             m_buf_packets, m_max_packet_size, m_irq_interval);
1417     if (this->getType() == eHT_Transmit) {
1418         debugOutputShort( DEBUG_LEVEL_NORMAL, "  Speed ..................: %2d\n",
1419                                             m_speed);
1420         #ifdef DEBUG
1421         debugOutputShort( DEBUG_LEVEL_NORMAL, "  Min ISOXMT bufferfill : %04d\n", m_min_ahead);
1422         #endif
1423     }
1424     #ifdef DEBUG
1425     debugOutputShort( DEBUG_LEVEL_NORMAL, "  Last cycle, dropped.........: %4d, %4u, %4u\n",
1426             m_last_cycle, m_dropped, m_skipped);
1427     #endif
1428
1429 }
1430
1431 void IsoHandlerManager::IsoHandler::setVerboseLevel(int l)
1432 {
1433     setDebugLevel(l);
1434     debugOutput( DEBUG_LEVEL_VERBOSE, "Setting verbose level to %d...\n", l );
1435 }
1436
1437 bool IsoHandlerManager::IsoHandler::registerStream(StreamProcessor *stream)
1438 {
1439     assert(stream);
1440     debugOutput( DEBUG_LEVEL_VERBOSE, "registering stream (%p)\n", stream);
1441
1442     if (m_Client) {
1443             debugFatal( "Generic IsoHandlers can have only one client\n");
1444             return false;
1445     }
1446     m_Client=stream;
1447     return true;
1448 }
1449
1450 bool IsoHandlerManager::IsoHandler::unregisterStream(StreamProcessor *stream)
1451 {
1452     assert(stream);
1453     debugOutput( DEBUG_LEVEL_VERBOSE, "unregistering stream (%p)\n", stream);
1454
1455     if(stream != m_Client) {
1456             debugFatal( "no client registered\n");
1457             return false;
1458     }
1459     m_Client=0;
1460     return true;
1461 }
1462
1463 // ISO packet interface
1464 enum raw1394_iso_disposition IsoHandlerManager::IsoHandler::putPacket(
1465                     unsigned char *data, unsigned int length,
1466                     unsigned char channel, unsigned char tag, unsigned char sy,
1467                     unsigned int cycle, unsigned int dropped) {
1468     // keep track of dropped cycles
1469     int dropped_cycles = 0;
1470     if (m_last_cycle != (int)cycle && m_last_cycle != -1 && m_manager.m_MissedCyclesOK == false) {
1471         dropped_cycles = diffCycles(cycle, m_last_cycle) - 1;
1472         #ifdef DEBUG
1473         if (dropped_cycles < 0) {
1474             debugWarning("(%p) dropped < 1 (%d), cycle: %d, last_cycle: %d, dropped: %d\n",
1475                          this, dropped_cycles, cycle, m_last_cycle, dropped);
1476         }
1477         if (dropped_cycles > 0) {
1478             debugOutput(DEBUG_LEVEL_VERBOSE,
1479                         "(%p) dropped %d packets on cycle %u, 'dropped'=%u, cycle=%d, m_last_cycle=%d\n",
1480                         this, dropped_cycles, cycle, dropped, cycle, m_last_cycle);
1481             m_dropped += dropped_cycles;
1482         }
1483         #endif
1484     }
1485     m_last_cycle = cycle;
1486
1487     // the m_last_now value is set when the iterate() function is called.
1488     uint32_t now_cycles = CYCLE_TIMER_GET_CYCLES(m_last_now);
1489
1490     // two cases can occur:
1491     // (1) this packet has been received before iterate() was called (normal case).
1492     // (2) this packet has been received after iterate() was called.
1493     //     happens when the kernel flushes more packets while we are already processing.
1494     //
1495     // In case (1) now_cycles is a small number of cycles larger than cycle. In
1496     // case (2) now_cycles is a small number of cycles smaller than cycle.
1497     // hence  abs(diffCycles(now_cycles, cycles)) has to be 'small'
1498
1499     // we can calculate the time of arrival for this packet as
1500     // 'now' + diffCycles(cycles, now_cycles) * TICKS_PER_CYCLE
1501     // in its properly wrapped version
1502     int64_t diff_cycles = diffCycles(cycle, now_cycles);
1503     int64_t tmp = CYCLE_TIMER_TO_TICKS(m_last_now);
1504     tmp += diff_cycles * (int64_t)TICKS_PER_CYCLE;
1505     uint64_t pkt_ctr_ticks = wrapAtMinMaxTicks(tmp);
1506     uint32_t pkt_ctr = TICKS_TO_CYCLE_TIMER(pkt_ctr_ticks);
1507     #ifdef DEBUG
1508     if( (now_cycles < cycle)
1509         && diffCycles(now_cycles, cycle) < 0
1510         // ignore this on dropped cycles, since it's normal
1511         // that now is ahead on the received packets (as we miss packets)
1512         && dropped_cycles == 0)
1513     {
1514         debugOutput(DEBUG_LEVEL_VERY_VERBOSE, "Special non-unwrapping happened\n");
1515     }
1516     #endif
1517
1518     #if ISOHANDLER_CHECK_CTR_RECONSTRUCTION
1519     // add a seconds field
1520     uint32_t now = m_manager.get1394Service().getCycleTimer();
1521     uint32_t now_secs_ref = CYCLE_TIMER_GET_SECS(now);
1522     // causality results in the fact that 'now' is always after 'cycle'
1523     // or at best, equal (if this handler was called within 125us after
1524     // the packet was on the wire).
1525     if(CYCLE_TIMER_GET_CYCLES(now) < cycle) {
1526         // the cycle field has wrapped, substract one second
1527         if(now_secs_ref == 0) {
1528             now_secs_ref = 127;
1529         } else  {
1530             now_secs_ref -= 1;
1531         }
1532     }
1533     uint32_t pkt_ctr_ref = cycle << 12;
1534     pkt_ctr_ref |= (now_secs_ref & 0x7F) << 25;
1535
1536     if((pkt_ctr & ~0x0FFFL) != pkt_ctr_ref) {
1537         debugWarning("reconstructed CTR counter discrepancy\n");
1538         debugWarning(" ingredients: %X, %X, %X, %X, %X, %d, %ld, %ld, %"PRId64"\n",
1539                      cycle, pkt_ctr_ref, pkt_ctr,
1540                      now, m_last_now, now_secs_ref,
1541                      (long int)CYCLE_TIMER_GET_SECS(now),
1542                      (long int)CYCLE_TIMER_GET_SECS(m_last_now),
1543                      tmp);
1544         debugWarning(" diffcy = %"PRId64" \n", diff_cycles);
1545     }
1546     #endif
1547     m_last_packet_handled_at = pkt_ctr;
1548
1549     // leave the offset field (for now?)
1550
1551     debugOutputExtreme(DEBUG_LEVEL_ULTRA_VERBOSE,
1552                 "received packet: length=%d, channel=%d, cycle=%d, at %08X\n",
1553                 length, channel, cycle, pkt_ctr);
1554     m_packets++;
1555     #ifdef DEBUG
1556     if (length > m_max_packet_size) {
1557         debugWarning("(%p, %s) packet too large: len=%u max=%u\n",
1558                      this, getTypeString(), length, m_max_packet_size);
1559     }
1560     if(m_last_cycle == -1) {
1561         debugOutput(DEBUG_LEVEL_VERBOSE, "Handler for %s SP %p is alive (cycle = %u)\n", getTypeString(), this, cycle);
1562     }
1563     #endif
1564
1565     // iterate the client if required
1566     if(m_Client)
1567         return m_Client->putPacket(data, length, channel, tag, sy, pkt_ctr, dropped_cycles);
1568
1569     return RAW1394_ISO_OK;
1570 }
1571
1572 enum raw1394_iso_disposition
1573 IsoHandlerManager::IsoHandler::getPacket(unsigned char *data, unsigned int *length,
1574                       unsigned char *tag, unsigned char *sy,
1575                       int cycle, unsigned int dropped, unsigned int skipped) {
1576
1577     uint32_t pkt_ctr;
1578     if (cycle < 0) {
1579         // mark invalid
1580         pkt_ctr = 0xFFFFFFFF;
1581     } else {
1582         // the m_last_now value is set when the iterate() function is called.
1583         uint32_t now_cycles = CYCLE_TIMER_GET_CYCLES(m_last_now);
1584
1585         // two cases can occur:
1586         // (1) this packet has been received before iterate() was called (normal case).
1587         // (2) this packet has been received after iterate() was called.
1588         //     happens when the kernel flushes more packets while we are already processing.
1589         //
1590         // In case (1) now_cycles is a small number of cycles larger than cycle. In
1591         // case (2) now_cycles is a small number of cycles smaller than cycle.
1592         // hence  abs(diffCycles(now_cycles, cycles)) has to be 'small'
1593
1594         // we can calculate the time of arrival for this packet as
1595         // 'now' + diffCycles(cycles, now_cycles) * TICKS_PER_CYCLE
1596         // in its properly wrapped version
1597         int64_t diff_cycles = diffCycles(cycle, now_cycles);
1598         int64_t tmp = CYCLE_TIMER_TO_TICKS(m_last_now);
1599         tmp += diff_cycles * (int64_t)TICKS_PER_CYCLE;
1600         uint64_t pkt_ctr_ticks = wrapAtMinMaxTicks(tmp);
1601         pkt_ctr = TICKS_TO_CYCLE_TIMER(pkt_ctr_ticks);
1602
1603         #if ISOHANDLER_CHECK_CTR_RECONSTRUCTION
1604         // add a seconds field
1605         uint32_t now = m_manager.get1394Service().getCycleTimer();
1606         uint32_t now_secs_ref = CYCLE_TIMER_GET_SECS(now);
1607         // causality results in the fact that 'now' is always after 'cycle'
1608         if(CYCLE_TIMER_GET_CYCLES(now) > (unsigned int)cycle) {
1609             // the cycle field has wrapped, add one second
1610             now_secs_ref += 1;
1611             // no need for this:
1612             if(now_secs_ref == 128) {
1613                now_secs_ref = 0;
1614             }
1615         }
1616         uint32_t pkt_ctr_ref = cycle << 12;
1617         pkt_ctr_ref |= (now_secs_ref & 0x7F) << 25;
1618
1619         if(((pkt_ctr & ~0x0FFFL) != pkt_ctr_ref) && (m_packets > m_buf_packets)) {
1620             debugWarning("reconstructed CTR counter discrepancy\n");
1621             debugWarning(" ingredients: %X, %X, %X, %X, %X, %d, %ld, %ld, %"PRId64"\n",
1622                         cycle, pkt_ctr_ref, pkt_ctr,
1623                          now, m_last_now, now_secs_ref,
1624                          (long int)CYCLE_TIMER_GET_SECS(now),
1625                          (long int)CYCLE_TIMER_GET_SECS(m_last_now),
1626                          tmp);
1627             debugWarning(" diffcy = %"PRId64" \n", diff_cycles);
1628         }
1629         #endif
1630     }
1631     if (m_packets < m_buf_packets) { // these are still prebuffer packets
1632         m_last_packet_handled_at = 0xFFFFFFFF;
1633     } else {
1634         m_last_packet_handled_at = pkt_ctr;
1635     }
1636     debugOutputExtreme(DEBUG_LEVEL_ULTRA_VERBOSE,
1637                 "sending packet: length=%d, cycle=%d, at %08X\n",
1638                 *length, cycle, pkt_ctr);
1639
1640     m_packets++;
1641
1642     #ifdef DEBUG
1643     if(m_last_cycle == -1) {
1644         debugOutput(DEBUG_LEVEL_VERBOSE, "Handler for %s SP %p is alive. cycle=%d state=%i\n", getTypeString(), this, cycle, m_State);
1645     }
1646     #endif
1647
1648     // keep track of dropped cycles
1649     int dropped_cycles = 0;
1650     if (m_last_cycle != cycle && m_last_cycle != -1) {
1651         dropped_cycles = diffCycles(cycle, m_last_cycle) - 1;
1652         // correct for skipped packets
1653         // since those are not dropped, but only delayed
1654         dropped_cycles -= skipped;
1655
1656         #ifdef DEBUG
1657         if(skipped) {
1658             debugOutput(DEBUG_LEVEL_VERY_VERBOSE,
1659                         "(%p) skipped %d cycles, cycle: %d, last_cycle: %d, dropped: %d\n",
1660                         this, skipped, cycle, m_last_cycle, dropped);
1661             m_skipped += skipped;
1662         }
1663         if (dropped_cycles < 0) {
1664             debugWarning("(%p) dropped < 1 (%d), cycle: %d, last_cycle: %d, dropped: %d, skipped: %d\n",
1665                          this, dropped_cycles, cycle, m_last_cycle, dropped, skipped);
1666         }
1667         if (dropped_cycles > 0) {
1668             debugOutput(DEBUG_LEVEL_VERBOSE,
1669                         "(%p) dropped %d packets on cycle %u (last_cycle=%u, dropped=%d, skipped: %d)\n",
1670                         this, dropped_cycles, cycle, m_last_cycle, dropped, skipped);
1671             m_dropped += dropped_cycles - skipped;
1672         }
1673         #endif
1674     }
1675     if (cycle >= 0) {
1676         m_last_cycle = cycle;
1677        
1678         #ifdef DEBUG
1679 /*        int ahead = diffCycles(cycle, now_cycles);
1680         if (ahead < m_min_ahead) m_min_ahead = ahead;
1681 */
1682         #endif
1683     }
1684
1685     #ifdef DEBUG
1686     if (dropped > 0) {
1687         debugOutput(DEBUG_LEVEL_VERBOSE,
1688                     "(%p) OHCI issue on cycle %u (dropped_cycles=%d, last_cycle=%u, dropped=%d, skipped: %d)\n",
1689                     this, cycle, dropped_cycles, m_last_cycle, dropped, skipped);
1690     }
1691     #endif
1692
1693     if(m_Client) {
1694         enum raw1394_iso_disposition retval;
1695         retval = m_Client->getPacket(data, length, tag, sy, pkt_ctr, dropped_cycles, skipped, m_max_packet_size);
1696         #ifdef DEBUG
1697         if (*length > m_max_packet_size) {
1698             debugWarning("(%p, %s) packet too large: len=%u max=%u\n",
1699                          this, getTypeString(), *length, m_max_packet_size);
1700         }
1701         #endif
1702             return retval;
1703     }
1704
1705     *tag = 0;
1706     *sy = 0;
1707     *length = 0;
1708     return RAW1394_ISO_OK;
1709 }
1710
1711 bool
1712 IsoHandlerManager::IsoHandler::enable(int cycle)
1713 {
1714     debugOutput( DEBUG_LEVEL_VERBOSE, "start on cycle %d\n", cycle);
1715
1716     // check the state
1717     if(m_State != eHS_Stopped) {
1718         debugError("Incorrect state, expected eHS_Stopped, got %d\n",(int)m_State);
1719         return false;
1720     }
1721
1722     assert(m_handle == NULL);
1723
1724     // create a handle for the ISO traffic
1725     m_handle = raw1394_new_handle_on_port( m_manager.get1394Service().getPort() );
1726     if ( !m_handle ) {
1727         if ( !errno ) {
1728             debugError("libraw1394 not compatible\n");
1729         } else {
1730             debugError("Could not get 1394 handle: %s\n", strerror(errno) );
1731             debugError("Are ieee1394 and raw1394 drivers loaded?\n");
1732         }
1733         return false;
1734     }
1735     raw1394_set_userdata(m_handle, static_cast<void *>(this));
1736
1737     // prepare the handler, allocate the resources
1738     debugOutput( DEBUG_LEVEL_VERBOSE, "Preparing iso handler (%p, client=%p)\n", this, m_Client);
1739     dumpInfo();
1740     if (getType() == eHT_Receive) {
1741         if(raw1394_iso_recv_init(m_handle,
1742                                 iso_receive_handler,
1743                                 m_buf_packets,
1744                                 m_max_packet_size,
1745                                 m_Client->getChannel(),
1746                                 m_receive_mode,
1747                                 m_irq_interval)) {
1748             debugFatal("Could not do receive initialization (PACKET_PER_BUFFER)!\n" );
1749             debugFatal("  %s\n",strerror(errno));
1750             return false;
1751         }
1752
1753         if(raw1394_iso_recv_start(m_handle, cycle, -1, 0)) {
1754             debugFatal("Could not start receive handler (%s)\n",strerror(errno));
1755             dumpInfo();
1756             return false;
1757         }
1758     } else {
1759         if(raw1394_iso_xmit_init(m_handle,
1760                                 iso_transmit_handler,
1761                                 m_buf_packets,
1762                                 m_max_packet_size,
1763                                 m_Client->getChannel(),
1764                                 m_speed,
1765                                 m_irq_interval)) {
1766             debugFatal("Could not do xmit initialisation!\n" );
1767             return false;
1768         }
1769
1770         if(raw1394_iso_xmit_start(m_handle, cycle, 0)) {
1771             debugFatal("Could not start xmit handler (%s)\n", strerror(errno));
1772             dumpInfo();
1773             return false;
1774         }
1775     }
1776
1777 #ifdef DEBUG
1778     m_min_ahead = 7999;
1779 #endif
1780
1781     m_packets = 0;
1782
1783     // indicate that the first iterate() still has to occur.
1784     m_last_now = 0xFFFFFFFF;
1785     m_last_packet_handled_at = 0xFFFFFFFF;
1786
1787     m_State = eHS_Running;
1788     m_NextState = eHS_Running;
1789     return true;
1790 }
1791
1792 bool
1793 IsoHandlerManager::IsoHandler::disable()
1794 {
1795     debugOutput( DEBUG_LEVEL_VERBOSE, "(%p, %s) enter...\n",
1796                  this, (m_type==eHT_Receive?"Receive":"Transmit"));
1797
1798     // check state
1799     if(m_State != eHS_Running) {
1800         debugError("Incorrect state, expected eHS_Running, got %d\n",(int)m_State);
1801         return false;
1802     }
1803
1804     assert(m_handle != NULL);
1805
1806     debugOutput( DEBUG_LEVEL_VERBOSE, "(%p, %s) wake up handle...\n",
1807                  this, (m_type==eHT_Receive?"Receive":"Transmit"));
1808
1809     // wake up any waiting reads/polls
1810     raw1394_wake_up(m_handle);
1811
1812     // this is put here to try and avoid the
1813     // Runaway context problem
1814     // don't know if it will help though.
1815 /*    if(m_State != eHS_Error) { // if the handler is dead, this might block forever
1816         raw1394_iso_xmit_sync(m_handle);
1817     }*/
1818     debugOutput( DEBUG_LEVEL_VERBOSE, "(%p, %s) stop...\n",
1819                  this, (m_type==eHT_Receive?"Receive":"Transmit"));
1820     // stop iso traffic
1821     raw1394_iso_stop(m_handle);
1822     // deallocate resources
1823
1824     // Don't call until libraw1394's raw1394_new_handle() function has been
1825     // fixed to correctly initialise the iso_packet_infos field.  Bug is
1826     // confirmed present in libraw1394 1.2.1.
1827     raw1394_iso_shutdown(m_handle);
1828
1829     raw1394_destroy_handle(m_handle);
1830     m_handle = NULL;
1831
1832     m_State = eHS_Stopped;
1833     m_NextState = eHS_Stopped;
1834     return true;
1835 }
1836
1837 // functions to request enable or disable at the next opportunity
1838 bool
1839 IsoHandlerManager::IsoHandler::requestEnable(int cycle)
1840 {
1841     if (m_State == eHS_Running) {
1842         debugError("Enable requested on enabled stream '%s'\n", getTypeString());
1843         return false;
1844     }
1845     if (m_State != eHS_Stopped) {
1846         debugError("Enable requested on stream '%s' with state: %d\n", getTypeString(), m_State);
1847         return false;
1848     }
1849     m_NextState = eHS_Running;
1850     return true;
1851 }
1852
1853 bool
1854 IsoHandlerManager::IsoHandler::requestDisable()
1855 {
1856     if (m_State == eHS_Stopped) {
1857         // Don't treat this as an error condition because during a user
1858         // shutdown the stream would have been disabled by
1859         // stopHandlerForStream().  Therefore when requestDisable() is
1860         // subnsequently called by IsoHandlerManager::stopHandlers() in the
1861         // IsoHandlerManager destructor with the stream disabled the
1862         // condition is not an error.
1863         //
1864         // For now print a warning, but this might be removed in future if
1865         // the above framework remains in place.
1866         debugWarning("Disable requested on disabled stream\n");
1867         return true;
1868     }
1869     if (m_State != eHS_Running) {
1870         debugError("Disable requested on stream with state=%d\n", m_State);
1871         return false;
1872     }
1873     m_NextState = eHS_Stopped;
1874     return true;
1875 }
1876
1877 // Explicitly preset m_switch_on_cycle since requestEnable doesn't do this
1878 // and thus all enables requested via that route always occur on cycle 0.
1879 void
1880 IsoHandlerManager::IsoHandler::setIsoStartCycle(signed int cycle)
1881 {
1882   m_switch_on_cycle = cycle;
1883 }
1884
1885 void
1886 IsoHandlerManager::IsoHandler::updateState()
1887 {
1888     // execute state changes requested
1889     if(m_State != m_NextState) {
1890         debugOutput(DEBUG_LEVEL_VERBOSE, "(%p) handler needs state update from %d => %d\n", this, m_State, m_NextState);
1891         if(m_State == eHS_Stopped && m_NextState == eHS_Running) {
1892             debugOutput(DEBUG_LEVEL_VERBOSE, "handler has to be enabled\n");
1893             enable(m_switch_on_cycle);
1894         } else if(m_State == eHS_Running && m_NextState == eHS_Stopped) {
1895             debugOutput(DEBUG_LEVEL_VERBOSE, "handler has to be disabled\n");
1896             disable();
1897         } else {
1898             debugError("Unknown state transition\n");
1899         }
1900     }
1901 }
1902
1903 /**
1904  * @brief convert a EHandlerType to a string
1905  * @param t the type
1906  * @return a char * describing the state
1907  */
1908 const char *
1909 IsoHandlerManager::IsoHandler::eHTToString(enum EHandlerType t) {
1910     switch (t) {
1911         case eHT_Receive: return "Receive";
1912         case eHT_Transmit: return "Transmit";
1913         default: return "error: unknown type";
1914     }
1915 }
Note: See TracBrowser for help on using the browser.