ethertap.cc revision 4981
1/*
2 * Copyright (c) 2003-2005 The Regents of The University of Michigan
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are
7 * met: redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer;
9 * redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution;
12 * neither the name of the copyright holders nor the names of its
13 * contributors may be used to endorse or promote products derived from
14 * this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 *
28 * Authors: Nathan Binkert
29 */
30
31/* @file
32 * Interface to connect a simulated ethernet device to the real world
33 */
34
35#if defined(__OpenBSD__) || defined(__APPLE__)
36#include <sys/param.h>
37#endif
38#include <netinet/in.h>
39
40#include <unistd.h>
41
42#include <deque>
43#include <string>
44
45#include "base/misc.hh"
46#include "base/pollevent.hh"
47#include "base/socket.hh"
48#include "base/trace.hh"
49#include "dev/etherdump.hh"
50#include "dev/etherint.hh"
51#include "dev/etherpkt.hh"
52#include "dev/ethertap.hh"
53
54using namespace std;
55
56/**
57 */
58class TapListener
59{
60  protected:
61    /**
62     */
63    class Event : public PollEvent
64    {
65      protected:
66        TapListener *listener;
67
68      public:
69        Event(TapListener *l, int fd, int e)
70            : PollEvent(fd, e), listener(l) {}
71
72        virtual void process(int revent) { listener->accept(); }
73    };
74
75    friend class Event;
76    Event *event;
77
78  protected:
79    ListenSocket listener;
80    EtherTap *tap;
81    int port;
82
83  public:
84    TapListener(EtherTap *t, int p)
85        : event(NULL), tap(t), port(p) {}
86    ~TapListener() { if (event) delete event; }
87
88    void accept();
89    void listen();
90};
91
92void
93TapListener::listen()
94{
95    while (!listener.listen(port, true)) {
96        DPRINTF(Ethernet, "TapListener(listen): Can't bind port %d\n", port);
97        port++;
98    }
99
100    ccprintf(cerr, "Listening for tap connection on port %d\n", port);
101    event = new Event(this, listener.getfd(), POLLIN|POLLERR);
102    pollQueue.schedule(event);
103}
104
105void
106TapListener::accept()
107{
108    if (!listener.islistening())
109        panic("TapListener(accept): cannot accept if we're not listening!");
110
111    int sfd = listener.accept(true);
112    if (sfd != -1)
113        tap->attach(sfd);
114}
115
116/**
117 */
118class TapEvent : public PollEvent
119{
120  protected:
121    EtherTap *tap;
122
123  public:
124    TapEvent(EtherTap *_tap, int fd, int e)
125        : PollEvent(fd, e), tap(_tap) {}
126    virtual void process(int revent) { tap->process(revent); }
127};
128
129EtherTap::EtherTap(const Params *p)
130    : EtherObject(p), event(NULL), socket(-1), buflen(p->bufsz), dump(p->dump),
131      interface(NULL), txEvent(this)
132{
133    buffer = new char[buflen];
134    listener = new TapListener(this, p->port);
135    listener->listen();
136    interface = new EtherTapInt(name() + ".interface", this);
137}
138
139EtherTap::~EtherTap()
140{
141    if (event)
142        delete event;
143    if (buffer)
144        delete [] buffer;
145
146    delete listener;
147}
148
149void
150EtherTap::attach(int fd)
151{
152    if (socket != -1)
153        close(fd);
154
155    buffer_offset = 0;
156    data_len = 0;
157    socket = fd;
158    DPRINTF(Ethernet, "EtherTap attached\n");
159    event = new TapEvent(this, socket, POLLIN|POLLERR);
160    pollQueue.schedule(event);
161}
162
163void
164EtherTap::detach()
165{
166    DPRINTF(Ethernet, "EtherTap detached\n");
167    delete event;
168    event = 0;
169    close(socket);
170    socket = -1;
171}
172
173bool
174EtherTap::recvPacket(EthPacketPtr packet)
175{
176    if (dump)
177        dump->dump(packet);
178
179    DPRINTF(Ethernet, "EtherTap output len=%d\n", packet->length);
180    DDUMP(EthernetData, packet->data, packet->length);
181    uint32_t len = htonl(packet->length);
182    write(socket, &len, sizeof(len));
183    write(socket, packet->data, packet->length);
184
185    interface->recvDone();
186
187    return true;
188}
189
190void
191EtherTap::sendDone()
192{}
193
194void
195EtherTap::process(int revent)
196{
197    if (revent & POLLERR) {
198        detach();
199        return;
200    }
201
202    char *data = buffer + sizeof(uint32_t);
203    if (!(revent & POLLIN))
204        return;
205
206    if (buffer_offset < data_len + sizeof(uint32_t)) {
207        int len = read(socket, buffer + buffer_offset, buflen - buffer_offset);
208        if (len == 0) {
209            detach();
210            return;
211        }
212
213        buffer_offset += len;
214
215        if (data_len == 0)
216            data_len = ntohl(*(uint32_t *)buffer);
217
218        DPRINTF(Ethernet, "Received data from peer: len=%d buffer_offset=%d "
219                "data_len=%d\n", len, buffer_offset, data_len);
220    }
221
222    while (data_len != 0 && buffer_offset >= data_len + sizeof(uint32_t)) {
223        EthPacketPtr packet;
224        packet = new EthPacketData(data_len);
225        packet->length = data_len;
226        memcpy(packet->data, data, data_len);
227
228        buffer_offset -= data_len + sizeof(uint32_t);
229        assert(buffer_offset >= 0);
230        if (buffer_offset > 0) {
231            memmove(buffer, data + data_len, buffer_offset);
232            data_len = ntohl(*(uint32_t *)buffer);
233        } else
234            data_len = 0;
235
236        DPRINTF(Ethernet, "EtherTap input len=%d\n", packet->length);
237        DDUMP(EthernetData, packet->data, packet->length);
238        if (!interface->sendPacket(packet)) {
239            DPRINTF(Ethernet, "bus busy...buffer for retransmission\n");
240            packetBuffer.push(packet);
241            if (!txEvent.scheduled())
242                txEvent.schedule(curTick + retryTime);
243        } else if (dump) {
244            dump->dump(packet);
245        }
246    }
247}
248
249void
250EtherTap::retransmit()
251{
252    if (packetBuffer.empty())
253        return;
254
255    EthPacketPtr packet = packetBuffer.front();
256    if (interface->sendPacket(packet)) {
257        if (dump)
258            dump->dump(packet);
259        DPRINTF(Ethernet, "EtherTap retransmit\n");
260        packetBuffer.front() = NULL;
261        packetBuffer.pop();
262    }
263
264    if (!packetBuffer.empty() && !txEvent.scheduled())
265        txEvent.schedule(curTick + retryTime);
266}
267
268EtherInt*
269EtherTap::getEthPort(const std::string &if_name, int idx)
270{
271    if (if_name == "tap") {
272        if (interface->getPeer())
273            panic("Interface already connected to\n");
274        return interface;
275    }
276    return NULL;
277}
278
279
280//=====================================================================
281
282void
283EtherTap::serialize(ostream &os)
284{
285    SERIALIZE_SCALAR(socket);
286    SERIALIZE_SCALAR(buflen);
287    uint8_t *buffer = (uint8_t *)this->buffer;
288    SERIALIZE_ARRAY(buffer, buflen);
289    SERIALIZE_SCALAR(buffer_offset);
290    SERIALIZE_SCALAR(data_len);
291
292    bool tapevent_present = false;
293    if (event) {
294        tapevent_present = true;
295        SERIALIZE_SCALAR(tapevent_present);
296        event->serialize(os);
297    }
298    else {
299        SERIALIZE_SCALAR(tapevent_present);
300    }
301}
302
303void
304EtherTap::unserialize(Checkpoint *cp, const std::string &section)
305{
306    UNSERIALIZE_SCALAR(socket);
307    UNSERIALIZE_SCALAR(buflen);
308    uint8_t *buffer = (uint8_t *)this->buffer;
309    UNSERIALIZE_ARRAY(buffer, buflen);
310    UNSERIALIZE_SCALAR(buffer_offset);
311    UNSERIALIZE_SCALAR(data_len);
312
313    bool tapevent_present;
314    UNSERIALIZE_SCALAR(tapevent_present);
315    if (tapevent_present) {
316        event = new TapEvent(this, socket, POLLIN|POLLERR);
317
318        event->unserialize(cp,section);
319
320        if (event->queued()) {
321            pollQueue.schedule(event);
322        }
323    }
324}
325
326//=====================================================================
327
328EtherTap *
329EtherTapParams::create()
330{
331    return new EtherTap(this);
332}
333