OpenCores
URL https://opencores.org/ocsvn/fade_ether_protocol/fade_ether_protocol/trunk

Subversion Repositories fade_ether_protocol

[/] [fade_ether_protocol/] [trunk/] [stable_jumbo_frames_version/] [linux/] [fpga_l3_fade.c] - Blame information for rev 47

Go to most recent revision | Details | Compare with Previous | View Log

Line No. Rev Author Line
1 15 wzab
/*
2
 * fpga_l3_fade - driver for L3 communication protocol with FPGA based system
3
 * Copyright (C) 2012 by Wojciech M. Zabolotny
4
 * Institute of Electronic Systems, Warsaw University of Technology
5
 *
6
 *  This program is free software; you can redistribute it and/or modify
7
 *  it under the terms of the GNU General Public License as published by
8
 *  the Free Software Foundation; either version 2 of the License, or
9
 *  (at your option) any later version.
10
 *
11
 *  This program is distributed in the hope that it will be useful,
12
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
 *  GNU General Public License for more details.
15
 *
16
 *  You should have received a copy of the GNU General Public License
17
 *  along with this program; if not, write to the Free Software
18
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19
 */
20
 
21
#include <linux/module.h>
22
#include <linux/kernel.h>
23 47 wzab
#include <linux/sched.h>
24 15 wzab
#include <asm/uaccess.h>
25
 
26
MODULE_LICENSE("GPL v2");
27
//#define FADE_DEBUG 1
28
#include <linux/device.h>
29
#include <linux/netdevice.h>
30
#include <linux/fs.h>
31
#include <linux/cdev.h>
32
#include <linux/poll.h>
33
#include <linux/mm.h>
34
#include <asm/io.h>
35
#include <linux/wait.h>
36
#include <linux/sched.h>
37
#include <asm/uaccess.h>  /* for put_user */
38
#include <linux/mutex.h>
39
 
40
#include "fpga_l3_fade.h"
41
 
42
#define SUCCESS 0
43
#define DEVICE_NAME "fpga_l3_fade"
44
 
45
 
46
/* Length of the user header in the packet
47
 * The following fields are BEFORE the user header
48
 * SRC+TGT - 12 bytes : source & destination
49
 * 0xFADE - 2 bytes : protocol ID
50
 *
51
 * Fields which belong to the user header:
52
 * 0x0100 - 2 bytes : protocol version - offset 0
53
 * For DATA - to PC
54
 * 0xA5A5 - 2 bytes : data ID 0 - offset 2
55
 * retry number - 2 bytes - offset 4
56
 * packet number - 4 bytes - offset 6
57
 * transm_delay - 4 bytes - offset 10
58
 * cmd_response - 12 bytes - offset 14
59
 *
60
 * Total: 26 bytes!
61 18 wzab
 * If the packet contains "flushed" buffer,
62
 * then data ID is 0xA5A6, and the last word
63
 * contains number of transmitted words.
64 15 wzab
 
65
 * For command response
66
 * 0xA55A : cmd_resp ID 2 bytes - offset 2
67
 * 0x0000 : filler - 2 bytes - offset 4
68
 * cmd_response - 12 bytes offset 6
69
 */
70
#define USER_HDR_LEN 26
71
 
72
/* Number of bytes of user data in a packet */
73
#define LOG2_USER_LEN 13
74
#define USER_LEN (1<<LOG2_USER_LEN) 
75
#define PAYL_LEN ( USER_HDR_LEN + USER_LEN )
76
 
77
/* Number of packets in window - this number depends on amount of RAM
78
 * in the FPGA - Packets in a widnow must fit in the FPGA RAM
79
 * Should be power of two! */
80 18 wzab
#define PKTS_IN_WINDOW (1<<4)
81 15 wzab
#define PKTS_IN_WINDOW_MASK (PKTS_IN_WINDOW-1)
82
 
83
/* Capacity of kernel buffer (mmapped into user space) measured in
84
 * number of windows - should be equal to power of two, to simplify
85
 * the modulo operation (replacing it by binary AND) */
86
#define WINDOWS_IN_BUFFER (1<<8)
87
 
88
#define MY_BUF_LEN (WINDOWS_IN_BUFFER * PKTS_IN_WINDOW * USER_LEN)
89
#define MY_BUF_LEN_MASK (MY_BUF_LEN-1)
90
 
91
 
92
/* Length of the acknowledment packet and command packets */
93
#define MY_ACK_LEN 64
94
 
95
/* Number of bytes to be copied from data packet to ack packet
96
 * It covers: retry_number, packet_number and transm_delay - 10 bytes
97
 */
98
#define MY_ACK_COPIED 10
99
 
100
/* The Ethernet type of our packet. This is NOT OFFICIALLY REGISTERED type,
101
 * however our protocol is:
102
 * 1. experimental,
103
 * 2. supposed to be used only in private networks
104
 */
105
#define MY_PROTO_ID 0xfade
106
#define MY_PROTO_VER 0x0100
107
 
108
static int max_slaves = 4;
109
module_param(max_slaves,int,0);
110
MODULE_PARM_DESC(max_slaves,"Maximum number of slave FPGA devices serviced by the system.");
111
 
112
static int proto_registered = 0; //Was the protocol registred? Should be deregistered at exit?
113
 
114
DEFINE_RWLOCK(slave_table_lock); //Used to protect table of slaves
115
 
116
/* Structure used to store offset of two currently serviced sets in the data buffer */
117
struct pkt_map {
118
  int num;
119
  int offset;
120
};
121
 
122
typedef struct
123
{
124
  // fields related to the circular buffer
125
  volatile int head;
126
  volatile int tail;
127
  rwlock_t ptrs_lock; //Used to protect the head and tail pointers
128
 
129
  unsigned char * buffer;
130
  struct mutex usercmd_lock;
131
  uint16_t cmd_code;
132
  uint16_t cmd_seq;
133
  uint8_t cmd_ack;
134
  uint8_t cmd_resp[12];
135
  rwlock_t pkts_rwlock; //Protects the pkts table and last_pkt
136
  uint32_t last_nack_pkt; /* Number of the last not acknowledged packet. This is also the number
137
                             of the first packet in the current transmission window */
138
  uint32_t pkts[PKTS_IN_WINDOW]; /* This array stores numbers of the last received packets in the
139
                                  * transmission window. It is used to avoid unnecessary copying of duplicated
140
                                  * packets into the receiver buffer */
141
  rwlock_t flags_lock; //Protects other fields of the slave_data struct
142 18 wzab
  uint32_t last_pkt_num; /* Number of the last "flushed" packet */
143
  uint32_t last_pkt_len; /* Number of words in the last "flushed" packet */
144 15 wzab
  char err_flag;
145 18 wzab
  char stopped_flag; /* Flag informing, that transmission has been already terminated */
146
  char eof_flag; /* Flag informing, that all packets are delivered after transmission is terminated */
147 15 wzab
  char active;
148
  char is_open;
149
  int rx_wakeup_thr;
150
  unsigned char mac[ETH_ALEN];
151
  struct net_device * dev;
152
} slave_data;
153
 
