GNU Linux-libre 4.19.286-gnu1
[releases.git] / net / can / gw.c
1 /*
2  * gw.c - CAN frame Gateway/Router/Bridge with netlink interface
3  *
4  * Copyright (c) 2017 Volkswagen Group Electronic Research
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. Neither the name of Volkswagen nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * Alternatively, provided that this notice is retained in full, this
20  * software may be distributed under the terms of the GNU General
21  * Public License ("GPL") version 2, in which case the provisions of the
22  * GPL apply INSTEAD OF those given above.
23  *
24  * The provided data structures and external interfaces from this code
25  * are not restricted to be used by modules with a GPL compatible license.
26  *
27  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
28  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
29  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
30  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
31  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
32  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
33  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
34  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
35  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
36  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
37  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
38  * DAMAGE.
39  *
40  */
41
42 #include <linux/module.h>
43 #include <linux/init.h>
44 #include <linux/types.h>
45 #include <linux/kernel.h>
46 #include <linux/list.h>
47 #include <linux/spinlock.h>
48 #include <linux/rcupdate.h>
49 #include <linux/rculist.h>
50 #include <linux/net.h>
51 #include <linux/netdevice.h>
52 #include <linux/if_arp.h>
53 #include <linux/skbuff.h>
54 #include <linux/can.h>
55 #include <linux/can/core.h>
56 #include <linux/can/skb.h>
57 #include <linux/can/gw.h>
58 #include <net/rtnetlink.h>
59 #include <net/net_namespace.h>
60 #include <net/sock.h>
61
62 #define CAN_GW_VERSION "20170425"
63 #define CAN_GW_NAME "can-gw"
64
65 MODULE_DESCRIPTION("PF_CAN netlink gateway");
66 MODULE_LICENSE("Dual BSD/GPL");
67 MODULE_AUTHOR("Oliver Hartkopp <oliver.hartkopp@volkswagen.de>");
68 MODULE_ALIAS(CAN_GW_NAME);
69
70 #define CGW_MIN_HOPS 1
71 #define CGW_MAX_HOPS 6
72 #define CGW_DEFAULT_HOPS 1
73
74 static unsigned int max_hops __read_mostly = CGW_DEFAULT_HOPS;
75 module_param(max_hops, uint, 0444);
76 MODULE_PARM_DESC(max_hops,
77                  "maximum " CAN_GW_NAME " routing hops for CAN frames "
78                  "(valid values: " __stringify(CGW_MIN_HOPS) "-"
79                  __stringify(CGW_MAX_HOPS) " hops, "
80                  "default: " __stringify(CGW_DEFAULT_HOPS) ")");
81
82 static struct notifier_block notifier;
83 static struct kmem_cache *cgw_cache __read_mostly;
84
85 /* structure that contains the (on-the-fly) CAN frame modifications */
86 struct cf_mod {
87         struct {
88                 struct can_frame and;
89                 struct can_frame or;
90                 struct can_frame xor;
91                 struct can_frame set;
92         } modframe;
93         struct {
94                 u8 and;
95                 u8 or;
96                 u8 xor;
97                 u8 set;
98         } modtype;
99         void (*modfunc[MAX_MODFUNCTIONS])(struct can_frame *cf,
100                                           struct cf_mod *mod);
101
102         /* CAN frame checksum calculation after CAN frame modifications */
103         struct {
104                 struct cgw_csum_xor xor;
105                 struct cgw_csum_crc8 crc8;
106         } csum;
107         struct {
108                 void (*xor)(struct can_frame *cf, struct cgw_csum_xor *xor);
109                 void (*crc8)(struct can_frame *cf, struct cgw_csum_crc8 *crc8);
110         } csumfunc;
111         u32 uid;
112 };
113
114
115 /*
116  * So far we just support CAN -> CAN routing and frame modifications.
117  *
118  * The internal can_can_gw structure contains data and attributes for
119  * a CAN -> CAN gateway job.
120  */
121 struct can_can_gw {
122         struct can_filter filter;
123         int src_idx;
124         int dst_idx;
125 };
126
127 /* list entry for CAN gateways jobs */
128 struct cgw_job {
129         struct hlist_node list;
130         struct rcu_head rcu;
131         u32 handled_frames;
132         u32 dropped_frames;
133         u32 deleted_frames;
134         struct cf_mod mod;
135         union {
136                 /* CAN frame data source */
137                 struct net_device *dev;
138         } src;
139         union {
140                 /* CAN frame data destination */
141                 struct net_device *dev;
142         } dst;
143         union {
144                 struct can_can_gw ccgw;
145                 /* tbc */
146         };
147         u8 gwtype;
148         u8 limit_hops;
149         u16 flags;
150 };
151
152 /* modification functions that are invoked in the hot path in can_can_gw_rcv */
153
154 #define MODFUNC(func, op) static void func(struct can_frame *cf, \
155                                            struct cf_mod *mod) { op ; }
156
157 MODFUNC(mod_and_id, cf->can_id &= mod->modframe.and.can_id)
158 MODFUNC(mod_and_dlc, cf->can_dlc &= mod->modframe.and.can_dlc)
159 MODFUNC(mod_and_data, *(u64 *)cf->data &= *(u64 *)mod->modframe.and.data)
160 MODFUNC(mod_or_id, cf->can_id |= mod->modframe.or.can_id)
161 MODFUNC(mod_or_dlc, cf->can_dlc |= mod->modframe.or.can_dlc)
162 MODFUNC(mod_or_data, *(u64 *)cf->data |= *(u64 *)mod->modframe.or.data)
163 MODFUNC(mod_xor_id, cf->can_id ^= mod->modframe.xor.can_id)
164 MODFUNC(mod_xor_dlc, cf->can_dlc ^= mod->modframe.xor.can_dlc)
165 MODFUNC(mod_xor_data, *(u64 *)cf->data ^= *(u64 *)mod->modframe.xor.data)
166 MODFUNC(mod_set_id, cf->can_id = mod->modframe.set.can_id)
167 MODFUNC(mod_set_dlc, cf->can_dlc = mod->modframe.set.can_dlc)
168 MODFUNC(mod_set_data, *(u64 *)cf->data = *(u64 *)mod->modframe.set.data)
169
170 static inline void canframecpy(struct can_frame *dst, struct can_frame *src)
171 {
172         /*
173          * Copy the struct members separately to ensure that no uninitialized
174          * data are copied in the 3 bytes hole of the struct. This is needed
175          * to make easy compares of the data in the struct cf_mod.
176          */
177
178         dst->can_id = src->can_id;
179         dst->can_dlc = src->can_dlc;
180         *(u64 *)dst->data = *(u64 *)src->data;
181 }
182
183 static int cgw_chk_csum_parms(s8 fr, s8 to, s8 re)
184 {
185         /*
186          * absolute dlc values 0 .. 7 => 0 .. 7, e.g. data [0]
187          * relative to received dlc -1 .. -8 :
188          * e.g. for received dlc = 8
189          * -1 => index = 7 (data[7])
190          * -3 => index = 5 (data[5])
191          * -8 => index = 0 (data[0])
192          */
193
194         if (fr > -9 && fr < 8 &&
195             to > -9 && to < 8 &&
196             re > -9 && re < 8)
197                 return 0;
198         else
199                 return -EINVAL;
200 }
201
202 static inline int calc_idx(int idx, int rx_dlc)
203 {
204         if (idx < 0)
205                 return rx_dlc + idx;
206         else
207                 return idx;
208 }
209
210 static void cgw_csum_xor_rel(struct can_frame *cf, struct cgw_csum_xor *xor)
211 {
212         int from = calc_idx(xor->from_idx, cf->can_dlc);
213         int to = calc_idx(xor->to_idx, cf->can_dlc);
214         int res = calc_idx(xor->result_idx, cf->can_dlc);
215         u8 val = xor->init_xor_val;
216         int i;
217
218         if (from < 0 || to < 0 || res < 0)
219                 return;
220
221         if (from <= to) {
222                 for (i = from; i <= to; i++)
223                         val ^= cf->data[i];
224         } else {
225                 for (i = from; i >= to; i--)
226                         val ^= cf->data[i];
227         }
228
229         cf->data[res] = val;
230 }
231
232 static void cgw_csum_xor_pos(struct can_frame *cf, struct cgw_csum_xor *xor)
233 {
234         u8 val = xor->init_xor_val;
235         int i;
236
237         for (i = xor->from_idx; i <= xor->to_idx; i++)
238                 val ^= cf->data[i];
239
240         cf->data[xor->result_idx] = val;
241 }
242
243 static void cgw_csum_xor_neg(struct can_frame *cf, struct cgw_csum_xor *xor)
244 {
245         u8 val = xor->init_xor_val;
246         int i;
247
248         for (i = xor->from_idx; i >= xor->to_idx; i--)
249                 val ^= cf->data[i];
250
251         cf->data[xor->result_idx] = val;
252 }
253
254 static void cgw_csum_crc8_rel(struct can_frame *cf, struct cgw_csum_crc8 *crc8)
255 {
256         int from = calc_idx(crc8->from_idx, cf->can_dlc);
257         int to = calc_idx(crc8->to_idx, cf->can_dlc);
258         int res = calc_idx(crc8->result_idx, cf->can_dlc);
259         u8 crc = crc8->init_crc_val;
260         int i;
261
262         if (from < 0 || to < 0 || res < 0)
263                 return;
264
265         if (from <= to) {
266                 for (i = crc8->from_idx; i <= crc8->to_idx; i++)
267                         crc = crc8->crctab[crc^cf->data[i]];
268         } else {
269                 for (i = crc8->from_idx; i >= crc8->to_idx; i--)
270                         crc = crc8->crctab[crc^cf->data[i]];
271         }
272
273         switch (crc8->profile) {
274
275         case CGW_CRC8PRF_1U8:
276                 crc = crc8->crctab[crc^crc8->profile_data[0]];
277                 break;
278
279         case  CGW_CRC8PRF_16U8:
280                 crc = crc8->crctab[crc^crc8->profile_data[cf->data[1] & 0xF]];
281                 break;
282
283         case CGW_CRC8PRF_SFFID_XOR:
284                 crc = crc8->crctab[crc^(cf->can_id & 0xFF)^
285                                    (cf->can_id >> 8 & 0xFF)];
286                 break;
287
288         }
289
290         cf->data[crc8->result_idx] = crc^crc8->final_xor_val;
291 }
292
293 static void cgw_csum_crc8_pos(struct can_frame *cf, struct cgw_csum_crc8 *crc8)
294 {
295         u8 crc = crc8->init_crc_val;
296         int i;
297
298         for (i = crc8->from_idx; i <= crc8->to_idx; i++)
299                 crc = crc8->crctab[crc^cf->data[i]];
300
301         switch (crc8->profile) {
302
303         case CGW_CRC8PRF_1U8:
304                 crc = crc8->crctab[crc^crc8->profile_data[0]];
305                 break;
306
307         case  CGW_CRC8PRF_16U8:
308                 crc = crc8->crctab[crc^crc8->profile_data[cf->data[1] & 0xF]];
309                 break;
310
311         case CGW_CRC8PRF_SFFID_XOR:
312                 crc = crc8->crctab[crc^(cf->can_id & 0xFF)^
313                                    (cf->can_id >> 8 & 0xFF)];
314                 break;
315         }
316
317         cf->data[crc8->result_idx] = crc^crc8->final_xor_val;
318 }
319
320 static void cgw_csum_crc8_neg(struct can_frame *cf, struct cgw_csum_crc8 *crc8)
321 {
322         u8 crc = crc8->init_crc_val;
323         int i;
324
325         for (i = crc8->from_idx; i >= crc8->to_idx; i--)
326                 crc = crc8->crctab[crc^cf->data[i]];
327
328         switch (crc8->profile) {
329
330         case CGW_CRC8PRF_1U8:
331                 crc = crc8->crctab[crc^crc8->profile_data[0]];
332                 break;
333
334         case  CGW_CRC8PRF_16U8:
335                 crc = crc8->crctab[crc^crc8->profile_data[cf->data[1] & 0xF]];
336                 break;
337
338         case CGW_CRC8PRF_SFFID_XOR:
339                 crc = crc8->crctab[crc^(cf->can_id & 0xFF)^
340                                    (cf->can_id >> 8 & 0xFF)];
341                 break;
342         }
343
344         cf->data[crc8->result_idx] = crc^crc8->final_xor_val;
345 }
346
347 /* the receive & process & send function */
348 static void can_can_gw_rcv(struct sk_buff *skb, void *data)
349 {
350         struct cgw_job *gwj = (struct cgw_job *)data;
351         struct can_frame *cf;
352         struct sk_buff *nskb;
353         int modidx = 0;
354
355         /*
356          * Do not handle CAN frames routed more than 'max_hops' times.
357          * In general we should never catch this delimiter which is intended
358          * to cover a misconfiguration protection (e.g. circular CAN routes).
359          *
360          * The Controller Area Network controllers only accept CAN frames with
361          * correct CRCs - which are not visible in the controller registers.
362          * According to skbuff.h documentation the csum_start element for IP
363          * checksums is undefined/unused when ip_summed == CHECKSUM_UNNECESSARY.
364          * Only CAN skbs can be processed here which already have this property.
365          */
366
367 #define cgw_hops(skb) ((skb)->csum_start)
368
369         BUG_ON(skb->ip_summed != CHECKSUM_UNNECESSARY);
370
371         if (cgw_hops(skb) >= max_hops) {
372                 /* indicate deleted frames due to misconfiguration */
373                 gwj->deleted_frames++;
374                 return;
375         }
376
377         if (!(gwj->dst.dev->flags & IFF_UP)) {
378                 gwj->dropped_frames++;
379                 return;
380         }
381
382         /* is sending the skb back to the incoming interface not allowed? */
383         if (!(gwj->flags & CGW_FLAGS_CAN_IIF_TX_OK) &&
384             can_skb_prv(skb)->ifindex == gwj->dst.dev->ifindex)
385                 return;
386
387         /*
388          * clone the given skb, which has not been done in can_rcv()
389          *
390          * When there is at least one modification function activated,
391          * we need to copy the skb as we want to modify skb->data.
392          */
393         if (gwj->mod.modfunc[0])
394                 nskb = skb_copy(skb, GFP_ATOMIC);
395         else
396                 nskb = skb_clone(skb, GFP_ATOMIC);
397
398         if (!nskb) {
399                 gwj->dropped_frames++;
400                 return;
401         }
402
403         /* put the incremented hop counter in the cloned skb */
404         cgw_hops(nskb) = cgw_hops(skb) + 1;
405
406         /* first processing of this CAN frame -> adjust to private hop limit */
407         if (gwj->limit_hops && cgw_hops(nskb) == 1)
408                 cgw_hops(nskb) = max_hops - gwj->limit_hops + 1;
409
410         nskb->dev = gwj->dst.dev;
411
412         /* pointer to modifiable CAN frame */
413         cf = (struct can_frame *)nskb->data;
414
415         /* perform preprocessed modification functions if there are any */
416         while (modidx < MAX_MODFUNCTIONS && gwj->mod.modfunc[modidx])
417                 (*gwj->mod.modfunc[modidx++])(cf, &gwj->mod);
418
419         /* Has the CAN frame been modified? */
420         if (modidx) {
421                 /* get available space for the processed CAN frame type */
422                 int max_len = nskb->len - offsetof(struct can_frame, data);
423
424                 /* dlc may have changed, make sure it fits to the CAN frame */
425                 if (cf->can_dlc > max_len)
426                         goto out_delete;
427
428                 /* check for checksum updates in classic CAN length only */
429                 if (gwj->mod.csumfunc.crc8) {
430                         if (cf->can_dlc > 8)
431                                 goto out_delete;
432
433                         (*gwj->mod.csumfunc.crc8)(cf, &gwj->mod.csum.crc8);
434                 }
435
436                 if (gwj->mod.csumfunc.xor) {
437                         if (cf->can_dlc > 8)
438                                 goto out_delete;
439
440                         (*gwj->mod.csumfunc.xor)(cf, &gwj->mod.csum.xor);
441                 }
442         }
443
444         /* clear the skb timestamp if not configured the other way */
445         if (!(gwj->flags & CGW_FLAGS_CAN_SRC_TSTAMP))
446                 nskb->tstamp = 0;
447
448         /* send to netdevice */
449         if (can_send(nskb, gwj->flags & CGW_FLAGS_CAN_ECHO))
450                 gwj->dropped_frames++;
451         else
452                 gwj->handled_frames++;
453
454         return;
455
456  out_delete:
457         /* delete frame due to misconfiguration */
458         gwj->deleted_frames++;
459         kfree_skb(nskb);
460         return;
461 }
462
463 static inline int cgw_register_filter(struct net *net, struct cgw_job *gwj)
464 {
465         return can_rx_register(net, gwj->src.dev, gwj->ccgw.filter.can_id,
466                                gwj->ccgw.filter.can_mask, can_can_gw_rcv,
467                                gwj, "gw", NULL);
468 }
469
470 static inline void cgw_unregister_filter(struct net *net, struct cgw_job *gwj)
471 {
472         can_rx_unregister(net, gwj->src.dev, gwj->ccgw.filter.can_id,
473                           gwj->ccgw.filter.can_mask, can_can_gw_rcv, gwj);
474 }
475
476 static int cgw_notifier(struct notifier_block *nb,
477                         unsigned long msg, void *ptr)
478 {
479         struct net_device *dev = netdev_notifier_info_to_dev(ptr);
480         struct net *net = dev_net(dev);
481
482         if (dev->type != ARPHRD_CAN)
483                 return NOTIFY_DONE;
484
485         if (msg == NETDEV_UNREGISTER) {
486
487                 struct cgw_job *gwj = NULL;
488                 struct hlist_node *nx;
489
490                 ASSERT_RTNL();
491
492                 hlist_for_each_entry_safe(gwj, nx, &net->can.cgw_list, list) {
493
494                         if (gwj->src.dev == dev || gwj->dst.dev == dev) {
495                                 hlist_del(&gwj->list);
496                                 cgw_unregister_filter(net, gwj);
497                                 synchronize_rcu();
498                                 kmem_cache_free(cgw_cache, gwj);
499                         }
500                 }
501         }
502
503         return NOTIFY_DONE;
504 }
505
506 static int cgw_put_job(struct sk_buff *skb, struct cgw_job *gwj, int type,
507                        u32 pid, u32 seq, int flags)
508 {
509         struct cgw_frame_mod mb;
510         struct rtcanmsg *rtcan;
511         struct nlmsghdr *nlh;
512
513         nlh = nlmsg_put(skb, pid, seq, type, sizeof(*rtcan), flags);
514         if (!nlh)
515                 return -EMSGSIZE;
516
517         rtcan = nlmsg_data(nlh);
518         rtcan->can_family = AF_CAN;
519         rtcan->gwtype = gwj->gwtype;
520         rtcan->flags = gwj->flags;
521
522         /* add statistics if available */
523
524         if (gwj->handled_frames) {
525                 if (nla_put_u32(skb, CGW_HANDLED, gwj->handled_frames) < 0)
526                         goto cancel;
527         }
528
529         if (gwj->dropped_frames) {
530                 if (nla_put_u32(skb, CGW_DROPPED, gwj->dropped_frames) < 0)
531                         goto cancel;
532         }
533
534         if (gwj->deleted_frames) {
535                 if (nla_put_u32(skb, CGW_DELETED, gwj->deleted_frames) < 0)
536                         goto cancel;
537         }
538
539         /* check non default settings of attributes */
540
541         if (gwj->limit_hops) {
542                 if (nla_put_u8(skb, CGW_LIM_HOPS, gwj->limit_hops) < 0)
543                         goto cancel;
544         }
545
546         if (gwj->mod.modtype.and) {
547                 memcpy(&mb.cf, &gwj->mod.modframe.and, sizeof(mb.cf));
548                 mb.modtype = gwj->mod.modtype.and;
549                 if (nla_put(skb, CGW_MOD_AND, sizeof(mb), &mb) < 0)
550                         goto cancel;
551         }
552
553         if (gwj->mod.modtype.or) {
554                 memcpy(&mb.cf, &gwj->mod.modframe.or, sizeof(mb.cf));
555                 mb.modtype = gwj->mod.modtype.or;
556                 if (nla_put(skb, CGW_MOD_OR, sizeof(mb), &mb) < 0)
557                         goto cancel;
558         }
559
560         if (gwj->mod.modtype.xor) {
561                 memcpy(&mb.cf, &gwj->mod.modframe.xor, sizeof(mb.cf));
562                 mb.modtype = gwj->mod.modtype.xor;
563                 if (nla_put(skb, CGW_MOD_XOR, sizeof(mb), &mb) < 0)
564                         goto cancel;
565         }
566
567         if (gwj->mod.modtype.set) {
568                 memcpy(&mb.cf, &gwj->mod.modframe.set, sizeof(mb.cf));
569                 mb.modtype = gwj->mod.modtype.set;
570                 if (nla_put(skb, CGW_MOD_SET, sizeof(mb), &mb) < 0)
571                         goto cancel;
572         }
573
574         if (gwj->mod.uid) {
575                 if (nla_put_u32(skb, CGW_MOD_UID, gwj->mod.uid) < 0)
576                         goto cancel;
577         }
578
579         if (gwj->mod.csumfunc.crc8) {
580                 if (nla_put(skb, CGW_CS_CRC8, CGW_CS_CRC8_LEN,
581                             &gwj->mod.csum.crc8) < 0)
582                         goto cancel;
583         }
584
585         if (gwj->mod.csumfunc.xor) {
586                 if (nla_put(skb, CGW_CS_XOR, CGW_CS_XOR_LEN,
587                             &gwj->mod.csum.xor) < 0)
588                         goto cancel;
589         }
590
591         if (gwj->gwtype == CGW_TYPE_CAN_CAN) {
592
593                 if (gwj->ccgw.filter.can_id || gwj->ccgw.filter.can_mask) {
594                         if (nla_put(skb, CGW_FILTER, sizeof(struct can_filter),
595                                     &gwj->ccgw.filter) < 0)
596                                 goto cancel;
597                 }
598
599                 if (nla_put_u32(skb, CGW_SRC_IF, gwj->ccgw.src_idx) < 0)
600                         goto cancel;
601
602                 if (nla_put_u32(skb, CGW_DST_IF, gwj->ccgw.dst_idx) < 0)
603                         goto cancel;
604         }
605
606         nlmsg_end(skb, nlh);
607         return 0;
608
609 cancel:
610         nlmsg_cancel(skb, nlh);
611         return -EMSGSIZE;
612 }
613
614 /* Dump information about all CAN gateway jobs, in response to RTM_GETROUTE */
615 static int cgw_dump_jobs(struct sk_buff *skb, struct netlink_callback *cb)
616 {
617         struct net *net = sock_net(skb->sk);
618         struct cgw_job *gwj = NULL;
619         int idx = 0;
620         int s_idx = cb->args[0];
621
622         rcu_read_lock();
623         hlist_for_each_entry_rcu(gwj, &net->can.cgw_list, list) {
624                 if (idx < s_idx)
625                         goto cont;
626
627                 if (cgw_put_job(skb, gwj, RTM_NEWROUTE, NETLINK_CB(cb->skb).portid,
628                     cb->nlh->nlmsg_seq, NLM_F_MULTI) < 0)
629                         break;
630 cont:
631                 idx++;
632         }
633         rcu_read_unlock();
634
635         cb->args[0] = idx;
636
637         return skb->len;
638 }
639
640 static const struct nla_policy cgw_policy[CGW_MAX+1] = {
641         [CGW_MOD_AND]   = { .len = sizeof(struct cgw_frame_mod) },
642         [CGW_MOD_OR]    = { .len = sizeof(struct cgw_frame_mod) },
643         [CGW_MOD_XOR]   = { .len = sizeof(struct cgw_frame_mod) },
644         [CGW_MOD_SET]   = { .len = sizeof(struct cgw_frame_mod) },
645         [CGW_CS_XOR]    = { .len = sizeof(struct cgw_csum_xor) },
646         [CGW_CS_CRC8]   = { .len = sizeof(struct cgw_csum_crc8) },
647         [CGW_SRC_IF]    = { .type = NLA_U32 },
648         [CGW_DST_IF]    = { .type = NLA_U32 },
649         [CGW_FILTER]    = { .len = sizeof(struct can_filter) },
650         [CGW_LIM_HOPS]  = { .type = NLA_U8 },
651         [CGW_MOD_UID]   = { .type = NLA_U32 },
652 };
653
654 /* check for common and gwtype specific attributes */
655 static int cgw_parse_attr(struct nlmsghdr *nlh, struct cf_mod *mod,
656                           u8 gwtype, void *gwtypeattr, u8 *limhops)
657 {
658         struct nlattr *tb[CGW_MAX+1];
659         struct cgw_frame_mod mb;
660         int modidx = 0;
661         int err = 0;
662
663         /* initialize modification & checksum data space */
664         memset(mod, 0, sizeof(*mod));
665
666         err = nlmsg_parse(nlh, sizeof(struct rtcanmsg), tb, CGW_MAX,
667                           cgw_policy, NULL);
668         if (err < 0)
669                 return err;
670
671         if (tb[CGW_LIM_HOPS]) {
672                 *limhops = nla_get_u8(tb[CGW_LIM_HOPS]);
673
674                 if (*limhops < 1 || *limhops > max_hops)
675                         return -EINVAL;
676         }
677
678         /* check for AND/OR/XOR/SET modifications */
679
680         if (tb[CGW_MOD_AND]) {
681                 nla_memcpy(&mb, tb[CGW_MOD_AND], CGW_MODATTR_LEN);
682
683                 canframecpy(&mod->modframe.and, &mb.cf);
684                 mod->modtype.and = mb.modtype;
685
686                 if (mb.modtype & CGW_MOD_ID)
687                         mod->modfunc[modidx++] = mod_and_id;
688
689                 if (mb.modtype & CGW_MOD_DLC)
690                         mod->modfunc[modidx++] = mod_and_dlc;
691
692                 if (mb.modtype & CGW_MOD_DATA)
693                         mod->modfunc[modidx++] = mod_and_data;
694         }
695
696         if (tb[CGW_MOD_OR]) {
697                 nla_memcpy(&mb, tb[CGW_MOD_OR], CGW_MODATTR_LEN);
698
699                 canframecpy(&mod->modframe.or, &mb.cf);
700                 mod->modtype.or = mb.modtype;
701
702                 if (mb.modtype & CGW_MOD_ID)
703                         mod->modfunc[modidx++] = mod_or_id;
704
705                 if (mb.modtype & CGW_MOD_DLC)
706                         mod->modfunc[modidx++] = mod_or_dlc;
707
708                 if (mb.modtype & CGW_MOD_DATA)
709                         mod->modfunc[modidx++] = mod_or_data;
710         }
711
712         if (tb[CGW_MOD_XOR]) {
713                 nla_memcpy(&mb, tb[CGW_MOD_XOR], CGW_MODATTR_LEN);
714
715                 canframecpy(&mod->modframe.xor, &mb.cf);
716                 mod->modtype.xor = mb.modtype;
717
718                 if (mb.modtype & CGW_MOD_ID)
719                         mod->modfunc[modidx++] = mod_xor_id;
720
721                 if (mb.modtype & CGW_MOD_DLC)
722                         mod->modfunc[modidx++] = mod_xor_dlc;
723
724                 if (mb.modtype & CGW_MOD_DATA)
725                         mod->modfunc[modidx++] = mod_xor_data;
726         }
727
728         if (tb[CGW_MOD_SET]) {
729                 nla_memcpy(&mb, tb[CGW_MOD_SET], CGW_MODATTR_LEN);
730
731                 canframecpy(&mod->modframe.set, &mb.cf);
732                 mod->modtype.set = mb.modtype;
733
734                 if (mb.modtype & CGW_MOD_ID)
735                         mod->modfunc[modidx++] = mod_set_id;
736
737                 if (mb.modtype & CGW_MOD_DLC)
738                         mod->modfunc[modidx++] = mod_set_dlc;
739
740                 if (mb.modtype & CGW_MOD_DATA)
741                         mod->modfunc[modidx++] = mod_set_data;
742         }
743
744         /* check for checksum operations after CAN frame modifications */
745         if (modidx) {
746
747                 if (tb[CGW_CS_CRC8]) {
748                         struct cgw_csum_crc8 *c = nla_data(tb[CGW_CS_CRC8]);
749
750                         err = cgw_chk_csum_parms(c->from_idx, c->to_idx,
751                                                  c->result_idx);
752                         if (err)
753                                 return err;
754
755                         nla_memcpy(&mod->csum.crc8, tb[CGW_CS_CRC8],
756                                    CGW_CS_CRC8_LEN);
757
758                         /*
759                          * select dedicated processing function to reduce
760                          * runtime operations in receive hot path.
761                          */
762                         if (c->from_idx < 0 || c->to_idx < 0 ||
763                             c->result_idx < 0)
764                                 mod->csumfunc.crc8 = cgw_csum_crc8_rel;
765                         else if (c->from_idx <= c->to_idx)
766                                 mod->csumfunc.crc8 = cgw_csum_crc8_pos;
767                         else
768                                 mod->csumfunc.crc8 = cgw_csum_crc8_neg;
769                 }
770
771                 if (tb[CGW_CS_XOR]) {
772                         struct cgw_csum_xor *c = nla_data(tb[CGW_CS_XOR]);
773
774                         err = cgw_chk_csum_parms(c->from_idx, c->to_idx,
775                                                  c->result_idx);
776                         if (err)
777                                 return err;
778
779                         nla_memcpy(&mod->csum.xor, tb[CGW_CS_XOR],
780                                    CGW_CS_XOR_LEN);
781
782                         /*
783                          * select dedicated processing function to reduce
784                          * runtime operations in receive hot path.
785                          */
786                         if (c->from_idx < 0 || c->to_idx < 0 ||
787                             c->result_idx < 0)
788                                 mod->csumfunc.xor = cgw_csum_xor_rel;
789                         else if (c->from_idx <= c->to_idx)
790                                 mod->csumfunc.xor = cgw_csum_xor_pos;
791                         else
792                                 mod->csumfunc.xor = cgw_csum_xor_neg;
793                 }
794
795                 if (tb[CGW_MOD_UID]) {
796                         nla_memcpy(&mod->uid, tb[CGW_MOD_UID], sizeof(u32));
797                 }
798         }
799
800         if (gwtype == CGW_TYPE_CAN_CAN) {
801
802                 /* check CGW_TYPE_CAN_CAN specific attributes */
803
804                 struct can_can_gw *ccgw = (struct can_can_gw *)gwtypeattr;
805                 memset(ccgw, 0, sizeof(*ccgw));
806
807                 /* check for can_filter in attributes */
808                 if (tb[CGW_FILTER])
809                         nla_memcpy(&ccgw->filter, tb[CGW_FILTER],
810                                    sizeof(struct can_filter));
811
812                 err = -ENODEV;
813
814                 /* specifying two interfaces is mandatory */
815                 if (!tb[CGW_SRC_IF] || !tb[CGW_DST_IF])
816                         return err;
817
818                 ccgw->src_idx = nla_get_u32(tb[CGW_SRC_IF]);
819                 ccgw->dst_idx = nla_get_u32(tb[CGW_DST_IF]);
820
821                 /* both indices set to 0 for flushing all routing entries */
822                 if (!ccgw->src_idx && !ccgw->dst_idx)
823                         return 0;
824
825                 /* only one index set to 0 is an error */
826                 if (!ccgw->src_idx || !ccgw->dst_idx)
827                         return err;
828         }
829
830         /* add the checks for other gwtypes here */
831
832         return 0;
833 }
834
835 static int cgw_create_job(struct sk_buff *skb,  struct nlmsghdr *nlh,
836                           struct netlink_ext_ack *extack)
837 {
838         struct net *net = sock_net(skb->sk);
839         struct rtcanmsg *r;
840         struct cgw_job *gwj;
841         struct cf_mod mod;
842         struct can_can_gw ccgw;
843         u8 limhops = 0;
844         int err = 0;
845
846         if (!netlink_capable(skb, CAP_NET_ADMIN))
847                 return -EPERM;
848
849         if (nlmsg_len(nlh) < sizeof(*r))
850                 return -EINVAL;
851
852         r = nlmsg_data(nlh);
853         if (r->can_family != AF_CAN)
854                 return -EPFNOSUPPORT;
855
856         /* so far we only support CAN -> CAN routings */
857         if (r->gwtype != CGW_TYPE_CAN_CAN)
858                 return -EINVAL;
859
860         err = cgw_parse_attr(nlh, &mod, CGW_TYPE_CAN_CAN, &ccgw, &limhops);
861         if (err < 0)
862                 return err;
863
864         if (mod.uid) {
865
866                 ASSERT_RTNL();
867
868                 /* check for updating an existing job with identical uid */
869                 hlist_for_each_entry(gwj, &net->can.cgw_list, list) {
870
871                         if (gwj->mod.uid != mod.uid)
872                                 continue;
873
874                         /* interfaces & filters must be identical */
875                         if (memcmp(&gwj->ccgw, &ccgw, sizeof(ccgw)))
876                                 return -EINVAL;
877
878                         /* update modifications with disabled softirq & quit */
879                         local_bh_disable();
880                         memcpy(&gwj->mod, &mod, sizeof(mod));
881                         local_bh_enable();
882                         return 0;
883                 }
884         }
885
886         /* ifindex == 0 is not allowed for job creation */
887         if (!ccgw.src_idx || !ccgw.dst_idx)
888                 return -ENODEV;
889
890         gwj = kmem_cache_alloc(cgw_cache, GFP_KERNEL);
891         if (!gwj)
892                 return -ENOMEM;
893
894         gwj->handled_frames = 0;
895         gwj->dropped_frames = 0;
896         gwj->deleted_frames = 0;
897         gwj->flags = r->flags;
898         gwj->gwtype = r->gwtype;
899         gwj->limit_hops = limhops;
900
901         /* insert already parsed information */
902         memcpy(&gwj->mod, &mod, sizeof(mod));
903         memcpy(&gwj->ccgw, &ccgw, sizeof(ccgw));
904
905         err = -ENODEV;
906
907         gwj->src.dev = __dev_get_by_index(net, gwj->ccgw.src_idx);
908
909         if (!gwj->src.dev)
910                 goto out;
911
912         if (gwj->src.dev->type != ARPHRD_CAN)
913                 goto out;
914
915         gwj->dst.dev = __dev_get_by_index(net, gwj->ccgw.dst_idx);
916
917         if (!gwj->dst.dev)
918                 goto out;
919
920         if (gwj->dst.dev->type != ARPHRD_CAN)
921                 goto out;
922
923         ASSERT_RTNL();
924
925         err = cgw_register_filter(net, gwj);
926         if (!err)
927                 hlist_add_head_rcu(&gwj->list, &net->can.cgw_list);
928 out:
929         if (err)
930                 kmem_cache_free(cgw_cache, gwj);
931
932         return err;
933 }
934
935 static void cgw_remove_all_jobs(struct net *net)
936 {
937         struct cgw_job *gwj = NULL;
938         struct hlist_node *nx;
939
940         ASSERT_RTNL();
941
942         hlist_for_each_entry_safe(gwj, nx, &net->can.cgw_list, list) {
943                 hlist_del(&gwj->list);
944                 cgw_unregister_filter(net, gwj);
945                 synchronize_rcu();
946                 kmem_cache_free(cgw_cache, gwj);
947         }
948 }
949
950 static int cgw_remove_job(struct sk_buff *skb, struct nlmsghdr *nlh,
951                           struct netlink_ext_ack *extack)
952 {
953         struct net *net = sock_net(skb->sk);
954         struct cgw_job *gwj = NULL;
955         struct hlist_node *nx;
956         struct rtcanmsg *r;
957         struct cf_mod mod;
958         struct can_can_gw ccgw;
959         u8 limhops = 0;
960         int err = 0;
961
962         if (!netlink_capable(skb, CAP_NET_ADMIN))
963                 return -EPERM;
964
965         if (nlmsg_len(nlh) < sizeof(*r))
966                 return -EINVAL;
967
968         r = nlmsg_data(nlh);
969         if (r->can_family != AF_CAN)
970                 return -EPFNOSUPPORT;
971
972         /* so far we only support CAN -> CAN routings */
973         if (r->gwtype != CGW_TYPE_CAN_CAN)
974                 return -EINVAL;
975
976         err = cgw_parse_attr(nlh, &mod, CGW_TYPE_CAN_CAN, &ccgw, &limhops);
977         if (err < 0)
978                 return err;
979
980         /* two interface indices both set to 0 => remove all entries */
981         if (!ccgw.src_idx && !ccgw.dst_idx) {
982                 cgw_remove_all_jobs(net);
983                 return 0;
984         }
985
986         err = -EINVAL;
987
988         ASSERT_RTNL();
989
990         /* remove only the first matching entry */
991         hlist_for_each_entry_safe(gwj, nx, &net->can.cgw_list, list) {
992
993                 if (gwj->flags != r->flags)
994                         continue;
995
996                 if (gwj->limit_hops != limhops)
997                         continue;
998
999                 /* we have a match when uid is enabled and identical */
1000                 if (gwj->mod.uid || mod.uid) {
1001                         if (gwj->mod.uid != mod.uid)
1002                                 continue;
1003                 } else {
1004                         /* no uid => check for identical modifications */
1005                         if (memcmp(&gwj->mod, &mod, sizeof(mod)))
1006                                 continue;
1007                 }
1008
1009                 /* if (r->gwtype == CGW_TYPE_CAN_CAN) - is made sure here */
1010                 if (memcmp(&gwj->ccgw, &ccgw, sizeof(ccgw)))
1011                         continue;
1012
1013                 hlist_del(&gwj->list);
1014                 cgw_unregister_filter(net, gwj);
1015                 synchronize_rcu();
1016                 kmem_cache_free(cgw_cache, gwj);
1017                 err = 0;
1018                 break;
1019         }
1020
1021         return err;
1022 }
1023
1024 static int __net_init cangw_pernet_init(struct net *net)
1025 {
1026         INIT_HLIST_HEAD(&net->can.cgw_list);
1027         return 0;
1028 }
1029
1030 static void __net_exit cangw_pernet_exit(struct net *net)
1031 {
1032         rtnl_lock();
1033         cgw_remove_all_jobs(net);
1034         rtnl_unlock();
1035 }
1036
1037 static struct pernet_operations cangw_pernet_ops = {
1038         .init = cangw_pernet_init,
1039         .exit = cangw_pernet_exit,
1040 };
1041
1042 static __init int cgw_module_init(void)
1043 {
1044         int ret;
1045
1046         /* sanitize given module parameter */
1047         max_hops = clamp_t(unsigned int, max_hops, CGW_MIN_HOPS, CGW_MAX_HOPS);
1048
1049         pr_info("can: netlink gateway (rev " CAN_GW_VERSION ") max_hops=%d\n",
1050                 max_hops);
1051
1052         ret = register_pernet_subsys(&cangw_pernet_ops);
1053         if (ret)
1054                 return ret;
1055
1056         ret = -ENOMEM;
1057         cgw_cache = kmem_cache_create("can_gw", sizeof(struct cgw_job),
1058                                       0, 0, NULL);
1059         if (!cgw_cache)
1060                 goto out_cache_create;
1061
1062         /* set notifier */
1063         notifier.notifier_call = cgw_notifier;
1064         ret = register_netdevice_notifier(&notifier);
1065         if (ret)
1066                 goto out_register_notifier;
1067
1068         ret = rtnl_register_module(THIS_MODULE, PF_CAN, RTM_GETROUTE,
1069                                    NULL, cgw_dump_jobs, 0);
1070         if (ret)
1071                 goto out_rtnl_register1;
1072
1073         ret = rtnl_register_module(THIS_MODULE, PF_CAN, RTM_NEWROUTE,
1074                                    cgw_create_job, NULL, 0);
1075         if (ret)
1076                 goto out_rtnl_register2;
1077         ret = rtnl_register_module(THIS_MODULE, PF_CAN, RTM_DELROUTE,
1078                                    cgw_remove_job, NULL, 0);
1079         if (ret)
1080                 goto out_rtnl_register3;
1081
1082         return 0;
1083
1084 out_rtnl_register3:
1085         rtnl_unregister(PF_CAN, RTM_NEWROUTE);
1086 out_rtnl_register2:
1087         rtnl_unregister(PF_CAN, RTM_GETROUTE);
1088 out_rtnl_register1:
1089         unregister_netdevice_notifier(&notifier);
1090 out_register_notifier:
1091         kmem_cache_destroy(cgw_cache);
1092 out_cache_create:
1093         unregister_pernet_subsys(&cangw_pernet_ops);
1094
1095         return ret;
1096 }
1097
1098 static __exit void cgw_module_exit(void)
1099 {
1100         rtnl_unregister_all(PF_CAN);
1101
1102         unregister_netdevice_notifier(&notifier);
1103
1104         unregister_pernet_subsys(&cangw_pernet_ops);
1105         rcu_barrier(); /* Wait for completion of call_rcu()'s */
1106
1107         kmem_cache_destroy(cgw_cache);
1108 }
1109
1110 module_init(cgw_module_init);
1111 module_exit(cgw_module_exit);