Statistics
| Branch: | Tag: | Revision:

root / host / lib / usrp / usrp2 / io_impl.cpp @ 0946176f

History | View | Annotate | Download (19 KB)

1
//
2
// Copyright 2010-2011 Ettus Research LLC
3
//
4
// This program is free software: you can redistribute it and/or modify
5
// it under the terms of the GNU General Public License as published by
6
// the Free Software Foundation, either version 3 of the License, or
7
// (at your option) any later version.
8
//
9
// This program is distributed in the hope that it will be useful,
10
// but WITHOUT ANY WARRANTY; without even the implied warranty of
11
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
// GNU General Public License for more details.
13
//
14
// You should have received a copy of the GNU General Public License
15
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
16
//
17

    
18
#include "validate_subdev_spec.hpp"
19
#include "../../transport/super_recv_packet_handler.hpp"
20
#include "../../transport/super_send_packet_handler.hpp"
21
#include "usrp2_impl.hpp"
22
#include "usrp2_regs.hpp"
23
#include <uhd/utils/log.hpp>
24
#include <uhd/utils/msg.hpp>
25
#include <uhd/utils/tasks.hpp>
26
#include <uhd/exception.hpp>
27
#include <uhd/utils/byteswap.hpp>
28
#include <uhd/utils/thread_priority.hpp>
29
#include <uhd/transport/bounded_buffer.hpp>
30
#include <boost/thread/thread.hpp>
31
#include <boost/format.hpp>
32
#include <boost/bind.hpp>
33
#include <boost/thread/mutex.hpp>
34
#include <boost/make_shared.hpp>
35
#include <iostream>
36

    
37
using namespace uhd;
38
using namespace uhd::usrp;
39
using namespace uhd::transport;
40
namespace asio = boost::asio;
41
namespace pt = boost::posix_time;
42

    
43
/***********************************************************************
44
 * helpers
45
 **********************************************************************/
46
static UHD_INLINE pt::time_duration to_time_dur(double timeout){
47
    return pt::microseconds(long(timeout*1e6));
48
}
49

    
50
static UHD_INLINE double from_time_dur(const pt::time_duration &time_dur){
51
    return 1e-6*time_dur.total_microseconds();
52
}
53

    
54
/***********************************************************************
55
 * constants
56
 **********************************************************************/
57
static const size_t vrt_send_header_offset_words32 = 1;
58

    
59
/***********************************************************************
60
 * flow control monitor for a single tx channel
61
 *  - the pirate thread calls update
62
 *  - the get send buffer calls check
63
 **********************************************************************/
64
class flow_control_monitor{
65
public:
66
    typedef boost::uint32_t seq_type;
67
    typedef boost::shared_ptr<flow_control_monitor> sptr;
68

    
69
    /*!
70
     * Make a new flow control monitor.
71
     * \param max_seqs_out num seqs before throttling
72
     */
73
    flow_control_monitor(seq_type max_seqs_out){
74
        _last_seq_out = 0;
75
        _last_seq_ack = 0;
76
        _max_seqs_out = max_seqs_out;
77
        _ready_fcn = boost::bind(&flow_control_monitor::ready, this);
78
    }
79

    
80
    /*!
81
     * Gets the current sequence number to go out.
82
     * Increments the sequence for the next call
83
     * \return the sequence to be sent to the dsp
84
     */
85
    UHD_INLINE seq_type get_curr_seq_out(void){
86
        return _last_seq_out++;
87
    }
88

    
89
    /*!
90
     * Check the flow control condition.
91
     * \param timeout the timeout in seconds
92
     * \return false on timeout
93
     */
94
    UHD_INLINE bool check_fc_condition(double timeout){
95
        boost::mutex::scoped_lock lock(_fc_mutex);
96
        if (this->ready()) return true;
97
        boost::this_thread::disable_interruption di; //disable because the wait can throw
98
        return _fc_cond.timed_wait(lock, to_time_dur(timeout), _ready_fcn);
99
    }
100

    
101
    /*!
102
     * Update the flow control condition.
103
     * \param seq the last sequence number to be ACK'd
104
     */
105
    UHD_INLINE void update_fc_condition(seq_type seq){
106
        boost::mutex::scoped_lock lock(_fc_mutex);
107
        _last_seq_ack = seq;
108
        lock.unlock();
109
        _fc_cond.notify_one();
110
    }
111

    
112
private:
113
    bool ready(void){
114
        return seq_type(_last_seq_out -_last_seq_ack) < _max_seqs_out;
115
    }
116

    
117
    boost::mutex _fc_mutex;
118
    boost::condition _fc_cond;
119
    seq_type _last_seq_out, _last_seq_ack, _max_seqs_out;
120
    boost::function<bool(void)> _ready_fcn;
121
};
122

    
123
/***********************************************************************
124
 * io impl details (internal to this file)
125
 * - pirate crew
126
 * - alignment buffer
127
 * - thread loop
128
 * - vrt packet handler states
129
 **********************************************************************/