154 16 wzab
/* Auxiliary inline functions */
155
static inline uint16_t get_be_u16(char * buf)
156
{
157
  return be16_to_cpu(*(uint16_t *)buf);
158
}
159
 
160
static inline uint32_t get_be_u32(char * buf)
161
{
162
  return be32_to_cpu(*(uint32_t *)buf);
163
}
164
 
165
static inline uint64_t get_be_u64(char * buf)
166
{
167
  return be64_to_cpu(*(uint64_t *)buf);
168
}
169
 
170
static inline void put_skb_u16(struct sk_buff * skb, uint16_t val)
171
{
172 18 wzab
  void * data = skb_put(skb,sizeof(val));
173 16 wzab
  * (uint16_t *) data = cpu_to_be16(val);
174
}
175
 
176
static inline void put_skb_u32(struct sk_buff * skb, uint32_t val)
177
{
178 18 wzab
  void * data = skb_put(skb,sizeof(val));
179 16 wzab
  * (uint32_t *) data = cpu_to_be32(val);
180
}
181
 
182
static inline void put_skb_u64(struct sk_buff * skb, uint64_t val)
183
{
184 18 wzab
  void * data = skb_put(skb,sizeof(val));
185 16 wzab
  * (uint64_t *) data = cpu_to_be64(val);
186
}
187
 
188 15 wzab
static slave_data * slave_table = NULL;
189
 
190
static int my_proto_rcv(struct sk_buff * skb, struct net_device * dev, struct packet_type * pt,
191
                        struct net_device * orig_dev);
192
 
193
static struct packet_type my_proto_pt __read_mostly = {
194
  .type = cpu_to_be16(MY_PROTO_ID),
195
  .dev = NULL,
196
  .func = my_proto_rcv,
197
};
198
 
199
// Prototypes of functions defined in module
200
void cleanup_my_proto1( void );
201
int init_my_proto1( void );
202
static int my_proto1_open(struct inode *inode, struct file *file);
203
static int my_proto1_release(struct inode *inode, struct file *file);
204
static long my_proto1_ioctl (struct file *filp,  unsigned int cmd, unsigned long arg);
205
int my_proto1_mmap(struct file *filp, struct vm_area_struct *vma);
206
unsigned int my_proto1_poll(struct file *filp,poll_table *wait);
207
 
208
//Wait queue for user application
209
DECLARE_WAIT_QUEUE_HEAD (read_queue);
210
//Wait queue for user commands
211
DECLARE_WAIT_QUEUE_HEAD (usercmd_queue);
212
dev_t my_dev=0;
213
struct cdev * my_cdev = NULL;
214
static struct class *class_my_proto = NULL;
215
 
216
struct file_operations Fops = {
217
  .owner = THIS_MODULE,
218
  .open=my_proto1_open,
219
  .release=my_proto1_release,  /* a.k.a. close */
220
  .poll = my_proto1_poll,
221
  .unlocked_ioctl=my_proto1_ioctl,
222
  .mmap=my_proto1_mmap
223
};
224
 
225 18 wzab
 
