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