130
struct usrp2_impl::io_impl{
131

    
132
    io_impl(void):
133
        async_msg_fifo(100/*messages deep*/)
134
    {
135
        /* NOP */
136
    }
137

    
138
    ~io_impl(void){
139
        //Manually deconstuct the tasks, since this was not happening automatically.
140
        pirate_tasks.clear();
141
    }
142

    
143
    managed_send_buffer::sptr get_send_buff(size_t chan, double timeout){
144
        flow_control_monitor &fc_mon = *fc_mons[chan];
145

    
146
        //wait on flow control w/ timeout
147
        if (not fc_mon.check_fc_condition(timeout)) return managed_send_buffer::sptr();
148

    
149
        //get a buffer from the transport w/ timeout
150
        managed_send_buffer::sptr buff = tx_xports[chan]->get_send_buff(timeout);
151

    
152
        //write the flow control word into the buffer
153
        if (buff.get()) buff->cast<boost::uint32_t *>()[0] = uhd::htonx(fc_mon.get_curr_seq_out());
154

    
155
        return buff;
156
    }
157

    
158
    //tx dsp: xports and flow control monitors
159
    std::vector<zero_copy_if::sptr> tx_xports;
160
    std::vector<flow_control_monitor::sptr> fc_mons;
161

    
162
    //methods and variables for the pirate crew
163
    void recv_pirate_loop(zero_copy_if::sptr, size_t);
164
    std::list<task::sptr> pirate_tasks;
165
    bounded_buffer<async_metadata_t> async_msg_fifo;
166
    double tick_rate;
167
};
168

    
169
/***********************************************************************
170
 * Receive Pirate Loop
171
 * - while raiding, loot for message packet
172
 * - update flow control condition count
173
 * - put async message packets into queue
174
 **********************************************************************/