226
/* Function used to send the user command and wait for confirmation */
227
static inline
228
long send_cmd(slave_data * sd, uint16_t cmd, uint32_t arg, void * resp, int nof_retries, int timeout)
229
{
230
  long result = -ETIMEDOUT;
231 19 wzab
  //First check, if the Ethernet device is claimed, otherwise return an error
232
  if(sd->dev==NULL) return -ENODEV;
233 18 wzab
  //Each slave may perform only one user command, so first check, if no other thread
234
  //attempts to send the command
235
  if ( mutex_trylock(&sd->usercmd_lock)==0) return -EBUSY;
236
  //Mutex acquired, we can proceed
237
  //First allocate the sequence number for the command
238
  sd->cmd_seq += 1;
239
  sd->cmd_code = cmd;
240
  sd->cmd_ack = 1; //Mark, that we are waiting for response
241
  //Now in the loop we send the packet, requesting execution of the command
242
  //and then we wait for response with timeout
243
  while(nof_retries--) {
244
    //Send the packet 
245
    struct sk_buff *newskb = NULL;
246
    uint8_t * my_data = NULL;
247
    newskb = alloc_skb(LL_RESERVED_SPACE(sd->dev)+MY_ACK_LEN, GFP_KERNEL);
248
    skb_reserve(newskb,LL_RESERVED_SPACE(sd->dev));
249
    skb_reset_network_header(newskb);
250
    newskb->dev = sd->dev;
251
    newskb->protocol = htons(MY_PROTO_ID);
252
    //Build the MAC header for the new packet
253 29 wzab
    // Here http://lxr.free-electrons.com/source/net/ipv4/arp.c?v=3.17#L608 it is shown how to build a packet!
254 18 wzab
    if (dev_hard_header(newskb,sd->dev,MY_PROTO_ID,&sd->mac,sd->dev->dev_addr,MY_ACK_LEN+ETH_HLEN) < 0)
255
      {
256 29 wzab
        mutex_unlock(&sd->usercmd_lock);
257 18 wzab
        kfree_skb(newskb);
258
        return -EINVAL;
259
      }
260
    //Put the protocol version id to the packet
261
    put_skb_u16(newskb,MY_PROTO_VER);
262
    //Put the command code
263
    put_skb_u16(newskb,cmd);
264
    //Put the sequence number
265
    put_skb_u16(newskb,sd->cmd_seq);
266
    //Put the argument
267
    put_skb_u32(newskb,arg);
268
    //Fill the packet
269
    my_data = skb_put(newskb,MY_ACK_LEN-10);
270
    memset(my_data,0xa5,MY_ACK_LEN-10);
271
    dev_queue_xmit(newskb);
272
    //Sleep with short timeout, waiting for response
273 30 wzab
    if(wait_event_interruptible_timeout(usercmd_queue,sd->cmd_ack==2,timeout)) {
274 18 wzab
      //Response received
275
      //If target buffer provided, copy data to the userspace buffer
276
      if(resp) memcpy(resp,sd->cmd_resp,12);
277
      result = SUCCESS;
278
      break; //exit loop
279
    }
280
  }
281
  //We don't wait for response any more
282
  sd->cmd_ack = 0;
283
  mutex_unlock(&sd->usercmd_lock);
284
  return result;
285
}
286 21 wzab
/* Function used to send RESET command (without confirmation, as
287
the core is reinitialized and can't send confirmation) */
288
static inline
289
long send_reset(slave_data * sd)
290
{
291
  struct sk_buff *newskb = NULL;
292
  uint8_t * my_data = NULL;
293
  //First check, if the Ethernet device is claimed, otherwise return an error
294
  if(sd->dev==NULL) return -ENODEV;
295
  //Each slave may perform only one user command, so first check, if no other thread
296
  //attempts to send the command
297
  if ( mutex_trylock(&sd->usercmd_lock)==0) return -EBUSY;
298
  //Mutex acquired, we can proceed
299
  //First allocate the sequence number for the command
300
  sd->cmd_seq = 0;
301
  sd->cmd_code = FCMD_RESET;
302
  sd->cmd_ack = 0; //We don't wait for response
303
  //Send the packet 
304
  newskb = alloc_skb(LL_RESERVED_SPACE(sd->dev)+MY_ACK_LEN, GFP_KERNEL);
305
  skb_reserve(newskb,LL_RESERVED_SPACE(sd->dev));
306
  skb_reset_network_header(newskb);
307
  newskb->dev = sd->dev;
308
  newskb->protocol = htons(MY_PROTO_ID);
309
  //Build the MAC header for the new packet
310 29 wzab
  // Here http://lxr.free-electrons.com/source/net/ipv4/arp.c?v=3.17#L608 it is shown how to build a packet!
311 21 wzab
  if (dev_hard_header(newskb,sd->dev,MY_PROTO_ID,&sd->mac,sd->dev->dev_addr,MY_ACK_LEN+ETH_HLEN) < 0)
312
    {
313 29 wzab
      mutex_unlock(&sd->usercmd_lock);
314 21 wzab
      kfree_skb(newskb);
315
      return -EINVAL;
316
    }
317
  //Put the protocol version id to the packet
318
  put_skb_u16(newskb,MY_PROTO_VER);
319
  //Put the command code
320
  put_skb_u16(newskb,sd->cmd_code);
321
  //Put the sequence number
322
  put_skb_u16(newskb,sd->cmd_seq);
323
  //Put the argument
324
  put_skb_u32(newskb,0);
325
  //Fill the packet
326
  my_data = skb_put(newskb,MY_ACK_LEN-10);
327
  memset(my_data,0xa5,MY_ACK_LEN-10);
328
  dev_queue_xmit(newskb);
329
  mutex_unlock(&sd->usercmd_lock);
330
  return SUCCESS;
331
}
332 18 wzab
 
333
/* Function free_mac may be safely called even if the MAC was not taken
334
   it checks sd->active to detect such situation
335
*/
336
static inline
337
long free_mac(slave_data *sd) {
338
  write_lock_bh(&slave_table_lock);
339
  if(sd->active) {
340
    /* Clear the MAC address */
341
    sd->active = 0;
342
    memset(&sd->mac,0,ETH_ALEN);
343
    write_unlock_bh(&slave_table_lock);
344
    /* Now send the "stop transmission" packet to the slave */
345
    /* Find the net device */
346
    if (!sd->dev) return -ENODEV;
347
    dev_put(sd->dev);
348
    sd->dev=NULL;
349
  } else {
350
    write_unlock_bh(&slave_table_lock);
351
  }
352
  return SUCCESS;
353
}
354
 
355 15 wzab
static long my_proto1_ioctl (struct file *filp,
356
                             unsigned int cmd, unsigned long arg)
