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