175
void usrp2_impl::io_impl::recv_pirate_loop(
176
    zero_copy_if::sptr err_xport, size_t index
177
){
178
    set_thread_priority_safe();
179

    
180
    //store a reference to the flow control monitor (offset by max dsps)
181
    flow_control_monitor &fc_mon = *(this->fc_mons[index]);
182

    
183
    while (not boost::this_thread::interruption_requested()){
184
        managed_recv_buffer::sptr buff = err_xport->get_recv_buff();
185
        if (not buff.get()) continue; //ignore timeout/error buffers
186

    
187
        try{
188
            //extract the vrt header packet info
189
            vrt::if_packet_info_t if_packet_info;
190
            if_packet_info.num_packet_words32 = buff->size()/sizeof(boost::uint32_t);
191
            const boost::uint32_t *vrt_hdr = buff->cast<const boost::uint32_t *>();
192
            vrt::if_hdr_unpack_be(vrt_hdr, if_packet_info);
193

    
194
            //handle a tx async report message
195
            if (if_packet_info.sid == USRP2_TX_ASYNC_SID and if_packet_info.packet_type != vrt::if_packet_info_t::PACKET_TYPE_DATA){
196

    
197
                //fill in the async metadata
198
                async_metadata_t metadata;
199
                metadata.channel = index;
200
                metadata.has_time_spec = if_packet_info.has_tsi and if_packet_info.has_tsf;
201
                metadata.time_spec = time_spec_t(
202
                    time_t(if_packet_info.tsi), size_t(if_packet_info.tsf), tick_rate
203
                );
204
                metadata.event_code = async_metadata_t::event_code_t(sph::get_context_code(vrt_hdr, if_packet_info));
205

    
206
                //catch the flow control packets and react
207
                if (metadata.event_code == 0){
208
                    boost::uint32_t fc_word32 = (vrt_hdr + if_packet_info.num_header_words32)[1];
209
                    fc_mon.update_fc_condition(uhd::ntohx(fc_word32));
210
                    continue;
211
                }
212
                //else UHD_MSG(often) << "metadata.event_code " << metadata.event_code << std::endl;
213
                async_msg_fifo.push_with_pop_on_full(metadata);
214

    
215
                if (metadata.event_code &
216
                    ( async_metadata_t::EVENT_CODE_UNDERFLOW
217
                    | async_metadata_t::EVENT_CODE_UNDERFLOW_IN_PACKET)
218
                ) UHD_MSG(fastpath) << "U";
219
                else if (metadata.event_code &
220
                    ( async_metadata_t::EVENT_CODE_SEQ_ERROR
221
                    | async_metadata_t::EVENT_CODE_SEQ_ERROR_IN_BURST)
222
                ) UHD_MSG(fastpath) << "S";
223
            }
224
            else{
225
                //TODO unknown received packet, may want to print error...
226
            }
227
        }catch(const std::exception &e){
228
            UHD_MSG(error) << "Error in recv pirate loop: " << e.what() << std::endl;
229
        }
230
    }
231
}
232

    
233
/***********************************************************************
234
 * Helper Functions
235
 **********************************************************************/