357
{
358
  slave_data * sd = filp->private_data;
359
  if (_IOC_TYPE(cmd) != L3_V1_IOC_MAGIC) {
360
    return -EINVAL;
361
  }
362
  switch (cmd) {
363
  case L3_V1_IOC_SETWAKEUP:
364
    if (arg > MY_BUF_LEN/2)
365
      return -EINVAL; //Don't allow to set too high read threshold!
366
    write_lock_bh(&sd->flags_lock);
367
    sd->rx_wakeup_thr = arg;
368
    write_unlock_bh(&sd->flags_lock);
369
    return 0;
370
  case L3_V1_IOC_GETBUFLEN:
371
    /* Inform the user application about the length of the buffer */
372
    return MY_BUF_LEN;
373
  case L3_V1_IOC_READPTRS:
374
    {
375
      void * res = (void *) arg;
376
      long res2;
377
      struct l3_v1_buf_pointers bp;
378
      if (!access_ok(VERIFY_WRITE,res,sizeof(bp))) {
379
        return -EFAULT;
380
      } else {
381
        read_lock_bh(&sd->ptrs_lock);
382
        bp.head=sd->head;
383
        bp.tail=sd->tail;
384 18 wzab
        bp.eof=sd->eof_flag;
385 15 wzab
        read_unlock_bh(&sd->ptrs_lock);
386
        res2 = __copy_to_user(res,&bp,sizeof(bp));
387
        if(res2)
388
          return -EFAULT;
389
        if (sd->err_flag)
390
          return -EIO; /* In this case user must him/herself
391
                          calculate the number of available bytes */
392
        else
393
          return (bp.head-bp.tail) & MY_BUF_LEN_MASK;
394
        /* Return the number of available bytes */
395
      }
396
    }
397
  case L3_V1_IOC_WRITEPTRS:
398
    /* Update the read pointer
399
     * The argument contains information about the number of bytes
400
     * consumed by the application
401
     */
402
    {
403
      int rptr;
404
      int wptr;
405
      int available_data;
406
      //We need to check if the amount of consumed data is correct
407
      write_lock_bh(&sd->ptrs_lock);
408
      wptr = sd->head;
409
      rptr = sd->tail;
410
      available_data = (wptr - rptr) & MY_BUF_LEN_MASK;
411
      if (arg>available_data)
412
        {
413
          write_unlock_bh(&sd->ptrs_lock);
414
          return -EINVAL;
415
        }
416
      //If the number of consumed bytes is correct, update the number of bytes
417
      sd->tail = (rptr + arg) & MY_BUF_LEN_MASK;
418
      write_unlock_bh(&sd->ptrs_lock);
419
      return SUCCESS;
420
    }
421
  case L3_V1_IOC_STARTMAC: //Open the slave
422
    {
423 18 wzab
      sd->stopped_flag = 0;
424
      sd->eof_flag = 0;
425
      //We just send a request to start transmission and wait for confirmation
426
      return send_cmd(sd,FCMD_START,0,NULL,100,2);
427 15 wzab
    }
428 18 wzab
  case L3_V1_IOC_STOPMAC: //Close the slave and reset it to stop transmission immediately
429
    {
430
      return send_cmd(sd,FCMD_STOP,0,NULL,100,2);
431
    }
432
  case L3_V1_IOC_RESETMAC: //Reset MAC so, that it stops transmission immediately
433
    {
434 21 wzab
      return send_reset(sd);
435 18 wzab
    }
436 15 wzab
  case L3_V1_IOC_GETMAC: //Open the slave
437
    {
438
      void * source = (void *) arg;
439
      struct l3_v1_slave sl;
440
      struct net_device *dev = NULL;
441
      long res2;
442
      if (!access_ok(VERIFY_READ,source,sizeof(sl))) {
443
        return -EFAULT;
444
      }
445
      /* First deactivate the slave to avoid situation where data are modified
446
       * while slave is active */
447
      if (sd->active) sd->active = 0;
448
      //Set the numbers of stored packets to MAX
449
      write_lock_bh(&sd->pkts_rwlock);
450
      memset(&sd->pkts,0xff,sizeof(sd->pkts));
451
      sd->last_nack_pkt=0;
452
      write_unlock_bh(&sd->pkts_rwlock);
453
      //Copy arguments from the user space
454
      res2 = __copy_from_user(&sl,source,sizeof(sl));
455
      if(res2) {
456
        return -EFAULT;
457
      }
458
      write_lock_bh(&slave_table_lock);
459
      /* Copy the MAC address */
460
      memcpy(&sd->mac,sl.mac,ETH_ALEN);
461
      sd->active = 1;
462
      write_unlock_bh(&slave_table_lock);
463
      /* Find the net device */
464
      sl.devname[IFNAMSIZ-1]=0; // Protect against incorrect device name
465
      if (sd->dev) {
466
        //Maybe there was no STOPMAC call after previous STARTMAC?
467
        dev_put(sd->dev);
468
        sd->dev=NULL;
469
      }
470
      dev = dev_get_by_name(&init_net,sl.devname);
471
      if (!dev) return -ENODEV;
472
      sd->dev = dev;
473
      return SUCCESS;
474
    }
475
  case L3_V1_IOC_FREEMAC: //Close the slave and reset it to stop transmission immediately
476
    {
477 18 wzab
      free_mac(sd);
478 15 wzab
      return SUCCESS;
479
    }
480
  case L3_V1_IOC_USERCMD: //Perform the user command
481
    {
482
      void * source = (void *) arg;
483
      long result = -EINVAL;
484
      struct l3_v1_usercmd ucmd;
485
      //First copy command data
486
      result = __copy_from_user(&ucmd,source,sizeof(ucmd));
487
      if(result) {
488
        return -EFAULT;
489
      }
490
      //Now we check if the command is valid user command
491
      if(ucmd.cmd < 0x0100) return -EINVAL;
492 18 wzab
      result = send_cmd(sd,ucmd.cmd, ucmd.arg, ucmd.resp, ucmd.nr_of_retries,ucmd.timeout);
493
      if(result<0) return result;
494
      result = __copy_to_user(source,&ucmd,sizeof(ucmd));
495 15 wzab
      return result;
496
    }
497
  }
498
  return -EINVAL;
499
}
500
/*
501
  Implementation of the poll method
502
*/
503
unsigned int my_proto1_poll(struct file *filp,poll_table *wait)
504
{
505
  unsigned int mask =0;
506
  slave_data * sd = filp->private_data;
507
  unsigned int data_available;
508
  poll_wait(filp,&read_queue,wait);
509
  read_lock_bh(&sd->ptrs_lock);
510
  data_available = (sd->head - sd->tail) & MY_BUF_LEN_MASK;
511 18 wzab
  if (data_available >= sd->rx_wakeup_thr) mask |= POLLIN |POLLRDNORM;
512
  if (sd->eof_flag) {
513
    if(data_available) mask |= POLLIN | POLLRDNORM;
514
    else mask |= POLLHUP;
515
  }
516 15 wzab
#ifdef FADE_DEBUG
517
  printk(KERN_INFO "poll head: %d tail: %d data: %d prog: %d.\n",sd->head,sd->tail,data_available,sd->rx_wakeup_thr);
518
#endif
519
  //Check if the error occured
520
  if (sd->err_flag) mask |= POLLERR;
521
  read_unlock_bh(&sd->ptrs_lock);
522
  return mask;
523
}
524
 
