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

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

- Implement basic HSS1394 support for the Stanton SCS devices
- Start of the implementation of a generic TCAT DICE EAP control
- Reworked part of the busreset / ARM handler code

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                 // if we are going to poll() it, let's ensure
259                 // it can run until someone wants it to exit
260                 h->allowIterateLoop();
261             }
262             m_poll_fds_shadow[i].events = events;
263         }
264
265         if(no_one_to_poll) {
266             debugOutput(DEBUG_LEVEL_ULTRA_VERBOSE,
267                         "(%p, %s) No one to poll, waiting for something to happen\n",
268                         this, (m_handlerType == IsoHandler::eHT_Transmit? "Transmit": "Receive"));
269             // wait for something to happen
270             switch(waitForActivity()) {
271                 case IsoTask::eAR_Error:
272                     debugError("Error while waiting for activity\n");
273                     return false;
274                 case IsoTask::eAR_Interrupted:
275                     // FIXME: what to do here?
276                     debugWarning("Interrupted while waiting for activity\n");
277                     break;
278                 case IsoTask::eAR_Timeout:
279                     // FIXME: what to do here?
280                     debugWarning("Timeout while waiting for activity\n");
281                     no_one_to_poll = false; // exit the loop to be able to detect failing handlers
282                     break;
283                 case IsoTask::eAR_Activity:
284                     // do nothing
285                     debugOutputExtreme(DEBUG_LEVEL_VERBOSE,
286                                        "(%p, %s) something happened\n",
287                                        this, (m_handlerType == IsoHandler::eHT_Transmit? "Transmit": "Receive"));
288                     break;
289             }
290         }
291     }
292
293     // Use a shadow map of the fd's such that we don't have to update
294     // the fd map everytime we run poll().
295     err = poll (m_poll_fds_shadow, m_poll_nfds_shadow, m_poll_timeout);
296     uint32_t ctr_at_poll_return = m_manager.get1394Service().getCycleTimer();
297
298     if (err < 0) {
299         if (errno == EINTR) {
300             debugOutput(DEBUG_LEVEL_VERBOSE, "Ignoring poll return due to signal\n");
301             return true;
302         }
303         debugFatal("poll error: %s\n", strerror (errno));
304         m_running = false;
305         return false;
306     }
307
308     // find handlers that have died
309     uint64_t ctr_at_poll_return_ticks = CYCLE_TIMER_TO_TICKS(ctr_at_poll_return);
310     bool handler_died = false;
311     for (i = 0; i < m_poll_nfds_shadow; i++) {
312         // figure out if a handler has died
313
314         // this is the time of the last packet we saw in the iterate() handler
315         uint32_t last_packet_seen = m_IsoHandler_map_shadow[i]->getLastPacketTime();
316         if (last_packet_seen == 0xFFFFFFFF) {
317             // this was not iterated yet, so can't be dead
318             debugOutput(DEBUG_LEVEL_VERY_VERBOSE,
319                         "(%p, %s) handler %d didn't see any packets yet\n",
320                         this, (m_handlerType == IsoHandler::eHT_Transmit? "Transmit": "Receive"), i);
321             continue;
322         }
323
324         uint64_t last_packet_seen_ticks = CYCLE_TIMER_TO_TICKS(last_packet_seen);
325         // we use a relatively large value to distinguish between "death" and xrun
326         int64_t max_diff_ticks = TICKS_PER_SECOND * 2;
327         int64_t measured_diff_ticks = diffTicks(ctr_at_poll_return_ticks, last_packet_seen_ticks);
328
329         debugOutputExtreme(DEBUG_LEVEL_VERBOSE,
330                            "(%p, %s) check handler %d: diff = %lld, max = %lld, now: %08lX, last: %08lX\n",
331                            this, (m_handlerType == IsoHandler::eHT_Transmit? "Transmit": "Receive"),
332                            i, measured_diff_ticks, max_diff_ticks, ctr_at_poll_return, last_packet_seen);
333         if(measured_diff_ticks > max_diff_ticks) {
334             debugFatal("(%p, %s) Handler died: now: %08lX, last: %08lX, diff: %lld (max: %lld)\n",
335                        this, (m_handlerType == IsoHandler::eHT_Transmit? "Transmit": "Receive"),
336                        ctr_at_poll_return, last_packet_seen, measured_diff_ticks, max_diff_ticks);
337             m_IsoHandler_map_shadow[i]->notifyOfDeath();
338             handler_died = true;
339         }
340     }
341
342     if(handler_died) {
343         m_running = false;
344         return false; // one or more handlers have died
345     }
346
347     // iterate the handlers
348     for (i = 0; i < m_poll_nfds_shadow; i++) {
349         #ifdef DEBUG
350         if(m_poll_fds_shadow[i].revents) {
351             debugOutputExtreme(DEBUG_LEVEL_VERBOSE,
352                         "(%p, %s) received events: %08X for (%d/%d, %p, %s)\n",
353                         this, (m_handlerType == IsoHandler::eHT_Transmit? "Transmit": "Receive"),
354                         m_poll_fds_shadow[i].revents,
355                         i, m_poll_nfds_shadow,
356                         m_IsoHandler_map_shadow[i],
357                         m_IsoHandler_map_shadow[i]->getTypeString());
358         }
359         #endif
360
361         // if we get here, it means two things:
362         // 1) the kernel can accept or provide packets (poll returned POLLIN)
363         // 2) the client can provide or accept packets (since we enabled polling)
364         if(m_poll_fds_shadow[i].revents & (POLLIN)) {
365             m_IsoHandler_map_shadow[i]->iterate(ctr_at_poll_return);
366         } else {
367             // there might be some error condition
368             if (m_poll_fds_shadow[i].revents & POLLERR) {
369                 debugWarning("(%p) error on fd for %d\n", this, i);
370             }
371             if (m_poll_fds_shadow[i].revents & POLLHUP) {
372                 debugWarning("(%p) hangup on fd for %d\n", this, i);
373             }
374         }
375     }
376     return true;
377 }
378
379 enum IsoTask::eActivityResult
380 IsoTask::waitForActivity()
381 {
382     debugOutputExtreme(DEBUG_LEVEL_VERBOSE,
383                        "(%p, %s) waiting for activity\n",
384                        this, (m_handlerType == IsoHandler::eHT_Transmit? "Transmit": "Receive"));
385     struct timespec ts;
386     int result;
387
388     if (clock_gettime(CLOCK_REALTIME, &ts) == -1) {
389         debugError("clock_gettime failed\n");
390         return eAR_Error;
391     }
392
393     ts.tv_nsec += m_activity_wait_timeout_nsec;
394     while(ts.tv_nsec >= 1000000000LL) {
395         ts.tv_sec += 1;
396         ts.tv_nsec -= 1000000000LL;
397     }
398
399     result = sem_timedwait(&m_activity_semaphore, &ts);
400
401     if(result != 0) {
402         if (errno == ETIMEDOUT) {
403             debugOutput(DEBUG_LEVEL_VERBOSE,
404                         "(%p) sem_timedwait() timed out (result=%d)\n",
405                         this, result);
406             return eAR_Timeout;
407         } else if (errno == EINTR) {
408             debugOutput(DEBUG_LEVEL_VERBOSE,
409                         "(%p) sem_timedwait() interrupted by signal (result=%d)\n",
410                         this, result);
411             return eAR_Interrupted;
412         } else if (errno == EINVAL) {
413             debugError("(%p) sem_timedwait error (result=%d errno=EINVAL)\n",
414                         this, result);
415             debugError("(%p) timeout_nsec=%lld ts.sec=%d ts.nsec=%lld\n",
416                        this, m_activity_wait_timeout_nsec, ts.tv_sec, ts.tv_nsec);
417             return eAR_Error;
418         } else {
419             debugError("(%p) sem_timedwait error (result=%d errno=%d)\n",
420                         this, result, errno);
421             debugError("(%p) timeout_nsec=%lld ts.sec=%d ts.nsec=%lld\n",
422                        this, m_activity_wait_timeout_nsec, ts.tv_sec, ts.tv_nsec);
423             return eAR_Error;
424         }
425     }
426
427     debugOutput(DEBUG_LEVEL_ULTRA_VERBOSE,
428                 "(%p, %s) got activity\n",
429                 this, (m_handlerType == IsoHandler::eHT_Transmit? "Transmit": "Receive"));
430     return eAR_Activity;
431 }
432
433 void
434 IsoTask::signalActivity()
435 {
436     // signal the activity cond var
437     sem_post(&m_activity_semaphore);
438     debugOutput(DEBUG_LEVEL_ULTRA_VERBOSE,
439                 "(%p, %s) activity\n",
440                 this, (m_handlerType == IsoHandler::eHT_Transmit? "Transmit": "Receive"));
441 }
442
443 void IsoTask::setVerboseLevel(int i) {
444     setDebugLevel(i);
445     debugOutput( DEBUG_LEVEL_VERBOSE, "Setting verbose level to %d...\n", i );
446 }
447
448 // -- the ISO handler manager -- //
449 IsoHandlerManager::IsoHandlerManager(Ieee1394Service& service)
450    : m_State(E_Created)
451    , m_service( service )
452    , m_realtime(false), m_priority(0)
453    , m_IsoThreadTransmit ( NULL )
454    , m_IsoTaskTransmit ( NULL )
455    , m_IsoThreadReceive ( NULL )
456    , m_IsoTaskReceive ( NULL )
457 {
458 }
459
460 IsoHandlerManager::IsoHandlerManager(Ieee1394Service& service, bool run_rt, int rt_prio)
461    : m_State(E_Created)
462    , m_service( service )
463    , m_realtime(run_rt), m_priority(rt_prio)
464    , m_IsoThreadTransmit ( NULL )
465    , m_IsoTaskTransmit ( NULL )
466    , m_IsoThreadReceive ( NULL )
467    , m_IsoTaskReceive ( NULL )
468 {
469 }
470
471 IsoHandlerManager::~IsoHandlerManager()
472 {
473     stopHandlers();
474     pruneHandlers();
475     if(m_IsoHandlers.size() > 0) {
476         debugError("Still some handlers in use\n");
477     }
478     if (m_IsoThreadTransmit) {
479         m_IsoThreadTransmit->Stop();
480         delete m_IsoThreadTransmit;
481     }
482     if (m_IsoThreadReceive) {
483         m_IsoThreadReceive->Stop();
484         delete m_IsoThreadReceive;
485     }
486     if (m_IsoTaskTransmit) {
487         delete m_IsoTaskTransmit;
488     }
489     if (m_IsoTaskReceive) {
490         delete m_IsoTaskReceive;
491     }
492 }
493
494 bool
495 IsoHandlerManager::handleBusReset()
496 {
497     debugOutput( DEBUG_LEVEL_NORMAL, "bus reset...\n");
498     // A few things can happen on bus reset:
499     // 1) no devices added/removed => streams are still valid, but might have to be restarted
500     // 2) a device was removed => some streams become invalid
501     // 3) a device was added => same as 1, new device is ignored
502     if (!m_IsoTaskTransmit) {
503         debugError("No xmit task\n");
504         return false;
505     }
506     if (!m_IsoTaskReceive) {
507         debugError("No receive task\n");
508         return false;
509     }
510     if (!m_IsoTaskTransmit->handleBusReset()) {
511         debugWarning("could no handle busreset on xmit\n");
512     }
513     if (!m_IsoTaskReceive->handleBusReset()) {
514         debugWarning("could no handle busreset on recv\n");
515     }
516     return true;
517 }
518
519 void
520 IsoHandlerManager::requestShadowMapUpdate()
521 {
522     if(m_IsoTaskTransmit) m_IsoTaskTransmit->requestShadowMapUpdate();
523     if(m_IsoTaskReceive) m_IsoTaskReceive->requestShadowMapUpdate();
524 }
525
526 bool
527 IsoHandlerManager::setThreadParameters(bool rt, int priority) {
528     debugOutput( DEBUG_LEVEL_VERBOSE, "(%p) switch to: (rt=%d, prio=%d)...\n", this, rt, priority);
529     if (priority > THREAD_MAX_RTPRIO) priority = THREAD_MAX_RTPRIO; // cap the priority
530     if (priority < THREAD_MIN_RTPRIO) priority = THREAD_MIN_RTPRIO; // cap the priority
531     m_realtime = rt;
532     m_priority = priority;
533
534     // grab the options from the parent
535     Util::Configuration *config = m_service.getConfiguration();
536     int ihm_iso_prio_increase = ISOHANDLERMANAGER_ISO_PRIO_INCREASE;
537     int ihm_iso_prio_increase_xmit = ISOHANDLERMANAGER_ISO_PRIO_INCREASE_XMIT;
538     int ihm_iso_prio_increase_recv = ISOHANDLERMANAGER_ISO_PRIO_INCREASE_RECV;
539     if(config) {
540         config->getValueForSetting("ieee1394.isomanager.prio_increase", ihm_iso_prio_increase);
541         config->getValueForSetting("ieee1394.isomanager.prio_increase_xmit", ihm_iso_prio_increase_xmit);
542         config->getValueForSetting("ieee1394.isomanager.prio_increase_recv", ihm_iso_prio_increase_recv);
543     }
544
545     if (m_IsoThreadTransmit) {
546         if (m_realtime) {
547             m_IsoThreadTransmit->AcquireRealTime(m_priority
548                                                  + ihm_iso_prio_increase
549                                                  + ihm_iso_prio_increase_xmit);
550         } else {
551             m_IsoThreadTransmit->DropRealTime();
552         }
553     }
554     if (m_IsoThreadReceive) {
555         if (m_realtime) {
556             m_IsoThreadReceive->AcquireRealTime(m_priority
557                                                 + ihm_iso_prio_increase
558                                                 + ihm_iso_prio_increase_recv);
559         } else {
560             m_IsoThreadReceive->DropRealTime();
561         }
562     }
563
564     return true;
565 }
566
567 bool IsoHandlerManager::init()
568 {
569     debugOutput( DEBUG_LEVEL_VERBOSE, "Initializing ISO manager %p...\n", this);
570     // check state
571     if(m_State != E_Created) {
572         debugError("Manager already initialized...\n");
573         return false;
574     }
575
576     // grab the options from the parent
577     Util::Configuration *config = m_service.getConfiguration();
578     int ihm_iso_prio_increase = ISOHANDLERMANAGER_ISO_PRIO_INCREASE;
579     int ihm_iso_prio_increase_xmit = ISOHANDLERMANAGER_ISO_PRIO_INCREASE_XMIT;
580     int ihm_iso_prio_increase_recv = ISOHANDLERMANAGER_ISO_PRIO_INCREASE_RECV;
581     int64_t isotask_activity_timeout_usecs = ISOHANDLERMANAGER_ISO_TASK_WAIT_TIMEOUT_USECS;
582     if(config) {
583         config->getValueForSetting("ieee1394.isomanager.prio_increase", ihm_iso_prio_increase);
584         config->getValueForSetting("ieee1394.isomanager.prio_increase_xmit", ihm_iso_prio_increase_xmit);
585         config->getValueForSetting("ieee1394.isomanager.prio_increase_recv", ihm_iso_prio_increase_recv);
586         config->getValueForSetting("ieee1394.isomanager.isotask_activity_timeout_usecs", isotask_activity_timeout_usecs);
587     }
588
589     // create threads to iterate our ISO handlers
590     debugOutput( DEBUG_LEVEL_VERBOSE, "Create iso thread for %p transmit...\n", this);
591     m_IsoTaskTransmit = new IsoTask( *this, IsoHandler::eHT_Transmit );
592     if(!m_IsoTaskTransmit) {
593         debugFatal("No task\n");
594         return false;
595     }
596     m_IsoTaskTransmit->setVerboseLevel(getDebugLevel());
597     m_IsoTaskTransmit->m_activity_wait_timeout_nsec = isotask_activity_timeout_usecs * 1000LL;
598     m_IsoThreadTransmit = new Util::PosixThread(m_IsoTaskTransmit, "ISOXMT", m_realtime,
599                                                 m_priority + ihm_iso_prio_increase
600                                                 + ihm_iso_prio_increase_xmit,
601                                                 PTHREAD_CANCEL_DEFERRED);
602
603     if(!m_IsoThreadTransmit) {
604         debugFatal("No thread\n");
605         return false;
606     }
607     m_IsoThreadTransmit->setVerboseLevel(getDebugLevel());
608
609     debugOutput( DEBUG_LEVEL_VERBOSE, "Create iso thread for %p receive...\n", this);
610     m_IsoTaskReceive = new IsoTask( *this, IsoHandler::eHT_Receive );
611     if(!m_IsoTaskReceive) {
612         debugFatal("No task\n");
613         return false;
614     }
615     m_IsoTaskReceive->setVerboseLevel(getDebugLevel());
616     m_IsoThreadReceive = new Util::PosixThread(m_IsoTaskReceive, "ISORCV", m_realtime,
617                                                m_priority + ihm_iso_prio_increase
618                                                + ihm_iso_prio_increase_recv,
619                                                PTHREAD_CANCEL_DEFERRED);
620
621     if(!m_IsoThreadReceive) {
622         debugFatal("No thread\n");
623         return false;
624     }
625     m_IsoThreadReceive->setVerboseLevel(getDebugLevel());
626     // register the thread with the RT watchdog
627     Util::Watchdog *watchdog = m_service.getWatchdog();
628     if(watchdog) {
629         if(!watchdog->registerThread(m_IsoThreadTransmit)) {
630             debugWarning("could not register iso transmit thread with watchdog\n");
631         }
632         if(!watchdog->registerThread(m_IsoThreadReceive)) {
633             debugWarning("could not register iso receive thread with watchdog\n");
634         }
635     } else {
636         debugWarning("could not find valid watchdog\n");
637     }
638
639     if (m_IsoThreadTransmit->Start() != 0) {
640         debugFatal("Could not start ISO Transmit thread\n");
641         return false;
642     }
643     if (m_IsoThreadReceive->Start() != 0) {
644         debugFatal("Could not start ISO Receive thread\n");
645         return false;
646     }
647
648     m_State=E_Running;
649     return true;
650 }
651
652 void
653 IsoHandlerManager::signalActivityTransmit()
654 {
655     assert(m_IsoTaskTransmit);
656     m_IsoTaskTransmit->signalActivity();
657 }
658
659 void
660 IsoHandlerManager::signalActivityReceive()
661 {
662     assert(m_IsoTaskReceive);
663     m_IsoTaskReceive->signalActivity();
664 }
665
666 bool IsoHandlerManager::registerHandler(IsoHandler *handler)
667 {
668     debugOutput( DEBUG_LEVEL_VERBOSE, "enter...\n");
669     assert(handler);
670     handler->setVerboseLevel(getDebugLevel());
671     m_IsoHandlers.push_back(handler);
672     requestShadowMapUpdate();
673     return true;
674 }
675
676 bool IsoHandlerManager::unregisterHandler(IsoHandler *handler)
677 {
678     debugOutput( DEBUG_LEVEL_VERBOSE, "enter...\n");
679     assert(handler);
680
681     for ( IsoHandlerVectorIterator it = m_IsoHandlers.begin();
682       it != m_IsoHandlers.end();
683       ++it )
684     {
685         if ( *it == handler ) {
686             m_IsoHandlers.erase(it);
687             requestShadowMapUpdate();
688             return true;
689         }
690     }
691     debugFatal("Could not find handler (%p)\n", handler);
692     return false; //not found
693 }
694
695 /**
696  * Registers an StreamProcessor with the IsoHandlerManager.
697  *
698  * If nescessary, an IsoHandler is created to handle this stream.
699  * Once an StreamProcessor is registered to the handler, it will be included
700  * in the ISO streaming cycle (i.e. receive/transmit of it will occur).
701  *
702  * @param stream the stream to register
703  * @return true if registration succeeds
704  *
705  * \todo : currently there is a one-to-one mapping
706  *        between streams and handlers, this is not ok for
707  *        multichannel receive
708  */
709 bool IsoHandlerManager::registerStream(StreamProcessor *stream)
710 {
711     debugOutput( DEBUG_LEVEL_VERBOSE, "Registering %s stream %p\n", stream->getTypeString(), stream);
712     assert(stream);
713
714     IsoHandler* h = NULL;
715
716     // make sure the stream isn't already attached to a handler
717     for ( IsoHandlerVectorIterator it = m_IsoHandlers.begin();
718       it != m_IsoHandlers.end();
719       ++it )
720     {
721         if((*it)->isStreamRegistered(stream)) {
722             debugError( "stream already registered!\n");
723             return false;
724         }
725     }
726
727     // clean up all handlers that aren't used
728     pruneHandlers();
729
730     // allocate a handler for this stream
731     if (stream->getType()==StreamProcessor::ePT_Receive) {
732         // grab the options from the parent
733         Util::Configuration *config = m_service.getConfiguration();
734         int receive_mode_setting = DEFAULT_ISO_RECEIVE_MODE;
735         int bufferfill_mode_threshold = BUFFERFILL_MODE_THRESHOLD;
736         int min_interrupts_per_period = MINIMUM_INTERRUPTS_PER_PERIOD;
737         int max_nb_buffers_recv = MAX_RECV_NB_BUFFERS;
738         int min_packetsize_recv = MIN_RECV_PACKET_SIZE;
739         if(config) {
740             config->getValueForSetting("ieee1394.isomanager.iso_receive_mode", receive_mode_setting);
741             config->getValueForSetting("ieee1394.isomanager.bufferfill_mode_threshold", bufferfill_mode_threshold);
742             config->getValueForSetting("ieee1394.isomanager.min_interrupts_per_period", min_interrupts_per_period);
743             config->getValueForSetting("ieee1394.isomanager.max_nb_buffers_recv", max_nb_buffers_recv);
744             config->getValueForSetting("ieee1394.isomanager.min_packetsize_recv", min_packetsize_recv);
745         }
746
747         // setup the optimal parameters for the raw1394 ISO buffering
748         unsigned int packets_per_period = stream->getPacketsPerPeriod();
749         // reserve space for the 1394 header too (might not be necessary)
750         unsigned int max_packet_size = stream->getMaxPacketSize() + 8;
751         unsigned int page_size = getpagesize();
752
753         enum raw1394_iso_dma_recv_mode receive_mode;
754         switch(receive_mode_setting) {
755             case 0:
756                 if(packets_per_period < (unsigned)bufferfill_mode_threshold) {
757                     debugOutput( DEBUG_LEVEL_VERBOSE, "Using packet-per-buffer mode (auto) [%d, %d]\n",
758                                  packets_per_period, bufferfill_mode_threshold);
759                     receive_mode = RAW1394_DMA_PACKET_PER_BUFFER;
760                 } else {
761                     debugOutput( DEBUG_LEVEL_VERBOSE, "Using bufferfill mode (auto) [%d, %d]\n",
762                                  packets_per_period, bufferfill_mode_threshold);
763                     receive_mode = RAW1394_DMA_BUFFERFILL;
764                 }
765                 break;
766             case 1:
767                 debugOutput( DEBUG_LEVEL_VERBOSE, "Using packet-per-buffer mode (config)\n");
768                 receive_mode = RAW1394_DMA_PACKET_PER_BUFFER;
769                 break;
770             case 2:
771                 debugOutput( DEBUG_LEVEL_VERBOSE, "Using bufferfill mode (config)\n");
772                 receive_mode = RAW1394_DMA_BUFFERFILL;
773                 break;
774             default: debugWarning("Bogus receive mode setting in config: %d\n", receive_mode_setting);
775         }
776
777         // Ensure we don't request a packet size bigger than the
778         // kernel-enforced maximum which is currently 1 page.
779         // NOTE: PP: this is not really true AFAICT
780         if (max_packet_size > page_size) {
781             debugError("max packet size (%u) > page size (%u)\n", max_packet_size, page_size);
782             return false;
783         }
784         if (max_packet_size < (unsigned)min_packetsize_recv) {
785             debugError("min packet size (%u) < MIN_RECV_PACKET_SIZE (%u), using min value\n",
786                        max_packet_size, min_packetsize_recv);
787             max_packet_size = min_packetsize_recv;
788         }
789
790         // apparently a too small value causes issues too
791         if(max_packet_size < 200) max_packet_size = 200;
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.