236
void usrp2_impl::io_init(void){
237
    //create new io impl
238
    _io_impl = UHD_PIMPL_MAKE(io_impl, ());
239

    
240
    //init first so we dont have an access race
241
    BOOST_FOREACH(const std::string &mb, _mbc.keys()){
242
        //init the tx xport and flow control monitor
243
        _io_impl->tx_xports.push_back(_mbc[mb].tx_dsp_xport);
244
        _io_impl->fc_mons.push_back(flow_control_monitor::sptr(new flow_control_monitor(
245
            USRP2_SRAM_BYTES/_mbc[mb].tx_dsp_xport->get_send_frame_size()
246
        )));
247
    }
248

    
249
    //allocate streamer weak ptrs containers
250
    BOOST_FOREACH(const std::string &mb, _mbc.keys()){
251
        _mbc[mb].rx_streamers.resize(_mbc[mb].rx_dsps.size());
252
        _mbc[mb].tx_streamers.resize(1/*known to be 1 dsp*/);
253
    }
254

    
255
    //create a new pirate thread for each zc if (yarr!!)
256
    size_t index = 0;
257
    BOOST_FOREACH(const std::string &mb, _mbc.keys()){
258
        //spawn a new pirate to plunder the recv booty
259
        _io_impl->pirate_tasks.push_back(task::make(boost::bind(
260
            &usrp2_impl::io_impl::recv_pirate_loop, _io_impl.get(),
261
            _mbc[mb].tx_dsp_xport, index++
262
        )));
263
    }
264
}
265

    
266
void usrp2_impl::update_tick_rate(const double rate){
267
    _io_impl->tick_rate = rate; //shadow for async msg
268

    
269
    //update the tick rate on all existing streamers -> thread safe
270
    BOOST_FOREACH(const std::string &mb, _mbc.keys()){
271
        for (size_t i = 0; i < _mbc[mb].rx_streamers.size(); i++){
272
            boost::shared_ptr<sph::recv_packet_streamer> my_streamer =
273
                boost::dynamic_pointer_cast<sph::recv_packet_streamer>(_mbc[mb].rx_streamers[i].lock());
274
            if (my_streamer.get() == NULL) continue;
275
            my_streamer->set_tick_rate(rate);
276
        }
277
        for (size_t i = 0; i < _mbc[mb].tx_streamers.size(); i++){
278
            boost::shared_ptr<sph::send_packet_streamer> my_streamer =
279
                boost::dynamic_pointer_cast<sph::send_packet_streamer>(_mbc[mb].tx_streamers[i].lock());
280
            if (my_streamer.get() == NULL) continue;
281
            my_streamer->set_tick_rate(rate);
282
        }
283
    }
284
}
285

    
286
void usrp2_impl::update_rx_samp_rate(const std::string &mb, const size_t dsp, const double rate){
287
    boost::shared_ptr<sph::recv_packet_streamer> my_streamer =
288
        boost::dynamic_pointer_cast<sph::recv_packet_streamer>(_mbc[mb].rx_streamers[dsp].lock());
289
    if (my_streamer.get() == NULL) return;
290

    
291
    my_streamer->set_samp_rate(rate);
292
    const double adj = _mbc[mb].rx_dsps[dsp]->get_scaling_adjustment();
293
    my_streamer->set_scale_factor(adj);
294
}
295

    
296
void usrp2_impl::update_tx_samp_rate(const std::string &mb, const size_t dsp, const double rate){
297
    boost::shared_ptr<sph::send_packet_streamer> my_streamer =
298
        boost::dynamic_pointer_cast<sph::send_packet_streamer>(_mbc[mb].tx_streamers[dsp].lock());
299
    if (my_streamer.get() == NULL) return;
300

    
301
    my_streamer->set_samp_rate(rate);
302
}
303

    
304
void usrp2_impl::update_rates(void){
305
    BOOST_FOREACH(const std::string &mb, _mbc.keys()){
306
        fs_path root = "/mboards/" + mb;
307
        _tree->access<double>(root / "tick_rate").update();
308

    
309
        //and now that the tick rate is set, init the host rates to something
310
        BOOST_FOREACH(const std::string &name, _tree->list(root / "rx_dsps")){
311
            _tree->access<double>(root / "rx_dsps" / name / "rate" / "value").update();
312
        }
313
        BOOST_FOREACH(const std::string &name, _tree->list(root / "tx_dsps")){
314
            _tree->access<double>(root / "tx_dsps" / name / "rate" / "value").update();
315
        }
316
    }
317
}
318

    
319
void usrp2_impl::update_rx_subdev_spec(const std::string &which_mb, const subdev_spec_t &spec){
320
    fs_path root = "/mboards/" + which_mb + "/dboards";
321

    
322
    //sanity checking
323
    validate_subdev_spec(_tree, spec, "rx", which_mb);
324

    
325
    //setup mux for this spec
326
    bool fe_swapped = false;
327
    for (size_t i = 0; i < spec.size(); i++){
328
        const std::string conn = _tree->access<std::string>(root / spec[i].db_name / "rx_frontends" / spec[i].sd_name / "connection").get();
329
        if (i == 0 and (conn == "QI" or conn == "Q")) fe_swapped = true;
330
        _mbc[which_mb].rx_dsps[i]->set_mux(conn, fe_swapped);
331
    }
332
    _mbc[which_mb].rx_fe->set_mux(fe_swapped);
333

    
334
    //compute the new occupancy and resize
335
    _mbc[which_mb].rx_chan_occ = spec.size();
336
    size_t nchan = 0;
337
    BOOST_FOREACH(const std::string &mb, _mbc.keys()) nchan += _mbc[mb].rx_chan_occ;
338
}
339

    
340
void usrp2_impl::update_tx_subdev_spec(const std::string &which_mb, const subdev_spec_t &spec){
341
    fs_path root = "/mboards/" + which_mb + "/dboards";
342

    
343
    //sanity checking
344
    validate_subdev_spec(_tree, spec, "tx", which_mb);
345

    
346
    //set the mux for this spec
347
    const std::string conn = _tree->access<std::string>(root / spec[0].db_name / "tx_frontends" / spec[0].sd_name / "connection").get();
348
    _mbc[which_mb].tx_fe->set_mux(conn);
349

    
350
    //compute the new occupancy and resize
351
    _mbc[which_mb].tx_chan_occ = spec.size();
352
    size_t nchan = 0;
353
    BOOST_FOREACH(const std::string &mb, _mbc.keys()) nchan += _mbc[mb].tx_chan_occ;
354
}
355

    
356
/***********************************************************************
357
 * Async Data
358
 **********************************************************************/
