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