net/sched: act_ipt: add sanity checks on table name and hook locations
[platform/kernel/linux-starfive.git] / net / can / isotp.c
1 // SPDX-License-Identifier: (GPL-2.0 OR BSD-3-Clause)
2 /* isotp.c - ISO 15765-2 CAN transport protocol for protocol family CAN
3  *
4  * This implementation does not provide ISO-TP specific return values to the
5  * userspace.
6  *
7  * - RX path timeout of data reception leads to -ETIMEDOUT
8  * - RX path SN mismatch leads to -EILSEQ
9  * - RX path data reception with wrong padding leads to -EBADMSG
10  * - TX path flowcontrol reception timeout leads to -ECOMM
11  * - TX path flowcontrol reception overflow leads to -EMSGSIZE
12  * - TX path flowcontrol reception with wrong layout/padding leads to -EBADMSG
13  * - when a transfer (tx) is on the run the next write() blocks until it's done
14  * - use CAN_ISOTP_WAIT_TX_DONE flag to block the caller until the PDU is sent
15  * - as we have static buffers the check whether the PDU fits into the buffer
16  *   is done at FF reception time (no support for sending 'wait frames')
17  *
18  * Copyright (c) 2020 Volkswagen Group Electronic Research
19  * All rights reserved.
20  *
21  * Redistribution and use in source and binary forms, with or without
22  * modification, are permitted provided that the following conditions
23  * are met:
24  * 1. Redistributions of source code must retain the above copyright
25  *    notice, this list of conditions and the following disclaimer.
26  * 2. Redistributions in binary form must reproduce the above copyright
27  *    notice, this list of conditions and the following disclaimer in the
28  *    documentation and/or other materials provided with the distribution.
29  * 3. Neither the name of Volkswagen nor the names of its contributors
30  *    may be used to endorse or promote products derived from this software
31  *    without specific prior written permission.
32  *
33  * Alternatively, provided that this notice is retained in full, this
34  * software may be distributed under the terms of the GNU General
35  * Public License ("GPL") version 2, in which case the provisions of the
36  * GPL apply INSTEAD OF those given above.
37  *
38  * The provided data structures and external interfaces from this code
39  * are not restricted to be used by modules with a GPL compatible license.
40  *
41  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
42  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
43  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
44  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
45  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
46  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
47  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
48  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
49  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
50  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
51  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
52  * DAMAGE.
53  */
54
55 #include <linux/module.h>
56 #include <linux/init.h>
57 #include <linux/interrupt.h>
58 #include <linux/spinlock.h>
59 #include <linux/hrtimer.h>
60 #include <linux/wait.h>
61 #include <linux/uio.h>
62 #include <linux/net.h>
63 #include <linux/netdevice.h>
64 #include <linux/socket.h>
65 #include <linux/if_arp.h>
66 #include <linux/skbuff.h>
67 #include <linux/can.h>
68 #include <linux/can/core.h>
69 #include <linux/can/skb.h>
70 #include <linux/can/isotp.h>
71 #include <linux/slab.h>
72 #include <net/sock.h>
73 #include <net/net_namespace.h>
74
75 MODULE_DESCRIPTION("PF_CAN isotp 15765-2:2016 protocol");
76 MODULE_LICENSE("Dual BSD/GPL");
77 MODULE_AUTHOR("Oliver Hartkopp <socketcan@hartkopp.net>");
78 MODULE_ALIAS("can-proto-6");
79
80 #define ISOTP_MIN_NAMELEN CAN_REQUIRED_SIZE(struct sockaddr_can, can_addr.tp)
81
82 #define SINGLE_MASK(id) (((id) & CAN_EFF_FLAG) ? \
83                          (CAN_EFF_MASK | CAN_EFF_FLAG | CAN_RTR_FLAG) : \
84                          (CAN_SFF_MASK | CAN_EFF_FLAG | CAN_RTR_FLAG))
85
86 /* ISO 15765-2:2016 supports more than 4095 byte per ISO PDU as the FF_DL can
87  * take full 32 bit values (4 Gbyte). We would need some good concept to handle
88  * this between user space and kernel space. For now increase the static buffer
89  * to something about 64 kbyte to be able to test this new functionality.
90  */
91 #define MAX_MSG_LENGTH 66000
92
93 /* N_PCI type values in bits 7-4 of N_PCI bytes */
94 #define N_PCI_SF 0x00   /* single frame */
95 #define N_PCI_FF 0x10   /* first frame */
96 #define N_PCI_CF 0x20   /* consecutive frame */
97 #define N_PCI_FC 0x30   /* flow control */
98
99 #define N_PCI_SZ 1      /* size of the PCI byte #1 */
100 #define SF_PCI_SZ4 1    /* size of SingleFrame PCI including 4 bit SF_DL */
101 #define SF_PCI_SZ8 2    /* size of SingleFrame PCI including 8 bit SF_DL */
102 #define FF_PCI_SZ12 2   /* size of FirstFrame PCI including 12 bit FF_DL */
103 #define FF_PCI_SZ32 6   /* size of FirstFrame PCI including 32 bit FF_DL */
104 #define FC_CONTENT_SZ 3 /* flow control content size in byte (FS/BS/STmin) */
105
106 #define ISOTP_CHECK_PADDING (CAN_ISOTP_CHK_PAD_LEN | CAN_ISOTP_CHK_PAD_DATA)
107 #define ISOTP_ALL_BC_FLAGS (CAN_ISOTP_SF_BROADCAST | CAN_ISOTP_CF_BROADCAST)
108
109 /* Flow Status given in FC frame */
110 #define ISOTP_FC_CTS 0          /* clear to send */
111 #define ISOTP_FC_WT 1           /* wait */
112 #define ISOTP_FC_OVFLW 2        /* overflow */
113
114 #define ISOTP_FC_TIMEOUT 1      /* 1 sec */
115 #define ISOTP_ECHO_TIMEOUT 2    /* 2 secs */
116
117 enum {
118         ISOTP_IDLE = 0,
119         ISOTP_WAIT_FIRST_FC,
120         ISOTP_WAIT_FC,
121         ISOTP_WAIT_DATA,
122         ISOTP_SENDING,
123         ISOTP_SHUTDOWN,
124 };
125
126 struct tpcon {
127         unsigned int idx;
128         unsigned int len;
129         u32 state;
130         u8 bs;
131         u8 sn;
132         u8 ll_dl;
133         u8 buf[MAX_MSG_LENGTH + 1];
134 };
135
136 struct isotp_sock {
137         struct sock sk;
138         int bound;
139         int ifindex;
140         canid_t txid;
141         canid_t rxid;
142         ktime_t tx_gap;
143         ktime_t lastrxcf_tstamp;
144         struct hrtimer rxtimer, txtimer, txfrtimer;
145         struct can_isotp_options opt;
146         struct can_isotp_fc_options rxfc, txfc;
147         struct can_isotp_ll_options ll;
148         u32 frame_txtime;
149         u32 force_tx_stmin;
150         u32 force_rx_stmin;
151         u32 cfecho; /* consecutive frame echo tag */
152         struct tpcon rx, tx;
153         struct list_head notifier;
154         wait_queue_head_t wait;
155         spinlock_t rx_lock; /* protect single thread state machine */
156 };
157
158 static LIST_HEAD(isotp_notifier_list);
159 static DEFINE_SPINLOCK(isotp_notifier_lock);
160 static struct isotp_sock *isotp_busy_notifier;
161
162 static inline struct isotp_sock *isotp_sk(const struct sock *sk)
163 {
164         return (struct isotp_sock *)sk;
165 }
166
167 static u32 isotp_bc_flags(struct isotp_sock *so)
168 {
169         return so->opt.flags & ISOTP_ALL_BC_FLAGS;
170 }
171
172 static bool isotp_register_rxid(struct isotp_sock *so)
173 {
174         /* no broadcast modes => register rx_id for FC frame reception */
175         return (isotp_bc_flags(so) == 0);
176 }
177
178 static bool isotp_register_txecho(struct isotp_sock *so)
179 {
180         /* all modes but SF_BROADCAST register for tx echo skbs */
181         return (isotp_bc_flags(so) != CAN_ISOTP_SF_BROADCAST);
182 }
183
184 static enum hrtimer_restart isotp_rx_timer_handler(struct hrtimer *hrtimer)
185 {
186         struct isotp_sock *so = container_of(hrtimer, struct isotp_sock,
187                                              rxtimer);
188         struct sock *sk = &so->sk;
189
190         if (so->rx.state == ISOTP_WAIT_DATA) {
191                 /* we did not get new data frames in time */
192
193                 /* report 'connection timed out' */
194                 sk->sk_err = ETIMEDOUT;
195                 if (!sock_flag(sk, SOCK_DEAD))
196                         sk_error_report(sk);
197
198                 /* reset rx state */
199                 so->rx.state = ISOTP_IDLE;
200         }
201
202         return HRTIMER_NORESTART;
203 }
204
205 static int isotp_send_fc(struct sock *sk, int ae, u8 flowstatus)
206 {
207         struct net_device *dev;
208         struct sk_buff *nskb;
209         struct canfd_frame *ncf;
210         struct isotp_sock *so = isotp_sk(sk);
211         int can_send_ret;
212
213         nskb = alloc_skb(so->ll.mtu + sizeof(struct can_skb_priv), gfp_any());
214         if (!nskb)
215                 return 1;
216
217         dev = dev_get_by_index(sock_net(sk), so->ifindex);
218         if (!dev) {
219                 kfree_skb(nskb);
220                 return 1;
221         }
222
223         can_skb_reserve(nskb);
224         can_skb_prv(nskb)->ifindex = dev->ifindex;
225         can_skb_prv(nskb)->skbcnt = 0;
226
227         nskb->dev = dev;
228         can_skb_set_owner(nskb, sk);
229         ncf = (struct canfd_frame *)nskb->data;
230         skb_put_zero(nskb, so->ll.mtu);
231
232         /* create & send flow control reply */
233         ncf->can_id = so->txid;
234
235         if (so->opt.flags & CAN_ISOTP_TX_PADDING) {
236                 memset(ncf->data, so->opt.txpad_content, CAN_MAX_DLEN);
237                 ncf->len = CAN_MAX_DLEN;
238         } else {
239                 ncf->len = ae + FC_CONTENT_SZ;
240         }
241
242         ncf->data[ae] = N_PCI_FC | flowstatus;
243         ncf->data[ae + 1] = so->rxfc.bs;
244         ncf->data[ae + 2] = so->rxfc.stmin;
245
246         if (ae)
247                 ncf->data[0] = so->opt.ext_address;
248
249         ncf->flags = so->ll.tx_flags;
250
251         can_send_ret = can_send(nskb, 1);
252         if (can_send_ret)
253                 pr_notice_once("can-isotp: %s: can_send_ret %pe\n",
254                                __func__, ERR_PTR(can_send_ret));
255
256         dev_put(dev);
257
258         /* reset blocksize counter */
259         so->rx.bs = 0;
260
261         /* reset last CF frame rx timestamp for rx stmin enforcement */
262         so->lastrxcf_tstamp = ktime_set(0, 0);
263
264         /* start rx timeout watchdog */
265         hrtimer_start(&so->rxtimer, ktime_set(ISOTP_FC_TIMEOUT, 0),
266                       HRTIMER_MODE_REL_SOFT);
267         return 0;
268 }
269
270 static void isotp_rcv_skb(struct sk_buff *skb, struct sock *sk)
271 {
272         struct sockaddr_can *addr = (struct sockaddr_can *)skb->cb;
273
274         BUILD_BUG_ON(sizeof(skb->cb) < sizeof(struct sockaddr_can));
275
276         memset(addr, 0, sizeof(*addr));
277         addr->can_family = AF_CAN;
278         addr->can_ifindex = skb->dev->ifindex;
279
280         if (sock_queue_rcv_skb(sk, skb) < 0)
281                 kfree_skb(skb);
282 }
283
284 static u8 padlen(u8 datalen)
285 {
286         static const u8 plen[] = {
287                 8, 8, 8, 8, 8, 8, 8, 8, 8,      /* 0 - 8 */
288                 12, 12, 12, 12,                 /* 9 - 12 */
289                 16, 16, 16, 16,                 /* 13 - 16 */
290                 20, 20, 20, 20,                 /* 17 - 20 */
291                 24, 24, 24, 24,                 /* 21 - 24 */
292                 32, 32, 32, 32, 32, 32, 32, 32, /* 25 - 32 */
293                 48, 48, 48, 48, 48, 48, 48, 48, /* 33 - 40 */
294                 48, 48, 48, 48, 48, 48, 48, 48  /* 41 - 48 */
295         };
296
297         if (datalen > 48)
298                 return 64;
299
300         return plen[datalen];
301 }
302
303 /* check for length optimization and return 1/true when the check fails */
304 static int check_optimized(struct canfd_frame *cf, int start_index)
305 {
306         /* for CAN_DL <= 8 the start_index is equal to the CAN_DL as the
307          * padding would start at this point. E.g. if the padding would
308          * start at cf.data[7] cf->len has to be 7 to be optimal.
309          * Note: The data[] index starts with zero.
310          */
311         if (cf->len <= CAN_MAX_DLEN)
312                 return (cf->len != start_index);
313
314         /* This relation is also valid in the non-linear DLC range, where
315          * we need to take care of the minimal next possible CAN_DL.
316          * The correct check would be (padlen(cf->len) != padlen(start_index)).
317          * But as cf->len can only take discrete values from 12, .., 64 at this
318          * point the padlen(cf->len) is always equal to cf->len.
319          */
320         return (cf->len != padlen(start_index));
321 }
322
323 /* check padding and return 1/true when the check fails */
324 static int check_pad(struct isotp_sock *so, struct canfd_frame *cf,
325                      int start_index, u8 content)
326 {
327         int i;
328
329         /* no RX_PADDING value => check length of optimized frame length */
330         if (!(so->opt.flags & CAN_ISOTP_RX_PADDING)) {
331                 if (so->opt.flags & CAN_ISOTP_CHK_PAD_LEN)
332                         return check_optimized(cf, start_index);
333
334                 /* no valid test against empty value => ignore frame */
335                 return 1;
336         }
337
338         /* check datalength of correctly padded CAN frame */
339         if ((so->opt.flags & CAN_ISOTP_CHK_PAD_LEN) &&
340             cf->len != padlen(cf->len))
341                 return 1;
342
343         /* check padding content */
344         if (so->opt.flags & CAN_ISOTP_CHK_PAD_DATA) {
345                 for (i = start_index; i < cf->len; i++)
346                         if (cf->data[i] != content)
347                                 return 1;
348         }
349         return 0;
350 }
351
352 static void isotp_send_cframe(struct isotp_sock *so);
353
354 static int isotp_rcv_fc(struct isotp_sock *so, struct canfd_frame *cf, int ae)
355 {
356         struct sock *sk = &so->sk;
357
358         if (so->tx.state != ISOTP_WAIT_FC &&
359             so->tx.state != ISOTP_WAIT_FIRST_FC)
360                 return 0;
361
362         hrtimer_cancel(&so->txtimer);
363
364         if ((cf->len < ae + FC_CONTENT_SZ) ||
365             ((so->opt.flags & ISOTP_CHECK_PADDING) &&
366              check_pad(so, cf, ae + FC_CONTENT_SZ, so->opt.rxpad_content))) {
367                 /* malformed PDU - report 'not a data message' */
368                 sk->sk_err = EBADMSG;
369                 if (!sock_flag(sk, SOCK_DEAD))
370                         sk_error_report(sk);
371
372                 so->tx.state = ISOTP_IDLE;
373                 wake_up_interruptible(&so->wait);
374                 return 1;
375         }
376
377         /* get communication parameters only from the first FC frame */
378         if (so->tx.state == ISOTP_WAIT_FIRST_FC) {
379                 so->txfc.bs = cf->data[ae + 1];
380                 so->txfc.stmin = cf->data[ae + 2];
381
382                 /* fix wrong STmin values according spec */
383                 if (so->txfc.stmin > 0x7F &&
384                     (so->txfc.stmin < 0xF1 || so->txfc.stmin > 0xF9))
385                         so->txfc.stmin = 0x7F;
386
387                 so->tx_gap = ktime_set(0, 0);
388                 /* add transmission time for CAN frame N_As */
389                 so->tx_gap = ktime_add_ns(so->tx_gap, so->frame_txtime);
390                 /* add waiting time for consecutive frames N_Cs */
391                 if (so->opt.flags & CAN_ISOTP_FORCE_TXSTMIN)
392                         so->tx_gap = ktime_add_ns(so->tx_gap,
393                                                   so->force_tx_stmin);
394                 else if (so->txfc.stmin < 0x80)
395                         so->tx_gap = ktime_add_ns(so->tx_gap,
396                                                   so->txfc.stmin * 1000000);
397                 else
398                         so->tx_gap = ktime_add_ns(so->tx_gap,
399                                                   (so->txfc.stmin - 0xF0)
400                                                   * 100000);
401                 so->tx.state = ISOTP_WAIT_FC;
402         }
403
404         switch (cf->data[ae] & 0x0F) {
405         case ISOTP_FC_CTS:
406                 so->tx.bs = 0;
407                 so->tx.state = ISOTP_SENDING;
408                 /* send CF frame and enable echo timeout handling */
409                 hrtimer_start(&so->txtimer, ktime_set(ISOTP_ECHO_TIMEOUT, 0),
410                               HRTIMER_MODE_REL_SOFT);
411                 isotp_send_cframe(so);
412                 break;
413
414         case ISOTP_FC_WT:
415                 /* start timer to wait for next FC frame */
416                 hrtimer_start(&so->txtimer, ktime_set(ISOTP_FC_TIMEOUT, 0),
417                               HRTIMER_MODE_REL_SOFT);
418                 break;
419
420         case ISOTP_FC_OVFLW:
421                 /* overflow on receiver side - report 'message too long' */
422                 sk->sk_err = EMSGSIZE;
423                 if (!sock_flag(sk, SOCK_DEAD))
424                         sk_error_report(sk);
425                 fallthrough;
426
427         default:
428                 /* stop this tx job */
429                 so->tx.state = ISOTP_IDLE;
430                 wake_up_interruptible(&so->wait);
431         }
432         return 0;
433 }
434
435 static int isotp_rcv_sf(struct sock *sk, struct canfd_frame *cf, int pcilen,
436                         struct sk_buff *skb, int len)
437 {
438         struct isotp_sock *so = isotp_sk(sk);
439         struct sk_buff *nskb;
440
441         hrtimer_cancel(&so->rxtimer);
442         so->rx.state = ISOTP_IDLE;
443
444         if (!len || len > cf->len - pcilen)
445                 return 1;
446
447         if ((so->opt.flags & ISOTP_CHECK_PADDING) &&
448             check_pad(so, cf, pcilen + len, so->opt.rxpad_content)) {
449                 /* malformed PDU - report 'not a data message' */
450                 sk->sk_err = EBADMSG;
451                 if (!sock_flag(sk, SOCK_DEAD))
452                         sk_error_report(sk);
453                 return 1;
454         }
455
456         nskb = alloc_skb(len, gfp_any());
457         if (!nskb)
458                 return 1;
459
460         memcpy(skb_put(nskb, len), &cf->data[pcilen], len);
461
462         nskb->tstamp = skb->tstamp;
463         nskb->dev = skb->dev;
464         isotp_rcv_skb(nskb, sk);
465         return 0;
466 }
467
468 static int isotp_rcv_ff(struct sock *sk, struct canfd_frame *cf, int ae)
469 {
470         struct isotp_sock *so = isotp_sk(sk);
471         int i;
472         int off;
473         int ff_pci_sz;
474
475         hrtimer_cancel(&so->rxtimer);
476         so->rx.state = ISOTP_IDLE;
477
478         /* get the used sender LL_DL from the (first) CAN frame data length */
479         so->rx.ll_dl = padlen(cf->len);
480
481         /* the first frame has to use the entire frame up to LL_DL length */
482         if (cf->len != so->rx.ll_dl)
483                 return 1;
484
485         /* get the FF_DL */
486         so->rx.len = (cf->data[ae] & 0x0F) << 8;
487         so->rx.len += cf->data[ae + 1];
488
489         /* Check for FF_DL escape sequence supporting 32 bit PDU length */
490         if (so->rx.len) {
491                 ff_pci_sz = FF_PCI_SZ12;
492         } else {
493                 /* FF_DL = 0 => get real length from next 4 bytes */
494                 so->rx.len = cf->data[ae + 2] << 24;
495                 so->rx.len += cf->data[ae + 3] << 16;
496                 so->rx.len += cf->data[ae + 4] << 8;
497                 so->rx.len += cf->data[ae + 5];
498                 ff_pci_sz = FF_PCI_SZ32;
499         }
500
501         /* take care of a potential SF_DL ESC offset for TX_DL > 8 */
502         off = (so->rx.ll_dl > CAN_MAX_DLEN) ? 1 : 0;
503
504         if (so->rx.len + ae + off + ff_pci_sz < so->rx.ll_dl)
505                 return 1;
506
507         if (so->rx.len > MAX_MSG_LENGTH) {
508                 /* send FC frame with overflow status */
509                 isotp_send_fc(sk, ae, ISOTP_FC_OVFLW);
510                 return 1;
511         }
512
513         /* copy the first received data bytes */
514         so->rx.idx = 0;
515         for (i = ae + ff_pci_sz; i < so->rx.ll_dl; i++)
516                 so->rx.buf[so->rx.idx++] = cf->data[i];
517
518         /* initial setup for this pdu reception */
519         so->rx.sn = 1;
520         so->rx.state = ISOTP_WAIT_DATA;
521
522         /* no creation of flow control frames */
523         if (so->opt.flags & CAN_ISOTP_LISTEN_MODE)
524                 return 0;
525
526         /* send our first FC frame */
527         isotp_send_fc(sk, ae, ISOTP_FC_CTS);
528         return 0;
529 }
530
531 static int isotp_rcv_cf(struct sock *sk, struct canfd_frame *cf, int ae,
532                         struct sk_buff *skb)
533 {
534         struct isotp_sock *so = isotp_sk(sk);
535         struct sk_buff *nskb;
536         int i;
537
538         if (so->rx.state != ISOTP_WAIT_DATA)
539                 return 0;
540
541         /* drop if timestamp gap is less than force_rx_stmin nano secs */
542         if (so->opt.flags & CAN_ISOTP_FORCE_RXSTMIN) {
543                 if (ktime_to_ns(ktime_sub(skb->tstamp, so->lastrxcf_tstamp)) <
544                     so->force_rx_stmin)
545                         return 0;
546
547                 so->lastrxcf_tstamp = skb->tstamp;
548         }
549
550         hrtimer_cancel(&so->rxtimer);
551
552         /* CFs are never longer than the FF */
553         if (cf->len > so->rx.ll_dl)
554                 return 1;
555
556         /* CFs have usually the LL_DL length */
557         if (cf->len < so->rx.ll_dl) {
558                 /* this is only allowed for the last CF */
559                 if (so->rx.len - so->rx.idx > so->rx.ll_dl - ae - N_PCI_SZ)
560                         return 1;
561         }
562
563         if ((cf->data[ae] & 0x0F) != so->rx.sn) {
564                 /* wrong sn detected - report 'illegal byte sequence' */
565                 sk->sk_err = EILSEQ;
566                 if (!sock_flag(sk, SOCK_DEAD))
567                         sk_error_report(sk);
568
569                 /* reset rx state */
570                 so->rx.state = ISOTP_IDLE;
571                 return 1;
572         }
573         so->rx.sn++;
574         so->rx.sn %= 16;
575
576         for (i = ae + N_PCI_SZ; i < cf->len; i++) {
577                 so->rx.buf[so->rx.idx++] = cf->data[i];
578                 if (so->rx.idx >= so->rx.len)
579                         break;
580         }
581
582         if (so->rx.idx >= so->rx.len) {
583                 /* we are done */
584                 so->rx.state = ISOTP_IDLE;
585
586                 if ((so->opt.flags & ISOTP_CHECK_PADDING) &&
587                     check_pad(so, cf, i + 1, so->opt.rxpad_content)) {
588                         /* malformed PDU - report 'not a data message' */
589                         sk->sk_err = EBADMSG;
590                         if (!sock_flag(sk, SOCK_DEAD))
591                                 sk_error_report(sk);
592                         return 1;
593                 }
594
595                 nskb = alloc_skb(so->rx.len, gfp_any());
596                 if (!nskb)
597                         return 1;
598
599                 memcpy(skb_put(nskb, so->rx.len), so->rx.buf,
600                        so->rx.len);
601
602                 nskb->tstamp = skb->tstamp;
603                 nskb->dev = skb->dev;
604                 isotp_rcv_skb(nskb, sk);
605                 return 0;
606         }
607
608         /* perform blocksize handling, if enabled */
609         if (!so->rxfc.bs || ++so->rx.bs < so->rxfc.bs) {
610                 /* start rx timeout watchdog */
611                 hrtimer_start(&so->rxtimer, ktime_set(ISOTP_FC_TIMEOUT, 0),
612                               HRTIMER_MODE_REL_SOFT);
613                 return 0;
614         }
615
616         /* no creation of flow control frames */
617         if (so->opt.flags & CAN_ISOTP_LISTEN_MODE)
618                 return 0;
619
620         /* we reached the specified blocksize so->rxfc.bs */
621         isotp_send_fc(sk, ae, ISOTP_FC_CTS);
622         return 0;
623 }
624
625 static void isotp_rcv(struct sk_buff *skb, void *data)
626 {
627         struct sock *sk = (struct sock *)data;
628         struct isotp_sock *so = isotp_sk(sk);
629         struct canfd_frame *cf;
630         int ae = (so->opt.flags & CAN_ISOTP_EXTEND_ADDR) ? 1 : 0;
631         u8 n_pci_type, sf_dl;
632
633         /* Strictly receive only frames with the configured MTU size
634          * => clear separation of CAN2.0 / CAN FD transport channels
635          */
636         if (skb->len != so->ll.mtu)
637                 return;
638
639         cf = (struct canfd_frame *)skb->data;
640
641         /* if enabled: check reception of my configured extended address */
642         if (ae && cf->data[0] != so->opt.rx_ext_address)
643                 return;
644
645         n_pci_type = cf->data[ae] & 0xF0;
646
647         /* Make sure the state changes and data structures stay consistent at
648          * CAN frame reception time. This locking is not needed in real world
649          * use cases but the inconsistency can be triggered with syzkaller.
650          */
651         spin_lock(&so->rx_lock);
652
653         if (so->opt.flags & CAN_ISOTP_HALF_DUPLEX) {
654                 /* check rx/tx path half duplex expectations */
655                 if ((so->tx.state != ISOTP_IDLE && n_pci_type != N_PCI_FC) ||
656                     (so->rx.state != ISOTP_IDLE && n_pci_type == N_PCI_FC))
657                         goto out_unlock;
658         }
659
660         switch (n_pci_type) {
661         case N_PCI_FC:
662                 /* tx path: flow control frame containing the FC parameters */
663                 isotp_rcv_fc(so, cf, ae);
664                 break;
665
666         case N_PCI_SF:
667                 /* rx path: single frame
668                  *
669                  * As we do not have a rx.ll_dl configuration, we can only test
670                  * if the CAN frames payload length matches the LL_DL == 8
671                  * requirements - no matter if it's CAN 2.0 or CAN FD
672                  */
673
674                 /* get the SF_DL from the N_PCI byte */
675                 sf_dl = cf->data[ae] & 0x0F;
676
677                 if (cf->len <= CAN_MAX_DLEN) {
678                         isotp_rcv_sf(sk, cf, SF_PCI_SZ4 + ae, skb, sf_dl);
679                 } else {
680                         if (can_is_canfd_skb(skb)) {
681                                 /* We have a CAN FD frame and CAN_DL is greater than 8:
682                                  * Only frames with the SF_DL == 0 ESC value are valid.
683                                  *
684                                  * If so take care of the increased SF PCI size
685                                  * (SF_PCI_SZ8) to point to the message content behind
686                                  * the extended SF PCI info and get the real SF_DL
687                                  * length value from the formerly first data byte.
688                                  */
689                                 if (sf_dl == 0)
690                                         isotp_rcv_sf(sk, cf, SF_PCI_SZ8 + ae, skb,
691                                                      cf->data[SF_PCI_SZ4 + ae]);
692                         }
693                 }
694                 break;
695
696         case N_PCI_FF:
697                 /* rx path: first frame */
698                 isotp_rcv_ff(sk, cf, ae);
699                 break;
700
701         case N_PCI_CF:
702                 /* rx path: consecutive frame */
703                 isotp_rcv_cf(sk, cf, ae, skb);
704                 break;
705         }
706
707 out_unlock:
708         spin_unlock(&so->rx_lock);
709 }
710
711 static void isotp_fill_dataframe(struct canfd_frame *cf, struct isotp_sock *so,
712                                  int ae, int off)
713 {
714         int pcilen = N_PCI_SZ + ae + off;
715         int space = so->tx.ll_dl - pcilen;
716         int num = min_t(int, so->tx.len - so->tx.idx, space);
717         int i;
718
719         cf->can_id = so->txid;
720         cf->len = num + pcilen;
721
722         if (num < space) {
723                 if (so->opt.flags & CAN_ISOTP_TX_PADDING) {
724                         /* user requested padding */
725                         cf->len = padlen(cf->len);
726                         memset(cf->data, so->opt.txpad_content, cf->len);
727                 } else if (cf->len > CAN_MAX_DLEN) {
728                         /* mandatory padding for CAN FD frames */
729                         cf->len = padlen(cf->len);
730                         memset(cf->data, CAN_ISOTP_DEFAULT_PAD_CONTENT,
731                                cf->len);
732                 }
733         }
734
735         for (i = 0; i < num; i++)
736                 cf->data[pcilen + i] = so->tx.buf[so->tx.idx++];
737
738         if (ae)
739                 cf->data[0] = so->opt.ext_address;
740 }
741
742 static void isotp_send_cframe(struct isotp_sock *so)
743 {
744         struct sock *sk = &so->sk;
745         struct sk_buff *skb;
746         struct net_device *dev;
747         struct canfd_frame *cf;
748         int can_send_ret;
749         int ae = (so->opt.flags & CAN_ISOTP_EXTEND_ADDR) ? 1 : 0;
750
751         dev = dev_get_by_index(sock_net(sk), so->ifindex);
752         if (!dev)
753                 return;
754
755         skb = alloc_skb(so->ll.mtu + sizeof(struct can_skb_priv), GFP_ATOMIC);
756         if (!skb) {
757                 dev_put(dev);
758                 return;
759         }
760
761         can_skb_reserve(skb);
762         can_skb_prv(skb)->ifindex = dev->ifindex;
763         can_skb_prv(skb)->skbcnt = 0;
764
765         cf = (struct canfd_frame *)skb->data;
766         skb_put_zero(skb, so->ll.mtu);
767
768         /* create consecutive frame */
769         isotp_fill_dataframe(cf, so, ae, 0);
770
771         /* place consecutive frame N_PCI in appropriate index */
772         cf->data[ae] = N_PCI_CF | so->tx.sn++;
773         so->tx.sn %= 16;
774         so->tx.bs++;
775
776         cf->flags = so->ll.tx_flags;
777
778         skb->dev = dev;
779         can_skb_set_owner(skb, sk);
780
781         /* cfecho should have been zero'ed by init/isotp_rcv_echo() */
782         if (so->cfecho)
783                 pr_notice_once("can-isotp: cfecho is %08X != 0\n", so->cfecho);
784
785         /* set consecutive frame echo tag */
786         so->cfecho = *(u32 *)cf->data;
787
788         /* send frame with local echo enabled */
789         can_send_ret = can_send(skb, 1);
790         if (can_send_ret) {
791                 pr_notice_once("can-isotp: %s: can_send_ret %pe\n",
792                                __func__, ERR_PTR(can_send_ret));
793                 if (can_send_ret == -ENOBUFS)
794                         pr_notice_once("can-isotp: tx queue is full\n");
795         }
796         dev_put(dev);
797 }
798
799 static void isotp_create_fframe(struct canfd_frame *cf, struct isotp_sock *so,
800                                 int ae)
801 {
802         int i;
803         int ff_pci_sz;
804
805         cf->can_id = so->txid;
806         cf->len = so->tx.ll_dl;
807         if (ae)
808                 cf->data[0] = so->opt.ext_address;
809
810         /* create N_PCI bytes with 12/32 bit FF_DL data length */
811         if (so->tx.len > 4095) {
812                 /* use 32 bit FF_DL notation */
813                 cf->data[ae] = N_PCI_FF;
814                 cf->data[ae + 1] = 0;
815                 cf->data[ae + 2] = (u8)(so->tx.len >> 24) & 0xFFU;
816                 cf->data[ae + 3] = (u8)(so->tx.len >> 16) & 0xFFU;
817                 cf->data[ae + 4] = (u8)(so->tx.len >> 8) & 0xFFU;
818                 cf->data[ae + 5] = (u8)so->tx.len & 0xFFU;
819                 ff_pci_sz = FF_PCI_SZ32;
820         } else {
821                 /* use 12 bit FF_DL notation */
822                 cf->data[ae] = (u8)(so->tx.len >> 8) | N_PCI_FF;
823                 cf->data[ae + 1] = (u8)so->tx.len & 0xFFU;
824                 ff_pci_sz = FF_PCI_SZ12;
825         }
826
827         /* add first data bytes depending on ae */
828         for (i = ae + ff_pci_sz; i < so->tx.ll_dl; i++)
829                 cf->data[i] = so->tx.buf[so->tx.idx++];
830
831         so->tx.sn = 1;
832 }
833
834 static void isotp_rcv_echo(struct sk_buff *skb, void *data)
835 {
836         struct sock *sk = (struct sock *)data;
837         struct isotp_sock *so = isotp_sk(sk);
838         struct canfd_frame *cf = (struct canfd_frame *)skb->data;
839
840         /* only handle my own local echo CF/SF skb's (no FF!) */
841         if (skb->sk != sk || so->cfecho != *(u32 *)cf->data)
842                 return;
843
844         /* cancel local echo timeout */
845         hrtimer_cancel(&so->txtimer);
846
847         /* local echo skb with consecutive frame has been consumed */
848         so->cfecho = 0;
849
850         if (so->tx.idx >= so->tx.len) {
851                 /* we are done */
852                 so->tx.state = ISOTP_IDLE;
853                 wake_up_interruptible(&so->wait);
854                 return;
855         }
856
857         if (so->txfc.bs && so->tx.bs >= so->txfc.bs) {
858                 /* stop and wait for FC with timeout */
859                 so->tx.state = ISOTP_WAIT_FC;
860                 hrtimer_start(&so->txtimer, ktime_set(ISOTP_FC_TIMEOUT, 0),
861                               HRTIMER_MODE_REL_SOFT);
862                 return;
863         }
864
865         /* no gap between data frames needed => use burst mode */
866         if (!so->tx_gap) {
867                 /* enable echo timeout handling */
868                 hrtimer_start(&so->txtimer, ktime_set(ISOTP_ECHO_TIMEOUT, 0),
869                               HRTIMER_MODE_REL_SOFT);
870                 isotp_send_cframe(so);
871                 return;
872         }
873
874         /* start timer to send next consecutive frame with correct delay */
875         hrtimer_start(&so->txfrtimer, so->tx_gap, HRTIMER_MODE_REL_SOFT);
876 }
877
878 static enum hrtimer_restart isotp_tx_timer_handler(struct hrtimer *hrtimer)
879 {
880         struct isotp_sock *so = container_of(hrtimer, struct isotp_sock,
881                                              txtimer);
882         struct sock *sk = &so->sk;
883
884         /* don't handle timeouts in IDLE or SHUTDOWN state */
885         if (so->tx.state == ISOTP_IDLE || so->tx.state == ISOTP_SHUTDOWN)
886                 return HRTIMER_NORESTART;
887
888         /* we did not get any flow control or echo frame in time */
889
890         /* report 'communication error on send' */
891         sk->sk_err = ECOMM;
892         if (!sock_flag(sk, SOCK_DEAD))
893                 sk_error_report(sk);
894
895         /* reset tx state */
896         so->tx.state = ISOTP_IDLE;
897         wake_up_interruptible(&so->wait);
898
899         return HRTIMER_NORESTART;
900 }
901
902 static enum hrtimer_restart isotp_txfr_timer_handler(struct hrtimer *hrtimer)
903 {
904         struct isotp_sock *so = container_of(hrtimer, struct isotp_sock,
905                                              txfrtimer);
906
907         /* start echo timeout handling and cover below protocol error */
908         hrtimer_start(&so->txtimer, ktime_set(ISOTP_ECHO_TIMEOUT, 0),
909                       HRTIMER_MODE_REL_SOFT);
910
911         /* cfecho should be consumed by isotp_rcv_echo() here */
912         if (so->tx.state == ISOTP_SENDING && !so->cfecho)
913                 isotp_send_cframe(so);
914
915         return HRTIMER_NORESTART;
916 }
917
918 static int isotp_sendmsg(struct socket *sock, struct msghdr *msg, size_t size)
919 {
920         struct sock *sk = sock->sk;
921         struct isotp_sock *so = isotp_sk(sk);
922         struct sk_buff *skb;
923         struct net_device *dev;
924         struct canfd_frame *cf;
925         int ae = (so->opt.flags & CAN_ISOTP_EXTEND_ADDR) ? 1 : 0;
926         int wait_tx_done = (so->opt.flags & CAN_ISOTP_WAIT_TX_DONE) ? 1 : 0;
927         s64 hrtimer_sec = ISOTP_ECHO_TIMEOUT;
928         int off;
929         int err;
930
931         if (!so->bound || so->tx.state == ISOTP_SHUTDOWN)
932                 return -EADDRNOTAVAIL;
933
934 wait_free_buffer:
935         /* we do not support multiple buffers - for now */
936         if (wq_has_sleeper(&so->wait) && (msg->msg_flags & MSG_DONTWAIT))
937                 return -EAGAIN;
938
939         /* wait for complete transmission of current pdu */
940         err = wait_event_interruptible(so->wait, so->tx.state == ISOTP_IDLE);
941         if (err)
942                 goto err_event_drop;
943
944         if (cmpxchg(&so->tx.state, ISOTP_IDLE, ISOTP_SENDING) != ISOTP_IDLE) {
945                 if (so->tx.state == ISOTP_SHUTDOWN)
946                         return -EADDRNOTAVAIL;
947
948                 goto wait_free_buffer;
949         }
950
951         if (!size || size > MAX_MSG_LENGTH) {
952                 err = -EINVAL;
953                 goto err_out_drop;
954         }
955
956         /* take care of a potential SF_DL ESC offset for TX_DL > 8 */
957         off = (so->tx.ll_dl > CAN_MAX_DLEN) ? 1 : 0;
958
959         /* does the given data fit into a single frame for SF_BROADCAST? */
960         if ((isotp_bc_flags(so) == CAN_ISOTP_SF_BROADCAST) &&
961             (size > so->tx.ll_dl - SF_PCI_SZ4 - ae - off)) {
962                 err = -EINVAL;
963                 goto err_out_drop;
964         }
965
966         err = memcpy_from_msg(so->tx.buf, msg, size);
967         if (err < 0)
968                 goto err_out_drop;
969
970         dev = dev_get_by_index(sock_net(sk), so->ifindex);
971         if (!dev) {
972                 err = -ENXIO;
973                 goto err_out_drop;
974         }
975
976         skb = sock_alloc_send_skb(sk, so->ll.mtu + sizeof(struct can_skb_priv),
977                                   msg->msg_flags & MSG_DONTWAIT, &err);
978         if (!skb) {
979                 dev_put(dev);
980                 goto err_out_drop;
981         }
982
983         can_skb_reserve(skb);
984         can_skb_prv(skb)->ifindex = dev->ifindex;
985         can_skb_prv(skb)->skbcnt = 0;
986
987         so->tx.len = size;
988         so->tx.idx = 0;
989
990         cf = (struct canfd_frame *)skb->data;
991         skb_put_zero(skb, so->ll.mtu);
992
993         /* cfecho should have been zero'ed by init / former isotp_rcv_echo() */
994         if (so->cfecho)
995                 pr_notice_once("can-isotp: uninit cfecho %08X\n", so->cfecho);
996
997         /* check for single frame transmission depending on TX_DL */
998         if (size <= so->tx.ll_dl - SF_PCI_SZ4 - ae - off) {
999                 /* The message size generally fits into a SingleFrame - good.
1000                  *
1001                  * SF_DL ESC offset optimization:
1002                  *
1003                  * When TX_DL is greater 8 but the message would still fit
1004                  * into a 8 byte CAN frame, we can omit the offset.
1005                  * This prevents a protocol caused length extension from
1006                  * CAN_DL = 8 to CAN_DL = 12 due to the SF_SL ESC handling.
1007                  */
1008                 if (size <= CAN_MAX_DLEN - SF_PCI_SZ4 - ae)
1009                         off = 0;
1010
1011                 isotp_fill_dataframe(cf, so, ae, off);
1012
1013                 /* place single frame N_PCI w/o length in appropriate index */
1014                 cf->data[ae] = N_PCI_SF;
1015
1016                 /* place SF_DL size value depending on the SF_DL ESC offset */
1017                 if (off)
1018                         cf->data[SF_PCI_SZ4 + ae] = size;
1019                 else
1020                         cf->data[ae] |= size;
1021
1022                 /* set CF echo tag for isotp_rcv_echo() (SF-mode) */
1023                 so->cfecho = *(u32 *)cf->data;
1024         } else {
1025                 /* send first frame */
1026
1027                 isotp_create_fframe(cf, so, ae);
1028
1029                 if (isotp_bc_flags(so) == CAN_ISOTP_CF_BROADCAST) {
1030                         /* set timer for FC-less operation (STmin = 0) */
1031                         if (so->opt.flags & CAN_ISOTP_FORCE_TXSTMIN)
1032                                 so->tx_gap = ktime_set(0, so->force_tx_stmin);
1033                         else
1034                                 so->tx_gap = ktime_set(0, so->frame_txtime);
1035
1036                         /* disable wait for FCs due to activated block size */
1037                         so->txfc.bs = 0;
1038
1039                         /* set CF echo tag for isotp_rcv_echo() (CF-mode) */
1040                         so->cfecho = *(u32 *)cf->data;
1041                 } else {
1042                         /* standard flow control check */
1043                         so->tx.state = ISOTP_WAIT_FIRST_FC;
1044
1045                         /* start timeout for FC */
1046                         hrtimer_sec = ISOTP_FC_TIMEOUT;
1047
1048                         /* no CF echo tag for isotp_rcv_echo() (FF-mode) */
1049                         so->cfecho = 0;
1050                 }
1051         }
1052
1053         hrtimer_start(&so->txtimer, ktime_set(hrtimer_sec, 0),
1054                       HRTIMER_MODE_REL_SOFT);
1055
1056         /* send the first or only CAN frame */
1057         cf->flags = so->ll.tx_flags;
1058
1059         skb->dev = dev;
1060         skb->sk = sk;
1061         err = can_send(skb, 1);
1062         dev_put(dev);
1063         if (err) {
1064                 pr_notice_once("can-isotp: %s: can_send_ret %pe\n",
1065                                __func__, ERR_PTR(err));
1066
1067                 /* no transmission -> no timeout monitoring */
1068                 hrtimer_cancel(&so->txtimer);
1069
1070                 /* reset consecutive frame echo tag */
1071                 so->cfecho = 0;
1072
1073                 goto err_out_drop;
1074         }
1075
1076         if (wait_tx_done) {
1077                 /* wait for complete transmission of current pdu */
1078                 err = wait_event_interruptible(so->wait, so->tx.state == ISOTP_IDLE);
1079                 if (err)
1080                         goto err_event_drop;
1081
1082                 err = sock_error(sk);
1083                 if (err)
1084                         return err;
1085         }
1086
1087         return size;
1088
1089 err_event_drop:
1090         /* got signal: force tx state machine to be idle */
1091         so->tx.state = ISOTP_IDLE;
1092         hrtimer_cancel(&so->txfrtimer);
1093         hrtimer_cancel(&so->txtimer);
1094 err_out_drop:
1095         /* drop this PDU and unlock a potential wait queue */
1096         so->tx.state = ISOTP_IDLE;
1097         wake_up_interruptible(&so->wait);
1098
1099         return err;
1100 }
1101
1102 static int isotp_recvmsg(struct socket *sock, struct msghdr *msg, size_t size,
1103                          int flags)
1104 {
1105         struct sock *sk = sock->sk;
1106         struct sk_buff *skb;
1107         struct isotp_sock *so = isotp_sk(sk);
1108         int ret = 0;
1109
1110         if (flags & ~(MSG_DONTWAIT | MSG_TRUNC | MSG_PEEK | MSG_CMSG_COMPAT))
1111                 return -EINVAL;
1112
1113         if (!so->bound)
1114                 return -EADDRNOTAVAIL;
1115
1116         skb = skb_recv_datagram(sk, flags, &ret);
1117         if (!skb)
1118                 return ret;
1119
1120         if (size < skb->len)
1121                 msg->msg_flags |= MSG_TRUNC;
1122         else
1123                 size = skb->len;
1124
1125         ret = memcpy_to_msg(msg, skb->data, size);
1126         if (ret < 0)
1127                 goto out_err;
1128
1129         sock_recv_cmsgs(msg, sk, skb);
1130
1131         if (msg->msg_name) {
1132                 __sockaddr_check_size(ISOTP_MIN_NAMELEN);
1133                 msg->msg_namelen = ISOTP_MIN_NAMELEN;
1134                 memcpy(msg->msg_name, skb->cb, msg->msg_namelen);
1135         }
1136
1137         /* set length of return value */
1138         ret = (flags & MSG_TRUNC) ? skb->len : size;
1139
1140 out_err:
1141         skb_free_datagram(sk, skb);
1142
1143         return ret;
1144 }
1145
1146 static int isotp_release(struct socket *sock)
1147 {
1148         struct sock *sk = sock->sk;
1149         struct isotp_sock *so;
1150         struct net *net;
1151
1152         if (!sk)
1153                 return 0;
1154
1155         so = isotp_sk(sk);
1156         net = sock_net(sk);
1157
1158         /* wait for complete transmission of current pdu */
1159         while (wait_event_interruptible(so->wait, so->tx.state == ISOTP_IDLE) == 0 &&
1160                cmpxchg(&so->tx.state, ISOTP_IDLE, ISOTP_SHUTDOWN) != ISOTP_IDLE)
1161                 ;
1162
1163         /* force state machines to be idle also when a signal occurred */
1164         so->tx.state = ISOTP_SHUTDOWN;
1165         so->rx.state = ISOTP_IDLE;
1166
1167         spin_lock(&isotp_notifier_lock);
1168         while (isotp_busy_notifier == so) {
1169                 spin_unlock(&isotp_notifier_lock);
1170                 schedule_timeout_uninterruptible(1);
1171                 spin_lock(&isotp_notifier_lock);
1172         }
1173         list_del(&so->notifier);
1174         spin_unlock(&isotp_notifier_lock);
1175
1176         lock_sock(sk);
1177
1178         /* remove current filters & unregister */
1179         if (so->bound && isotp_register_txecho(so)) {
1180                 if (so->ifindex) {
1181                         struct net_device *dev;
1182
1183                         dev = dev_get_by_index(net, so->ifindex);
1184                         if (dev) {
1185                                 if (isotp_register_rxid(so))
1186                                         can_rx_unregister(net, dev, so->rxid,
1187                                                           SINGLE_MASK(so->rxid),
1188                                                           isotp_rcv, sk);
1189
1190                                 can_rx_unregister(net, dev, so->txid,
1191                                                   SINGLE_MASK(so->txid),
1192                                                   isotp_rcv_echo, sk);
1193                                 dev_put(dev);
1194                                 synchronize_rcu();
1195                         }
1196                 }
1197         }
1198
1199         hrtimer_cancel(&so->txfrtimer);
1200         hrtimer_cancel(&so->txtimer);
1201         hrtimer_cancel(&so->rxtimer);
1202
1203         so->ifindex = 0;
1204         so->bound = 0;
1205
1206         sock_orphan(sk);
1207         sock->sk = NULL;
1208
1209         release_sock(sk);
1210         sock_put(sk);
1211
1212         return 0;
1213 }
1214
1215 static int isotp_bind(struct socket *sock, struct sockaddr *uaddr, int len)
1216 {
1217         struct sockaddr_can *addr = (struct sockaddr_can *)uaddr;
1218         struct sock *sk = sock->sk;
1219         struct isotp_sock *so = isotp_sk(sk);
1220         struct net *net = sock_net(sk);
1221         int ifindex;
1222         struct net_device *dev;
1223         canid_t tx_id = addr->can_addr.tp.tx_id;
1224         canid_t rx_id = addr->can_addr.tp.rx_id;
1225         int err = 0;
1226         int notify_enetdown = 0;
1227
1228         if (len < ISOTP_MIN_NAMELEN)
1229                 return -EINVAL;
1230
1231         if (addr->can_family != AF_CAN)
1232                 return -EINVAL;
1233
1234         /* sanitize tx CAN identifier */
1235         if (tx_id & CAN_EFF_FLAG)
1236                 tx_id &= (CAN_EFF_FLAG | CAN_EFF_MASK);
1237         else
1238                 tx_id &= CAN_SFF_MASK;
1239
1240         /* give feedback on wrong CAN-ID value */
1241         if (tx_id != addr->can_addr.tp.tx_id)
1242                 return -EINVAL;
1243
1244         /* sanitize rx CAN identifier (if needed) */
1245         if (isotp_register_rxid(so)) {
1246                 if (rx_id & CAN_EFF_FLAG)
1247                         rx_id &= (CAN_EFF_FLAG | CAN_EFF_MASK);
1248                 else
1249                         rx_id &= CAN_SFF_MASK;
1250
1251                 /* give feedback on wrong CAN-ID value */
1252                 if (rx_id != addr->can_addr.tp.rx_id)
1253                         return -EINVAL;
1254         }
1255
1256         if (!addr->can_ifindex)
1257                 return -ENODEV;
1258
1259         lock_sock(sk);
1260
1261         if (so->bound) {
1262                 err = -EINVAL;
1263                 goto out;
1264         }
1265
1266         /* ensure different CAN IDs when the rx_id is to be registered */
1267         if (isotp_register_rxid(so) && rx_id == tx_id) {
1268                 err = -EADDRNOTAVAIL;
1269                 goto out;
1270         }
1271
1272         dev = dev_get_by_index(net, addr->can_ifindex);
1273         if (!dev) {
1274                 err = -ENODEV;
1275                 goto out;
1276         }
1277         if (dev->type != ARPHRD_CAN) {
1278                 dev_put(dev);
1279                 err = -ENODEV;
1280                 goto out;
1281         }
1282         if (dev->mtu < so->ll.mtu) {
1283                 dev_put(dev);
1284                 err = -EINVAL;
1285                 goto out;
1286         }
1287         if (!(dev->flags & IFF_UP))
1288                 notify_enetdown = 1;
1289
1290         ifindex = dev->ifindex;
1291
1292         if (isotp_register_rxid(so))
1293                 can_rx_register(net, dev, rx_id, SINGLE_MASK(rx_id),
1294                                 isotp_rcv, sk, "isotp", sk);
1295
1296         if (isotp_register_txecho(so)) {
1297                 /* no consecutive frame echo skb in flight */
1298                 so->cfecho = 0;
1299
1300                 /* register for echo skb's */
1301                 can_rx_register(net, dev, tx_id, SINGLE_MASK(tx_id),
1302                                 isotp_rcv_echo, sk, "isotpe", sk);
1303         }
1304
1305         dev_put(dev);
1306
1307         /* switch to new settings */
1308         so->ifindex = ifindex;
1309         so->rxid = rx_id;
1310         so->txid = tx_id;
1311         so->bound = 1;
1312
1313 out:
1314         release_sock(sk);
1315
1316         if (notify_enetdown) {
1317                 sk->sk_err = ENETDOWN;
1318                 if (!sock_flag(sk, SOCK_DEAD))
1319                         sk_error_report(sk);
1320         }
1321
1322         return err;
1323 }
1324
1325 static int isotp_getname(struct socket *sock, struct sockaddr *uaddr, int peer)
1326 {
1327         struct sockaddr_can *addr = (struct sockaddr_can *)uaddr;
1328         struct sock *sk = sock->sk;
1329         struct isotp_sock *so = isotp_sk(sk);
1330
1331         if (peer)
1332                 return -EOPNOTSUPP;
1333
1334         memset(addr, 0, ISOTP_MIN_NAMELEN);
1335         addr->can_family = AF_CAN;
1336         addr->can_ifindex = so->ifindex;
1337         addr->can_addr.tp.rx_id = so->rxid;
1338         addr->can_addr.tp.tx_id = so->txid;
1339
1340         return ISOTP_MIN_NAMELEN;
1341 }
1342
1343 static int isotp_setsockopt_locked(struct socket *sock, int level, int optname,
1344                             sockptr_t optval, unsigned int optlen)
1345 {
1346         struct sock *sk = sock->sk;
1347         struct isotp_sock *so = isotp_sk(sk);
1348         int ret = 0;
1349
1350         if (so->bound)
1351                 return -EISCONN;
1352
1353         switch (optname) {
1354         case CAN_ISOTP_OPTS:
1355                 if (optlen != sizeof(struct can_isotp_options))
1356                         return -EINVAL;
1357
1358                 if (copy_from_sockptr(&so->opt, optval, optlen))
1359                         return -EFAULT;
1360
1361                 /* no separate rx_ext_address is given => use ext_address */
1362                 if (!(so->opt.flags & CAN_ISOTP_RX_EXT_ADDR))
1363                         so->opt.rx_ext_address = so->opt.ext_address;
1364
1365                 /* these broadcast flags are not allowed together */
1366                 if (isotp_bc_flags(so) == ISOTP_ALL_BC_FLAGS) {
1367                         /* CAN_ISOTP_SF_BROADCAST is prioritized */
1368                         so->opt.flags &= ~CAN_ISOTP_CF_BROADCAST;
1369
1370                         /* give user feedback on wrong config attempt */
1371                         ret = -EINVAL;
1372                 }
1373
1374                 /* check for frame_txtime changes (0 => no changes) */
1375                 if (so->opt.frame_txtime) {
1376                         if (so->opt.frame_txtime == CAN_ISOTP_FRAME_TXTIME_ZERO)
1377                                 so->frame_txtime = 0;
1378                         else
1379                                 so->frame_txtime = so->opt.frame_txtime;
1380                 }
1381                 break;
1382
1383         case CAN_ISOTP_RECV_FC:
1384                 if (optlen != sizeof(struct can_isotp_fc_options))
1385                         return -EINVAL;
1386
1387                 if (copy_from_sockptr(&so->rxfc, optval, optlen))
1388                         return -EFAULT;
1389                 break;
1390
1391         case CAN_ISOTP_TX_STMIN:
1392                 if (optlen != sizeof(u32))
1393                         return -EINVAL;
1394
1395                 if (copy_from_sockptr(&so->force_tx_stmin, optval, optlen))
1396                         return -EFAULT;
1397                 break;
1398
1399         case CAN_ISOTP_RX_STMIN:
1400                 if (optlen != sizeof(u32))
1401                         return -EINVAL;
1402
1403                 if (copy_from_sockptr(&so->force_rx_stmin, optval, optlen))
1404                         return -EFAULT;
1405                 break;
1406
1407         case CAN_ISOTP_LL_OPTS:
1408                 if (optlen == sizeof(struct can_isotp_ll_options)) {
1409                         struct can_isotp_ll_options ll;
1410
1411                         if (copy_from_sockptr(&ll, optval, optlen))
1412                                 return -EFAULT;
1413
1414                         /* check for correct ISO 11898-1 DLC data length */
1415                         if (ll.tx_dl != padlen(ll.tx_dl))
1416                                 return -EINVAL;
1417
1418                         if (ll.mtu != CAN_MTU && ll.mtu != CANFD_MTU)
1419                                 return -EINVAL;
1420
1421                         if (ll.mtu == CAN_MTU &&
1422                             (ll.tx_dl > CAN_MAX_DLEN || ll.tx_flags != 0))
1423                                 return -EINVAL;
1424
1425                         memcpy(&so->ll, &ll, sizeof(ll));
1426
1427                         /* set ll_dl for tx path to similar place as for rx */
1428                         so->tx.ll_dl = ll.tx_dl;
1429                 } else {
1430                         return -EINVAL;
1431                 }
1432                 break;
1433
1434         default:
1435                 ret = -ENOPROTOOPT;
1436         }
1437
1438         return ret;
1439 }
1440
1441 static int isotp_setsockopt(struct socket *sock, int level, int optname,
1442                             sockptr_t optval, unsigned int optlen)
1443
1444 {
1445         struct sock *sk = sock->sk;
1446         int ret;
1447
1448         if (level != SOL_CAN_ISOTP)
1449                 return -EINVAL;
1450
1451         lock_sock(sk);
1452         ret = isotp_setsockopt_locked(sock, level, optname, optval, optlen);
1453         release_sock(sk);
1454         return ret;
1455 }
1456
1457 static int isotp_getsockopt(struct socket *sock, int level, int optname,
1458                             char __user *optval, int __user *optlen)
1459 {
1460         struct sock *sk = sock->sk;
1461         struct isotp_sock *so = isotp_sk(sk);
1462         int len;
1463         void *val;
1464
1465         if (level != SOL_CAN_ISOTP)
1466                 return -EINVAL;
1467         if (get_user(len, optlen))
1468                 return -EFAULT;
1469         if (len < 0)
1470                 return -EINVAL;
1471
1472         switch (optname) {
1473         case CAN_ISOTP_OPTS:
1474                 len = min_t(int, len, sizeof(struct can_isotp_options));
1475                 val = &so->opt;
1476                 break;
1477
1478         case CAN_ISOTP_RECV_FC:
1479                 len = min_t(int, len, sizeof(struct can_isotp_fc_options));
1480                 val = &so->rxfc;
1481                 break;
1482
1483         case CAN_ISOTP_TX_STMIN:
1484                 len = min_t(int, len, sizeof(u32));
1485                 val = &so->force_tx_stmin;
1486                 break;
1487
1488         case CAN_ISOTP_RX_STMIN:
1489                 len = min_t(int, len, sizeof(u32));
1490                 val = &so->force_rx_stmin;
1491                 break;
1492
1493         case CAN_ISOTP_LL_OPTS:
1494                 len = min_t(int, len, sizeof(struct can_isotp_ll_options));
1495                 val = &so->ll;
1496                 break;
1497
1498         default:
1499                 return -ENOPROTOOPT;
1500         }
1501
1502         if (put_user(len, optlen))
1503                 return -EFAULT;
1504         if (copy_to_user(optval, val, len))
1505                 return -EFAULT;
1506         return 0;
1507 }
1508
1509 static void isotp_notify(struct isotp_sock *so, unsigned long msg,
1510                          struct net_device *dev)
1511 {
1512         struct sock *sk = &so->sk;
1513
1514         if (!net_eq(dev_net(dev), sock_net(sk)))
1515                 return;
1516
1517         if (so->ifindex != dev->ifindex)
1518                 return;
1519
1520         switch (msg) {
1521         case NETDEV_UNREGISTER:
1522                 lock_sock(sk);
1523                 /* remove current filters & unregister */
1524                 if (so->bound && isotp_register_txecho(so)) {
1525                         if (isotp_register_rxid(so))
1526                                 can_rx_unregister(dev_net(dev), dev, so->rxid,
1527                                                   SINGLE_MASK(so->rxid),
1528                                                   isotp_rcv, sk);
1529
1530                         can_rx_unregister(dev_net(dev), dev, so->txid,
1531                                           SINGLE_MASK(so->txid),
1532                                           isotp_rcv_echo, sk);
1533                 }
1534
1535                 so->ifindex = 0;
1536                 so->bound  = 0;
1537                 release_sock(sk);
1538
1539                 sk->sk_err = ENODEV;
1540                 if (!sock_flag(sk, SOCK_DEAD))
1541                         sk_error_report(sk);
1542                 break;
1543
1544         case NETDEV_DOWN:
1545                 sk->sk_err = ENETDOWN;
1546                 if (!sock_flag(sk, SOCK_DEAD))
1547                         sk_error_report(sk);
1548                 break;
1549         }
1550 }
1551
1552 static int isotp_notifier(struct notifier_block *nb, unsigned long msg,
1553                           void *ptr)
1554 {
1555         struct net_device *dev = netdev_notifier_info_to_dev(ptr);
1556
1557         if (dev->type != ARPHRD_CAN)
1558                 return NOTIFY_DONE;
1559         if (msg != NETDEV_UNREGISTER && msg != NETDEV_DOWN)
1560                 return NOTIFY_DONE;
1561         if (unlikely(isotp_busy_notifier)) /* Check for reentrant bug. */
1562                 return NOTIFY_DONE;
1563
1564         spin_lock(&isotp_notifier_lock);
1565         list_for_each_entry(isotp_busy_notifier, &isotp_notifier_list, notifier) {
1566                 spin_unlock(&isotp_notifier_lock);
1567                 isotp_notify(isotp_busy_notifier, msg, dev);
1568                 spin_lock(&isotp_notifier_lock);
1569         }
1570         isotp_busy_notifier = NULL;
1571         spin_unlock(&isotp_notifier_lock);
1572         return NOTIFY_DONE;
1573 }
1574
1575 static int isotp_init(struct sock *sk)
1576 {
1577         struct isotp_sock *so = isotp_sk(sk);
1578
1579         so->ifindex = 0;
1580         so->bound = 0;
1581
1582         so->opt.flags = CAN_ISOTP_DEFAULT_FLAGS;
1583         so->opt.ext_address = CAN_ISOTP_DEFAULT_EXT_ADDRESS;
1584         so->opt.rx_ext_address = CAN_ISOTP_DEFAULT_EXT_ADDRESS;
1585         so->opt.rxpad_content = CAN_ISOTP_DEFAULT_PAD_CONTENT;
1586         so->opt.txpad_content = CAN_ISOTP_DEFAULT_PAD_CONTENT;
1587         so->opt.frame_txtime = CAN_ISOTP_DEFAULT_FRAME_TXTIME;
1588         so->frame_txtime = CAN_ISOTP_DEFAULT_FRAME_TXTIME;
1589         so->rxfc.bs = CAN_ISOTP_DEFAULT_RECV_BS;
1590         so->rxfc.stmin = CAN_ISOTP_DEFAULT_RECV_STMIN;
1591         so->rxfc.wftmax = CAN_ISOTP_DEFAULT_RECV_WFTMAX;
1592         so->ll.mtu = CAN_ISOTP_DEFAULT_LL_MTU;
1593         so->ll.tx_dl = CAN_ISOTP_DEFAULT_LL_TX_DL;
1594         so->ll.tx_flags = CAN_ISOTP_DEFAULT_LL_TX_FLAGS;
1595
1596         /* set ll_dl for tx path to similar place as for rx */
1597         so->tx.ll_dl = so->ll.tx_dl;
1598
1599         so->rx.state = ISOTP_IDLE;
1600         so->tx.state = ISOTP_IDLE;
1601
1602         hrtimer_init(&so->rxtimer, CLOCK_MONOTONIC, HRTIMER_MODE_REL_SOFT);
1603         so->rxtimer.function = isotp_rx_timer_handler;
1604         hrtimer_init(&so->txtimer, CLOCK_MONOTONIC, HRTIMER_MODE_REL_SOFT);
1605         so->txtimer.function = isotp_tx_timer_handler;
1606         hrtimer_init(&so->txfrtimer, CLOCK_MONOTONIC, HRTIMER_MODE_REL_SOFT);
1607         so->txfrtimer.function = isotp_txfr_timer_handler;
1608
1609         init_waitqueue_head(&so->wait);
1610         spin_lock_init(&so->rx_lock);
1611
1612         spin_lock(&isotp_notifier_lock);
1613         list_add_tail(&so->notifier, &isotp_notifier_list);
1614         spin_unlock(&isotp_notifier_lock);
1615
1616         return 0;
1617 }
1618
1619 static __poll_t isotp_poll(struct file *file, struct socket *sock, poll_table *wait)
1620 {
1621         struct sock *sk = sock->sk;
1622         struct isotp_sock *so = isotp_sk(sk);
1623
1624         __poll_t mask = datagram_poll(file, sock, wait);
1625         poll_wait(file, &so->wait, wait);
1626
1627         /* Check for false positives due to TX state */
1628         if ((mask & EPOLLWRNORM) && (so->tx.state != ISOTP_IDLE))
1629                 mask &= ~(EPOLLOUT | EPOLLWRNORM);
1630
1631         return mask;
1632 }
1633
1634 static int isotp_sock_no_ioctlcmd(struct socket *sock, unsigned int cmd,
1635                                   unsigned long arg)
1636 {
1637         /* no ioctls for socket layer -> hand it down to NIC layer */
1638         return -ENOIOCTLCMD;
1639 }
1640
1641 static const struct proto_ops isotp_ops = {
1642         .family = PF_CAN,
1643         .release = isotp_release,
1644         .bind = isotp_bind,
1645         .connect = sock_no_connect,
1646         .socketpair = sock_no_socketpair,
1647         .accept = sock_no_accept,
1648         .getname = isotp_getname,
1649         .poll = isotp_poll,
1650         .ioctl = isotp_sock_no_ioctlcmd,
1651         .gettstamp = sock_gettstamp,
1652         .listen = sock_no_listen,
1653         .shutdown = sock_no_shutdown,
1654         .setsockopt = isotp_setsockopt,
1655         .getsockopt = isotp_getsockopt,
1656         .sendmsg = isotp_sendmsg,
1657         .recvmsg = isotp_recvmsg,
1658         .mmap = sock_no_mmap,
1659         .sendpage = sock_no_sendpage,
1660 };
1661
1662 static struct proto isotp_proto __read_mostly = {
1663         .name = "CAN_ISOTP",
1664         .owner = THIS_MODULE,
1665         .obj_size = sizeof(struct isotp_sock),
1666         .init = isotp_init,
1667 };
1668
1669 static const struct can_proto isotp_can_proto = {
1670         .type = SOCK_DGRAM,
1671         .protocol = CAN_ISOTP,
1672         .ops = &isotp_ops,
1673         .prot = &isotp_proto,
1674 };
1675
1676 static struct notifier_block canisotp_notifier = {
1677         .notifier_call = isotp_notifier
1678 };
1679
1680 static __init int isotp_module_init(void)
1681 {
1682         int err;
1683
1684         pr_info("can: isotp protocol\n");
1685
1686         err = can_proto_register(&isotp_can_proto);
1687         if (err < 0)
1688                 pr_err("can: registration of isotp protocol failed %pe\n", ERR_PTR(err));
1689         else
1690                 register_netdevice_notifier(&canisotp_notifier);
1691
1692         return err;
1693 }
1694
1695 static __exit void isotp_module_exit(void)
1696 {
1697         can_proto_unregister(&isotp_can_proto);
1698         unregister_netdevice_notifier(&canisotp_notifier);
1699 }
1700
1701 module_init(isotp_module_init);
1702 module_exit(isotp_module_exit);