359
bool usrp2_impl::recv_async_msg(
360
    async_metadata_t &async_metadata, double timeout
361
){
362
    boost::this_thread::disable_interruption di; //disable because the wait can throw
363
    return _io_impl->async_msg_fifo.pop_with_timed_wait(async_metadata, timeout);
364
}
365

    
366
/***********************************************************************
367
 * Receive streamer
368
 **********************************************************************/
369
rx_streamer::sptr usrp2_impl::get_rx_stream(const uhd::stream_args_t &args_){
370
    stream_args_t args = args_;
371

    
372
    //setup defaults for unspecified values
373
    args.otw_format = args.otw_format.empty()? "sc16" : args.otw_format;
374
    args.channels = args.channels.empty()? std::vector<size_t>(1, 0) : args.channels;
375

    
376
    //calculate packet size
377
    static const size_t hdr_size = 0
378
        + vrt::max_if_hdr_words32*sizeof(boost::uint32_t)
379
        + sizeof(vrt::if_packet_info_t().tlr) //forced to have trailer
380
        - sizeof(vrt::if_packet_info_t().cid) //no class id ever used
381
    ;
382
    const size_t bpp = _mbc[_mbc.keys().front()].rx_dsp_xports[0]->get_recv_frame_size() - hdr_size;
383
    const size_t spp = bpp/convert::get_bytes_per_item(args.otw_format);
384

    
385
    //make the new streamer given the samples per packet
386
    boost::shared_ptr<sph::recv_packet_streamer> my_streamer = boost::make_shared<sph::recv_packet_streamer>(spp);
387

    
388
    //init some streamer stuff
389
    my_streamer->resize(args.channels.size());
390
    my_streamer->set_vrt_unpacker(&vrt::if_hdr_unpack_be);
391

    
392
    //set the converter
393
    uhd::convert::id_type id;
394
    id.input_markup = args.otw_format + "_item32_be";
395
    id.num_inputs = 1;
396
    id.output_markup = args.cpu_format;
397
    id.num_outputs = 1;
398
    id.args = args.args;
399
    my_streamer->set_converter(id);
400

    
401
    //bind callbacks for the handler
402
    for (size_t chan_i = 0; chan_i < args.channels.size(); chan_i++){
403
        const size_t chan = args.channels[chan_i];
404
        size_t num_chan_so_far = 0;
405
        BOOST_FOREACH(const std::string &mb, _mbc.keys()){
406
            num_chan_so_far += _mbc[mb].rx_chan_occ;
407
            if (chan < num_chan_so_far){
408
                const size_t dsp = num_chan_so_far - chan - 1;
409
                _mbc[mb].rx_dsps[dsp]->set_nsamps_per_packet(spp); //seems to be a good place to set this
410
                _mbc[mb].rx_dsps[dsp]->set_format(args.otw_format, 0x400);
411
                my_streamer->set_xport_chan_get_buff(chan_i, boost::bind(
412
                    &zero_copy_if::get_recv_buff, _mbc[mb].rx_dsp_xports[dsp], _1
413
                ));
414
                _mbc[mb].rx_streamers[dsp] = my_streamer; //store weak pointer
415
                break;
416
            }
417
        }
418
    }
419

    
420
    //set the packet threshold to be an entire socket buffer's worth
421
    const size_t packets_per_sock_buff = size_t(50e6/_mbc[_mbc.keys().front()].rx_dsp_xports[0]->get_recv_frame_size());
422
    my_streamer->set_alignment_failure_threshold(packets_per_sock_buff);
423

    
424
    //sets all tick and samp rates on this streamer
425
    this->update_rates();
426

    
427
    return my_streamer;
428
}
429

    
430
/***********************************************************************
431
 * Transmit streamer
432
 **********************************************************************/
