lib: added back m_seen_usb_error check in DefaultRead()
[barry.git] / src / router.cc
blob39f4bb9073f1151ae91d3a9fd3cda24ac6f0ce05
1 ///
2 /// \file router.cc
3 /// Support classes for the pluggable socket routing system.
4 ///
6 /*
7 Copyright (C) 2008-2010, Net Direct Inc. (http://www.netdirect.ca/)
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) any later version.
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.
18 See the GNU General Public License in the COPYING file at the
19 root directory of this project for more details.
22 #include "router.h"
23 #include "scoped_lock.h"
24 #include "data.h"
25 #include "protostructs.h"
26 #include "usbwrap.h"
27 #include "endian.h"
28 #include "debug.h"
29 #include <unistd.h>
31 namespace Barry {
33 ///////////////////////////////////////////////////////////////////////////////
34 // SocketDataHandler default methods
36 void SocketRoutingQueue::SocketDataHandler::Error(Barry::Error &error)
38 // Just log the error
39 eout("SocketDataHandler: Error: " << error.what());
40 (void) error;
43 SocketRoutingQueue::SocketDataHandler::~SocketDataHandler()
45 // Nothing to destroy
48 ///////////////////////////////////////////////////////////////////////////////
49 // SocketRoutingQueue constructors
51 SocketRoutingQueue::SocketRoutingQueue(int prealloc_buffer_count)
52 : m_dev(0)
53 , m_writeEp(0)
54 , m_readEp(0)
55 , m_interest(false)
56 , m_seen_usb_error(false)
57 , m_continue_reading(false)
59 pthread_mutex_init(&m_mutex, NULL);
61 pthread_mutex_init(&m_readwaitMutex, NULL);
62 pthread_cond_init(&m_readwaitCond, NULL);
64 AllocateBuffers(prealloc_buffer_count);
67 SocketRoutingQueue::~SocketRoutingQueue()
69 // thread running?
70 if( m_continue_reading ) {
71 m_continue_reading = false;
72 pthread_join(m_usb_read_thread, NULL);
76 ///////////////////////////////////////////////////////////////////////////////
77 // protected members
80 // ReturnBuffer
82 /// Provides a method of returning a buffer to the free queue
83 /// after processing. The DataHandle class calls this automatically
84 /// from its destructor.
85 void SocketRoutingQueue::ReturnBuffer(Data *buf)
87 // don't need to lock here, since m_free handles its own locking
88 m_free.push(buf);
92 // SimpleReadThread()
94 /// Convenience thread to handle USB read activity.
95 ///
96 void *SocketRoutingQueue::SimpleReadThread(void *userptr)
98 SocketRoutingQueue *q = (SocketRoutingQueue *)userptr;
100 // read from USB and write to stdout until finished
101 q->m_seen_usb_error = false;
102 while( q->m_continue_reading ) {
103 try {
104 q->DoRead(1000); // timeout in milliseconds
106 catch (std::runtime_error const &e) {
107 eout("SimpleReadThread received uncaught exception: " << typeid(e).name() << " what: " << e.what());
109 catch (...) {
110 eout("SimpleReadThread recevied uncaught exception of unknown type");
113 return 0;
117 ///////////////////////////////////////////////////////////////////////////////
118 // public API
120 // These functions connect the router to an external Usb::Device
121 // object. Normally this is handled automatically by the
122 // Controller class, but are public here in case they are needed.
123 void SocketRoutingQueue::SetUsbDevice(Usb::Device *dev, int writeEp, int readEp,
124 SocketDataHandlerPtr callback)
126 scoped_lock lock(m_mutex);
127 m_dev = dev;
128 m_usb_error_dev_callback = callback;
129 m_writeEp = writeEp;
130 m_readEp = readEp;
133 void SocketRoutingQueue::ClearUsbDevice()
135 scoped_lock lock(m_mutex);
136 m_dev = 0;
137 m_usb_error_dev_callback.reset();
138 lock.unlock();
140 // wait for the DoRead cycle to finish, so the external
141 // Usb::Device object doesn't close before we're done with it
142 scoped_lock wait(m_readwaitMutex);
143 pthread_cond_wait(&m_readwaitCond, &m_readwaitMutex);
146 bool SocketRoutingQueue::UsbDeviceReady()
148 scoped_lock lock(m_mutex);
149 return m_dev != 0 && !m_seen_usb_error;
153 // AllocateBuffers
155 /// This class starts out with no buffers, and will grow one buffer
156 /// at a time if needed. Call this to allocate count buffers
157 /// all at once and place them on the free queue. After calling
158 /// this function, at least count buffers will exist in the free
159 /// queue. If there are already count buffers, none will be added.
161 void SocketRoutingQueue::AllocateBuffers(int count)
163 int todo = count - m_free.size();
165 for( int i = 0; i < todo; i++ ) {
166 // m_free handles its own locking
167 m_free.push( new Data );
172 // DefaultRead (both variations)
174 /// Returns the data for the next unregistered socket.
175 /// Blocks until timeout or data is available.
176 /// Returns false (or null pointer) on timeout and no data.
177 /// With the return version of the function, there is no
178 /// copying performed.
180 /// This version performs a copy.
182 bool SocketRoutingQueue::DefaultRead(Data &receive, int timeout)
184 DataHandle buf = DefaultRead(timeout);
185 if( !buf.get() )
186 return false;
188 // copy to desired buffer
189 receive = *buf.get();
190 return true;
194 /// This version does not perform a copy.
196 DataHandle SocketRoutingQueue::DefaultRead(int timeout)
198 if( m_seen_usb_error && timeout == -1 ) {
199 // If an error has been seen and not cleared then no
200 // more data will be read into the queue by
201 // DoRead(). Forcing the timeout to zero allows any
202 // data already in the queue to be read, but prevents
203 // waiting for data which will never arrive.
204 timeout = 0;
207 // m_default handles its own locking
208 Data *buf = m_default.wait_pop(timeout);
209 return DataHandle(*this, buf);
213 // RegisterInterest
215 /// Register an interest in data from a certain socket. To read
216 /// from that socket, use the SocketRead() function from then on.
218 /// Any non-registered socket goes in the default queue
219 /// and must be read by DefaultRead()
221 /// If not null, handler is called when new data is read. It will
222 /// be called in the same thread instance that DoRead() is called from.
223 /// Handler is passed the DataQueue Data pointer, and so no
224 /// copying is done. Once the handler returns, the data is
225 /// considered processed and not added to the interested queue,
226 /// but instead returned to m_free.
228 /// Throws std::logic_error if already registered.
230 void SocketRoutingQueue::RegisterInterest(SocketId socket,
231 SocketDataHandlerPtr handler)
233 // modifying our own std::map, need a lock
234 scoped_lock lock(m_mutex);
236 SocketQueueMap::iterator qi = m_socketQueues.find(socket);
237 if( qi != m_socketQueues.end() )
238 throw std::logic_error("RegisterInterest requesting a previously registered socket.");
240 m_socketQueues[socket] = QueueEntryPtr( new QueueEntry(handler) );
241 m_interest = true;
245 // UnregisterInterest
247 /// Unregisters interest in data from the given socket, and discards
248 /// any existing data in its interest queue. Any new incoming data
249 /// for this socket will be placed in the default queue.
251 void SocketRoutingQueue::UnregisterInterest(SocketId socket)
253 // modifying our own std::map, need a lock
254 scoped_lock lock(m_mutex);
256 SocketQueueMap::iterator qi = m_socketQueues.find(socket);
257 if( qi == m_socketQueues.end() )
258 return; // nothing registered, done
260 // salvage all our data buffers
261 m_free.append_from( qi->second->m_queue );
263 // remove the QueueEntryPtr from the map
264 m_socketQueues.erase( qi );
266 // check the interest flag
267 m_interest = m_socketQueues.size() > 0;
271 // SocketRead
273 /// Reads data from the interested socket cache. Can only read
274 /// from sockets that have been previously registered.
276 /// Blocks until timeout or data is available.
278 /// Returns false (or null pointer) on timeout and no data.
279 /// With the return version of the function, there is no
280 /// copying performed.
282 /// Throws std::logic_error if a socket was requested that was
283 /// not previously registered.
285 /// Copying is performed with this function.
287 bool SocketRoutingQueue::SocketRead(SocketId socket, Data &receive, int timeout)
289 DataHandle buf = SocketRead(socket, timeout);
290 if( !buf.get() )
291 return false;
293 // copy to desired buffer
294 receive = *buf.get();
295 return true;
299 /// Copying is not performed with this function.
301 /// Throws std::logic_error if a socket was requested that was
302 /// not previously registered.
304 DataHandle SocketRoutingQueue::SocketRead(SocketId socket, int timeout)
306 QueueEntryPtr qep;
307 DataQueue *dq = 0;
309 // accessing our own std::map, need a lock
311 scoped_lock lock(m_mutex);
312 SocketQueueMap::iterator qi = m_socketQueues.find(socket);
313 if( qi == m_socketQueues.end() )
314 throw std::logic_error("SocketRead requested data from unregistered socket.");
316 // got our queue, save the whole QueueEntryPtr (shared_ptr),
317 // and unlock, since we will be waiting on the DataQueue,
318 // not the socketQueues map
320 // This is safe, since even if UnregisterInterest is called,
321 // our pointer won't be deleted until our shared_ptr
322 // (QueueEntryPtr) goes out of scope.
324 // The remaining problem is that wait_pop() might wait
325 // forever if there is no timeout... c'est la vie.
326 // Should'a used a timeout. :-)
327 qep = qi->second;
328 dq = &qep->m_queue;
331 // get data from DataQueue
332 Data *buf = dq->wait_pop(timeout);
334 // specifically delete our copy of shared pointer, in a locked
335 // environment
337 scoped_lock lock(m_mutex);
338 qep.reset();
341 return DataHandle(*this, buf);
344 // Returns true if data is available for that socket.
345 bool SocketRoutingQueue::IsAvailable(SocketId socket) const
347 scoped_lock lock(m_mutex);
348 SocketQueueMap::const_iterator qi = m_socketQueues.find(socket);
349 if( qi == m_socketQueues.end() )
350 return false;
351 return qi->second->m_queue.size() > 0;
355 // DoRead
357 /// Called by the application's "read thread" to read the next usb
358 /// packet and route it to the correct queue. Returns after every
359 /// read, even if a handler is associated with a queue.
360 /// Note: this function is safe to call before SetUsbDevice() is
361 /// called... it just doesn't do anything if there is no usb
362 /// device to work with.
364 /// Timeout is in milliseconds.
365 void SocketRoutingQueue::DoRead(int timeout)
367 class ReadWaitSignal
369 pthread_mutex_t &m_Mutex;
370 pthread_cond_t &m_Cond;
371 public:
372 ReadWaitSignal(pthread_mutex_t &mut, pthread_cond_t &cond)
373 : m_Mutex(mut), m_Cond(cond)
375 ~ReadWaitSignal()
377 scoped_lock wait(m_Mutex);
378 pthread_cond_signal(&m_Cond);
380 } readwait(m_readwaitMutex, m_readwaitCond);
382 Usb::Device * volatile dev = 0;
383 int readEp;
384 DataHandle buf(*this, 0);
386 // if we are not connected to a USB device yet, just wait
388 scoped_lock lock(m_mutex);
390 if( !m_dev || m_seen_usb_error ) {
391 lock.unlock(); // unlock early, since we're sleeping
392 // sleep only a short time, since things could be
393 // in the process of setup or teardown
394 usleep(125000);
395 return;
398 dev = m_dev;
399 readEp = m_readEp;
401 // fetch a free buffer
402 Data *raw = m_free.pop();
403 if( !raw )
404 buf = DataHandle(*this, new Data);
405 else
406 buf = DataHandle(*this, raw);
409 // take a chance and do the read unlocked, as this has the potential
410 // for blocking for a while
411 try {
413 Data &data = *buf.get();
415 if( !dev->BulkRead(readEp, data, timeout) )
416 return; // no data, done!
418 MAKE_PACKET(pack, data);
420 // make sure the size is right
421 if( data.GetSize() < SB_PACKET_SOCKET_SIZE )
422 return; // bad size, just skip
424 // extract the socket from the packet
425 uint16_t socket = btohs(pack->socket);
427 // we have data, now lock up again to place it
428 // in the right queue
429 scoped_lock lock(m_mutex);
431 // search for registration of socket
432 if( m_interest ) {
433 SocketQueueMap::iterator qi = m_socketQueues.find(socket);
434 if( qi != m_socketQueues.end() ) {
435 SocketDataHandlerPtr &sdh = qi->second->m_handler;
437 // is there a handler?
438 if( sdh ) {
439 // unlock & let the handler process it
440 lock.unlock();
441 sdh->DataReceived(*buf.get());
442 return;
444 else {
445 qi->second->m_queue.push(buf.release());
446 return;
450 // fall through
453 // safe to unlock now, we are done with the map
454 lock.unlock();
456 // if we get here, send to default queue
457 m_default.push(buf.release());
459 catch( Usb::Timeout & ) {
460 // this is expected... just ignore
462 catch( Usb::Error &ue ) {
463 // set the flag first, in case any of the handlers
464 // are able to recover from this error
465 m_seen_usb_error = true;
467 // this is unexpected, but we're in a thread here...
468 // Need to iterate through all the registered handlers
469 // calling their error callback.
470 // Can't be locked when calling the callback, so need
471 // to make a list of them first.
472 scoped_lock lock(m_mutex);
473 std::vector<SocketDataHandlerPtr> handlers;
474 SocketQueueMap::iterator qi = m_socketQueues.begin();
475 while( qi != m_socketQueues.end() ) {
476 SocketDataHandlerPtr &sdh = qi->second->m_handler;
477 // is there a handler?
478 if( sdh ) {
479 handlers.push_back(sdh);
481 ++qi;
484 SocketDataHandlerPtr usb_error_handler = m_usb_error_dev_callback;
486 lock.unlock();
487 std::vector<SocketDataHandlerPtr>::iterator hi = handlers.begin();
488 while( hi != handlers.end() ) {
489 (*hi)->Error(ue);
490 ++hi;
493 // and finally, call the specific error callback if available
494 if( usb_error_handler.get() ) {
495 usb_error_handler->Error(ue);
500 void SocketRoutingQueue::SpinoffSimpleReadThread()
502 // signal that it's ok to run inside the thread
503 if( m_continue_reading )
504 return; // already running
505 m_continue_reading = true;
507 // Start USB read thread, to handle all routing
508 int ret = pthread_create(&m_usb_read_thread, NULL, &SimpleReadThread, this);
509 if( ret ) {
510 m_continue_reading = false;
511 throw Barry::ErrnoError("SocketRoutingQueue: Error creating USB read thread.", ret);
515 } // namespace Barry