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

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

svn merge -r 1506:HEAD svn+ssh://ffadosvn@ffado.org/ffado/branches/libffado-2.0

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