525
/* Module initialization  */
526
int init_my_proto1( void )
527
{
528
  int res;
529
  int i;
530
  /* Create the device class for udev */
531
  class_my_proto = class_create(THIS_MODULE, "my_proto");
532
  if (IS_ERR(class_my_proto)) {
533
    printk(KERN_ERR "Error creating my_proto class.\n");
534
    res=PTR_ERR(class_my_proto);
535
    goto err1;
536
  }
537
  /* Allocate the device number */
538
  res=alloc_chrdev_region(&my_dev, 0, max_slaves, DEVICE_NAME);
539
  if (res) {
540
    printk (KERN_ERR "Alocation of the device number for %s failed\n",
541
            DEVICE_NAME);
542
    goto err1;
543
  };
544
  /* Allocate the character device structure */
545
  my_cdev = cdev_alloc( );
546
  if (my_cdev == NULL) {
547
    printk (KERN_ERR "Allocation of cdev for %s failed\n",
548
            DEVICE_NAME);
549
    goto err1;
550
  }
551
  my_cdev->ops = &Fops;
552
  my_cdev->owner = THIS_MODULE;
553
  /* Add the character device to the system */
554
  res=cdev_add(my_cdev, my_dev, max_slaves);
555
  if (res) {
556
    printk (KERN_ERR "Registration of the device number for %s failed\n",
557
            DEVICE_NAME);
558
    goto err1;
559
  };
560
  /* Create our devices in the system */
561
  for (i=0;i<max_slaves;i++) {
562
    device_create(class_my_proto,NULL,MKDEV(MAJOR(my_dev),MINOR(my_dev)+i),NULL,"l3_fpga%d",i);
563
  }
564
  printk (KERN_ERR "%s The major device number is %d.\n",
565
          "Registration is a success.",
566
          MAJOR(my_dev));
567
  //Prepare the table of slaves
568
  slave_table = kzalloc(sizeof(slave_data)*max_slaves, GFP_KERNEL);
569
  if (!slave_table) return -ENOMEM;
570
  for (i=0;i<max_slaves;i++) {
571
    /* Perform initialization, which should be done only once, when the module
572
     * is loaded. Other actions may be needed, when the transmission from
573
     * particular slave is started. This will be done in IOCTL STARTMAC
574
     */
575
    slave_data * sd = &slave_table[i];
576
    sd->active=0; //Entry not used
577
    sd->dev=NULL;
578
    rwlock_init(&sd->pkts_rwlock);
579
    rwlock_init(&sd->ptrs_lock);
580
    rwlock_init(&sd->flags_lock);
581
    mutex_init(&sd->usercmd_lock);
582
  }
583
  //Install our protocol sniffer
584
  dev_add_pack(&my_proto_pt);
585
  proto_registered = 1;
586
  return SUCCESS;
587
 err1:
588
  /* In case of error free all allocated resources */
589
  cleanup_my_proto1();
590
  return res;
591
}
592
 
593
module_init(init_my_proto1);
594
 
595
/* Clean-up when removing the module */
596
void cleanup_my_proto1( void )
597
{
598
  /* Unregister the protocol sniffer */
599
  if (proto_registered) dev_remove_pack(&my_proto_pt);
600
  /* Free the slave table */
601
  if (slave_table) {
602
    int i;
603
    for (i=0;i<max_slaves;i++) {
604
      if (slave_table[i].buffer) {
605
        vfree(slave_table[i].buffer);
606
        slave_table[i].buffer = NULL;
607
      }
608
      if (slave_table[i].dev) {
609
        dev_put(slave_table[i].dev);
610
        slave_table[i].dev=NULL;
611
      }
612
      if (slave_table[i].active) {
613
        slave_table[i].active = 0;
614
      }
615
    }
616
    kfree(slave_table);
617
    slave_table=NULL;
618
  }
619
  /* Remove device from the class */
620
  if (my_dev && class_my_proto) {
621
    int i;
622
    for (i=0;i<max_slaves;i++) {
623
      device_destroy(class_my_proto,MKDEV(MAJOR(my_dev),MINOR(my_dev)+i));
624
    }
625
  }
626
  /* Deregister device */
627
  if (my_cdev) cdev_del(my_cdev);
628
  my_cdev=NULL;
629
  /* Free the device number */
630
  unregister_chrdev_region(my_dev, max_slaves);
631
  /* Deregister class */
632
  if (class_my_proto) {
633
    class_destroy(class_my_proto);
634
    class_my_proto=NULL;
635
  }
636
 
637
}
638
module_exit(cleanup_my_proto1);
639
/*
640
  Function, which receives my packet, copies the data and acknowledges the packet
641
  as soon as possible...
642
  I've tried to allow this function to handle multiple packets in parallel
643
  in the SMP system, however I've used rwlocks for that.
644
  Probably it should be improved, according to the last tendency to avoid
645
  rwlocks in the kernel...
646
*/
647
 
648
static int my_proto_rcv(struct sk_buff * skb, struct net_device * dev, struct packet_type * pt,
649
                        struct net_device * orig_dev)
