root/branches/api-cleanup/src/libieee1394/IsoHandler.cpp

Revision 815, 18.4 kB (checked in by ppalmers, 16 years ago)

- AMDTP transmit port caching for better performance
- less debug output in critical path

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 #include "config.h"
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 {
162     debugOutput( DEBUG_LEVEL_VERBOSE, "%p: Init thread...\n", this);
163     m_poll_fd.fd = getFileDescriptor();
164     m_poll_fd.revents = 0;
165     if (isEnabled()) {
166         m_poll_fd.events = POLLIN;
167     } else {
168         m_poll_fd.events = 0;
169     }
170     return true;
171 }
172
173 bool
174 IsoHandler::waitForClient()
175 {
176     //debugOutput(DEBUG_LEVEL_VERBOSE, "waiting...\n");
177     if(m_Client) {
178         bool result = m_Client->waitForSignal();
179         //debugOutput(DEBUG_LEVEL_VERBOSE, " returns %d\n", result);
180         return result;
181     } else {
182         debugOutput(DEBUG_LEVEL_VERBOSE, " no client\n");
183     }
184     return false;
185 }
186
187 bool
188 IsoHandler::tryWaitForClient()
189 {
190     //debugOutput(DEBUG_LEVEL_VERY_VERBOSE, "waiting...\n");
191     if(m_Client) {
192         bool result = m_Client->tryWaitForSignal();
193         //debugOutput(DEBUG_LEVEL_VERY_VERBOSE, " returns %d\n", result);
194         return result;
195     } else {
196         debugOutput(DEBUG_LEVEL_VERY_VERBOSE, " no client\n");
197     }
198     return false;
199 }
200
201 bool
202 IsoHandler::Execute()
203 {
204     //debugOutput( DEBUG_LEVEL_VERY_VERBOSE, "%p: Execute thread...\n", this);
205
206     // bypass if not running
207     if (m_State != E_Running) {
208         debugOutput( DEBUG_LEVEL_VERBOSE, "%p: not polling since not running...\n", this);
209         usleep(m_poll_timeout * 1000);
210         debugOutput( DEBUG_LEVEL_VERBOSE, "%p: done sleeping...\n", this);
211         return true;
212     }
213
214     // wait for the availability of frames in the client
215     // (blocking for transmit handlers)
216
217 #if 0 //#ifdef DEBUG
218     if (getType() == eHT_Transmit) {
219         debugOutput(DEBUG_LEVEL_VERBOSE, "(%p) Waiting for Client to signal frame availability...\n", this);
220     }
221 #endif
222     if (getType() == eHT_Receive || waitForClient()) {
223
224 #if ISOHANDLER_USE_POLL
225         uint64_t poll_enter = m_manager.get1394Service().getCurrentTimeAsUsecs();
226         err = poll(&m_poll_fd, 1, m_poll_timeout);
227         uint64_t poll_exit = m_manager.get1394Service().getCurrentTimeAsUsecs();
228         if (err == -1) {
229             if (errno == EINTR) {
230                 return true;
231             }
232             debugFatal("%p, poll error: %s\n", this, strerror (errno));
233             return false;
234         }
235         uint64_t iter_enter=0;
236         uint64_t iter_exit=0;
237         if(m_poll_fd.revents & (POLLIN)) {
238             iter_enter = m_manager.get1394Service().getCurrentTimeAsUsecs();
239             if(!iterate()) {
240                 debugOutput( DEBUG_LEVEL_VERBOSE,
241                             "IsoHandler (%p): Failed to iterate handler\n",
242                             this);
243                 return false;
244             }
245             iter_exit = m_manager.get1394Service().getCurrentTimeAsUsecs();
246         } else {
247             if (m_poll_fd.revents & POLLERR) {
248                 debugWarning("error on fd for %p\n", this);
249             }
250             if (m_poll_fd.revents & POLLHUP) {
251                 debugWarning("hangup on fd for %p\n",this);
252             }
253         }
254         debugOutput(DEBUG_LEVEL_VERY_VERBOSE, "(%c %p) poll took %lldus, iterate took %lldus\n",
255                     (getType()==eHT_Receive?'R':'X'), this,
256                     poll_exit-poll_enter, iter_exit-iter_enter);
257         return true;
258 #else
259         // iterate() is blocking if no 1394 data is available
260         // so poll'ing is not really necessary
261         bool result = true;
262         while(result && m_Client->canProcessPackets()) {
263             result = iterate();
264             //debugOutput(DEBUG_LEVEL_VERBOSE, "(%p, %s) Iterate returned: %d\n",
265             //            this, (m_type==eHT_Receive?"Receive":"Transmit"), result);
266         }
267         return result;
268 #endif
269     } else {
270         debugError("waitForClient() failed.\n");
271         return false;
272     }
273 }
274
275 bool
276 IsoHandler::iterate() {
277     //debugOutput(DEBUG_LEVEL_VERBOSE, "(%p, %s) Iterating ISO handler\n",
278     //            this, (m_type==eHT_Receive?"Receive":"Transmit"));
279     if(m_State == E_Running) {
280 #if ISOHANDLER_FLUSH_BEFORE_ITERATE
281         flush();
282 #endif
283         if(raw1394_loop_iterate(m_handle)) {
284             debugOutput( DEBUG_LEVEL_VERBOSE,
285                         "IsoHandler (%p): Failed to iterate handler: %s\n",
286                         this, strerror(errno));
287             return false;
288         }
289         return true;
290     } else {
291         debugOutput(DEBUG_LEVEL_VERBOSE, "(%p, %s) Not iterating a non-running handler...\n",
292                     this, (m_type==eHT_Receive?"Receive":"Transmit"));
293         return false;
294     }
295 }
296
297 bool
298 IsoHandler::setThreadParameters(bool rt, int priority) {
299     debugOutput( DEBUG_LEVEL_VERBOSE, "(%p) switch to: (rt=%d, prio=%d)...\n", this, rt, priority);
300     if (priority > THREAD_MAX_RTPRIO) priority = THREAD_MAX_RTPRIO; // cap the priority
301     m_realtime = rt;
302     m_priority = priority;
303
304     if (m_Thread) {
305         if (m_realtime) {
306             m_Thread->AcquireRealTime(m_priority);
307         } else {
308             m_Thread->DropRealTime();
309         }
310     }
311     return true;
312 }
313
314 bool
315 IsoHandler::init()
316 {
317     debugOutput( DEBUG_LEVEL_VERBOSE, "IsoHandler (%p) enter...\n",this);
318     // check the state
319     if(m_State != E_Created) {
320         debugError("Incorrect state, expected E_Created, got %d\n",(int)m_State);
321         return false;
322     }
323
324     // the main handle for the ISO traffic
325     m_handle = raw1394_new_handle_on_port( m_manager.get1394Service().getPort() );
326     if ( !m_handle ) {
327         if ( !errno ) {
328             debugError("libraw1394 not compatible\n");
329         } else {
330             debugError("Could not get 1394 handle: %s\n", strerror(errno) );
331             debugError("Are ieee1394 and raw1394 drivers loaded?\n");
332         }
333         return false;
334     }
335     raw1394_set_userdata(m_handle, static_cast<void *>(this));
336
337     // bus reset handling
338     if(raw1394_busreset_notify (m_handle, RAW1394_NOTIFY_ON)) {
339         debugWarning("Could not enable busreset notification.\n");
340         debugWarning(" Error message: %s\n",strerror(errno));
341         debugWarning("Continuing without bus reset support.\n");
342     } else {
343         // apparently this cannot fail
344         raw1394_set_bus_reset_handler(m_handle, busreset_handler);
345     }
346
347 #if ISOHANDLER_PER_HANDLER_THREAD
348     // create a thread to iterate ourselves
349     debugOutput( DEBUG_LEVEL_VERBOSE, "Start thread for %p...\n", this);
350     m_Thread = new Util::PosixThread(this, m_realtime, m_priority,
351                                      PTHREAD_CANCEL_DEFERRED);
352     if(!m_Thread) {
353         debugFatal("No thread\n");
354         return false;
355     }
356     if (m_Thread->Start() != 0) {
357         debugFatal("Could not start update thread\n");
358         return false;
359     }
360 #endif
361
362     // update the internal state
363     m_State=E_Initialized;
364     return true;
365 }
366
367 bool IsoHandler::disable()
368 {
369     debugOutput( DEBUG_LEVEL_VERBOSE, "(%p, %s) enter...\n",
370                  this, (m_type==eHT_Receive?"Receive":"Transmit"));
371
372     // check state
373     if(m_State == E_Prepared) return true;
374     if(m_State != E_Running) {
375         debugError("Incorrect state, expected E_Running, got %d\n",(int)m_State);
376         return false;
377     }
378
379     m_poll_fd.events = 0;
380
381     // this is put here to try and avoid the
382     // Runaway context problem
383     // don't know if it will help though.
384     raw1394_iso_xmit_sync(m_handle);
385     raw1394_iso_stop(m_handle);
386     m_State = E_Prepared;
387     return true;
388 }
389
390 /**
391  * Bus reset handler
392  *
393  * @return ?
394  */
395
396 int
397 IsoHandler::handleBusReset(unsigned int generation)
398 {
399     debugOutput( DEBUG_LEVEL_VERBOSE, "bus reset...\n");
400
401     #define CSR_CYCLE_TIME            0x200
402     #define CSR_REGISTER_BASE  0xfffff0000000ULL
403     // do a simple read on ourself in order to update the internal structures
404     // this avoids read failures after a bus reset
405     quadlet_t buf=0;
406     raw1394_read(m_handle, raw1394_get_local_id(m_handle),
407                  CSR_REGISTER_BASE | CSR_CYCLE_TIME, 4, &buf);
408     return 0;
409 }
410
411 void IsoHandler::dumpInfo()
412 {
413     int channel=-1;
414     if (m_Client) channel=m_Client->getChannel();
415
416     debugOutputShort( DEBUG_LEVEL_NORMAL, "  Handler type................: %s\n",
417             (this->getType() == eHT_Receive ? "Receive" : "Transmit"));
418     debugOutputShort( DEBUG_LEVEL_NORMAL, "  Port, Channel...............: %2d, %2d\n",
419             m_manager.get1394Service().getPort(), channel);
420     debugOutputShort( DEBUG_LEVEL_NORMAL, "  Buffer, MaxPacketSize, IRQ..: %4d, %4d, %4d\n",
421             m_buf_packets, m_max_packet_size, m_irq_interval);
422     if (this->getType() == eHT_Transmit) {
423         debugOutputShort( DEBUG_LEVEL_NORMAL, "  Speed, PreBuffers...........: %2d, %2d\n",
424                                             m_speed, m_prebuffers);
425     }
426     debugOutputShort( DEBUG_LEVEL_NORMAL, "  Packet count................: %10d (%5d dropped)\n",
427             this->getPacketCount(), this->getDroppedCount());
428 }
429
430 void IsoHandler::setVerboseLevel(int l)
431 {
432     setDebugLevel(l);
433     if(m_Thread) m_Thread->setVerboseLevel(l);
434 }
435
436 bool IsoHandler::registerStream(StreamProcessor *stream)
437 {
438     assert(stream);
439     debugOutput( DEBUG_LEVEL_VERBOSE, "registering stream (%p)\n", stream);
440
441     if (m_Client) {
442             debugFatal( "Generic IsoHandlers can have only one client\n");
443             return false;
444     }
445     m_Client=stream;
446     return true;
447 }
448
449 bool IsoHandler::unregisterStream(StreamProcessor *stream)
450 {
451     assert(stream);
452     debugOutput( DEBUG_LEVEL_VERBOSE, "unregistering stream (%p)\n", stream);
453
454     if(stream != m_Client) {
455             debugFatal( "no client registered\n");
456             return false;
457     }
458     m_Client=0;
459     return true;
460 }
461
462 void IsoHandler::flush()
463 {
464     if(m_type == eHT_Receive) {
465         raw1394_iso_recv_flush(m_handle);
466     } else {
467         // do nothing
468     }
469 }
470
471 // ISO packet interface
472 enum raw1394_iso_disposition IsoHandler::putPacket(
473                     unsigned char *data, unsigned int length,
474                     unsigned char channel, unsigned char tag, unsigned char sy,
475                     unsigned int cycle, unsigned int dropped) {
476
477     debugOutput( DEBUG_LEVEL_VERY_VERBOSE,
478                  "received packet: length=%d, channel=%d, cycle=%d\n",
479                  length, channel, cycle );
480     m_packetcount++;
481     m_dropped += dropped;
482
483     if(m_Client) {
484         return m_Client->putPacket(data, length, channel, tag, sy, cycle, dropped);
485     }
486
487     return RAW1394_ISO_OK;
488 }
489
490
491 enum raw1394_iso_disposition IsoHandler::getPacket(
492                     unsigned char *data, unsigned int *length,
493                     unsigned char *tag, unsigned char *sy,
494                     int cycle, unsigned int dropped) {
495
496     debugOutput( DEBUG_LEVEL_ULTRA_VERBOSE,
497                     "sending packet: length=%d, cycle=%d\n",
498                     *length, cycle );
499     m_packetcount++;
500     m_dropped += dropped;
501
502     if(m_Client) {
503         return m_Client->getPacket(data, length, tag, sy, cycle, dropped, m_max_packet_size);
504     }
505     return RAW1394_ISO_OK;
506 }
507
508 bool IsoHandler::prepare()
509 {
510     // check the state
511     if(m_State != E_Initialized) {
512         debugError("Incorrect state, expected E_Initialized, got %d\n",(int)m_State);
513         return false;
514     }
515
516     // Don't call until libraw1394's raw1394_new_handle() function has been
517     // fixed to correctly initialise the iso_packet_infos field.  Bug is
518     // confirmed present in libraw1394 1.2.1.
519     //     raw1394_iso_shutdown(m_handle);
520     m_State = E_Prepared;
521
522     debugOutput( DEBUG_LEVEL_VERBOSE, "Preparing iso handler (%p, client=%p)\n", this, m_Client);
523     dumpInfo();
524     if (getType() == eHT_Receive) {
525         if(m_irq_interval > 1) {
526             if(raw1394_iso_recv_init(m_handle,
527                                     iso_receive_handler,
528                                     m_buf_packets,
529                                     m_max_packet_size,
530                                     m_Client->getChannel(),
531 //                                     RAW1394_DMA_BUFFERFILL,
532                                     RAW1394_DMA_PACKET_PER_BUFFER,
533                                     m_irq_interval)) {
534                 debugFatal("Could not do receive initialisation (DMA_BUFFERFILL)!\n" );
535                 debugFatal("  %s\n",strerror(errno));
536                 return false;
537             }
538         } else {
539             if(raw1394_iso_recv_init(m_handle,
540                                     iso_receive_handler,
541                                     m_buf_packets,
542                                     m_max_packet_size,
543                                     m_Client->getChannel(),
544                                     RAW1394_DMA_PACKET_PER_BUFFER,
545                                     m_irq_interval)) {
546                 debugFatal("Could not do receive initialisation (PACKET_PER_BUFFER)!\n" );
547                 debugFatal("  %s\n",strerror(errno));
548                 return false;
549             }
550         }
551         return true;
552     } else {
553         if(raw1394_iso_xmit_init(m_handle,
554                                 iso_transmit_handler,
555                                 m_buf_packets,
556                                 m_max_packet_size,
557                                 m_Client->getChannel(),
558                                 m_speed,
559                                 m_irq_interval)) {
560             debugFatal("Could not do xmit initialisation!\n" );
561             return false;
562         }
563         return true;
564     }
565 }
566
567 bool IsoHandler::enable(int cycle)
568 {
569     debugOutput( DEBUG_LEVEL_VERBOSE, "start on cycle %d\n", cycle);
570     // check the state
571     if(m_State != E_Prepared) {
572         if(!prepare()) {
573             debugFatal("Could not prepare handler\n");
574             return false;
575         }
576     }
577
578     if (getType() == eHT_Receive) {
579         if(raw1394_iso_recv_start(m_handle, cycle, -1, 0)) {
580             debugFatal("Could not start receive handler (%s)\n",strerror(errno));
581             dumpInfo();
582             return false;
583         }
584     } else {
585         if(raw1394_iso_xmit_start(m_handle, cycle, m_prebuffers)) {
586             debugFatal("Could not start xmit handler (%s)\n",strerror(errno));
587             dumpInfo();
588             return false;
589         }
590     }
591
592     m_poll_fd.events = POLLIN;
593     m_State = E_Running;
594     return true;
595 }
Note: See TracBrowser for help on using the browser.