ethertap.cc revision 12055:945e851d846b
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#include "dev/net/ethertap.hh"
36
37#if defined(__OpenBSD__) || defined(__APPLE__)
38#include <sys/param.h>
39
40#endif
41#include <netinet/in.h>
42#include <unistd.h>
43
44#include <deque>
45#include <string>
46
47#include "base/misc.hh"
48#include "base/pollevent.hh"
49#include "base/socket.hh"
50#include "base/trace.hh"
51#include "debug/Ethernet.hh"
52#include "debug/EthernetData.hh"
53#include "dev/net/etherdump.hh"
54#include "dev/net/etherint.hh"
55#include "dev/net/etherpkt.hh"
56
57using namespace std;
58
59class TapEvent : public PollEvent
60{
61  protected:
62    EtherTapBase *tap;
63
64  public:
65    TapEvent(EtherTapBase *_tap, int fd, int e)
66        : PollEvent(fd, e), tap(_tap) {}
67    virtual void process(int revent) { tap->recvReal(revent); }
68};
69
70EtherTapBase::EtherTapBase(const Params *p)
71    : EtherObject(p), buflen(p->bufsz), dump(p->dump), event(NULL),
72      interface(NULL), txEvent(this)
73{
74    buffer = new uint8_t[buflen];
75    interface = new EtherTapInt(name() + ".interface", this);
76}
77
78EtherTapBase::~EtherTapBase()
79{
80    delete buffer;
81    delete event;
82    delete interface;
83}
84
85void
86EtherTapBase::serialize(CheckpointOut &cp) const
87{
88    SERIALIZE_SCALAR(buflen);
89    uint8_t *buffer = (uint8_t *)this->buffer;
90    SERIALIZE_ARRAY(buffer, buflen);
91
92    bool tapevent_present = false;
93    if (event) {
94        tapevent_present = true;
95        SERIALIZE_SCALAR(tapevent_present);
96        event->serialize(cp);
97    } else {
98        SERIALIZE_SCALAR(tapevent_present);
99    }
100}
101
102void
103EtherTapBase::unserialize(CheckpointIn &cp)
104{
105    UNSERIALIZE_SCALAR(buflen);
106    uint8_t *buffer = (uint8_t *)this->buffer;
107    UNSERIALIZE_ARRAY(buffer, buflen);
108
109    bool tapevent_present;
110    UNSERIALIZE_SCALAR(tapevent_present);
111    if (tapevent_present) {
112        event = new TapEvent(this, 0, 0);
113        event->unserialize(cp);
114        if (event->queued())
115            pollQueue.schedule(event);
116    }
117}
118
119
120void
121EtherTapBase::pollFd(int fd)
122{
123    assert(!event);
124    event = new TapEvent(this, fd, POLLIN|POLLERR);
125    pollQueue.schedule(event);
126}
127
128void
129EtherTapBase::stopPolling()
130{
131    assert(event);
132    delete event;
133    event = NULL;
134}
135
136
137EtherInt*
138EtherTapBase::getEthPort(const std::string &if_name, int idx)
139{
140    if (if_name == "tap") {
141        if (interface->getPeer())
142            panic("Interface already connected to\n");
143        return interface;
144    }
145    return NULL;
146}
147
148bool
149EtherTapBase::recvSimulated(EthPacketPtr packet)
150{
151    if (dump)
152        dump->dump(packet);
153
154    DPRINTF(Ethernet, "EtherTap sim->real len=%d\n", packet->length);
155    DDUMP(EthernetData, packet->data, packet->length);
156
157    bool success = sendReal(packet->data, packet->length);
158
159    interface->recvDone();
160
161    return success;
162}
163
164void
165EtherTapBase::sendSimulated(void *data, size_t len)
166{
167    EthPacketPtr packet;
168    packet = make_shared<EthPacketData>(len);
169    packet->length = len;
170    packet->simLength = len;
171    memcpy(packet->data, data, len);
172
173    DPRINTF(Ethernet, "EtherTap real->sim len=%d\n", packet->length);
174    DDUMP(EthernetData, packet->data, packet->length);
175    if (!packetBuffer.empty() || !interface->sendPacket(packet)) {
176        DPRINTF(Ethernet, "bus busy...buffer for retransmission\n");
177        packetBuffer.push(packet);
178        if (!txEvent.scheduled())
179            schedule(txEvent, curTick() + retryTime);
180    } else if (dump) {
181        dump->dump(packet);
182    }
183}
184
185void
186EtherTapBase::retransmit()
187{
188    if (packetBuffer.empty())
189        return;
190
191    EthPacketPtr packet = packetBuffer.front();
192    if (interface->sendPacket(packet)) {
193        if (dump)
194            dump->dump(packet);
195        DPRINTF(Ethernet, "EtherTap retransmit\n");
196        packetBuffer.front() = NULL;
197        packetBuffer.pop();
198    }
199
200    if (!packetBuffer.empty() && !txEvent.scheduled())
201        schedule(txEvent, curTick() + retryTime);
202}
203
204
205class TapListener
206{
207  protected:
208    class Event : public PollEvent
209    {
210      protected:
211        TapListener *listener;
212
213      public:
214        Event(TapListener *l, int fd, int e) : PollEvent(fd, e), listener(l) {}
215
216        void process(int revent) override { listener->accept(); }
217    };
218
219    friend class Event;
220    Event *event;
221
222    void accept();
223
224  protected:
225    ListenSocket listener;
226    EtherTapStub *tap;
227    int port;
228
229  public:
230    TapListener(EtherTapStub *t, int p) : event(NULL), tap(t), port(p) {}
231    ~TapListener() { delete event; }
232
233    void listen();
234};
235
236void
237TapListener::listen()
238{
239    while (!listener.listen(port, true)) {
240        DPRINTF(Ethernet, "TapListener(listen): Can't bind port %d\n", port);
241        port++;
242    }
243
244    ccprintf(cerr, "Listening for tap connection on port %d\n", port);
245    event = new Event(this, listener.getfd(), POLLIN|POLLERR);
246    pollQueue.schedule(event);
247}
248
249void
250TapListener::accept()
251{
252    // As a consequence of being called from the PollQueue, we might
253    // have been called from a different thread. Migrate to "our"
254    // thread.
255    EventQueue::ScopedMigration migrate(tap->eventQueue());
256
257    if (!listener.islistening())
258        panic("TapListener(accept): cannot accept if we're not listening!");
259
260    int sfd = listener.accept(true);
261    if (sfd != -1)
262        tap->attach(sfd);
263}
264
265
266EtherTapStub::EtherTapStub(const Params *p) : EtherTapBase(p), socket(-1)
267{
268    if (ListenSocket::allDisabled())
269        fatal("All listeners are disabled! EtherTapStub can't work!");
270
271    listener = new TapListener(this, p->port);
272    listener->listen();
273}
274
275EtherTapStub::~EtherTapStub()
276{
277    delete listener;
278}
279
280void
281EtherTapStub::serialize(CheckpointOut &cp) const
282{
283    EtherTapBase::serialize(cp);
284
285    SERIALIZE_SCALAR(socket);
286    SERIALIZE_SCALAR(buffer_used);
287    SERIALIZE_SCALAR(frame_len);
288}
289
290void
291EtherTapStub::unserialize(CheckpointIn &cp)
292{
293    EtherTapBase::unserialize(cp);
294
295    UNSERIALIZE_SCALAR(socket);
296    UNSERIALIZE_SCALAR(buffer_used);
297    UNSERIALIZE_SCALAR(frame_len);
298}
299
300
301void
302EtherTapStub::attach(int fd)
303{
304    if (socket != -1)
305        close(fd);
306
307    buffer_used = 0;
308    frame_len = 0;
309    socket = fd;
310    DPRINTF(Ethernet, "EtherTapStub attached\n");
311    pollFd(socket);
312}
313
314void
315EtherTapStub::detach()
316{
317    DPRINTF(Ethernet, "EtherTapStub detached\n");
318    stopPolling();
319    close(socket);
320    socket = -1;
321}
322
323void
324EtherTapStub::recvReal(int revent)
325{
326    if (revent & POLLERR) {
327        detach();
328        return;
329    }
330
331    if (!(revent & POLLIN))
332        return;
333
334    // Read in as much of the new data as we can.
335    int len = read(socket, buffer + buffer_used, buflen - buffer_used);
336    if (len == 0) {
337        detach();
338        return;
339    }
340    buffer_used += len;
341
342    // If there's not enough data for the frame length, wait for more.
343    if (buffer_used < sizeof(uint32_t))
344        return;
345
346    if (frame_len == 0)
347        frame_len = ntohl(*(uint32_t *)buffer);
348
349    DPRINTF(Ethernet, "Received data from peer: len=%d buffer_used=%d "
350            "frame_len=%d\n", len, buffer_used, frame_len);
351
352    uint8_t *frame_start = &buffer[sizeof(uint32_t)];
353    while (frame_len != 0 && buffer_used >= frame_len + sizeof(uint32_t)) {
354        sendSimulated(frame_start, frame_len);
355
356        // Bookkeeping.
357        buffer_used -= frame_len + sizeof(uint32_t);
358        if (buffer_used > 0) {
359            // If there's still any data left, move it into position.
360            memmove(buffer, frame_start + frame_len, buffer_used);
361        }
362        frame_len = 0;
363
364        if (buffer_used >= sizeof(uint32_t))
365            frame_len = ntohl(*(uint32_t *)buffer);
366    }
367}
368
369bool
370EtherTapStub::sendReal(const void *data, size_t len)
371{
372    uint32_t frame_len = htonl(len);
373    ssize_t ret = write(socket, &frame_len, sizeof(frame_len));
374    if (ret != sizeof(frame_len))
375        return false;
376    return write(socket, data, len) == len;
377}
378
379
380EtherTapStub *
381EtherTapStubParams::create()
382{
383    return new EtherTapStub(this);
384}
385