433
tx_streamer::sptr usrp2_impl::get_tx_stream(const uhd::stream_args_t &args_){
434
    stream_args_t args = args_;
435

    
436
    //setup defaults for unspecified values
437
    args.otw_format = args.otw_format.empty()? "sc16" : args.otw_format;
438
    args.channels = args.channels.empty()? std::vector<size_t>(1, 0) : args.channels;
439

    
440
    if (args.otw_format != "sc16"){
441
        throw uhd::value_error("USRP TX cannot handle requested wire format: " + args.otw_format);
442
    }
443

    
444
    //calculate packet size
445
    static const size_t hdr_size = 0
446
        + vrt::max_if_hdr_words32*sizeof(boost::uint32_t)
447
        + vrt_send_header_offset_words32*sizeof(boost::uint32_t)
448
        - sizeof(vrt::if_packet_info_t().cid) //no class id ever used
449
    ;
450
    const size_t bpp = _mbc[_mbc.keys().front()].tx_dsp_xport->get_send_frame_size() - hdr_size;
451
    const size_t spp = bpp/convert::get_bytes_per_item(args.otw_format);
452

    
453
    //make the new streamer given the samples per packet
454
    boost::shared_ptr<sph::send_packet_streamer> my_streamer = boost::make_shared<sph::send_packet_streamer>(spp);
455

    
456
    //init some streamer stuff
457
    my_streamer->resize(args.channels.size());
458
    my_streamer->set_vrt_packer(&vrt::if_hdr_pack_be, vrt_send_header_offset_words32);
459

    
460
    //set the converter
461
    uhd::convert::id_type id;
462
    id.input_markup = args.cpu_format;
463
    id.num_inputs = 1;
464
    id.output_markup = args.otw_format + "_item32_be";
465
    id.num_outputs = 1;
466
    id.args = args.args;
467
    my_streamer->set_converter(id);
468

    
469
    //bind callbacks for the handler
470
    for (size_t chan_i = 0; chan_i < args.channels.size(); chan_i++){
471
        const size_t chan = args.channels[chan_i];
472
        size_t num_chan_so_far = 0;
473
        size_t abs = 0;
474
        BOOST_FOREACH(const std::string &mb, _mbc.keys()){
475
            num_chan_so_far += _mbc[mb].tx_chan_occ;
476
            if (chan < num_chan_so_far){
477
                const size_t dsp = num_chan_so_far - chan - 1;
478
                my_streamer->set_xport_chan_get_buff(chan_i, boost::bind(
479
                    &usrp2_impl::io_impl::get_send_buff, _io_impl.get(), abs, _1
480
                ));
481
                _mbc[mb].tx_streamers[dsp] = my_streamer; //store weak pointer
482
                break;
483
            }
484
            abs += 1; //assume 1 tx dsp
485
        }
486
    }
487

    
488
    //sets all tick and samp rates on this streamer
489
    this->update_rates();
490

    
491
    return my_streamer;
492
}