]> rtime.felk.cvut.cz Git - linux-lin.git/blob - sllin/sllin.c
908cce9735e78ca4766e002d11aa10cc661ac7df
[linux-lin.git] / sllin / sllin.c
1 /*
2  * sllin.c - serial line LIN interface driver (using tty line discipline)
3  *
4  * This file is derived from drivers/net/can/slcan.c
5  * slcan.c Author: Oliver Hartkopp <socketcan@hartkopp.net>
6  *
7  * This program is free software; you can redistribute it and/or modify it
8  * under the terms of the GNU General Public License as published by the
9  * Free Software Foundation; either version 2 of the License, or (at your
10  * option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful, but
13  * WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15  * General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License along
18  * with this program; if not, write to the Free Software Foundation, Inc.,
19  * 59 Temple Place, Suite 330, Boston, MA 02111-1307. You can also get it
20  * at http://www.gnu.org/licenses/gpl.html
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
23  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
24  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
25  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
26  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
27  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
28  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
29  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
30  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
31  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
32  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
33  * DAMAGE.
34  *
35  * Idea:       Oliver Hartkopp <oliver.hartkopp@volkswagen.de>
36  * Copyright:  (c) 2011 Czech Technical University in Prague
37  *             (c) 2011 Volkswagen Group Research
38  * Authors:    Pavel Pisa <pisa@cmp.felk.cvut.cz>
39  *             Rostislav Lisovy <lisovy@kormus.cz>
40  *             Michal Sojka <sojkam1@fel.cvut.cz>
41  * Funded by:  Volkswagen Group Research
42  */
43
44 //#define DEBUG                 1 /* Enables pr_debug() printouts */
45
46 #include <linux/module.h>
47 #include <linux/moduleparam.h>
48
49 #include <linux/uaccess.h>
50 #include <linux/bitops.h>
51 #include <linux/string.h>
52 #include <linux/tty.h>
53 #include <linux/errno.h>
54 #include <linux/netdevice.h>
55 #include <linux/skbuff.h>
56 #include <linux/rtnetlink.h>
57 #include <linux/if_arp.h>
58 #include <linux/if_ether.h>
59 #include <linux/sched.h>
60 #include <linux/delay.h>
61 #include <linux/init.h>
62 #include <linux/can.h>
63 #include <linux/kthread.h>
64 #include <linux/hrtimer.h>
65 #include <linux/version.h>
66 #include "linux/lin_bus.h"
67
68 /* Should be in include/linux/tty.h */
69 #define N_SLLIN                 25
70 /* -------------------------------- */
71
72 static __initdata const char banner[] =
73         KERN_INFO "sllin: serial line LIN interface driver\n";
74
75 MODULE_ALIAS_LDISC(N_SLLIN);
76 MODULE_DESCRIPTION("serial line LIN interface");
77 MODULE_LICENSE("GPL");
78 MODULE_AUTHOR("Pavel Pisa <pisa@cmp.felk.cvut.cz>");
79
80 #define SLLIN_MAGIC             0x53CA
81 /* #define BREAK_BY_BAUD */
82
83 static bool master = true;
84 static int baudrate; /* Use LIN_DEFAULT_BAUDRATE when not set */
85
86 module_param(master, bool, 0);
87 MODULE_PARM_DESC(master, "LIN interface is Master device");
88 module_param(baudrate, int, 0);
89 MODULE_PARM_DESC(baudrate, "Baudrate of LIN interface");
90
91 static int maxdev = 10;         /* MAX number of SLLIN channels;
92                                    This can be overridden with
93                                    insmod sllin.ko maxdev=nnn   */
94 module_param(maxdev, int, 0);
95 MODULE_PARM_DESC(maxdev, "Maximum number of sllin interfaces");
96
97 /* maximum buffer len to store whole LIN message*/
98 #define SLLIN_DATA_MAX          8
99 #define SLLIN_BUFF_LEN          (1 /*break*/ + 1 /*sync*/ + 1 /*ID*/ + \
100                                 SLLIN_DATA_MAX + 1 /*checksum*/)
101 #define SLLIN_BUFF_BREAK        0
102 #define SLLIN_BUFF_SYNC         1
103 #define SLLIN_BUFF_ID           2
104 #define SLLIN_BUFF_DATA         3
105
106 #define SLLIN_SAMPLES_PER_CHAR  10
107 #define SLLIN_CHARS_TO_TIMEOUT  24
108
109 enum slstate {
110         SLSTATE_IDLE = 0,
111         SLSTATE_BREAK_SENT,
112         SLSTATE_ID_SENT,
113         SLSTATE_RESPONSE_WAIT, /* Wait for response */
114         SLSTATE_RESPONSE_WAIT_BUS, /* Wait for response from LIN bus
115                                 only (CAN frames from network stack
116                                 are not processed in this moment) */
117         SLSTATE_ID_RECEIVED,
118         SLSTATE_RESPONSE_SENT,
119 };
120
121 struct sllin_conf_entry {
122         int dlc;                /* Length of data in LIN frame */
123         canid_t frame_fl;       /* LIN frame flags. Passed from userspace as
124                                    canid_t data type */
125         u8 data[8];             /* LIN frame data payload */
126 };
127
128 struct sllin {
129         int                     magic;
130
131         /* Various fields. */
132         struct tty_struct       *tty;           /* ptr to TTY structure      */
133         struct net_device       *dev;           /* easy for intr handling    */
134         spinlock_t              lock;
135
136         /* LIN message buffer and actual processed data counts */
137         unsigned char           rx_buff[SLLIN_BUFF_LEN]; /* LIN Rx buffer */
138         unsigned char           tx_buff[SLLIN_BUFF_LEN]; /* LIN Tx buffer */
139         int                     rx_expect;      /* expected number of Rx chars */
140         int                     rx_lim;         /* maximum Rx chars for current frame */
141         int                     rx_cnt;         /* message buffer Rx fill level  */
142         int                     tx_lim;         /* actual limit of bytes to Tx */
143         int                     tx_cnt;         /* number of already Tx bytes */
144         char                    lin_master;     /* node is a master node */
145         int                     lin_baud;       /* LIN baudrate */
146         int                     lin_state;      /* state */
147         char                    id_to_send;     /* there is ID to be sent */
148         char                    data_to_send;   /* there are data to be sent */
149         char                    resp_len_known; /* Length of the response is known */
150         char                    header_received;/* In Slave mode, set when header was already
151                                                    received */
152         char                    rx_len_unknown; /* We are not sure how much data will be sent to us --
153                                                    we just guess the length */
154
155         unsigned long           flags;          /* Flag values/ mode etc     */
156 #define SLF_INUSE               0               /* Channel in use            */
157 #define SLF_ERROR               1               /* Parity, etc. error        */
158 #define SLF_RXEVENT             2               /* Rx wake event             */
159 #define SLF_TXEVENT             3               /* Tx wake event             */
160 #define SLF_MSGEVENT            4               /* CAN message to sent       */
161 #define SLF_TMOUTEVENT          5               /* Timeout on received data  */
162 #define SLF_TXBUFF_RQ           6               /* Req. to send buffer to UART*/
163 #define SLF_TXBUFF_INPR         7               /* Above request in progress */
164
165         dev_t                   line;
166         struct task_struct      *kwthread;
167         wait_queue_head_t       kwt_wq;         /* Wait queue used by kwthread */
168         struct hrtimer          rx_timer;       /* RX timeout timer */
169         ktime_t                 rx_timer_timeout; /* RX timeout timer value */
170         struct sk_buff          *tx_req_skb;    /* Socket buffer with CAN frame
171                                                 received from network stack*/
172
173         /* List with configurations for each of 0 to LIN_ID_MAX LIN IDs */
174         struct sllin_conf_entry linfr_cache[LIN_ID_MAX + 1];
175         spinlock_t              linfr_lock;     /* frame cache and buffers lock */
176 };
177
178 static struct net_device **sllin_devs;
179 static int sllin_configure_frame_cache(struct sllin *sl, struct can_frame *cf);
180 static void sllin_slave_receive_buf(struct tty_struct *tty,
181                               const unsigned char *cp, char *fp, int count);
182 static void sllin_master_receive_buf(struct tty_struct *tty,
183                               const unsigned char *cp, char *fp, int count);
184
185
186 /* Values of two parity bits in LIN Protected
187    Identifier for each particular LIN ID */
188 const unsigned char sllin_id_parity_table[] = {
189         0x80, 0xc0, 0x40, 0x00, 0xc0, 0x80, 0x00, 0x40,
190         0x00, 0x40, 0xc0, 0x80, 0x40, 0x00, 0x80, 0xc0,
191         0x40, 0x00, 0x80, 0xc0, 0x00, 0x40, 0xc0, 0x80,
192         0xc0, 0x80, 0x00, 0x40, 0x80, 0xc0, 0x40, 0x00,
193         0x00, 0x40, 0xc0, 0x80, 0x40, 0x00, 0x80, 0xc0,
194         0x80, 0xc0, 0x40, 0x00, 0xc0, 0x80, 0x00, 0x40,
195         0xc0, 0x80, 0x00, 0x40, 0x80, 0xc0, 0x40, 0x00,
196         0x40, 0x00, 0x80, 0xc0, 0x00, 0x40, 0xc0, 0x80
197 };
198
199 /**
200  * sltty_change_speed() -- Change baudrate of Serial device belonging
201  *                         to particular @tty
202  *
203  * @tty:        Pointer to TTY to change speed for.
204  * @speed:      Integer value of new speed. It is possible to
205  *              assign non-standard values, i.e. those which
206  *              are not defined in termbits.h.
207  */
208 static int sltty_change_speed(struct tty_struct *tty, unsigned speed)
209 {
210         struct ktermios old_termios, termios;
211         int cflag;
212
213 #if LINUX_VERSION_CODE < KERNEL_VERSION(3, 12, 0)
214         mutex_lock(&tty->termios_mutex);
215 #else
216         down_write(&tty->termios_rwsem);
217 #endif
218
219 #if LINUX_VERSION_CODE < KERNEL_VERSION(3, 7, 0)
220         old_termios = termios = *(tty->termios);
221 #else
222         old_termios = termios = tty->termios;
223 #endif
224
225         cflag = CS8 | CREAD | CLOCAL | HUPCL;
226         cflag &= ~(CBAUD | CIBAUD);
227         cflag |= BOTHER;
228         termios.c_cflag = cflag;
229         termios.c_oflag = 0;
230         termios.c_lflag = 0;
231
232         /* Enable interrupt when UART-Break or Framing error received */
233         termios.c_iflag = BRKINT | INPCK;
234 #if LINUX_VERSION_CODE < KERNEL_VERSION(3, 7, 0)
235         *(tty->termios) = termios;
236 #else
237         tty->termios = termios;
238 #endif
239
240         tty_encode_baud_rate(tty, speed, speed);
241
242         if (tty->ops->set_termios)
243                 tty->ops->set_termios(tty, &old_termios);
244
245 #if LINUX_VERSION_CODE < KERNEL_VERSION(3, 12, 0)
246         mutex_unlock(&tty->termios_mutex);
247 #else
248         up_write(&tty->termios_rwsem);
249 #endif
250
251         return 0;
252 }
253
254 /* Send one can_frame to the network layer */
255 static void sllin_send_canfr(struct sllin *sl, canid_t id, char *data, int len)
256 {
257         struct sk_buff *skb;
258         struct can_frame cf;
259
260         cf.can_id = id;
261         cf.can_dlc = len;
262         if (cf.can_dlc > 0)
263                 memcpy(&cf.data, data, cf.can_dlc);
264
265         skb = dev_alloc_skb(sizeof(struct can_frame));
266         if (!skb)
267                 return;
268
269         skb->dev = sl->dev;
270         skb->protocol = htons(ETH_P_CAN);
271         skb->pkt_type = PACKET_BROADCAST;
272         skb->ip_summed = CHECKSUM_UNNECESSARY;
273         memcpy(skb_put(skb, sizeof(struct can_frame)),
274                &cf, sizeof(struct can_frame));
275         netif_rx(skb);
276
277         sl->dev->stats.rx_packets++;
278         sl->dev->stats.rx_bytes += cf.can_dlc;
279 }
280
281 /**
282  * sll_bump() -- Send data of received LIN frame (existing in sl->rx_buff)
283  *               as CAN frame
284  *
285  * @sl:
286  */
287 static void sll_bump(struct sllin *sl)
288 {
289         int len = sl->rx_cnt - SLLIN_BUFF_DATA - 1; /* without checksum */
290         len = (len < 0) ? 0 : len;
291
292         sllin_send_canfr(sl, sl->rx_buff[SLLIN_BUFF_ID] & LIN_ID_MASK,
293                 sl->rx_buff + SLLIN_BUFF_DATA, len);
294 }
295
296 static void sll_send_rtr(struct sllin *sl)
297 {
298         sllin_send_canfr(sl, (sl->rx_buff[SLLIN_BUFF_ID] & LIN_ID_MASK) |
299                 CAN_RTR_FLAG, NULL, 0);
300 }
301
302 /*
303  * Called by the driver when there's room for more data.  If we have
304  * more packets to send, we send them here.
305  */
306 static void sllin_write_wakeup(struct tty_struct *tty)
307 {
308         int actual = 0;
309         int remains;
310         struct sllin *sl = (struct sllin *) tty->disc_data;
311
312         /* First make sure we're connected. */
313         if (!sl || sl->magic != SLLIN_MAGIC || !netif_running(sl->dev))
314                 return;
315
316         set_bit(SLF_TXBUFF_RQ, &sl->flags);
317         do {
318                 if (unlikely(test_and_set_bit(SLF_TXBUFF_INPR, &sl->flags)))
319                         return; /* ongoing concurrent processing */
320
321                 clear_bit(SLF_TXBUFF_RQ, &sl->flags);
322
323 #if LINUX_VERSION_CODE < KERNEL_VERSION(3, 18, 0)
324                 smp_mb__after_clear_bit();
325 #else
326                 smp_mb__after_atomic();
327 #endif
328
329                 if (sl->lin_state != SLSTATE_BREAK_SENT)
330                         remains = sl->tx_lim - sl->tx_cnt;
331                 else
332                         remains = SLLIN_BUFF_BREAK + 1 - sl->tx_cnt;
333
334                 if (remains > 0) {
335                         actual = tty->ops->write(tty, sl->tx_buff + sl->tx_cnt,
336                                 sl->tx_cnt - sl->tx_lim);
337                         sl->tx_cnt += actual;
338                         remains -= actual;
339                 }
340                 clear_bit(SLF_TXBUFF_INPR, &sl->flags);
341 #if LINUX_VERSION_CODE < KERNEL_VERSION(3, 18, 0)
342                 smp_mb__after_clear_bit();
343 #else
344                 smp_mb__after_atomic();
345 #endif
346
347         } while (unlikely(test_bit(SLF_TXBUFF_RQ, &sl->flags)));
348
349         if ((remains > 0) && (actual >= 0)) {
350                 netdev_dbg(sl->dev, "sllin_write_wakeup sent %d, remains %d, waiting\n",
351                         sl->tx_cnt, sl->tx_lim - sl->tx_cnt);
352                 return;
353         }
354
355         clear_bit(TTY_DO_WRITE_WAKEUP, &tty->flags);
356         set_bit(SLF_TXEVENT, &sl->flags);
357         wake_up(&sl->kwt_wq);
358
359         netdev_dbg(sl->dev, "sllin_write_wakeup sent %d, wakeup\n", sl->tx_cnt);
360 }
361
362 /**
363  * sll_xmit() -- Send a can_frame to a TTY queue.
364  *
365  * @skb: Pointer to Socket buffer to be sent.
366  * @dev: Network device where @skb will be sent.
367  */
368 static netdev_tx_t sll_xmit(struct sk_buff *skb, struct net_device *dev)
369 {
370         struct sllin *sl = netdev_priv(dev);
371         struct can_frame *cf;
372
373         if (skb->len != sizeof(struct can_frame))
374                 goto err_out;
375
376         spin_lock(&sl->lock);
377         if (!netif_running(dev))  {
378                 netdev_warn(sl->dev, "xmit: iface is down\n");
379                 goto err_out_unlock;
380         }
381         if (sl->tty == NULL) {
382                 netdev_warn(sl->dev, "xmit: no tty device connected\n");
383                 goto err_out_unlock;
384         }
385
386         cf = (struct can_frame *) skb->data;
387         if (cf->can_id & LIN_CTRL_FRAME) {
388                 sllin_configure_frame_cache(sl, cf);
389                 goto free_out_unlock;
390         }
391
392         netif_stop_queue(sl->dev);
393
394         sl->tx_req_skb = skb;
395         set_bit(SLF_MSGEVENT, &sl->flags);
396         wake_up(&sl->kwt_wq);
397         spin_unlock(&sl->lock);
398         return NETDEV_TX_OK;
399
400 free_out_unlock:
401 err_out_unlock:
402         spin_unlock(&sl->lock);
403 err_out:
404         kfree_skb(skb);
405         return NETDEV_TX_OK;
406 }
407
408
409 /******************************************
410  *   Routines looking at netdevice side.
411  ******************************************/
412
413 /* Netdevice UP -> DOWN routine */
414 static int sll_close(struct net_device *dev)
415 {
416         struct sllin *sl = netdev_priv(dev);
417
418         spin_lock_bh(&sl->lock);
419         if (sl->tty) {
420                 /* TTY discipline is running. */
421                 clear_bit(TTY_DO_WRITE_WAKEUP, &sl->tty->flags);
422         }
423         netif_stop_queue(dev);
424         sl->rx_expect = 0;
425         sl->tx_lim    = 0;
426         spin_unlock_bh(&sl->lock);
427
428         return 0;
429 }
430
431 /* Netdevice DOWN -> UP routine */
432 static int sll_open(struct net_device *dev)
433 {
434         struct sllin *sl = netdev_priv(dev);
435
436         netdev_dbg(sl->dev, "%s() invoked\n", __func__);
437
438         if (sl->tty == NULL)
439                 return -ENODEV;
440
441         sl->flags &= (1 << SLF_INUSE);
442         netif_start_queue(dev);
443         return 0;
444 }
445
446 /* Hook the destructor so we can free sllin devs at the right point in time */
447 static void sll_free_netdev(struct net_device *dev)
448 {
449         int i = dev->base_addr;
450         free_netdev(dev);
451         sllin_devs[i] = NULL;
452 }
453
454 static const struct net_device_ops sll_netdev_ops = {
455         .ndo_open               = sll_open,
456         .ndo_stop               = sll_close,
457         .ndo_start_xmit         = sll_xmit,
458 };
459
460 static void sll_setup(struct net_device *dev)
461 {
462         dev->netdev_ops         = &sll_netdev_ops;
463         dev->destructor         = sll_free_netdev;
464
465         dev->hard_header_len    = 0;
466         dev->addr_len           = 0;
467         dev->tx_queue_len       = 10;
468
469         dev->mtu                = sizeof(struct can_frame);
470         dev->type               = ARPHRD_CAN;
471
472         /* New-style flags. */
473         dev->flags              = IFF_NOARP;
474         dev->features           = NETIF_F_HW_CSUM; /* NETIF_F_NO_CSUM;*/
475 }
476
477 /******************************************
478   Routines looking at TTY side.
479  ******************************************/
480 static void sllin_master_receive_buf(struct tty_struct *tty,
481                               const unsigned char *cp, char *fp, int count)
482 {
483         struct sllin *sl = (struct sllin *) tty->disc_data;
484
485         /* Read the characters out of the buffer */
486         while (count--) {
487                 if (fp && *fp++) {
488                         netdev_dbg(sl->dev, "sllin_master_receive_buf char 0x%02x ignored "
489                                 "due marker 0x%02x, flags 0x%lx\n",
490                                 *cp, *(fp-1), sl->flags);
491
492                         /* i.e. Real error -- not Break */
493                         if (sl->rx_cnt > SLLIN_BUFF_BREAK) {
494                                 set_bit(SLF_ERROR, &sl->flags);
495                                 wake_up(&sl->kwt_wq);
496                                 return;
497                         }
498                 }
499
500 #ifndef BREAK_BY_BAUD
501                 /* We didn't receive Break character -- fake it! */
502                 if ((sl->rx_cnt == SLLIN_BUFF_BREAK) && (*cp == 0x55)) {
503                         netdev_dbg(sl->dev, "LIN_RX[%d]: 0x00\n", sl->rx_cnt);
504                         sl->rx_buff[sl->rx_cnt++] = 0x00;
505                 }
506 #endif /* BREAK_BY_BAUD */
507
508                 if (sl->rx_cnt < SLLIN_BUFF_LEN) {
509                         netdev_dbg(sl->dev, "LIN_RX[%d]: 0x%02x\n", sl->rx_cnt, *cp);
510                         sl->rx_buff[sl->rx_cnt++] = *cp++;
511                 }
512         }
513
514
515         if (sl->rx_cnt >= sl->rx_expect) {
516                 set_bit(SLF_RXEVENT, &sl->flags);
517                 wake_up(&sl->kwt_wq);
518                 netdev_dbg(sl->dev, "sllin_receive_buf count %d, wakeup\n", sl->rx_cnt);
519         } else {
520                 netdev_dbg(sl->dev, "sllin_receive_buf count %d, waiting\n", sl->rx_cnt);
521         }
522 }
523
524
525 /*****************************************
526  *  sllin message helper routines
527  *****************************************/
528 /**
529  * sllin_report_error() -- Report an error by sending CAN frame
530  *      with particular error flag set in can_id
531  *
532  * @sl:
533  * @err: Error flag to be sent.
534  */
535 static void sllin_report_error(struct sllin *sl, int err)
536 {
537         unsigned char *lin_buff;
538         int lin_id;
539
540         switch (err) {
541         case LIN_ERR_CHECKSUM:
542                 sl->dev->stats.rx_crc_errors++;
543                 break;
544
545         case LIN_ERR_RX_TIMEOUT:
546                 sl->dev->stats.rx_errors++;
547                 break;
548
549         case LIN_ERR_FRAMING:
550                 sl->dev->stats.rx_frame_errors++;
551                 break;
552         }
553
554         lin_buff = (sl->lin_master) ? sl->tx_buff : sl->rx_buff;
555         lin_id = lin_buff[SLLIN_BUFF_ID] & LIN_ID_MASK;
556         sllin_send_canfr(sl, lin_id | CAN_EFF_FLAG |
557                 (err & ~LIN_ID_MASK), NULL, 0);
558 }
559
560 /**
561  * sllin_configure_frame_cache() -- Configure particular entry in linfr_cache
562  *
563  * @sl:
564  * @cf: Pointer to CAN frame sent to this driver
565  *      holding configuration information
566  */
567 static int sllin_configure_frame_cache(struct sllin *sl, struct can_frame *cf)
568 {
569         unsigned long flags;
570         struct sllin_conf_entry *sce;
571
572         if (!(cf->can_id & LIN_CTRL_FRAME))
573                 return -1;
574
575         sce = &sl->linfr_cache[cf->can_id & LIN_ID_MASK];
576         netdev_dbg(sl->dev, "Setting frame cache with EFF CAN frame. LIN ID = %d\n",
577                 cf->can_id & LIN_ID_MASK);
578
579         spin_lock_irqsave(&sl->linfr_lock, flags);
580
581         sce->dlc = cf->can_dlc;
582         if (sce->dlc > SLLIN_DATA_MAX)
583                 sce->dlc = SLLIN_DATA_MAX;
584
585         sce->frame_fl = (cf->can_id & ~LIN_ID_MASK) & CAN_EFF_MASK;
586         memcpy(sce->data, cf->data, cf->can_dlc);
587
588         spin_unlock_irqrestore(&sl->linfr_lock, flags);
589
590         return 0;
591 }
592
593 /**
594  * sllin_checksum() -- Count checksum for particular data
595  *
596  * @data:        Pointer to the buffer containing whole LIN
597  *               frame (i.e. including break and sync bytes).
598  * @length:      Length of the buffer.
599  * @enhanced_fl: Flag determining whether Enhanced or Classic
600  *               checksum should be counted.
601  */
602 static inline unsigned sllin_checksum(unsigned char *data, int length, int enhanced_fl)
603 {
604         unsigned csum = 0;
605         int i;
606
607         if (enhanced_fl)
608                 i = SLLIN_BUFF_ID;
609         else
610                 i = SLLIN_BUFF_DATA;
611
612         for (; i < length; i++) {
613                 csum += data[i];
614                 if (csum > 255)
615                         csum -= 255;
616         }
617
618         return ~csum & 0xff;
619 }
620
621 #define SLLIN_STPMSG_RESPONLY           (1) /* Message will be LIN Response only */
622 #define SLLIN_STPMSG_CHCKSUM_CLS        (1 << 1)
623 #define SLLIN_STPMSG_CHCKSUM_ENH        (1 << 2)
624
625 static int sllin_setup_msg(struct sllin *sl, int mode, int id,
626                 unsigned char *data, int len)
627 {
628         if (id > LIN_ID_MASK)
629                 return -1;
630
631         if (!(mode & SLLIN_STPMSG_RESPONLY)) {
632                 sl->rx_cnt = 0;
633                 sl->tx_cnt = 0;
634                 sl->rx_expect = 0;
635                 sl->rx_lim = SLLIN_BUFF_LEN;
636         }
637
638         sl->tx_buff[SLLIN_BUFF_BREAK] = 0;
639         sl->tx_buff[SLLIN_BUFF_SYNC]  = 0x55;
640         sl->tx_buff[SLLIN_BUFF_ID]    = id | sllin_id_parity_table[id];
641         sl->tx_lim = SLLIN_BUFF_DATA;
642
643         if ((data != NULL) && len) {
644                 sl->tx_lim += len;
645                 memcpy(sl->tx_buff + SLLIN_BUFF_DATA, data, len);
646                 sl->tx_buff[sl->tx_lim] = sllin_checksum(sl->tx_buff,
647                                 sl->tx_lim, mode & SLLIN_STPMSG_CHCKSUM_ENH);
648                 sl->tx_lim++;
649         }
650         if (len != 0)
651                 sl->rx_lim = SLLIN_BUFF_DATA + len + 1;
652
653         return 0;
654 }
655
656 static void sllin_reset_buffs(struct sllin *sl)
657 {
658         sl->rx_cnt = 0;
659         sl->rx_expect = 0;
660         sl->rx_lim = sl->lin_master ? 0 : SLLIN_BUFF_LEN;
661         sl->tx_cnt = 0;
662         sl->tx_lim = 0;
663         sl->id_to_send = false;
664         sl->data_to_send = false;
665 }
666
667 /**
668  * sllin_rx_validate() -- Validate received frame, i,e. check checksum
669  *
670  * @sl:
671  */
672 static int sllin_rx_validate(struct sllin *sl)
673 {
674         unsigned long flags;
675         int actual_id;
676         int ext_chcks_fl;
677         int lin_dlc;
678         unsigned char rec_chcksm = sl->rx_buff[sl->rx_cnt - 1];
679         struct sllin_conf_entry *sce;
680
681         actual_id = sl->rx_buff[SLLIN_BUFF_ID] & LIN_ID_MASK;
682         sce = &sl->linfr_cache[actual_id];
683
684         spin_lock_irqsave(&sl->linfr_lock, flags);
685         lin_dlc = sce->dlc;
686         ext_chcks_fl = sce->frame_fl & LIN_CHECKSUM_EXTENDED;
687         spin_unlock_irqrestore(&sl->linfr_lock, flags);
688
689         if (sllin_checksum(sl->rx_buff, sl->rx_cnt - 1, ext_chcks_fl) !=
690                 rec_chcksm) {
691
692                 /* Type of checksum is configured for particular frame */
693                 if (lin_dlc > 0) {
694                         return -1;
695                 } else {
696                         if (sllin_checksum(sl->rx_buff, sl->rx_cnt - 1,
697                                 !ext_chcks_fl) != rec_chcksm) {
698                                 return -1;
699                         }
700                 }
701         }
702
703         return 0;
704 }
705
706 static void sllin_slave_finish_rx_msg(struct sllin *sl)
707 {
708         if (sllin_rx_validate(sl) == -1) {
709                 netdev_dbg(sl->dev, "sllin: RX validation failed.\n");
710                 sllin_report_error(sl, LIN_ERR_CHECKSUM);
711         } else {
712                 /* Send CAN non-RTR frame with data */
713                 netdev_dbg(sl->dev, "sllin: sending NON-RTR CAN frame with LIN payload.");
714                 sll_bump(sl); /* send packet to the network layer */
715         }
716         /* Prepare for reception of new header */
717         sl->rx_cnt = 0;
718         sl->rx_expect = SLLIN_BUFF_ID + 1;
719         sl->rx_len_unknown = false; /* We do know exact length of the header */
720         sl->header_received = false;
721 }
722
723 static void sllin_slave_receive_buf(struct tty_struct *tty,
724                               const unsigned char *cp, char *fp, int count)
725 {
726         struct sllin *sl = (struct sllin *) tty->disc_data;
727         int lin_id;
728         struct sllin_conf_entry *sce;
729
730
731         /* Read the characters out of the buffer */
732         while (count--) {
733                 if (fp && *fp++) {
734                         /*
735                          * If we don't know the length of the current message
736                          * and received at least the LIN ID, we received here
737                          * the break of the next message.
738                          * Evaluate the previous one before continuing.
739                          */
740                         if ((sl->rx_len_unknown == true) &&
741                                 (sl->rx_cnt >= SLLIN_BUFF_ID))
742                         {
743                                 hrtimer_cancel(&sl->rx_timer);
744                                 sllin_slave_finish_rx_msg(sl);
745
746                                 set_bit(SLF_RXEVENT, &sl->flags);
747                                 wake_up(&sl->kwt_wq);
748                         }
749
750                         netdev_dbg(sl->dev, "sllin_slave_receive_buf char 0x%02x ignored "
751                                 "due marker 0x%02x, flags 0x%lx\n",
752                                 *cp, *(fp-1), sl->flags);
753
754                         /* Received Break */
755                         sl->rx_cnt = 0;
756                         sl->rx_expect = SLLIN_BUFF_ID + 1;
757                         sl->rx_len_unknown = false; /* We do know exact length of the header */
758                         sl->header_received = false;
759                 }
760
761                 if (sl->rx_cnt < SLLIN_BUFF_LEN) {
762                         netdev_dbg(sl->dev, "LIN_RX[%d]: 0x%02x\n", sl->rx_cnt, *cp);
763
764                         /* We did not receive break (0x00) character */
765                         if ((sl->rx_cnt == SLLIN_BUFF_BREAK) && (*cp == 0x55)) {
766                                 sl->rx_buff[sl->rx_cnt++] = 0x00;
767                         }
768
769                         if (sl->rx_cnt == SLLIN_BUFF_SYNC) {
770                                 /* 'Duplicated' break character -- ignore */
771                                 if (*cp == 0x00) {
772                                         cp++;
773                                         continue;
774                                 }
775
776                                 /* Wrong sync character */
777                                 if (*cp != 0x55)
778                                         break;
779                         }
780
781                         sl->rx_buff[sl->rx_cnt++] = *cp++;
782                 }
783
784                 /* Header received */
785                 if ((sl->header_received == false) && (sl->rx_cnt >= (SLLIN_BUFF_ID + 1))) {
786                         unsigned long flags;
787
788                         lin_id = sl->rx_buff[SLLIN_BUFF_ID] & LIN_ID_MASK;
789                         sce = &sl->linfr_cache[lin_id];
790
791                         spin_lock_irqsave(&sl->linfr_lock, flags);
792
793                         sl->lin_state = SLSTATE_ID_RECEIVED;
794                         /* Is the length of data set in frame cache? */
795                         if (sce->dlc > 0) {
796                                 sl->rx_expect += sce->dlc + 1; /* + checksum */
797                                 sl->rx_len_unknown = false;
798                                 wake_up(&sl->kwt_wq);
799                         } else {
800                                 sl->rx_expect += SLLIN_DATA_MAX + 1; /* + checksum */
801                                 sl->rx_len_unknown = true;
802                         }
803                         spin_unlock_irqrestore(&sl->linfr_lock, flags);
804
805                         sl->header_received = true;
806
807                         hrtimer_start(&sl->rx_timer,
808                                 ktime_add(ktime_get(), sl->rx_timer_timeout),
809                                 HRTIMER_MODE_ABS);
810                         sll_send_rtr(sl);
811                         continue;
812                 }
813
814                 /* Response received */
815                 if ((sl->header_received == true) &&
816                         ((sl->rx_cnt >= sl->rx_expect))) {
817
818                         hrtimer_cancel(&sl->rx_timer);
819                         netdev_dbg(sl->dev, "Received LIN header & LIN response. "
820                                         "rx_cnt = %u, rx_expect = %u\n", sl->rx_cnt,
821                                         sl->rx_expect);
822                         sllin_slave_finish_rx_msg(sl);
823
824                         set_bit(SLF_RXEVENT, &sl->flags);
825                         wake_up(&sl->kwt_wq);
826                 }
827         }
828 }
829
830 static void sllin_receive_buf(struct tty_struct *tty,
831                               const unsigned char *cp, char *fp, int count)
832 {
833         struct sllin *sl = (struct sllin *) tty->disc_data;
834         netdev_dbg(sl->dev, "sllin_receive_buf invoked, count = %u\n", count);
835
836         if (!sl || sl->magic != SLLIN_MAGIC || !netif_running(sl->dev))
837                 return;
838
839         if (sl->lin_master)
840                 sllin_master_receive_buf(tty, cp, fp, count);
841         else
842                 sllin_slave_receive_buf(tty, cp, fp, count);
843
844 }
845
846 static int sllin_send_tx_buff(struct sllin *sl)
847 {
848         struct tty_struct *tty = sl->tty;
849         int remains;
850         int res;
851
852         set_bit(SLF_TXBUFF_RQ, &sl->flags);
853         do {
854                 if (unlikely(test_and_set_bit(SLF_TXBUFF_INPR, &sl->flags)))
855                         return 0;       /* ongoing concurrent processing */
856
857                 clear_bit(SLF_TXBUFF_RQ, &sl->flags);
858 #if LINUX_VERSION_CODE < KERNEL_VERSION(3, 18, 0)
859                 smp_mb__after_clear_bit();
860 #else
861                 smp_mb__after_atomic();
862 #endif
863
864 #ifdef BREAK_BY_BAUD
865                 if (sl->lin_state != SLSTATE_BREAK_SENT)
866                         remains = sl->tx_lim - sl->tx_cnt;
867                 else
868                         remains = 1;
869 #else
870                 remains = sl->tx_lim - sl->tx_cnt;
871 #endif
872
873                 res = tty->ops->write(tty, sl->tx_buff + sl->tx_cnt, remains);
874                 if (res < 0)
875                         goto error_in_write;
876
877                 remains -= res;
878                 sl->tx_cnt += res;
879
880                 if (remains > 0) {
881                         set_bit(TTY_DO_WRITE_WAKEUP, &tty->flags);
882                         res = tty->ops->write(tty, sl->tx_buff + sl->tx_cnt, remains);
883                         if (res < 0) {
884                                 clear_bit(TTY_DO_WRITE_WAKEUP, &tty->flags);
885                                 goto error_in_write;
886                         }
887
888                         remains -= res;
889                         sl->tx_cnt += res;
890                 }
891
892                 netdev_dbg(sl->dev, "sllin_send_tx_buff sent %d, remains %d\n",
893                                 sl->tx_cnt, remains);
894
895                 clear_bit(SLF_TXBUFF_INPR, &sl->flags);
896 #if LINUX_VERSION_CODE < KERNEL_VERSION(3, 18, 0)
897                 smp_mb__after_clear_bit();
898 #else
899                 smp_mb__after_atomic();
900 #endif
901
902         } while (unlikely(test_bit(SLF_TXBUFF_RQ, &sl->flags)));
903
904         return 0;
905
906 error_in_write:
907         clear_bit(SLF_TXBUFF_INPR, &sl->flags);
908         return -1;
909
910 }
911
912 #ifdef BREAK_BY_BAUD
913 static int sllin_send_break(struct sllin *sl)
914 {
915         struct tty_struct *tty = sl->tty;
916         unsigned long break_baud;
917         int res;
918
919         break_baud = ((sl->lin_baud * 2) / 3);
920         sltty_change_speed(tty, break_baud);
921
922         tty->ops->flush_buffer(tty);
923         sl->rx_cnt = SLLIN_BUFF_BREAK;
924
925         sl->rx_expect = SLLIN_BUFF_BREAK + 1;
926         sl->lin_state = SLSTATE_BREAK_SENT;
927
928         res = sllin_send_tx_buff(sl);
929         if (res < 0) {
930                 sl->lin_state = SLSTATE_IDLE;
931                 return res;
932         }
933
934         return 0;
935 }
936 #else /* BREAK_BY_BAUD */
937
938 static int sllin_send_break(struct sllin *sl)
939 {
940         struct tty_struct *tty = sl->tty;
941         int retval;
942         unsigned long break_baud;
943         unsigned long usleep_range_min;
944         unsigned long usleep_range_max;
945
946         break_baud = ((sl->lin_baud * 2) / 3);
947         sl->rx_cnt = SLLIN_BUFF_BREAK;
948         sl->rx_expect = SLLIN_BUFF_BREAK + 1;
949         sl->lin_state = SLSTATE_BREAK_SENT;
950
951         /* Do the break ourselves; Inspired by
952            http://lxr.linux.no/#linux+v3.1.2/drivers/tty/tty_io.c#L2452 */
953         retval = tty->ops->break_ctl(tty, -1);
954         if (retval)
955                 return retval;
956
957         /* udelay(712); */
958         usleep_range_min = (1000000l * SLLIN_SAMPLES_PER_CHAR) / break_baud;
959         usleep_range_max = usleep_range_min + 50;
960         usleep_range(usleep_range_min, usleep_range_max);
961
962         retval = tty->ops->break_ctl(tty, 0);
963         usleep_range_min = (1000000l * 1 /* 1 bit */) / break_baud;
964         usleep_range_max = usleep_range_min + 30;
965         usleep_range(usleep_range_min, usleep_range_max);
966
967         tty->ops->flush_buffer(tty);
968
969         sl->tx_cnt = SLLIN_BUFF_SYNC;
970
971         netdev_dbg(sl->dev, "Break sent.\n");
972         set_bit(SLF_RXEVENT, &sl->flags);
973         wake_up(&sl->kwt_wq);
974
975         return 0;
976 }
977 #endif /* BREAK_BY_BAUD */
978
979
980 static enum hrtimer_restart sllin_rx_timeout_handler(struct hrtimer *hrtimer)
981 {
982         struct sllin *sl = container_of(hrtimer, struct sllin, rx_timer);
983
984         /*
985          * Signal timeout when:
986          * master: We did not receive as much characters as expected
987          * slave: * we did not receive any data bytes at all
988          *        * we know the length and didn't receive enough
989          */
990         if ((sl->lin_master) ||
991                         (sl->rx_cnt <= SLLIN_BUFF_DATA) ||
992                         ((!sl->rx_len_unknown) &&
993                         (sl->rx_cnt < sl->rx_expect))) {
994                 sllin_report_error(sl, LIN_ERR_RX_TIMEOUT);
995                 set_bit(SLF_TMOUTEVENT, &sl->flags);
996         } else {
997                 sllin_slave_finish_rx_msg(sl);
998                 set_bit(SLF_RXEVENT, &sl->flags);
999         }
1000         wake_up(&sl->kwt_wq);
1001
1002         return HRTIMER_NORESTART;
1003 }
1004
1005 /*****************************************
1006  *  sllin_kwthread - kernel worker thread
1007  *****************************************/
1008
1009 static int sllin_kwthread(void *ptr)
1010 {
1011         struct sllin *sl = (struct sllin *)ptr;
1012         struct tty_struct *tty = sl->tty;
1013         struct sched_param schparam = { .sched_priority = 40 };
1014         int tx_bytes = 0; /* Used for Network statistics */
1015         unsigned long flags;
1016         int mode;
1017         int lin_id;
1018         struct sllin_conf_entry *sce;
1019
1020         netdev_dbg(sl->dev, "sllin_kwthread started.\n");
1021         sched_setscheduler(current, SCHED_FIFO, &schparam);
1022
1023         clear_bit(SLF_ERROR, &sl->flags);
1024         sltty_change_speed(tty, sl->lin_baud);
1025
1026         while (!kthread_should_stop()) {
1027                 struct can_frame *cf;
1028                 u8 *lin_data;
1029                 int lin_dlc;
1030                 u8 lin_data_buff[SLLIN_DATA_MAX];
1031
1032
1033                 if ((sl->lin_state == SLSTATE_IDLE) && sl->lin_master &&
1034                         sl->id_to_send) {
1035                         if (sllin_send_break(sl) < 0) {
1036                                 /* error processing */
1037                         }
1038                 }
1039
1040                 wait_event_killable(sl->kwt_wq, kthread_should_stop() ||
1041                         test_bit(SLF_RXEVENT, &sl->flags) ||
1042                         test_bit(SLF_TXEVENT, &sl->flags) ||
1043                         test_bit(SLF_TMOUTEVENT, &sl->flags) ||
1044                         test_bit(SLF_ERROR, &sl->flags) ||
1045                         (sl->lin_state == SLSTATE_ID_RECEIVED) ||
1046                         (((sl->lin_state == SLSTATE_IDLE) ||
1047                                 (sl->lin_state == SLSTATE_RESPONSE_WAIT))
1048                                 && test_bit(SLF_MSGEVENT, &sl->flags)));
1049
1050                 if (test_and_clear_bit(SLF_RXEVENT, &sl->flags)) {
1051                         netdev_dbg(sl->dev, "sllin_kthread RXEVENT\n");
1052                 }
1053
1054                 if (test_and_clear_bit(SLF_ERROR, &sl->flags)) {
1055                         unsigned long usleep_range_min;
1056                         unsigned long usleep_range_max;
1057                         hrtimer_cancel(&sl->rx_timer);
1058                         netdev_dbg(sl->dev, "sllin_kthread ERROR\n");
1059
1060                         if (sl->lin_state != SLSTATE_IDLE)
1061                                 sllin_report_error(sl, LIN_ERR_FRAMING);
1062
1063                         usleep_range_min = (1000000l * SLLIN_SAMPLES_PER_CHAR * 10) /
1064                                                 sl->lin_baud;
1065                         usleep_range_max = usleep_range_min + 50;
1066                         usleep_range(usleep_range_min, usleep_range_max);
1067                         sllin_reset_buffs(sl);
1068                         sl->lin_state = SLSTATE_IDLE;
1069                 }
1070
1071                 if (test_and_clear_bit(SLF_TXEVENT, &sl->flags)) {
1072                         netdev_dbg(sl->dev, "sllin_kthread TXEVENT\n");
1073                 }
1074
1075                 if (test_and_clear_bit(SLF_TMOUTEVENT, &sl->flags)) {
1076                         netdev_dbg(sl->dev, "sllin_kthread TMOUTEVENT\n");
1077                         sllin_reset_buffs(sl);
1078
1079                         sl->lin_state = SLSTATE_IDLE;
1080                 }
1081
1082                 switch (sl->lin_state) {
1083                 case SLSTATE_IDLE:
1084                         if (!test_bit(SLF_MSGEVENT, &sl->flags))
1085                                 break;
1086
1087                         mode = 0;
1088                         cf = (struct can_frame *)sl->tx_req_skb->data;
1089
1090                         if (cf->can_id & LIN_CHECKSUM_EXTENDED)
1091                                 mode |= SLLIN_STPMSG_CHCKSUM_ENH;
1092
1093                         /* SFF RTR CAN frame -> LIN header */
1094                         if (cf->can_id & CAN_RTR_FLAG) {
1095                                 struct sllin_conf_entry *sce;
1096
1097                                 netdev_dbg(sl->dev, "%s: RTR SFF CAN frame, ID = %x\n",
1098                                         __func__, cf->can_id & LIN_ID_MASK);
1099
1100                                 sce = &sl->linfr_cache[cf->can_id & LIN_ID_MASK];
1101                                 spin_lock_irqsave(&sl->linfr_lock, flags);
1102                                 if (sce->frame_fl & LIN_CHECKSUM_EXTENDED)
1103                                         mode |= SLLIN_STPMSG_CHCKSUM_ENH;
1104
1105                                 /* Is there Slave response in linfr_cache to be sent? */
1106                                 if ((sce->frame_fl & LIN_CACHE_RESPONSE)
1107                                         && (sce->dlc > 0)) {
1108
1109                                         netdev_dbg(sl->dev, "Sending LIN response from linfr_cache\n");
1110
1111                                         lin_data = sce->data;
1112                                         lin_dlc = sce->dlc;
1113                                         if (lin_dlc > SLLIN_DATA_MAX)
1114                                                 lin_dlc = SLLIN_DATA_MAX;
1115                                         memcpy(lin_data_buff, lin_data, lin_dlc);
1116                                         lin_data = lin_data_buff;
1117                                 } else {
1118                                         lin_data = NULL;
1119                                         lin_dlc = sce->dlc;
1120                                 }
1121                                 spin_unlock_irqrestore(&sl->linfr_lock, flags);
1122
1123                         } else { /* SFF NON-RTR CAN frame -> LIN header + LIN response */
1124                                 struct sllin_conf_entry *sce;
1125
1126                                 netdev_dbg(sl->dev, "%s: NON-RTR SFF CAN frame, ID = %x\n",
1127                                         __func__, (int)cf->can_id & LIN_ID_MASK);
1128
1129                                 sce = &sl->linfr_cache[cf->can_id & LIN_ID_MASK];
1130                                 if (sce->frame_fl & LIN_CHECKSUM_EXTENDED)
1131                                         mode |= SLLIN_STPMSG_CHCKSUM_ENH;
1132
1133                                 lin_data = cf->data;
1134                                 lin_dlc = cf->can_dlc;
1135                                 if (lin_dlc > SLLIN_DATA_MAX)
1136                                         lin_dlc = SLLIN_DATA_MAX;
1137                                 tx_bytes = lin_dlc;
1138                         }
1139
1140                         if (sllin_setup_msg(sl, mode, cf->can_id & LIN_ID_MASK,
1141                                 lin_data, lin_dlc) != -1) {
1142
1143                                 sl->id_to_send = true;
1144                                 sl->data_to_send = (lin_data != NULL) ? true : false;
1145                                 sl->resp_len_known = (lin_dlc > 0) ? true : false;
1146                                 sl->dev->stats.tx_packets++;
1147                                 sl->dev->stats.tx_bytes += tx_bytes;
1148                         }
1149
1150                         clear_bit(SLF_MSGEVENT, &sl->flags);
1151                         kfree_skb(sl->tx_req_skb);
1152                         netif_wake_queue(sl->dev);
1153                         hrtimer_start(&sl->rx_timer,
1154                                 ktime_add(ktime_get(), sl->rx_timer_timeout),
1155                                 HRTIMER_MODE_ABS);
1156                         break;
1157
1158                 case SLSTATE_BREAK_SENT:
1159 #ifdef BREAK_BY_BAUD
1160                         if (sl->rx_cnt <= SLLIN_BUFF_BREAK)
1161                                 continue;
1162
1163                         res = sltty_change_speed(tty, sl->lin_baud);
1164 #endif
1165
1166                         sl->lin_state = SLSTATE_ID_SENT;
1167                         sllin_send_tx_buff(sl);
1168                         break;
1169
1170                 case SLSTATE_ID_SENT:
1171                         hrtimer_cancel(&sl->rx_timer);
1172                         sl->id_to_send = false;
1173                         if (sl->data_to_send) {
1174                                 sllin_send_tx_buff(sl);
1175                                 sl->lin_state = SLSTATE_RESPONSE_SENT;
1176                                 sl->rx_expect = sl->tx_lim;
1177                                 goto slstate_response_sent;
1178                         } else {
1179                                 if (sl->resp_len_known) {
1180                                         sl->rx_expect = sl->rx_lim;
1181                                 } else {
1182                                         sl->rx_expect = SLLIN_BUFF_DATA + 2;
1183                                 }
1184                                 sl->lin_state = SLSTATE_RESPONSE_WAIT;
1185                                 /* If we don't receive anything, timer will "unblock" us */
1186                                 hrtimer_start(&sl->rx_timer,
1187                                         ktime_add(ktime_get(), sl->rx_timer_timeout),
1188                                         HRTIMER_MODE_ABS);
1189                                 goto slstate_response_wait;
1190                         }
1191                         break;
1192
1193                 case SLSTATE_RESPONSE_WAIT:
1194 slstate_response_wait:
1195                         if (test_bit(SLF_MSGEVENT, &sl->flags)) {
1196                                 unsigned char *lin_buff;
1197                                 cf = (struct can_frame *)sl->tx_req_skb->data;
1198
1199                                 lin_buff = (sl->lin_master) ? sl->tx_buff : sl->rx_buff;
1200                                 if (cf->can_id == (lin_buff[SLLIN_BUFF_ID] & LIN_ID_MASK)) {
1201                                         hrtimer_cancel(&sl->rx_timer);
1202                                         netdev_dbg(sl->dev, "received LIN response in a CAN frame.\n");
1203                                         if (sllin_setup_msg(sl, SLLIN_STPMSG_RESPONLY,
1204                                                 cf->can_id & LIN_ID_MASK,
1205                                                 cf->data, cf->can_dlc) != -1) {
1206
1207                                                 sl->rx_expect = sl->tx_lim;
1208                                                 sl->data_to_send = true;
1209                                                 sl->dev->stats.tx_packets++;
1210                                                 sl->dev->stats.tx_bytes += tx_bytes;
1211
1212                                                 if (!sl->lin_master) {
1213                                                         sl->tx_cnt = SLLIN_BUFF_DATA;
1214                                                 }
1215
1216                                                 sllin_send_tx_buff(sl);
1217                                                 clear_bit(SLF_MSGEVENT, &sl->flags);
1218                                                 kfree_skb(sl->tx_req_skb);
1219                                                 netif_wake_queue(sl->dev);
1220
1221                                                 sl->lin_state = SLSTATE_RESPONSE_SENT;
1222                                                 goto slstate_response_sent;
1223                                         }
1224                                 } else {
1225                                         sl->lin_state = SLSTATE_RESPONSE_WAIT_BUS;
1226                                 }
1227                         }
1228
1229                         /* Be aware, no BREAK here */
1230                 case SLSTATE_RESPONSE_WAIT_BUS:
1231                         if (sl->rx_cnt < sl->rx_expect)
1232                                 continue;
1233
1234                         hrtimer_cancel(&sl->rx_timer);
1235                         netdev_dbg(sl->dev, "response received ID %d len %d\n",
1236                                 sl->rx_buff[SLLIN_BUFF_ID], sl->rx_cnt - SLLIN_BUFF_DATA - 1);
1237
1238                         if (sllin_rx_validate(sl) == -1) {
1239                                 netdev_dbg(sl->dev, "RX validation failed.\n");
1240                                 sllin_report_error(sl, LIN_ERR_CHECKSUM);
1241                         } else {
1242                                 /* Send CAN non-RTR frame with data */
1243                                 netdev_dbg(sl->dev, "sending NON-RTR CAN frame with LIN payload.");
1244                                 sll_bump(sl); /* send packet to the network layer */
1245                         }
1246
1247                         sl->id_to_send = false;
1248                         sl->lin_state = SLSTATE_IDLE;
1249                         break;
1250
1251                 case SLSTATE_ID_RECEIVED:
1252                         lin_id = sl->rx_buff[SLLIN_BUFF_ID] & LIN_ID_MASK;
1253                         sce = &sl->linfr_cache[lin_id];
1254                         spin_lock_irqsave(&sl->linfr_lock, flags);
1255
1256                         if ((sce->frame_fl & LIN_CACHE_RESPONSE)
1257                                         && (sce->dlc > 0)) {
1258
1259                                 netdev_dbg(sl->dev, "Sending LIN response from linfr_cache\n");
1260
1261                                 lin_data = sce->data;
1262                                 lin_dlc = sce->dlc;
1263                                 if (lin_dlc > SLLIN_DATA_MAX)
1264                                         lin_dlc = SLLIN_DATA_MAX;
1265                                 memcpy(lin_data_buff, lin_data, lin_dlc);
1266                                 lin_data = lin_data_buff;
1267                                 tx_bytes = lin_dlc;
1268
1269                                 mode = SLLIN_STPMSG_RESPONLY;
1270                                 if (sce->frame_fl & LIN_CHECKSUM_EXTENDED)
1271                                         mode |= SLLIN_STPMSG_CHCKSUM_ENH;
1272
1273                                 if (sllin_setup_msg(sl, mode, lin_id & LIN_ID_MASK,
1274                                         lin_data, lin_dlc) != -1) {
1275
1276                                         sl->rx_expect = sl->tx_lim;
1277                                         sl->data_to_send = true;
1278                                         sl->dev->stats.tx_packets++;
1279                                         sl->dev->stats.tx_bytes += tx_bytes;
1280                                         sl->resp_len_known = true;
1281
1282                                         if (!sl->lin_master) {
1283                                                 sl->tx_cnt = SLLIN_BUFF_DATA;
1284                                         }
1285                                         sllin_send_tx_buff(sl);
1286                                 }
1287
1288                                 hrtimer_start(&sl->rx_timer,
1289                                         ktime_add(ktime_get(), sl->rx_timer_timeout),
1290                                         HRTIMER_MODE_ABS);
1291                         }
1292                         spin_unlock_irqrestore(&sl->linfr_lock, flags);
1293                         sl->lin_state = SLSTATE_IDLE;
1294                         break;
1295
1296                 case SLSTATE_RESPONSE_SENT:
1297 slstate_response_sent:
1298                         if (sl->rx_cnt < sl->tx_lim)
1299                                 continue;
1300
1301                         hrtimer_cancel(&sl->rx_timer);
1302                         sll_bump(sl); /* send packet to the network layer */
1303                         netdev_dbg(sl->dev, "response sent ID %d len %d\n",
1304                                 sl->rx_buff[SLLIN_BUFF_ID], sl->rx_cnt - SLLIN_BUFF_DATA - 1);
1305
1306                         sl->id_to_send = false;
1307                         sl->lin_state = SLSTATE_IDLE;
1308                         break;
1309                 }
1310         }
1311
1312         hrtimer_cancel(&sl->rx_timer);
1313         netdev_dbg(sl->dev, "sllin_kwthread stopped.\n");
1314
1315         return 0;
1316 }
1317
1318
1319 /************************************
1320  *  sllin_open helper routines.
1321  ************************************/
1322
1323 /* Collect hanged up channels */
1324 static void sll_sync(void)
1325 {
1326         int i;
1327         struct net_device *dev;
1328         struct sllin      *sl;
1329
1330         for (i = 0; i < maxdev; i++) {
1331                 dev = sllin_devs[i];
1332                 if (dev == NULL)
1333                         break;
1334
1335                 sl = netdev_priv(dev);
1336                 if (sl->tty)
1337                         continue;
1338                 if (dev->flags & IFF_UP)
1339                         dev_close(dev);
1340         }
1341 }
1342
1343 /* Find a free SLLIN channel, and link in this `tty' line. */
1344 static struct sllin *sll_alloc(dev_t line)
1345 {
1346         int i;
1347         struct net_device *dev = NULL;
1348         struct sllin       *sl;
1349
1350         if (sllin_devs == NULL)
1351                 return NULL;    /* Master array missing ! */
1352
1353         for (i = 0; i < maxdev; i++) {
1354                 dev = sllin_devs[i];
1355                 if (dev == NULL)
1356                         break;
1357
1358         }
1359
1360         /* Sorry, too many, all slots in use */
1361         if (i >= maxdev)
1362                 return NULL;
1363
1364         if (dev) {
1365                 sl = netdev_priv(dev);
1366                 if (test_bit(SLF_INUSE, &sl->flags)) {
1367                         unregister_netdevice(dev);
1368                         dev = NULL;
1369                         sllin_devs[i] = NULL;
1370                 }
1371         }
1372
1373         if (!dev) {
1374                 char name[IFNAMSIZ];
1375                 sprintf(name, "sllin%d", i);
1376
1377 #if (LINUX_VERSION_CODE < KERNEL_VERSION(3, 17, 0))
1378                 dev = alloc_netdev(sizeof(*sl), name, sll_setup);
1379 #else
1380                 dev = alloc_netdev(sizeof(*sl), name, NET_NAME_UNKNOWN, sll_setup);
1381 #endif
1382
1383                 if (!dev)
1384                         return NULL;
1385                 dev->base_addr  = i;
1386         }
1387
1388         sl = netdev_priv(dev);
1389         /* Initialize channel control data */
1390         sl->magic = SLLIN_MAGIC;
1391         sl->dev = dev;
1392         spin_lock_init(&sl->lock);
1393         spin_lock_init(&sl->linfr_lock);
1394         sllin_devs[i] = dev;
1395
1396         return sl;
1397 }
1398
1399 /*
1400  * Open the high-level part of the SLLIN channel.
1401  * This function is called by the TTY module when the
1402  * SLLIN line discipline is called for.  Because we are
1403  * sure the tty line exists, we only have to link it to
1404  * a free SLLIN channel...
1405  *
1406  * Called in process context serialized from other ldisc calls.
1407  */
1408
1409 static int sllin_open(struct tty_struct *tty)
1410 {
1411         struct sllin *sl;
1412         int err;
1413
1414         pr_debug("sllin: %s() invoked\n", __func__);
1415
1416         if (!capable(CAP_NET_ADMIN))
1417                 return -EPERM;
1418
1419         if (tty->ops->write == NULL)
1420                 return -EOPNOTSUPP;
1421
1422         /* RTnetlink lock is misused here to serialize concurrent
1423            opens of sllin channels. There are better ways, but it is
1424            the simplest one.
1425          */
1426         rtnl_lock();
1427
1428         /* Collect hanged up channels. */
1429         sll_sync();
1430
1431         sl = tty->disc_data;
1432
1433         err = -EEXIST;
1434         /* First make sure we're not already connected. */
1435         if (sl && sl->magic == SLLIN_MAGIC)
1436                 goto err_exit;
1437
1438         /* OK.  Find a free SLLIN channel to use. */
1439         err = -ENFILE;
1440         sl = sll_alloc(tty_devnum(tty));
1441         if (sl == NULL)
1442                 goto err_exit;
1443
1444         sl->tty = tty;
1445         tty->disc_data = sl;
1446         sl->line = tty_devnum(tty);
1447
1448         if (!test_bit(SLF_INUSE, &sl->flags)) {
1449                 /* Perform the low-level SLLIN initialization. */
1450                 sl->lin_master = master;
1451                 if (master)
1452                         pr_debug("sllin: Configured as MASTER\n");
1453                 else
1454                         pr_debug("sllin: Configured as SLAVE\n");
1455
1456                 sllin_reset_buffs(sl);
1457
1458                 sl->lin_baud = (baudrate == 0) ? LIN_DEFAULT_BAUDRATE : baudrate;
1459                 pr_debug("sllin: Baudrate set to %u\n", sl->lin_baud);
1460
1461                 sl->lin_state = SLSTATE_IDLE;
1462
1463                 hrtimer_init(&sl->rx_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
1464                 sl->rx_timer.function = sllin_rx_timeout_handler;
1465                 /* timeval_to_ktime(msg_head->ival1); */
1466                 sl->rx_timer_timeout = ns_to_ktime(
1467                         (1000000000l / sl->lin_baud) *
1468                         SLLIN_SAMPLES_PER_CHAR * SLLIN_CHARS_TO_TIMEOUT);
1469
1470                 set_bit(SLF_INUSE, &sl->flags);
1471
1472                 init_waitqueue_head(&sl->kwt_wq);
1473                 sl->kwthread = kthread_run(sllin_kwthread, sl, "sllin");
1474                 if (sl->kwthread == NULL)
1475                         goto err_free_chan;
1476
1477                 err = register_netdevice(sl->dev);
1478                 if (err)
1479                         goto err_free_chan_and_thread;
1480         }
1481
1482         /* Done.  We have linked the TTY line to a channel. */
1483         rtnl_unlock();
1484         tty->receive_room = SLLIN_BUFF_LEN * 40; /* We don't flow control */
1485
1486         /* TTY layer expects 0 on success */
1487         return 0;
1488
1489 err_free_chan_and_thread:
1490         kthread_stop(sl->kwthread);
1491         sl->kwthread = NULL;
1492
1493 err_free_chan:
1494         sl->tty = NULL;
1495         tty->disc_data = NULL;
1496         clear_bit(SLF_INUSE, &sl->flags);
1497
1498 err_exit:
1499         rtnl_unlock();
1500
1501         /* Count references from TTY module */
1502         return err;
1503 }
1504
1505 /*
1506  * Close down a SLLIN channel.
1507  * This means flushing out any pending queues, and then returning. This
1508  * call is serialized against other ldisc functions.
1509  *
1510  * We also use this method for a hangup event.
1511  */
1512
1513 static void sllin_close(struct tty_struct *tty)
1514 {
1515         struct sllin *sl = (struct sllin *) tty->disc_data;
1516
1517         /* First make sure we're connected. */
1518         if (!sl || sl->magic != SLLIN_MAGIC || sl->tty != tty)
1519                 return;
1520
1521         kthread_stop(sl->kwthread);
1522         sl->kwthread = NULL;
1523
1524         tty->disc_data = NULL;
1525         sl->tty = NULL;
1526
1527         /* Flush network side */
1528         unregister_netdev(sl->dev);
1529         /* This will complete via sl_free_netdev */
1530 }
1531
1532 static int sllin_hangup(struct tty_struct *tty)
1533 {
1534         sllin_close(tty);
1535         return 0;
1536 }
1537
1538 /* Perform I/O control on an active SLLIN channel. */
1539 static int sllin_ioctl(struct tty_struct *tty, struct file *file,
1540                        unsigned int cmd, unsigned long arg)
1541 {
1542         struct sllin *sl = (struct sllin *) tty->disc_data;
1543         unsigned int tmp;
1544
1545         /* First make sure we're connected. */
1546         if (!sl || sl->magic != SLLIN_MAGIC)
1547                 return -EINVAL;
1548
1549         switch (cmd) {
1550         case SIOCGIFNAME:
1551                 tmp = strlen(sl->dev->name) + 1;
1552                 if (copy_to_user((void __user *)arg, sl->dev->name, tmp))
1553                         return -EFAULT;
1554                 return 0;
1555
1556         case SIOCSIFHWADDR:
1557                 return -EINVAL;
1558
1559         default:
1560                 return tty_mode_ioctl(tty, file, cmd, arg);
1561         }
1562 }
1563
1564 static struct tty_ldisc_ops sll_ldisc = {
1565         .owner          = THIS_MODULE,
1566         .magic          = TTY_LDISC_MAGIC,
1567         .name           = "sllin",
1568         .open           = sllin_open,
1569         .close          = sllin_close,
1570         .hangup         = sllin_hangup,
1571         .ioctl          = sllin_ioctl,
1572         .receive_buf    = sllin_receive_buf,
1573         .write_wakeup   = sllin_write_wakeup,
1574 };
1575
1576 static int __init sllin_init(void)
1577 {
1578         int status;
1579
1580         if (maxdev < 4)
1581                 maxdev = 4; /* Sanity */
1582
1583         printk(banner);
1584         pr_debug("sllin: %d dynamic interface channels.\n", maxdev);
1585
1586         sllin_devs = kzalloc(sizeof(struct net_device *)*maxdev, GFP_KERNEL);
1587         if (!sllin_devs) {
1588                 pr_err("sllin: can't allocate sllin device array!\n");
1589                 return -ENOMEM;
1590         }
1591
1592         /* Fill in our line protocol discipline, and register it */
1593         status = tty_register_ldisc(N_SLLIN, &sll_ldisc);
1594         if (status)  {
1595                 pr_err("sllin: can't register line discipline\n");
1596                 kfree(sllin_devs);
1597         }
1598
1599 #ifdef BREAK_BY_BAUD
1600         pr_debug("sllin: Break is generated by baud-rate change.");
1601 #else
1602         pr_debug("sllin: Break is generated manually with tiny sleep.");
1603 #endif
1604
1605         return status;
1606 }
1607
1608 static void __exit sllin_exit(void)
1609 {
1610         int i;
1611         struct net_device *dev;
1612         struct sllin *sl;
1613         unsigned long timeout = jiffies + HZ;
1614         int busy = 0;
1615
1616         if (sllin_devs == NULL)
1617                 return;
1618
1619         /* First of all: check for active disciplines and hangup them.
1620          */
1621         do {
1622                 if (busy)
1623                         msleep_interruptible(100);
1624
1625                 busy = 0;
1626                 for (i = 0; i < maxdev; i++) {
1627                         dev = sllin_devs[i];
1628                         if (!dev)
1629                                 continue;
1630                         sl = netdev_priv(dev);
1631                         spin_lock_bh(&sl->lock);
1632                         if (sl->tty) {
1633                                 busy++;
1634                                 tty_hangup(sl->tty);
1635                         }
1636                         spin_unlock_bh(&sl->lock);
1637                 }
1638         } while (busy && time_before(jiffies, timeout));
1639
1640         /* FIXME: hangup is async so we should wait when doing this second
1641            phase */
1642
1643         for (i = 0; i < maxdev; i++) {
1644                 dev = sllin_devs[i];
1645                 if (!dev)
1646                         continue;
1647                 sllin_devs[i] = NULL;
1648
1649                 sl = netdev_priv(dev);
1650                 if (sl->tty) {
1651                         netdev_dbg(sl->dev, "tty discipline still running\n");
1652                         /* Intentionally leak the control block. */
1653                         dev->destructor = NULL;
1654                 }
1655
1656                 unregister_netdev(dev);
1657         }
1658
1659         kfree(sllin_devs);
1660         sllin_devs = NULL;
1661
1662         i = tty_unregister_ldisc(N_SLLIN);
1663         if (i)
1664                 pr_err("sllin: can't unregister ldisc (err %d)\n", i);
1665 }
1666
1667 module_init(sllin_init);
1668 module_exit(sllin_exit);