650
{
651
  struct sk_buff *newskb = NULL;
652
  struct ethhdr * rcv_hdr = NULL;
653
  //unsigned int head;
654
  //unsigned int tail;
655
  int is_duplicate = 0;
656
  int res;
657
  uint32_t packet_number;
658
  int ns; //Number of slave
659
  slave_data * sd = NULL;
660
  int32_t pkt_dist;
661
  char * my_data = NULL;
662
  unsigned char tmp_buf[USER_HDR_LEN];
663
  char ack_packet = 0; //Should we acknowledge the packet?
664 18 wzab
  uint32_t pkt_pos, needed_space, buf_free;
665 15 wzab
  //Extract the MAC header from the received packet
666
  rcv_hdr=eth_hdr(skb);
667
  //First we try to identify the sender so we search the table of active slaves
668
  //The table is protected during the search, so it should not be changed
669
#ifdef FADE_DEBUG
670
  printk("snd: %2.2x:%2.2x:%2.2x:%2.2x:%2.2x:%2.2x\n",(int)rcv_hdr->h_source[0],
671
         (int)rcv_hdr->h_source[1],(int)rcv_hdr->h_source[2],(int)rcv_hdr->h_source[3],
672
         (int)rcv_hdr->h_source[4],(int)rcv_hdr->h_source[5]);
673
#endif
674
  read_lock_bh(&slave_table_lock);
675
  for (ns=0;ns<max_slaves;ns++) {
676
#ifdef FADE_DEBUG
677
    printk("slv: %2.2x:%2.2x:%2.2x:%2.2x:%2.2x:%2.2x  act: %d\n",
678
           (int)slave_table[ns].mac[0],(int)slave_table[ns].mac[1],(int)slave_table[ns].mac[2],
679
           (int)slave_table[ns].mac[3],(int)slave_table[ns].mac[4],(int)slave_table[ns].mac[5],
680
           (int)slave_table[ns].active);
681
#endif
682
    if (
683
        slave_table[ns].active!=0 &&
684
        memcmp(slave_table[ns].mac,rcv_hdr->h_source, sizeof(slave_table[0].mac))==0
685
        ) break;
686
  }
687
  read_unlock_bh(&slave_table_lock);
688
  //Now we know which slave sent us the packet (ns<max_slaves) or that
689
  //the packet came from an unknown slave (ns==max_slaves)
690
  if (unlikely(ns==max_slaves)) {
691
    printk(KERN_WARNING " Received packet from incorrect slave!\n");
692
    //Sender is not opened, so ignore the packet, and send
693
    //to the sender request to stop the transmission immediately
694
    newskb = alloc_skb(LL_RESERVED_SPACE(dev)+MY_ACK_LEN, GFP_ATOMIC);
695
    skb_reserve(newskb,LL_RESERVED_SPACE(dev));
696
    skb_reset_network_header(newskb);
697
    newskb->dev = dev;
698
    newskb->protocol = htons(MY_PROTO_ID);
699
    //Build the MAC header for the new packet
700 29 wzab
    // Here http://lxr.free-electrons.com/source/net/ipv4/arp.c?v=3.17#L608 it is shown how to build a packet!
701 15 wzab
    if (dev_hard_header(newskb,dev,MY_PROTO_ID,&rcv_hdr->h_source,&rcv_hdr->h_dest,MY_ACK_LEN+ETH_HLEN) < 0)
702
      goto error;
703
    //Put the protocol version id to the packet
704 16 wzab
    put_skb_u16(newskb,MY_PROTO_VER);
705 18 wzab
    //Put the "restart" command to the packet, which should force it to stop transmission
706
    //immediately
707
    put_skb_u16(newskb,FCMD_RESET);
708 15 wzab
    my_data = skb_put(newskb,MY_ACK_LEN - 4);
709
    memset(my_data,0xa5,MY_ACK_LEN - 4);
710
    dev_queue_xmit(newskb);
711
    kfree_skb(skb);
712
    return NET_RX_DROP;
713
  }
714
  sd = &slave_table[ns]; //To speed up access to the data describing state of the slave
715
#ifdef FADE_DEBUG
716
  printk(KERN_INFO " Received packet!\n");
717
#endif
718
  //Now we should analyze the origin and meaning of the packet
719
  //To avoid problems with scattered packets, we copy initial part of data to the buffer
720
  //using the skb_copy_bits
721
  skb_copy_bits(skb,0,tmp_buf,USER_HDR_LEN);
722
  /* We extract the information from the user header
723
   * First we check if this is correct version of the protocol */
724 18 wzab
  if (unlikely(get_be_u16(&tmp_buf[0]) != MY_PROTO_VER)) goto wrong_pkt_type_error;
725 16 wzab
  if (unlikely(get_be_u16(&tmp_buf[2]) == 0xa55a)) {
726 15 wzab
    //This is a command response packet
727
    printk(KERN_INFO " received command response packet");
728
    if(sd->cmd_ack==1) {
729
      //We are waiting for response
730
      printk(KERN_INFO "we were waiting for command response packet");
731 16 wzab
      if ((get_be_u16(&tmp_buf[6]) == sd->cmd_code) &&
732 18 wzab
          (get_be_u16(&tmp_buf[8]) == sd->cmd_seq)){
733 15 wzab
        //This is a response for the right command
734
        //copy the response to the slave data
735
        printk(KERN_INFO "It was response for the right command");
736
        memcpy(&sd->cmd_resp,&tmp_buf[6],12);
737
        sd->cmd_ack=2;
738
        //Wake up the waiting process
739
        wake_up_interruptible(&usercmd_queue);
740
      }
741
    }
742
    kfree_skb(skb);
743
    return NET_RX_SUCCESS;
744
  }
745 18 wzab
  if (unlikely((get_be_u16(&tmp_buf[2]) != 0xa5a5) &&
746
               (get_be_u16(&tmp_buf[2]) != 0xa5a6))
747
      ) {
748 15 wzab
    //This is not a data packet
749
    goto wrong_pkt_type_error;
750
  }
751
  /* Now we handle the data packet
752
     PLEASE NOTE, THAT THIS MUST TIGHTLY CORRESPOND
753
     TO YOUR FPGA IMPLEMENTATION! */
754
  //Check, if we need to read a command response
755
  if(sd->cmd_ack==1) {
756
    //We are waiting for response
757 16 wzab
    if ((get_be_u16(&tmp_buf[14]) == sd->cmd_code) &&
758
        (get_be_u16(&tmp_buf[16]) == sd->cmd_seq)) {
759 15 wzab
      //This is a response for the right command
760
      //copy the response to the slave data
761
      memcpy(&sd->cmd_resp,&tmp_buf[14],12);
762
      sd->cmd_ack=2;
763
      //Wake up the waiting process
764
      wake_up_interruptible(&usercmd_queue);
765
    }
766
  }
767 16 wzab
  packet_number = get_be_u32(&tmp_buf[6]);
768 15 wzab
#ifdef FADE_DEBUG
769
  printk(KERN_INFO "pkt=%d\n",(int)packet_number);
770
#endif
771
  /* To know if this is a new packet, we compare the packet number
772
   * in the received packet with the number of the last unconfirmed packet,
773
   * calculating the difference between those two numbers: */
774
  read_lock_bh(&sd->pkts_rwlock);
775
  pkt_dist=(int32_t) packet_number - (int32_t) sd->last_nack_pkt;
776 18 wzab
  //Check if this packet was received before
777 15 wzab
  is_duplicate=(sd->pkts[packet_number & PKTS_IN_WINDOW_MASK] == packet_number) ? 1 : 0;
778
  read_unlock_bh(&sd->pkts_rwlock);
779 18 wzab
  if (unlikely((pkt_dist<0) || (pkt_dist>=PKTS_IN_WINDOW))) {
780
    //This is a "too old" packet, or packet "from the future", which should not be transimtted
781
    //by the FPGA
782 15 wzab
    if (pkt_dist<0) {
783 18 wzab
      // This is a packet which was already confirmed, but probably ACK was lost
784 15 wzab
#ifdef FADE_DEBUG
785
      printk(KERN_INFO "Packet already confirmed: pkt=%d expect=%d last=%d\n",packet_number, sd->pkts[packet_number], sd->last_nack_pkt);
786
#endif
787 18 wzab
      ack_packet = 1;
788
      goto confirm;
789 15 wzab
    } else {
790
      /* This is a packet with too high set number (packet "from the future"
791
       * it my be a symptom of serious communication problem! */
792
      printk(KERN_ERR "Packet from the future! number: %d last_confirmed: %d\n", packet_number, sd->last_nack_pkt);
793 18 wzab
      goto error2;
794 15 wzab
    }
795
  }
796 18 wzab
  //If we get there, it means, that:
797
  //   pkt_dist >= 0 and pkt_dist < PKTS_IN_WINDOW
798
  // So this is an expected data packet.
799
  if(is_duplicate) {
800
    //Packet already confirmed, probably the ACK was lost, so simply generate the ACK
801
    ack_packet = 1;
802
    goto confirm;
803
  }
804
  //Packet not confirmed yet. Confirm it only after all processing is successfully completed
805
  pkt_pos=(packet_number<<LOG2_USER_LEN) & MY_BUF_LEN_MASK;
806
  //We must be sure, that the pointers do not change during this check
807
  read_lock_bh(&sd->ptrs_lock);
808
  //Calculate free space needed to copy the packet
809
  needed_space = (pkt_pos+USER_LEN-1-(sd->head)) & MY_BUF_LEN_MASK;
810
  //Calculate the amount of free space in the buffer
811
  buf_free = (sd->tail - sd->head -1 ) & MY_BUF_LEN_MASK;
812
#ifdef FADE_DEBUG
813
  printk(KERN_INFO "packet_nr: %d Free buffer: %d needed space: %d head=%d last_nack=%d\n",
814
         packet_number, needed_space, buf_free, sd->head, sd->last_nack_pkt);
815
#endif
816
  read_unlock_bh(&sd->ptrs_lock);
817
  if (unlikely( buf_free <= needed_space )) goto error2; //No place for copying, drop the packet
818
  // Check the length of the package
819
  if (unlikely(skb->len != PAYL_LEN)) {
820
    printk(KERN_ERR "Error! Length of data should be %d but is %d!\n",PAYL_LEN, skb->len);
821
    sd->err_flag |= FADE_ERR_INCORRECT_LENGTH;
822
    goto error2;
823
  }
824
  // We can safely copy all the packet to the buffer:
825
  res = skb_copy_bits(skb,USER_HDR_LEN,&(sd->buffer[pkt_pos]),USER_LEN);
826
#ifdef FADE_DEBUG
827
  printk(KERN_INFO " skb_copy_bits: %d", res);
828
#endif
829
  if (res<0) goto error2; //Unsuccessfull copying
830
  //Packet was copied, so note, that we should confirm it
831
  ack_packet=1;
832
  /* When packet is copied, we can check if this is the last "flushed" packet */
833
  if (get_be_u16(&tmp_buf[2])==0xa5a6) {
834
    //Flushed packet, store its number and length (should it be protected with spinlock?)
835
    sd->last_pkt_num = packet_number;
836
    //Copy the length, truncating it from 64 bits
837 46 wzab
    sd->last_pkt_len = get_be_u64(&(sd->buffer[pkt_pos+USER_LEN-sizeof(uint64_t)]));
838 18 wzab
    //We have received the "flushed" buffer, mark that transmission is stopped
839
    sd->stopped_flag = 1;
840 20 wzab
    //printk(KERN_INFO "set stopped flag");
841 18 wzab
  }
842
  /* We modify the number of the copied packet in the pkts array, to avoid
843
   * unnecessary copying if we receive a duplicate
844
   * To modify the pkts table, we must close pkts_rwlock for writing */
845
  write_lock_bh(&sd->pkts_rwlock);
846
  sd->pkts[packet_number & PKTS_IN_WINDOW_MASK]= packet_number;
847
  if (packet_number == sd->last_nack_pkt) {
848
    /* If our packet was the last, which prevented shifting of the head pointer,
849
     * we can try now to move the head pointer.
850
     * We browse the pkts table, looking for the first packet with incorrect number
851
     * i.e. the packet which was not received and not confimed yet
852
     */
853
    uint32_t chk_packet_num = packet_number+1;
854
    uint32_t count=0;
855
    while (++count < PKTS_IN_WINDOW) {
856
      if (sd->pkts[(sd->last_nack_pkt + count) & PKTS_IN_WINDOW_MASK] != chk_packet_num) break; //Packet not confirmed
857
      chk_packet_num++;
858
    }
859
    sd->last_nack_pkt += count;
860
    write_unlock_bh(&sd->pkts_rwlock);
861
    /* Now we can move the head position */
862
    if(likely((sd->stopped_flag == 0) ||
863
              ((uint32_t)(sd->last_nack_pkt-1) != sd->last_pkt_num))) {
864
      //Normal packet, set head right after the last serviced packet
865
      write_lock_bh(&sd->ptrs_lock);
866
      sd->head = (sd->last_nack_pkt*USER_LEN) & MY_BUF_LEN_MASK;
867
      //Now try to wake up the reading process
868
      if (((sd->head - sd->tail) & MY_BUF_LEN_MASK) >= sd->rx_wakeup_thr)
869
        wake_up_interruptible(&read_queue);
870
    } else {
871
      //Flushed packet, set head right after the end of the packet
872
      write_lock_bh(&sd->ptrs_lock);
873 46 wzab
      sd->head = ((sd->last_nack_pkt-1)*USER_LEN+8*sd->last_pkt_len) & MY_BUF_LEN_MASK;
874 18 wzab
      //We have consumed the last, "flushed" buffer, so now we can set the eof flag
875
      sd-> eof_flag = 1;
876 20 wzab
      //printk(KERN_ALERT "set eof flag!");
877 18 wzab
      //And we wake up the reading process
878
      wake_up_interruptible(&read_queue);
879
    } //if - stopped_flag
880
    write_unlock_bh(&sd->ptrs_lock);
881
  } else { // if - last_nack_pkt 
882
    write_unlock_bh(&sd->pkts_rwlock);
883
  }
884
 confirm:
885
  //Send the confirmation if required
886 15 wzab
  if (likely(ack_packet)) {
887
    newskb = alloc_skb(LL_RESERVED_SPACE(dev)+MY_ACK_LEN, GFP_ATOMIC);
888
    skb_reserve(newskb,LL_RESERVED_SPACE(dev));
889
    skb_reset_network_header(newskb);
890
    newskb->dev = dev;
891
    newskb->protocol = htons(MY_PROTO_ID);
892
    //Build the MAC header for the new packet
893 29 wzab
    // Here http://lxr.free-electrons.com/source/net/ipv4/arp.c?v=3.17#L608 it is shown how to build a packet!
894 15 wzab
    if (dev_hard_header(newskb,dev,MY_PROTO_ID,&rcv_hdr->h_source,&rcv_hdr->h_dest,MY_ACK_LEN+ETH_HLEN) < 0)
895
      goto error;
896
    //Put the protocol version id to the packet
897 18 wzab
    put_skb_u16(newskb,MY_PROTO_VER);
898 15 wzab
    //Put the "ACKNOWLEDGE" type
899 18 wzab
    put_skb_u16(newskb,FCMD_ACK);
900 15 wzab
    //Copy the begining of the received packet to the acknowledge packet
901
    my_data = skb_put(newskb,MY_ACK_COPIED);
902
    res = skb_copy_bits(skb,4,my_data,MY_ACK_COPIED);
903
    my_data = skb_put(newskb,MY_ACK_LEN -MY_ACK_COPIED-4);
904
    memset(my_data,0xa5,MY_ACK_LEN - MY_ACK_COPIED-4);
905
#ifdef FADE_DEBUG
906
    printk(KERN_INFO " skb_nh: %x, skb_dt: %x, skb_nh2: %x, skb_t: %x\n tail: %d head: %d\n",skb_network_header(newskb),newskb->data,
907
           newskb->network_header,newskb->tail, sd->tail, sd->head) ;
908
#endif
909
    dev_queue_xmit(newskb);
910
  }
911
  kfree_skb(skb);
912
  return NET_RX_SUCCESS;
913
 wrong_pkt_type_error:
914
  //This code should be called with sd initialized,
915
  //but to avoid kernel panic, check if sd was set
916
  if(sd) {
917
    write_lock_bh(&sd->flags_lock);
918
    sd->err_flag |= FADE_ERR_INCORRECT_PACKET_TYPE;
919
    write_unlock_bh(&sd->flags_lock);
920
  } else {
921
    printk(KERN_ERR "FADE: wrong_pkt_type_error called with null sd");
922
  }
923
 error:
924
  if (newskb) kfree_skb(newskb);
925 18 wzab
 error2:
926 15 wzab
  if (skb) kfree_skb(skb);
927
  return NET_RX_DROP;
928
}
929
 
