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

Revision 1731, 40.9 kB (checked in by arnonym, 11 years ago)

Looks as if this doesn't break using the old stack. see #240

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