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

Revision 776, 16.3 kB (checked in by ppalmers, 16 years ago)

try to fix deadlock / performace issues

Line 
1 /*
2  * Copyright (C) 2005-2007 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 3 of the License, or
12  * (at your option) any later version.
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 //#define PER_HANDLER_THREAD
25
26 #include "IsoHandler.h"
27 #include "ieee1394service.h"
28
29 #include "libstreaming/generic/StreamProcessor.h"
30 #include "libutil/PosixThread.h"
31
32 #include <errno.h>
33 #include <netinet/in.h>
34 #include <assert.h>
35 #include <unistd.h>
36 #include <string.h>
37
38 #include <iostream>
39 using namespace std;
40 using namespace Streaming;
41
42 IMPL_DEBUG_MODULE( IsoHandler, IsoHandler, DEBUG_LEVEL_NORMAL );
43
44 /* the C callbacks */
45 enum raw1394_iso_disposition
46 IsoHandler::iso_transmit_handler(raw1394handle_t handle,
47         unsigned char *data, unsigned int *length,
48         unsigned char *tag, unsigned char *sy,
49         int cycle, unsigned int dropped) {
50
51     IsoHandler *xmitHandler = static_cast<IsoHandler *>(raw1394_get_userdata(handle));
52     assert(xmitHandler);
53
54     return xmitHandler->getPacket(data, length, tag, sy, cycle, dropped);
55 }
56
57 enum raw1394_iso_disposition
58 IsoHandler::iso_receive_handler(raw1394handle_t handle, unsigned char *data,
59                         unsigned int length, unsigned char channel,
60                         unsigned char tag, unsigned char sy, unsigned int cycle,
61                         unsigned int dropped) {
62
63     IsoHandler *recvHandler = static_cast<IsoHandler *>(raw1394_get_userdata(handle));
64     assert(recvHandler);
65
66     return recvHandler->putPacket(data, length, channel, tag, sy, cycle, dropped);
67 }
68
69 int IsoHandler::busreset_handler(raw1394handle_t handle, unsigned int generation)
70 {
71     debugOutput( DEBUG_LEVEL_VERBOSE, "Busreset happened, generation %d...\n", generation);
72
73     IsoHandler *handler = static_cast<IsoHandler *>(raw1394_get_userdata(handle));
74     assert(handler);
75     return handler->handleBusReset(generation);
76 }
77
78 IsoHandler::IsoHandler(IsoHandlerManager& manager, enum EHandlerType t)
79    : m_manager( manager )
80    , m_type ( t )
81    , m_handle( 0 )
82    , m_buf_packets( 400 )
83    , m_max_packet_size( 1024 )
84    , m_irq_interval( -1 )
85    , m_packetcount( 0 )
86    , m_dropped( 0 )
87    , m_Client( 0 )
88    , m_poll_timeout( 100 )
89    , m_realtime ( false )
90    , m_priority ( 0 )
91    , m_Thread ( NULL )
92    , m_speed( RAW1394_ISO_SPEED_400 )
93    , m_prebuffers( 0 )
94    , m_State( E_Created )
95 {
96 }
97
98 IsoHandler::IsoHandler(IsoHandlerManager& manager, enum EHandlerType t,
99                        unsigned int buf_packets, unsigned int max_packet_size, int irq)
100    : m_manager( manager )
101    , m_type ( t )
102    , m_handle( 0 )
103    , m_buf_packets( buf_packets )
104    , m_max_packet_size( max_packet_size )
105    , m_irq_interval( irq )
106    , m_packetcount( 0 )
107    , m_dropped( 0 )
108    , m_Client( 0 )
109    , m_poll_timeout( 100 )
110    , m_realtime ( false )
111    , m_priority ( 0 )
112    , m_Thread ( NULL )
113    , m_speed( RAW1394_ISO_SPEED_400 )
114    , m_prebuffers( 0 )
115    , m_State( E_Created )
116 {
117 }
118
119 IsoHandler::IsoHandler(IsoHandlerManager& manager, enum EHandlerType t, unsigned int buf_packets,
120                        unsigned int max_packet_size, int irq,
121                        enum raw1394_iso_speed speed)
122    : m_manager( manager )
123    , m_type ( t )
124    , m_handle( 0 )
125    , m_buf_packets( buf_packets )
126    , m_max_packet_size( max_packet_size )
127    , m_irq_interval( irq )
128    , m_packetcount( 0 )
129    , m_dropped( 0 )
130    , m_Client( 0 )
131    , m_poll_timeout( 100 )
132    , m_realtime ( false )
133    , m_priority ( 0 )
134    , m_Thread ( NULL )
135    , m_speed( speed )
136    , m_prebuffers( 0 )
137    , m_State( E_Created )
138 {
139 }
140
141 IsoHandler::~IsoHandler() {
142     if (m_Thread) {
143         m_Thread->Stop();
144         delete m_Thread;
145     }
146 // Don't call until libraw1394's raw1394_new_handle() function has been
147 // fixed to correctly initialise the iso_packet_infos field.  Bug is
148 // confirmed present in libraw1394 1.2.1.  In any case,
149 // raw1394_destroy_handle() will do any iso system shutdown required.
150 //     raw1394_iso_shutdown(m_handle);
151     if(m_handle) {
152         if (m_State == E_Running) {
153             disable();
154         }
155         raw1394_destroy_handle(m_handle);
156     }
157 }
158
159 bool
160 IsoHandler::Init() {
161     debugOutput( DEBUG_LEVEL_VERBOSE, "%p: Init thread...\n", this);
162     m_poll_fd.fd = getFileDescriptor();
163     m_poll_fd.revents = 0;
164     if (isEnabled()) {
165         m_poll_fd.events = POLLIN;
166     } else {
167         m_poll_fd.events = 0;
168     }
169     return true;
170 }
171
172 bool
173 IsoHandler::Execute() {
174     int err;
175
176     debugOutput( DEBUG_LEVEL_VERY_VERBOSE, "%p: Execute thread...\n", this);
177     // bypass if not running
178     if (m_State != E_Running) {
179         debugOutput( DEBUG_LEVEL_VERBOSE, "%p: not polling since not running...\n", this);
180         usleep(m_poll_timeout * 1000);
181         debugOutput( DEBUG_LEVEL_VERBOSE, "%p: done sleeping...\n", this);
182         return true;
183     }
184
185 #ifdef DO_POLL
186     uint64_t poll_enter = m_manager.get1394Service().getCurrentTimeAsUsecs();
187     err = poll(&m_poll_fd, 1, m_poll_timeout);
188     uint64_t poll_exit = m_manager.get1394Service().getCurrentTimeAsUsecs();
189     if (err == -1) {
190         if (errno == EINTR) {
191             return true;
192         }
193         debugFatal("%p, poll error: %s\n", this, strerror (errno));
194         return false;
195     }
196     uint64_t iter_enter=0;
197     uint64_t iter_exit=0;
198     if(m_poll_fd.revents & (POLLIN)) {
199         iter_enter = m_manager.get1394Service().getCurrentTimeAsUsecs();
200         if(!iterate()) {
201             debugOutput( DEBUG_LEVEL_VERBOSE,
202                         "IsoHandler (%p): Failed to iterate handler\n",
203                         this);
204             return false;
205         }
206         iter_exit = m_manager.get1394Service().getCurrentTimeAsUsecs();
207     } else {
208         if (m_poll_fd.revents & POLLERR) {
209             debugWarning("error on fd for %p\n", this);
210         }
211         if (m_poll_fd.revents & POLLHUP) {
212             debugWarning("hangup on fd for %p\n",this);
213         }
214     }
215     debugOutput(DEBUG_LEVEL_VERY_VERBOSE, "(%c %p) poll took %lldus, iterate took %lldus\n",
216                 (this->getType()==eHT_Receive?'R':'X'), this,
217                 poll_exit-poll_enter, iter_exit-iter_enter);
218 #else
219     // iterate itself blocks if nothing is available
220     // so poll'ing is not really necessary
221     bool result = iterate();
222     usleep(125);
223     return result;
224 #endif
225     return true;
226 }
227
228 bool
229 IsoHandler::iterate() {
230     if(raw1394_loop_iterate(m_handle)) {
231         debugOutput( DEBUG_LEVEL_VERBOSE,
232                     "IsoHandler (%p): Failed to iterate handler: %s\n",
233                     this,strerror(errno));
234         return false;
235     }
236     return true;
237 }
238
239 bool
240 IsoHandler::setThreadParameters(bool rt, int priority) {
241     debugOutput( DEBUG_LEVEL_VERBOSE, "(%p) switch to: (rt=%d, prio=%d)...\n", this, rt, priority);
242     if (priority > 98) priority = 98; // cap the priority
243     m_realtime = rt;
244     m_priority = priority;
245
246     if (m_Thread) {
247         if (m_realtime) {
248             m_Thread->AcquireRealTime(m_priority);
249         } else {
250             m_Thread->DropRealTime();
251         }
252     }
253     return true;
254 }
255
256 bool
257 IsoHandler::init()
258 {
259     debugOutput( DEBUG_LEVEL_VERBOSE, "IsoHandler (%p) enter...\n",this);
260     // check the state
261     if(m_State != E_Created) {
262         debugError("Incorrect state, expected E_Created, got %d\n",(int)m_State);
263         return false;
264     }
265
266     // the main handle for the ISO traffic
267     m_handle = raw1394_new_handle_on_port( m_manager.get1394Service().getPort() );
268     if ( !m_handle ) {
269         if ( !errno ) {
270             debugError("libraw1394 not compatible\n");
271         } else {
272             debugError("Could not get 1394 handle: %s\n", strerror(errno) );
273             debugError("Are ieee1394 and raw1394 drivers loaded?\n");
274         }
275         return false;
276     }
277     raw1394_set_userdata(m_handle, static_cast<void *>(this));
278
279     // bus reset handling
280     if(raw1394_busreset_notify (m_handle, RAW1394_NOTIFY_ON)) {
281         debugWarning("Could not enable busreset notification.\n");
282         debugWarning(" Error message: %s\n",strerror(errno));
283         debugWarning("Continuing without bus reset support.\n");
284     } else {
285         // apparently this cannot fail
286         raw1394_set_bus_reset_handler(m_handle, busreset_handler);
287     }
288
289 #ifdef THREAD_PER_ISOHANDLER
290     // create a thread to iterate ourselves
291     debugOutput( DEBUG_LEVEL_VERBOSE, "Start thread for %p...\n", this);
292     m_Thread = new Util::PosixThread(this, m_realtime, m_priority,
293                                      PTHREAD_CANCEL_DEFERRED);
294     if(!m_Thread) {
295         debugFatal("No thread\n");
296         return false;
297     }
298     if (m_Thread->Start() != 0) {
299         debugFatal("Could not start update thread\n");
300         return false;
301     }
302 #endif
303
304     // update the internal state
305     m_State=E_Initialized;
306     return true;
307 }
308
309 bool IsoHandler::disable()
310 {
311     debugOutput( DEBUG_LEVEL_VERBOSE, "enter...\n");
312
313     // check state
314     if(m_State == E_Prepared) return true;
315     if(m_State != E_Running) {
316         debugError("Incorrect state, expected E_Running, got %d\n",(int)m_State);
317         return false;
318     }
319
320     m_poll_fd.events = 0;
321
322     // this is put here to try and avoid the
323     // Runaway context problem
324     // don't know if it will help though.
325     raw1394_iso_xmit_sync(m_handle);
326     raw1394_iso_stop(m_handle);
327     m_State = E_Prepared;
328     return true;
329 }
330
331 /**
332  * Bus reset handler
333  *
334  * @return ?
335  */
336
337 int
338 IsoHandler::handleBusReset(unsigned int generation)
339 {
340     debugOutput( DEBUG_LEVEL_VERBOSE, "bus reset...\n");
341
342     #define CSR_CYCLE_TIME            0x200
343     #define CSR_REGISTER_BASE  0xfffff0000000ULL
344     // do a simple read on ourself in order to update the internal structures
345     // this avoids read failures after a bus reset
346     quadlet_t buf=0;
347     raw1394_read(m_handle, raw1394_get_local_id(m_handle),
348                  CSR_REGISTER_BASE | CSR_CYCLE_TIME, 4, &buf);
349     return 0;
350 }
351
352 void IsoHandler::dumpInfo()
353 {
354     int channel=-1;
355     if (m_Client) channel=m_Client->getChannel();
356
357     debugOutputShort( DEBUG_LEVEL_NORMAL, "  Handler type................: %s\n",
358             (this->getType() == eHT_Receive ? "Receive" : "Transmit"));
359     debugOutputShort( DEBUG_LEVEL_NORMAL, "  Port, Channel...............: %2d, %2d\n",
360             m_manager.get1394Service().getPort(), channel);
361     debugOutputShort( DEBUG_LEVEL_NORMAL, "  Buffer, MaxPacketSize, IRQ..: %4d, %4d, %4d\n",
362             m_buf_packets, m_max_packet_size, m_irq_interval);
363     if (this->getType() == eHT_Transmit) {
364         debugOutputShort( DEBUG_LEVEL_NORMAL, "  Speed, PreBuffers...........: %2d, %2d\n",
365                                             m_speed, m_prebuffers);
366     }
367     debugOutputShort( DEBUG_LEVEL_NORMAL, "  Packet count................: %10d (%5d dropped)\n",
368             this->getPacketCount(), this->getDroppedCount());
369 }
370
371 void IsoHandler::setVerboseLevel(int l)
372 {
373     setDebugLevel(l);
374     if(m_Thread) m_Thread->setVerboseLevel(l);
375 }
376
377 bool IsoHandler::registerStream(StreamProcessor *stream)
378 {
379     assert(stream);
380     debugOutput( DEBUG_LEVEL_VERBOSE, "registering stream (%p)\n", stream);
381
382     if (m_Client) {
383             debugFatal( "Generic IsoHandlers can have only one client\n");
384             return false;
385     }
386     m_Client=stream;
387     return true;
388 }
389
390 bool IsoHandler::unregisterStream(StreamProcessor *stream)
391 {
392     assert(stream);
393     debugOutput( DEBUG_LEVEL_VERBOSE, "unregistering stream (%p)\n", stream);
394
395     if(stream != m_Client) {
396             debugFatal( "no client registered\n");
397             return false;
398     }
399     m_Client=0;
400     return true;
401 }
402
403 void IsoHandler::flush()
404 {
405     if(m_type == eHT_Receive) {
406         raw1394_iso_recv_flush(m_handle);
407     } else {
408         // do nothing
409     }
410 }
411
412 // ISO packet interface
413 enum raw1394_iso_disposition IsoHandler::putPacket(
414                     unsigned char *data, unsigned int length,
415                     unsigned char channel, unsigned char tag, unsigned char sy,
416                     unsigned int cycle, unsigned int dropped) {
417
418     debugOutput( DEBUG_LEVEL_VERY_VERBOSE,
419                  "received packet: length=%d, channel=%d, cycle=%d\n",
420                  length, channel, cycle );
421     m_packetcount++;
422     m_dropped += dropped;
423
424     if(m_Client) {
425         return m_Client->putPacket(data, length, channel, tag, sy, cycle, dropped);
426     }
427
428     return RAW1394_ISO_OK;
429 }
430
431
432 enum raw1394_iso_disposition IsoHandler::getPacket(
433                     unsigned char *data, unsigned int *length,
434                     unsigned char *tag, unsigned char *sy,
435                     int cycle, unsigned int dropped) {
436
437     debugOutput( DEBUG_LEVEL_VERY_VERBOSE,
438                     "sending packet: length=%d, cycle=%d\n",
439                     *length, cycle );
440     m_packetcount++;
441     m_dropped += dropped;
442
443     if(m_Client) {
444         return m_Client->getPacket(data, length, tag, sy, cycle, dropped, m_max_packet_size);
445     }
446     return RAW1394_ISO_OK;
447 }
448
449 bool IsoHandler::prepare()
450 {
451     // check the state
452     if(m_State != E_Initialized) {
453         debugError("Incorrect state, expected E_Initialized, got %d\n",(int)m_State);
454         return false;
455     }
456
457     // Don't call until libraw1394's raw1394_new_handle() function has been
458     // fixed to correctly initialise the iso_packet_infos field.  Bug is
459     // confirmed present in libraw1394 1.2.1.
460     //     raw1394_iso_shutdown(m_handle);
461     m_State = E_Prepared;
462
463     debugOutput( DEBUG_LEVEL_VERBOSE, "Preparing iso handler (%p, client=%p)\n", this, m_Client);
464     dumpInfo();
465     if (getType() == eHT_Receive) {
466         if(m_irq_interval > 1) {
467             if(raw1394_iso_recv_init(m_handle,
468                                     iso_receive_handler,
469                                     m_buf_packets,
470                                     m_max_packet_size,
471                                     m_Client->getChannel(),
472                                     RAW1394_DMA_BUFFERFILL,
473                                     m_irq_interval)) {
474                 debugFatal("Could not do receive initialisation (DMA_BUFFERFILL)!\n" );
475                 debugFatal("  %s\n",strerror(errno));
476                 return false;
477             }
478         } else {
479             if(raw1394_iso_recv_init(m_handle,
480                                     iso_receive_handler,
481                                     m_buf_packets,
482                                     m_max_packet_size,
483                                     m_Client->getChannel(),
484                                     RAW1394_DMA_PACKET_PER_BUFFER,
485                                     m_irq_interval)) {
486                 debugFatal("Could not do receive initialisation (PACKET_PER_BUFFER)!\n" );
487                 debugFatal("  %s\n",strerror(errno));
488                 return false;
489             }
490         }
491         return true;
492     } else {
493         if(raw1394_iso_xmit_init(m_handle,
494                                 iso_transmit_handler,
495                                 m_buf_packets,
496                                 m_max_packet_size,
497                                 m_Client->getChannel(),
498                                 m_speed,
499                                 m_irq_interval)) {
500             debugFatal("Could not do xmit initialisation!\n" );
501             return false;
502         }
503         return true;
504     }
505 }
506
507 bool IsoHandler::enable(int cycle)
508 {
509     debugOutput( DEBUG_LEVEL_VERBOSE, "start on cycle %d\n", cycle);
510     // check the state
511     if(m_State != E_Prepared) {
512         if(!prepare()) {
513             debugFatal("Could not prepare handler\n");
514             return false;
515         }
516     }
517
518     if (getType() == eHT_Receive) {
519         if(raw1394_iso_recv_start(m_handle, cycle, -1, 0)) {
520             debugFatal("Could not start receive handler (%s)\n",strerror(errno));
521             dumpInfo();
522             return false;
523         }
524     } else {
525         if(raw1394_iso_xmit_start(m_handle, cycle, m_prebuffers)) {
526             debugFatal("Could not start xmit handler (%s)\n",strerror(errno));
527             dumpInfo();
528             return false;
529         }
530     }
531
532     m_poll_fd.events = POLLIN;
533     m_State = E_Running;
534     return true;
535 }
Note: See TracBrowser for help on using the browser.