930
/*
931
  Implementation of the "device open" function
932
*/
933
static int my_proto1_open(struct inode *inode,
934
                          struct file *file)
935
{
936
  int i;
937
  slave_data * sd = NULL;
938
  unsigned long flags;
939
  i=iminor(inode)-MINOR(my_dev);
940
  if (i >= max_slaves) {
941
    printk(KERN_WARNING "Trying to access %s slave with too high minor number: %d\n",
942
           DEVICE_NAME, i);
943
    return -ENODEV;
944
  }
945
  read_lock_irqsave(&slave_table_lock,flags);
946
  sd = &slave_table[i];
947
  //Each device may be opened only once!
948
  if (sd->is_open) {
949 28 wzab
    read_unlock_irqrestore(&slave_table_lock,flags);
950 15 wzab
    return -EBUSY;
951
  }
952
  //Prepare slave_table for operation
953
  read_unlock_irqrestore(&slave_table_lock,flags);
954
  sd->buffer = vmalloc_user(MY_BUF_LEN);
955
  if (!sd->buffer) return -ENOMEM;
956
  //Set the MAC address to 0
957
  memset(sd->mac,0,sizeof(sd->mac));
958
  sd->head = 0;
959
  sd->tail = 0;
960 18 wzab
  sd->eof_flag = 0;
961
  sd->stopped_flag = 0;
962 15 wzab
  sd->err_flag = 0;
963
  sd->last_nack_pkt = 0;
964
  sd->rx_wakeup_thr = 1;
965
  sd->active = 0;
966
  sd->cmd_seq = 0;
967
  sd->is_open = 1;
968
  file->private_data=sd;
969
  return SUCCESS;
970
}
971
 
