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

Revision 1526, 41.1 kB (checked in by ppalmers, 12 years ago)

fix the freewheeling issue. clean up the IsoHandler? and the interactions with the Manager.

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