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

Revision 1859, 65.9 kB (checked in by arnonym, 11 years ago)

Result of several days of searching a bug (that turned out to be a pebkac): some modifications of the debug-strings.

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 bool
1012 IsoHandlerManager::startHandlerForStream(Streaming::StreamProcessor *stream) {
1013     return startHandlerForStream(stream, -1);
1014 }
1015
1016 bool
1017 IsoHandlerManager::startHandlerForStream(Streaming::StreamProcessor *stream, int cycle) {
1018     // check state
1019     if(m_State != E_Running) {
1020         debugError("Incorrect state, expected E_Running, got %s\n", eHSToString(m_State));
1021         return false;
1022     }
1023     for ( IsoHandlerVectorIterator it = m_IsoHandlers.begin();
1024       it != m_IsoHandlers.end();
1025       ++it )
1026     {
1027         if((*it)->isStreamRegistered(stream)) {
1028             debugOutput( DEBUG_LEVEL_VERBOSE, " starting handler %p for stream %p\n", *it, stream);
1029             if(!(*it)->requestEnable(cycle)) {
1030                 debugOutput( DEBUG_LEVEL_VERBOSE, " could not request enable for handler %p)\n",*it);
1031                 return false;
1032             }
1033
1034             if((*it)->getType() == IsoHandler::eHT_Transmit) {
1035                 m_IsoTaskTransmit->requestShadowMapUpdate();
1036             } else {
1037                 m_IsoTaskReceive->requestShadowMapUpdate();
1038             }
1039
1040             debugOutput(DEBUG_LEVEL_VERY_VERBOSE, " requested enable for handler %p\n", *it);
1041             return true;
1042         }
1043     }
1044     debugError("Stream %p has no attached handler\n", stream);
1045     return false;
1046 }
1047
1048 bool
1049 IsoHandlerManager::stopHandlerForStream(Streaming::StreamProcessor *stream) {
1050     // check state
1051     if(m_State != E_Running) {
1052         debugError("Incorrect state, expected E_Running, got %s\n", eHSToString(m_State));
1053         return false;
1054     }
1055     for ( IsoHandlerVectorIterator it = m_IsoHandlers.begin();
1056       it != m_IsoHandlers.end();
1057       ++it )
1058     {
1059         if((*it)->isStreamRegistered(stream)) {
1060             debugOutput( DEBUG_LEVEL_VERBOSE, " stopping handler %p for stream %p\n", *it, stream);
1061             if(!(*it)->requestDisable()) {
1062                 debugOutput( DEBUG_LEVEL_VERBOSE, " could not request disable for handler %p\n",*it);
1063                 return false;
1064             }
1065
1066             if((*it)->getType() == IsoHandler::eHT_Transmit) {
1067                 m_IsoTaskTransmit->requestShadowMapUpdate();
1068             } else {
1069                 m_IsoTaskReceive->requestShadowMapUpdate();
1070             }
1071
1072             debugOutput(DEBUG_LEVEL_VERBOSE, " requested disable for handler %p\n", *it);
1073             return true;
1074         }
1075     }
1076     debugError("Stream %p has no attached handler\n", stream);
1077     return false;
1078 }
1079
1080 bool IsoHandlerManager::stopHandlers() {
1081     debugOutput( DEBUG_LEVEL_VERBOSE, "enter...\n");
1082
1083     // check state
1084     if(m_State != E_Running) {
1085         debugError("Incorrect state, expected E_Running, got %s\n", eHSToString(m_State));
1086         return false;
1087     }
1088
1089     bool retval=true;
1090
1091     for ( IsoHandlerVectorIterator it = m_IsoHandlers.begin();
1092         it != m_IsoHandlers.end();
1093         ++it )
1094     {
1095         debugOutput( DEBUG_LEVEL_VERBOSE, "Stopping handler (%p)\n",*it);
1096
1097         if(!(*it)->requestDisable()) {
1098             debugOutput( DEBUG_LEVEL_VERBOSE, " could not request disable for handler %p\n",*it);
1099             return false;
1100         }
1101
1102         if((*it)->getType() == IsoHandler::eHT_Transmit) {
1103             m_IsoTaskTransmit->requestShadowMapUpdate();
1104         } else {
1105             m_IsoTaskReceive->requestShadowMapUpdate();
1106         }
1107
1108         debugOutput(DEBUG_LEVEL_VERBOSE, " requested disable for handler %p\n", *it);
1109     }
1110
1111     if (retval) {
1112         m_State=E_Prepared;
1113     } else {
1114         m_State=E_Error;
1115     }
1116     return retval;
1117 }
1118
1119 bool IsoHandlerManager::reset() {
1120     debugOutput( DEBUG_LEVEL_VERBOSE, "enter...\n");
1121     // check state
1122     if(m_State == E_Error) {
1123         debugFatal("Resetting from error condition not yet supported...\n");
1124         return false;
1125     }
1126     // if not in an error condition, reset means stop the handlers
1127     return stopHandlers();
1128 }
1129
1130 void IsoHandlerManager::setVerboseLevel(int i) {
1131     setDebugLevel(i);
1132     // propagate the debug level
1133     for ( IsoHandlerVectorIterator it = m_IsoHandlers.begin();
1134           it != m_IsoHandlers.end();
1135           ++it )
1136     {
1137         (*it)->setVerboseLevel(i);
1138     }
1139     if(m_IsoThreadTransmit) m_IsoThreadTransmit->setVerboseLevel(i);
1140     if(m_IsoTaskTransmit)   m_IsoTaskTransmit->setVerboseLevel(i);
1141     if(m_IsoThreadReceive)  m_IsoThreadReceive->setVerboseLevel(i);
1142     if(m_IsoTaskReceive)    m_IsoTaskReceive->setVerboseLevel(i);
1143     setDebugLevel(i);
1144     debugOutput( DEBUG_LEVEL_VERBOSE, "Setting verbose level to %d...\n", i );
1145 }
1146
1147 void IsoHandlerManager::dumpInfo() {
1148     #ifdef DEBUG
1149     unsigned int i=0;
1150     debugOutputShort( DEBUG_LEVEL_NORMAL, "Dumping IsoHandlerManager Stream handler information...\n");
1151     debugOutputShort( DEBUG_LEVEL_NORMAL, " State: %d\n",(int)m_State);
1152
1153     for ( IsoHandlerVectorIterator it = m_IsoHandlers.begin();
1154           it != m_IsoHandlers.end();
1155           ++it )
1156     {
1157         debugOutputShort( DEBUG_LEVEL_NORMAL, " IsoHandler %d (%p)\n",i++,*it);
1158         (*it)->dumpInfo();
1159     }
1160     #endif
1161 }
1162
1163 const char *
1164 IsoHandlerManager::eHSToString(enum eHandlerStates s) {
1165     switch (s) {
1166         default: return "Invalid";
1167         case E_Created: return "Created";
1168         case E_Prepared: return "Prepared";
1169         case E_Running: return "Running";
1170         case E_Error: return "Error";
1171     }
1172 }
1173
1174
1175 // ISOHANDLER
1176
1177 /* the C callbacks */
1178 enum raw1394_iso_disposition
1179 IsoHandlerManager::IsoHandler::iso_transmit_handler(raw1394handle_t handle,
1180         unsigned char *data, unsigned int *length,
1181         unsigned char *tag, unsigned char *sy,
1182         int cycle, unsigned int dropped1) {
1183
1184     IsoHandler *xmitHandler = static_cast<IsoHandler *>(raw1394_get_userdata(handle));
1185     assert(xmitHandler);
1186     unsigned int skipped = (dropped1 & 0xFFFF0000) >> 16;
1187     unsigned int dropped = dropped1 & 0xFFFF;
1188     return xmitHandler->getPacket(data, length, tag, sy, cycle, dropped, skipped);
1189 }
1190
1191 enum raw1394_iso_disposition
1192 IsoHandlerManager::IsoHandler::iso_receive_handler(raw1394handle_t handle, unsigned char *data,
1193                         unsigned int length, unsigned char channel,
1194                         unsigned char tag, unsigned char sy, unsigned int cycle,
1195                         unsigned int dropped) {
1196
1197     IsoHandler *recvHandler = static_cast<IsoHandler *>(raw1394_get_userdata(handle));
1198     assert(recvHandler);
1199
1200     return recvHandler->putPacket(data, length, channel, tag, sy, cycle, dropped);
1201 }
1202
1203 IsoHandlerManager::IsoHandler::IsoHandler(IsoHandlerManager& manager, enum EHandlerType t)
1204    : m_manager( manager )
1205    , m_type ( t )
1206    , m_handle( NULL )
1207    , m_buf_packets( 400 )
1208    , m_max_packet_size( 1024 )
1209    , m_irq_interval( -1 )
1210    , m_last_cycle( -1 )
1211    , m_last_now( 0xFFFFFFFF )
1212    , m_last_packet_handled_at( 0xFFFFFFFF )
1213    , m_receive_mode ( RAW1394_DMA_PACKET_PER_BUFFER )
1214    , m_Client( 0 )
1215    , m_speed( RAW1394_ISO_SPEED_400 )
1216    , m_State( eHS_Stopped )
1217    , m_NextState( eHS_Stopped )
1218    , m_switch_on_cycle(0)
1219 #ifdef DEBUG
1220    , m_packets ( 0 )
1221    , m_dropped( 0 )
1222    , m_skipped( 0 )
1223    , m_min_ahead( 7999 )
1224 #endif
1225 {
1226 }
1227
1228 IsoHandlerManager::IsoHandler::IsoHandler(IsoHandlerManager& manager, enum EHandlerType t,
1229                        unsigned int buf_packets, unsigned int max_packet_size, int irq)
1230    : m_manager( manager )
1231    , m_type ( t )
1232    , m_handle( NULL )
1233    , m_buf_packets( buf_packets )
1234    , m_max_packet_size( max_packet_size )
1235    , m_irq_interval( irq )
1236    , m_last_cycle( -1 )
1237    , m_last_now( 0xFFFFFFFF )
1238    , m_last_packet_handled_at( 0xFFFFFFFF )
1239    , m_receive_mode ( RAW1394_DMA_PACKET_PER_BUFFER )
1240    , m_Client( 0 )
1241    , m_speed( RAW1394_ISO_SPEED_400 )
1242    , m_State( eHS_Stopped )
1243    , m_NextState( eHS_Stopped )
1244    , m_switch_on_cycle(0)
1245 #ifdef DEBUG
1246    , m_packets ( 0 )
1247    , m_dropped( 0 )
1248    , m_skipped( 0 )
1249    , m_min_ahead( 7999 )
1250 #endif
1251 {
1252 }
1253
1254 IsoHandlerManager::IsoHandler::IsoHandler(IsoHandlerManager& manager, enum EHandlerType t, unsigned int buf_packets,
1255                        unsigned int max_packet_size, int irq,
1256                        enum raw1394_iso_speed speed)
1257    : m_manager( manager )
1258    , m_type ( t )
1259    , m_handle( NULL )
1260    , m_buf_packets( buf_packets )
1261    , m_max_packet_size( max_packet_size )
1262    , m_irq_interval( irq )
1263    , m_last_cycle( -1 )
1264    , m_last_now( 0xFFFFFFFF )
1265    , m_last_packet_handled_at( 0xFFFFFFFF )
1266    , m_receive_mode ( RAW1394_DMA_PACKET_PER_BUFFER )
1267    , m_Client( 0 )
1268    , m_speed( speed )
1269    , m_State( eHS_Stopped )
1270    , m_NextState( eHS_Stopped )
1271    , m_switch_on_cycle(0)
1272 #ifdef DEBUG
1273    , m_packets( 0 )
1274    , m_dropped( 0 )
1275    , m_skipped( 0 )
1276    , m_min_ahead( 7999 )
1277 #endif
1278 {
1279 }
1280
1281 IsoHandlerManager::IsoHandler::~IsoHandler() {
1282 // Don't call until libraw1394's raw1394_new_handle() function has been
1283 // fixed to correctly initialise the iso_packet_infos field.  Bug is
1284 // confirmed present in libraw1394 1.2.1.  In any case,
1285 // raw1394_destroy_handle() will do any iso system shutdown required.
1286 //     raw1394_iso_shutdown(m_handle);
1287     if(m_handle) {
1288         if (m_State == eHS_Running) {
1289             debugError("BUG: Handler still running!\n");
1290             disable();
1291         }
1292     }
1293 }
1294
1295 bool
1296 IsoHandlerManager::IsoHandler::canIterateClient()
1297 {
1298     debugOutputExtreme(DEBUG_LEVEL_VERY_VERBOSE, "checking...\n");
1299     if(m_Client) {
1300         bool result;
1301
1302         if (m_type == eHT_Receive) {
1303             result = m_Client->canProducePacket();
1304         } else {
1305             result = m_Client->canConsumePacket();
1306         }
1307         debugOutputExtreme(DEBUG_LEVEL_VERY_VERBOSE, " returns %d\n", result);
1308         return result && (m_State != eHS_Error);
1309     } else {
1310         debugOutputExtreme(DEBUG_LEVEL_VERY_VERBOSE, " no client\n");
1311     }
1312     return false;
1313 }
1314
1315 bool
1316 IsoHandlerManager::IsoHandler::iterate() {
1317     return iterate(m_manager.get1394Service().getCycleTimer());
1318 }
1319
1320 bool
1321 IsoHandlerManager::IsoHandler::iterate(uint32_t cycle_timer_now) {
1322     debugOutputExtreme(DEBUG_LEVEL_VERY_VERBOSE, "(%p, %s) Iterating ISO handler at %08X...\n",
1323                        this, getTypeString(), cycle_timer_now);
1324     m_last_now = cycle_timer_now;
1325     if(m_State == eHS_Running) {
1326         assert(m_handle);
1327
1328         #if ISOHANDLER_FLUSH_BEFORE_ITERATE
1329         // this flushes all packets received since the poll() returned
1330         // from kernel to userspace such that they are processed by this
1331         // iterate. Doing so might result in lower latency capability
1332         // and/or better reliability
1333         if(m_type == eHT_Receive) {
1334             raw1394_iso_recv_flush(m_handle);
1335         }
1336         #endif
1337
1338         if(raw1394_loop_iterate(m_handle)) {
1339             debugError( "IsoHandler (%p): Failed to iterate handler: %s\n",
1340                         this, strerror(errno));
1341             return false;
1342         }
1343         debugOutputExtreme(DEBUG_LEVEL_VERY_VERBOSE, "(%p, %s) done interating ISO handler...\n",
1344                            this, getTypeString());
1345         return true;
1346     } else {
1347         debugOutput(DEBUG_LEVEL_VERBOSE, "(%p, %s) Not iterating a non-running handler...\n",
1348                     this, getTypeString());
1349         return false;
1350     }
1351 }
1352
1353 /**
1354  * Bus reset handler
1355  *
1356  * @return ?
1357  */
1358
1359 bool
1360 IsoHandlerManager::IsoHandler::handleBusReset()
1361 {
1362     debugOutput( DEBUG_LEVEL_NORMAL, "bus reset...\n");
1363     m_last_packet_handled_at = 0xFFFFFFFF;
1364
1365     #define CSR_CYCLE_TIME            0x200
1366     #define CSR_REGISTER_BASE  0xfffff0000000ULL
1367     // do a simple read on ourself in order to update the internal structures
1368     // this avoids read failures after a bus reset
1369     quadlet_t buf=0;
1370     raw1394_read(m_handle, raw1394_get_local_id(m_handle),
1371                  CSR_REGISTER_BASE | CSR_CYCLE_TIME, 4, &buf);
1372
1373     return m_Client->handleBusReset();
1374 }
1375
1376 /**
1377  * Call this if you find out that this handler has died for some
1378  * external reason.
1379  */
1380 void
1381 IsoHandlerManager::IsoHandler::notifyOfDeath()
1382 {
1383     m_State = eHS_Error;
1384     m_NextState = eHS_Error;
1385
1386     // notify the client of the fact that we have died
1387     m_Client->handlerDied();
1388
1389     // wake ourselves up
1390     if(m_handle) raw1394_wake_up(m_handle);
1391 }
1392
1393 void IsoHandlerManager::IsoHandler::dumpInfo()
1394 {
1395     int channel=-1;
1396     if (m_Client) channel=m_Client->getChannel();
1397
1398     debugOutputShort( DEBUG_LEVEL_NORMAL, "  Handler type................: %s\n",
1399             getTypeString());
1400     debugOutputShort( DEBUG_LEVEL_NORMAL, "  Port, Channel...............: %2d, %2d\n",
1401             m_manager.get1394Service().getPort(), channel);
1402     debugOutputShort( DEBUG_LEVEL_NORMAL, "  Buffer, MaxPacketSize, IRQ..: %4d, %4d, %4d\n",
1403             m_buf_packets, m_max_packet_size, m_irq_interval);
1404     if (this->getType() == eHT_Transmit) {
1405         debugOutputShort( DEBUG_LEVEL_NORMAL, "  Speed ..................: %2d\n",
1406                                             m_speed);
1407         #ifdef DEBUG
1408         debugOutputShort( DEBUG_LEVEL_NORMAL, "  Min ISOXMT bufferfill : %04d\n", m_min_ahead);
1409         #endif
1410     }
1411     #ifdef DEBUG
1412     debugOutputShort( DEBUG_LEVEL_NORMAL, "  Last cycle, dropped.........: %4d, %4u, %4u\n",
1413             m_last_cycle, m_dropped, m_skipped);
1414     #endif
1415
1416 }
1417
1418 void IsoHandlerManager::IsoHandler::setVerboseLevel(int l)
1419 {
1420     setDebugLevel(l);
1421     debugOutput( DEBUG_LEVEL_VERBOSE, "Setting verbose level to %d...\n", l );
1422 }
1423
1424 bool IsoHandlerManager::IsoHandler::registerStream(StreamProcessor *stream)
1425 {
1426     assert(stream);
1427     debugOutput( DEBUG_LEVEL_VERBOSE, "registering stream (%p)\n", stream);
1428
1429     if (m_Client) {
1430             debugFatal( "Generic IsoHandlers can have only one client\n");
1431             return false;
1432     }
1433     m_Client=stream;
1434     return true;
1435 }
1436
1437 bool IsoHandlerManager::IsoHandler::unregisterStream(StreamProcessor *stream)
1438 {
1439     assert(stream);
1440     debugOutput( DEBUG_LEVEL_VERBOSE, "unregistering stream (%p)\n", stream);
1441
1442     if(stream != m_Client) {
1443             debugFatal( "no client registered\n");
1444             return false;
1445     }
1446     m_Client=0;
1447     return true;
1448 }
1449
1450 // ISO packet interface
1451 enum raw1394_iso_disposition IsoHandlerManager::IsoHandler::putPacket(
1452                     unsigned char *data, unsigned int length,
1453                     unsigned char channel, unsigned char tag, unsigned char sy,
1454                     unsigned int cycle, unsigned int dropped) {
1455     // keep track of dropped cycles
1456     int dropped_cycles = 0;
1457     if (m_last_cycle != (int)cycle && m_last_cycle != -1 && m_manager.m_MissedCyclesOK == false) {
1458         dropped_cycles = diffCycles(cycle, m_last_cycle) - 1;
1459         #ifdef DEBUG
1460         if (dropped_cycles < 0) {
1461             debugWarning("(%p) dropped < 1 (%d), cycle: %d, last_cycle: %d, dropped: %d\n",
1462                          this, dropped_cycles, cycle, m_last_cycle, dropped);
1463         }
1464         if (dropped_cycles > 0) {
1465             debugOutput(DEBUG_LEVEL_VERBOSE,
1466                         "(%p) dropped %d packets on cycle %u, 'dropped'=%u, cycle=%d, m_last_cycle=%d\n",
1467                         this, dropped_cycles, cycle, dropped, cycle, m_last_cycle);
1468             m_dropped += dropped_cycles;
1469         }
1470         #endif
1471     }
1472     m_last_cycle = cycle;
1473
1474     // the m_last_now value is set when the iterate() function is called.
1475     uint32_t now_cycles = CYCLE_TIMER_GET_CYCLES(m_last_now);
1476
1477     // two cases can occur:
1478     // (1) this packet has been received before iterate() was called (normal case).
1479     // (2) this packet has been received after iterate() was called.
1480     //     happens when the kernel flushes more packets while we are already processing.
1481     //
1482     // In case (1) now_cycles is a small number of cycles larger than cycle. In
1483     // case (2) now_cycles is a small number of cycles smaller than cycle.
1484     // hence  abs(diffCycles(now_cycles, cycles)) has to be 'small'
1485
1486     // we can calculate the time of arrival for this packet as
1487     // 'now' + diffCycles(cycles, now_cycles) * TICKS_PER_CYCLE
1488     // in its properly wrapped version
1489     int64_t diff_cycles = diffCycles(cycle, now_cycles);
1490     int64_t tmp = CYCLE_TIMER_TO_TICKS(m_last_now);
1491     tmp += diff_cycles * (int64_t)TICKS_PER_CYCLE;
1492     uint64_t pkt_ctr_ticks = wrapAtMinMaxTicks(tmp);
1493     uint32_t pkt_ctr = TICKS_TO_CYCLE_TIMER(pkt_ctr_ticks);
1494     #ifdef DEBUG
1495     if( (now_cycles < cycle)
1496         && diffCycles(now_cycles, cycle) < 0
1497         // ignore this on dropped cycles, since it's normal
1498         // that now is ahead on the received packets (as we miss packets)
1499         && dropped_cycles == 0)
1500     {
1501         debugOutput(DEBUG_LEVEL_VERY_VERBOSE, "Special non-unwrapping happened\n");
1502     }
1503     #endif
1504
1505     #if ISOHANDLER_CHECK_CTR_RECONSTRUCTION
1506     // add a seconds field
1507     uint32_t now = m_manager.get1394Service().getCycleTimer();
1508     uint32_t now_secs_ref = CYCLE_TIMER_GET_SECS(now);
1509     // causality results in the fact that 'now' is always after 'cycle'
1510     // or at best, equal (if this handler was called within 125us after
1511     // the packet was on the wire).
1512     if(CYCLE_TIMER_GET_CYCLES(now) < cycle) {
1513         // the cycle field has wrapped, substract one second
1514         if(now_secs_ref == 0) {
1515             now_secs_ref = 127;
1516         } else  {
1517             now_secs_ref -= 1;
1518         }
1519     }
1520     uint32_t pkt_ctr_ref = cycle << 12;
1521     pkt_ctr_ref |= (now_secs_ref & 0x7F) << 25;
1522
1523     if((pkt_ctr & ~0x0FFFL) != pkt_ctr_ref) {
1524         debugWarning("reconstructed CTR counter discrepancy\n");
1525         debugWarning(" ingredients: %X, %X, %X, %X, %X, %d, %ld, %ld, %"PRId64"\n",
1526                      cycle, pkt_ctr_ref, pkt_ctr,
1527                      now, m_last_now, now_secs_ref,
1528                      (long int)CYCLE_TIMER_GET_SECS(now),
1529                      (long int)CYCLE_TIMER_GET_SECS(m_last_now),
1530                      tmp);
1531         debugWarning(" diffcy = %"PRId64" \n", diff_cycles);
1532     }
1533     #endif
1534     m_last_packet_handled_at = pkt_ctr;
1535
1536     // leave the offset field (for now?)
1537
1538     debugOutputExtreme(DEBUG_LEVEL_ULTRA_VERBOSE,
1539                 "received packet: length=%d, channel=%d, cycle=%d, at %08X\n",
1540                 length, channel, cycle, pkt_ctr);
1541     m_packets++;
1542     #ifdef DEBUG
1543     if (length > m_max_packet_size) {
1544         debugWarning("(%p, %s) packet too large: len=%u max=%u\n",
1545                      this, getTypeString(), length, m_max_packet_size);
1546     }
1547     if(m_last_cycle == -1) {
1548         debugOutput(DEBUG_LEVEL_VERBOSE, "Handler for %s SP %p is alive (cycle = %u)\n", getTypeString(), this, cycle);
1549     }
1550     #endif
1551
1552     // iterate the client if required
1553     if(m_Client)
1554         return m_Client->putPacket(data, length, channel, tag, sy, pkt_ctr, dropped_cycles);
1555
1556     return RAW1394_ISO_OK;
1557 }
1558
1559 enum raw1394_iso_disposition
1560 IsoHandlerManager::IsoHandler::getPacket(unsigned char *data, unsigned int *length,
1561                       unsigned char *tag, unsigned char *sy,
1562                       int cycle, unsigned int dropped, unsigned int skipped) {
1563
1564     uint32_t pkt_ctr;
1565     if (cycle < 0) {
1566         // mark invalid
1567         pkt_ctr = 0xFFFFFFFF;
1568     } else {
1569         // the m_last_now value is set when the iterate() function is called.
1570         uint32_t now_cycles = CYCLE_TIMER_GET_CYCLES(m_last_now);
1571
1572         // two cases can occur:
1573         // (1) this packet has been received before iterate() was called (normal case).
1574         // (2) this packet has been received after iterate() was called.
1575         //     happens when the kernel flushes more packets while we are already processing.
1576         //
1577         // In case (1) now_cycles is a small number of cycles larger than cycle. In
1578         // case (2) now_cycles is a small number of cycles smaller than cycle.
1579         // hence  abs(diffCycles(now_cycles, cycles)) has to be 'small'
1580
1581         // we can calculate the time of arrival for this packet as
1582         // 'now' + diffCycles(cycles, now_cycles) * TICKS_PER_CYCLE
1583         // in its properly wrapped version
1584         int64_t diff_cycles = diffCycles(cycle, now_cycles);
1585         int64_t tmp = CYCLE_TIMER_TO_TICKS(m_last_now);
1586         tmp += diff_cycles * (int64_t)TICKS_PER_CYCLE;
1587         uint64_t pkt_ctr_ticks = wrapAtMinMaxTicks(tmp);
1588         pkt_ctr = TICKS_TO_CYCLE_TIMER(pkt_ctr_ticks);
1589
1590         #if ISOHANDLER_CHECK_CTR_RECONSTRUCTION
1591         // add a seconds field
1592         uint32_t now = m_manager.get1394Service().getCycleTimer();
1593         uint32_t now_secs_ref = CYCLE_TIMER_GET_SECS(now);
1594         // causality results in the fact that 'now' is always after 'cycle'
1595         if(CYCLE_TIMER_GET_CYCLES(now) > (unsigned int)cycle) {
1596             // the cycle field has wrapped, add one second
1597             now_secs_ref += 1;
1598             // no need for this:
1599             if(now_secs_ref == 128) {
1600                now_secs_ref = 0;
1601             }
1602         }
1603         uint32_t pkt_ctr_ref = cycle << 12;
1604         pkt_ctr_ref |= (now_secs_ref & 0x7F) << 25;
1605
1606         if(((pkt_ctr & ~0x0FFFL) != pkt_ctr_ref) && (m_packets > m_buf_packets)) {
1607             debugWarning("reconstructed CTR counter discrepancy\n");
1608             debugWarning(" ingredients: %X, %X, %X, %X, %X, %d, %ld, %ld, %"PRId64"\n",
1609                         cycle, pkt_ctr_ref, pkt_ctr,
1610                          now, m_last_now, now_secs_ref,
1611                          (long int)CYCLE_TIMER_GET_SECS(now),
1612                          (long int)CYCLE_TIMER_GET_SECS(m_last_now),
1613                          tmp);
1614             debugWarning(" diffcy = %"PRId64" \n", diff_cycles);
1615         }
1616         #endif
1617     }
1618     if (m_packets < m_buf_packets) { // these are still prebuffer packets
1619         m_last_packet_handled_at = 0xFFFFFFFF;
1620     } else {
1621         m_last_packet_handled_at = pkt_ctr;
1622     }
1623     debugOutputExtreme(DEBUG_LEVEL_ULTRA_VERBOSE,
1624                 "sending packet: length=%d, cycle=%d, at %08X\n",
1625                 *length, cycle, pkt_ctr);
1626
1627     m_packets++;
1628
1629     #ifdef DEBUG
1630     if(m_last_cycle == -1) {
1631         debugOutput(DEBUG_LEVEL_VERBOSE, "Handler for %s SP %p is alive. cycle=%d state=%i\n", getTypeString(), this, cycle, m_State);
1632     }
1633     #endif
1634
1635     // keep track of dropped cycles
1636     int dropped_cycles = 0;
1637     if (m_last_cycle != cycle && m_last_cycle != -1) {
1638         dropped_cycles = diffCycles(cycle, m_last_cycle) - 1;
1639         // correct for skipped packets
1640         // since those are not dropped, but only delayed
1641         dropped_cycles -= skipped;
1642
1643         #ifdef DEBUG
1644         if(skipped) {
1645             debugOutput(DEBUG_LEVEL_VERY_VERBOSE,
1646                         "(%p) skipped %d cycles, cycle: %d, last_cycle: %d, dropped: %d\n",
1647                         this, skipped, cycle, m_last_cycle, dropped);
1648             m_skipped += skipped;
1649         }
1650         if (dropped_cycles < 0) {
1651             debugWarning("(%p) dropped < 1 (%d), cycle: %d, last_cycle: %d, dropped: %d, skipped: %d\n",
1652                          this, dropped_cycles, cycle, m_last_cycle, dropped, skipped);
1653         }
1654         if (dropped_cycles > 0) {
1655             debugOutput(DEBUG_LEVEL_VERBOSE,
1656                         "(%p) dropped %d packets on cycle %u (last_cycle=%u, dropped=%d, skipped: %d)\n",
1657                         this, dropped_cycles, cycle, m_last_cycle, dropped, skipped);
1658             m_dropped += dropped_cycles - skipped;
1659         }
1660         #endif
1661     }
1662     if (cycle >= 0) {
1663         m_last_cycle = cycle;
1664        
1665         #ifdef DEBUG
1666 /*        int ahead = diffCycles(cycle, now_cycles);
1667         if (ahead < m_min_ahead) m_min_ahead = ahead;
1668 */
1669         #endif
1670     }
1671
1672     #ifdef DEBUG
1673     if (dropped > 0) {
1674         debugOutput(DEBUG_LEVEL_VERBOSE,
1675                     "(%p) OHCI issue on cycle %u (dropped_cycles=%d, last_cycle=%u, dropped=%d, skipped: %d)\n",
1676                     this, cycle, dropped_cycles, m_last_cycle, dropped, skipped);
1677     }
1678     #endif
1679
1680     if(m_Client) {
1681         enum raw1394_iso_disposition retval;
1682         retval = m_Client->getPacket(data, length, tag, sy, pkt_ctr, dropped_cycles, skipped, m_max_packet_size);
1683         #ifdef DEBUG
1684         if (*length > m_max_packet_size) {
1685             debugWarning("(%p, %s) packet too large: len=%u max=%u\n",
1686                          this, getTypeString(), *length, m_max_packet_size);
1687         }
1688         #endif
1689             return retval;
1690     }
1691
1692     *tag = 0;
1693     *sy = 0;
1694     *length = 0;
1695     return RAW1394_ISO_OK;
1696 }
1697
1698 bool
1699 IsoHandlerManager::IsoHandler::enable(int cycle)
1700 {
1701     debugOutput( DEBUG_LEVEL_VERBOSE, "start on cycle %d\n", cycle);
1702
1703     // check the state
1704     if(m_State != eHS_Stopped) {
1705         debugError("Incorrect state, expected eHS_Stopped, got %d\n",(int)m_State);
1706         return false;
1707     }
1708
1709     assert(m_handle == NULL);
1710
1711     // create a handle for the ISO traffic
1712     m_handle = raw1394_new_handle_on_port( m_manager.get1394Service().getPort() );
1713     if ( !m_handle ) {
1714         if ( !errno ) {
1715             debugError("libraw1394 not compatible\n");
1716         } else {
1717             debugError("Could not get 1394 handle: %s\n", strerror(errno) );
1718             debugError("Are ieee1394 and raw1394 drivers loaded?\n");
1719         }
1720         return false;
1721     }
1722     raw1394_set_userdata(m_handle, static_cast<void *>(this));
1723
1724     // prepare the handler, allocate the resources
1725     debugOutput( DEBUG_LEVEL_VERBOSE, "Preparing iso handler (%p, client=%p)\n", this, m_Client);
1726     dumpInfo();
1727     if (getType() == eHT_Receive) {
1728         if(raw1394_iso_recv_init(m_handle,
1729                                 iso_receive_handler,
1730                                 m_buf_packets,
1731                                 m_max_packet_size,
1732                                 m_Client->getChannel(),
1733                                 m_receive_mode,
1734                                 m_irq_interval)) {
1735             debugFatal("Could not do receive initialization (PACKET_PER_BUFFER)!\n" );
1736             debugFatal("  %s\n",strerror(errno));
1737             return false;
1738         }
1739
1740         if(raw1394_iso_recv_start(m_handle, cycle, -1, 0)) {
1741             debugFatal("Could not start receive handler (%s)\n",strerror(errno));
1742             dumpInfo();
1743             return false;
1744         }
1745     } else {
1746         if(raw1394_iso_xmit_init(m_handle,
1747                                 iso_transmit_handler,
1748                                 m_buf_packets,
1749                                 m_max_packet_size,
1750                                 m_Client->getChannel(),
1751                                 m_speed,
1752                                 m_irq_interval)) {
1753             debugFatal("Could not do xmit initialisation!\n" );
1754             return false;
1755         }
1756
1757         if(raw1394_iso_xmit_start(m_handle, cycle, 0)) {
1758             debugFatal("Could not start xmit handler (%s)\n", strerror(errno));
1759             dumpInfo();
1760             return false;
1761         }
1762     }
1763
1764 #ifdef DEBUG
1765     m_min_ahead = 7999;
1766 #endif
1767
1768     m_packets = 0;
1769
1770     // indicate that the first iterate() still has to occur.
1771     m_last_now = 0xFFFFFFFF;
1772     m_last_packet_handled_at = 0xFFFFFFFF;
1773
1774     m_State = eHS_Running;
1775     m_NextState = eHS_Running;
1776     return true;
1777 }
1778
1779 bool
1780 IsoHandlerManager::IsoHandler::disable()
1781 {
1782     debugOutput( DEBUG_LEVEL_VERBOSE, "(%p, %s) enter...\n",
1783                  this, (m_type==eHT_Receive?"Receive":"Transmit"));
1784
1785     // check state
1786     if(m_State != eHS_Running) {
1787         debugError("Incorrect state, expected eHS_Running, got %d\n",(int)m_State);
1788         return false;
1789     }
1790
1791     assert(m_handle != NULL);
1792
1793     debugOutput( DEBUG_LEVEL_VERBOSE, "(%p, %s) wake up handle...\n",
1794                  this, (m_type==eHT_Receive?"Receive":"Transmit"));
1795
1796     // wake up any waiting reads/polls
1797     raw1394_wake_up(m_handle);
1798
1799     // this is put here to try and avoid the
1800     // Runaway context problem
1801     // don't know if it will help though.
1802 /*    if(m_State != eHS_Error) { // if the handler is dead, this might block forever
1803         raw1394_iso_xmit_sync(m_handle);
1804     }*/
1805     debugOutput( DEBUG_LEVEL_VERBOSE, "(%p, %s) stop...\n",
1806                  this, (m_type==eHT_Receive?"Receive":"Transmit"));
1807     // stop iso traffic
1808     raw1394_iso_stop(m_handle);
1809     // deallocate resources
1810
1811     // Don't call until libraw1394's raw1394_new_handle() function has been
1812     // fixed to correctly initialise the iso_packet_infos field.  Bug is
1813     // confirmed present in libraw1394 1.2.1.
1814     raw1394_iso_shutdown(m_handle);
1815
1816     raw1394_destroy_handle(m_handle);
1817     m_handle = NULL;
1818
1819     m_State = eHS_Stopped;
1820     m_NextState = eHS_Stopped;
1821     return true;
1822 }
1823
1824 // functions to request enable or disable at the next opportunity
1825 bool
1826 IsoHandlerManager::IsoHandler::requestEnable(int cycle)
1827 {
1828     if (m_State == eHS_Running) {
1829         debugError("Enable requested on enabled stream '%s'\n", getTypeString());
1830         return false;
1831     }
1832     if (m_State != eHS_Stopped) {
1833         debugError("Enable requested on stream '%s' with state: %d\n", getTypeString(), m_State);
1834         return false;
1835     }
1836     m_NextState = eHS_Running;
1837     return true;
1838 }
1839
1840 bool
1841 IsoHandlerManager::IsoHandler::requestDisable()
1842 {
1843     if (m_State == eHS_Stopped) {
1844         debugError("Disable requested on disabled stream\n");
1845         return false;
1846     }
1847     if (m_State != eHS_Running) {
1848         debugError("Disable requested on stream with state=%d\n", m_State);
1849         return false;
1850     }
1851     m_NextState = eHS_Stopped;
1852     return true;
1853 }
1854
1855 void
1856 IsoHandlerManager::IsoHandler::updateState()
1857 {
1858     // execute state changes requested
1859     if(m_State != m_NextState) {
1860         debugOutput(DEBUG_LEVEL_VERBOSE, "(%p) handler needs state update from %d => %d\n", this, m_State, m_NextState);
1861         if(m_State == eHS_Stopped && m_NextState == eHS_Running) {
1862             debugOutput(DEBUG_LEVEL_VERBOSE, "handler has to be enabled\n");
1863             enable(m_switch_on_cycle);
1864         } else if(m_State == eHS_Running && m_NextState == eHS_Stopped) {
1865             debugOutput(DEBUG_LEVEL_VERBOSE, "handler has to be disabled\n");
1866             disable();
1867         } else {
1868             debugError("Unknown state transition\n");
1869         }
1870     }
1871 }
1872
1873 /**
1874  * @brief convert a EHandlerType to a string
1875  * @param t the type
1876  * @return a char * describing the state
1877  */
1878 const char *
1879 IsoHandlerManager::IsoHandler::eHTToString(enum EHandlerType t) {
1880     switch (t) {
1881         case eHT_Receive: return "Receive";
1882         case eHT_Transmit: return "Transmit";
1883         default: return "error: unknown type";
1884     }
1885 }
Note: See TracBrowser for help on using the browser.