972
 
973
static int my_proto1_release(struct inode *inode,
974
                             struct file *file)
975
{
976
  slave_data * sd = file->private_data;
977 18 wzab
  //#ifdef FADE_DEBUG
978 15 wzab
  printk (KERN_INFO "device_release(%p,%p)\n", inode, file);
979 18 wzab
  //#endif
980 15 wzab
  //Release resources associated with servicing of the particular device
981
  if (sd) {
982
    if (sd->is_open) {
983
      sd->is_open = 0; //It can be dangerous! Before freeing the buffer, we must be sure, that
984
      //no our packet is being processed!
985 18 wzab
      printk (KERN_INFO "freed MAC\n");
986
      free_mac(sd); //It also sets sd->active to 0!
987 15 wzab
      if (sd->buffer) {
988 18 wzab
        printk (KERN_INFO "freed buffer\n");
989 15 wzab
        vfree(sd->buffer);
990
        sd->buffer = NULL;
991
      }
992
    }
993
  }
994
  return SUCCESS;
995
}
996
 
997
/* Memory mapping */
998
void my_proto1_vma_open (struct vm_area_struct * area)
999
{  }
1000
 
1001
void my_proto1_vma_close (struct vm_area_struct * area)
1002
{  }
1003
 
1004
static struct vm_operations_struct my_proto1_vm_ops = {
1005
  my_proto1_vma_open,
1006
  my_proto1_vma_close,
1007
};
1008
 
1009
/*
1010
  mmap method implementation
1011
*/
1012
int my_proto1_mmap(struct file *filp,
1013
                   struct vm_area_struct *vma)
1014
{
1015
  slave_data * sd = filp->private_data;
1016
  unsigned long vsize = vma->vm_end - vma->vm_start;
1017
  unsigned long psize = MY_BUF_LEN;
1018
  if (vsize>psize)
1019
    return -EINVAL;
1020
  remap_vmalloc_range(vma,sd->buffer, 0);
1021
  if (vma->vm_ops)
1022
    return -EINVAL; //It should never happen...
1023
  vma->vm_ops = &my_proto1_vm_ops;
1024
  my_proto1_vma_open(vma); //No open(vma) was called, we have called it ourselves
1025
  return 0;
1026
}
1027
 

powered by: WebSVN 2.1.0

© copyright 1999-2024 OpenCores.org, equivalent to Oliscience, all rights reserved. OpenCores®, registered trademark.