Upgrade to 4.4.50-rt62
[kvmfornfv.git] / kernel / drivers / net / can / dev.c
1 /*
2  * Copyright (C) 2005 Marc Kleine-Budde, Pengutronix
3  * Copyright (C) 2006 Andrey Volkov, Varma Electronics
4  * Copyright (C) 2008-2009 Wolfgang Grandegger <wg@grandegger.com>
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the version 2 of the GNU General Public License
8  * as published by the Free Software Foundation
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, see <http://www.gnu.org/licenses/>.
17  */
18
19 #include <linux/module.h>
20 #include <linux/kernel.h>
21 #include <linux/slab.h>
22 #include <linux/netdevice.h>
23 #include <linux/if_arp.h>
24 #include <linux/workqueue.h>
25 #include <linux/can.h>
26 #include <linux/can/dev.h>
27 #include <linux/can/skb.h>
28 #include <linux/can/netlink.h>
29 #include <linux/can/led.h>
30 #include <net/rtnetlink.h>
31
32 #define MOD_DESC "CAN device driver interface"
33
34 MODULE_DESCRIPTION(MOD_DESC);
35 MODULE_LICENSE("GPL v2");
36 MODULE_AUTHOR("Wolfgang Grandegger <wg@grandegger.com>");
37
38 /* CAN DLC to real data length conversion helpers */
39
40 static const u8 dlc2len[] = {0, 1, 2, 3, 4, 5, 6, 7,
41                              8, 12, 16, 20, 24, 32, 48, 64};
42
43 /* get data length from can_dlc with sanitized can_dlc */
44 u8 can_dlc2len(u8 can_dlc)
45 {
46         return dlc2len[can_dlc & 0x0F];
47 }
48 EXPORT_SYMBOL_GPL(can_dlc2len);
49
50 static const u8 len2dlc[] = {0, 1, 2, 3, 4, 5, 6, 7, 8,         /* 0 - 8 */
51                              9, 9, 9, 9,                        /* 9 - 12 */
52                              10, 10, 10, 10,                    /* 13 - 16 */
53                              11, 11, 11, 11,                    /* 17 - 20 */
54                              12, 12, 12, 12,                    /* 21 - 24 */
55                              13, 13, 13, 13, 13, 13, 13, 13,    /* 25 - 32 */
56                              14, 14, 14, 14, 14, 14, 14, 14,    /* 33 - 40 */
57                              14, 14, 14, 14, 14, 14, 14, 14,    /* 41 - 48 */
58                              15, 15, 15, 15, 15, 15, 15, 15,    /* 49 - 56 */
59                              15, 15, 15, 15, 15, 15, 15, 15};   /* 57 - 64 */
60
61 /* map the sanitized data length to an appropriate data length code */
62 u8 can_len2dlc(u8 len)
63 {
64         if (unlikely(len > 64))
65                 return 0xF;
66
67         return len2dlc[len];
68 }
69 EXPORT_SYMBOL_GPL(can_len2dlc);
70
71 #ifdef CONFIG_CAN_CALC_BITTIMING
72 #define CAN_CALC_MAX_ERROR 50 /* in one-tenth of a percent */
73
74 /*
75  * Bit-timing calculation derived from:
76  *
77  * Code based on LinCAN sources and H8S2638 project
78  * Copyright 2004-2006 Pavel Pisa - DCE FELK CVUT cz
79  * Copyright 2005      Stanislav Marek
80  * email: pisa@cmp.felk.cvut.cz
81  *
82  * Calculates proper bit-timing parameters for a specified bit-rate
83  * and sample-point, which can then be used to set the bit-timing
84  * registers of the CAN controller. You can find more information
85  * in the header file linux/can/netlink.h.
86  */
87 static int can_update_spt(const struct can_bittiming_const *btc,
88                           int sampl_pt, int tseg, int *tseg1, int *tseg2)
89 {
90         *tseg2 = tseg + 1 - (sampl_pt * (tseg + 1)) / 1000;
91         if (*tseg2 < btc->tseg2_min)
92                 *tseg2 = btc->tseg2_min;
93         if (*tseg2 > btc->tseg2_max)
94                 *tseg2 = btc->tseg2_max;
95         *tseg1 = tseg - *tseg2;
96         if (*tseg1 > btc->tseg1_max) {
97                 *tseg1 = btc->tseg1_max;
98                 *tseg2 = tseg - *tseg1;
99         }
100         return 1000 * (tseg + 1 - *tseg2) / (tseg + 1);
101 }
102
103 static int can_calc_bittiming(struct net_device *dev, struct can_bittiming *bt,
104                               const struct can_bittiming_const *btc)
105 {
106         struct can_priv *priv = netdev_priv(dev);
107         long best_error = 1000000000, error = 0;
108         int best_tseg = 0, best_brp = 0, brp = 0;
109         int tsegall, tseg = 0, tseg1 = 0, tseg2 = 0;
110         int spt_error = 1000, spt = 0, sampl_pt;
111         long rate;
112         u64 v64;
113
114         /* Use CiA recommended sample points */
115         if (bt->sample_point) {
116                 sampl_pt = bt->sample_point;
117         } else {
118                 if (bt->bitrate > 800000)
119                         sampl_pt = 750;
120                 else if (bt->bitrate > 500000)
121                         sampl_pt = 800;
122                 else
123                         sampl_pt = 875;
124         }
125
126         /* tseg even = round down, odd = round up */
127         for (tseg = (btc->tseg1_max + btc->tseg2_max) * 2 + 1;
128              tseg >= (btc->tseg1_min + btc->tseg2_min) * 2; tseg--) {
129                 tsegall = 1 + tseg / 2;
130                 /* Compute all possible tseg choices (tseg=tseg1+tseg2) */
131                 brp = priv->clock.freq / (tsegall * bt->bitrate) + tseg % 2;
132                 /* chose brp step which is possible in system */
133                 brp = (brp / btc->brp_inc) * btc->brp_inc;
134                 if ((brp < btc->brp_min) || (brp > btc->brp_max))
135                         continue;
136                 rate = priv->clock.freq / (brp * tsegall);
137                 error = bt->bitrate - rate;
138                 /* tseg brp biterror */
139                 if (error < 0)
140                         error = -error;
141                 if (error > best_error)
142                         continue;
143                 best_error = error;
144                 if (error == 0) {
145                         spt = can_update_spt(btc, sampl_pt, tseg / 2,
146                                              &tseg1, &tseg2);
147                         error = sampl_pt - spt;
148                         if (error < 0)
149                                 error = -error;
150                         if (error > spt_error)
151                                 continue;
152                         spt_error = error;
153                 }
154                 best_tseg = tseg / 2;
155                 best_brp = brp;
156                 if (error == 0)
157                         break;
158         }
159
160         if (best_error) {
161                 /* Error in one-tenth of a percent */
162                 error = (best_error * 1000) / bt->bitrate;
163                 if (error > CAN_CALC_MAX_ERROR) {
164                         netdev_err(dev,
165                                    "bitrate error %ld.%ld%% too high\n",
166                                    error / 10, error % 10);
167                         return -EDOM;
168                 } else {
169                         netdev_warn(dev, "bitrate error %ld.%ld%%\n",
170                                     error / 10, error % 10);
171                 }
172         }
173
174         /* real sample point */
175         bt->sample_point = can_update_spt(btc, sampl_pt, best_tseg,
176                                           &tseg1, &tseg2);
177
178         v64 = (u64)best_brp * 1000000000UL;
179         do_div(v64, priv->clock.freq);
180         bt->tq = (u32)v64;
181         bt->prop_seg = tseg1 / 2;
182         bt->phase_seg1 = tseg1 - bt->prop_seg;
183         bt->phase_seg2 = tseg2;
184
185         /* check for sjw user settings */
186         if (!bt->sjw || !btc->sjw_max)
187                 bt->sjw = 1;
188         else {
189                 /* bt->sjw is at least 1 -> sanitize upper bound to sjw_max */
190                 if (bt->sjw > btc->sjw_max)
191                         bt->sjw = btc->sjw_max;
192                 /* bt->sjw must not be higher than tseg2 */
193                 if (tseg2 < bt->sjw)
194                         bt->sjw = tseg2;
195         }
196
197         bt->brp = best_brp;
198         /* real bit-rate */
199         bt->bitrate = priv->clock.freq / (bt->brp * (tseg1 + tseg2 + 1));
200
201         return 0;
202 }
203 #else /* !CONFIG_CAN_CALC_BITTIMING */
204 static int can_calc_bittiming(struct net_device *dev, struct can_bittiming *bt,
205                               const struct can_bittiming_const *btc)
206 {
207         netdev_err(dev, "bit-timing calculation not available\n");
208         return -EINVAL;
209 }
210 #endif /* CONFIG_CAN_CALC_BITTIMING */
211
212 /*
213  * Checks the validity of the specified bit-timing parameters prop_seg,
214  * phase_seg1, phase_seg2 and sjw and tries to determine the bitrate
215  * prescaler value brp. You can find more information in the header
216  * file linux/can/netlink.h.
217  */
218 static int can_fixup_bittiming(struct net_device *dev, struct can_bittiming *bt,
219                                const struct can_bittiming_const *btc)
220 {
221         struct can_priv *priv = netdev_priv(dev);
222         int tseg1, alltseg;
223         u64 brp64;
224
225         tseg1 = bt->prop_seg + bt->phase_seg1;
226         if (!bt->sjw)
227                 bt->sjw = 1;
228         if (bt->sjw > btc->sjw_max ||
229             tseg1 < btc->tseg1_min || tseg1 > btc->tseg1_max ||
230             bt->phase_seg2 < btc->tseg2_min || bt->phase_seg2 > btc->tseg2_max)
231                 return -ERANGE;
232
233         brp64 = (u64)priv->clock.freq * (u64)bt->tq;
234         if (btc->brp_inc > 1)
235                 do_div(brp64, btc->brp_inc);
236         brp64 += 500000000UL - 1;
237         do_div(brp64, 1000000000UL); /* the practicable BRP */
238         if (btc->brp_inc > 1)
239                 brp64 *= btc->brp_inc;
240         bt->brp = (u32)brp64;
241
242         if (bt->brp < btc->brp_min || bt->brp > btc->brp_max)
243                 return -EINVAL;
244
245         alltseg = bt->prop_seg + bt->phase_seg1 + bt->phase_seg2 + 1;
246         bt->bitrate = priv->clock.freq / (bt->brp * alltseg);
247         bt->sample_point = ((tseg1 + 1) * 1000) / alltseg;
248
249         return 0;
250 }
251
252 static int can_get_bittiming(struct net_device *dev, struct can_bittiming *bt,
253                              const struct can_bittiming_const *btc)
254 {
255         int err;
256
257         /* Check if the CAN device has bit-timing parameters */
258         if (!btc)
259                 return -EOPNOTSUPP;
260
261         /*
262          * Depending on the given can_bittiming parameter structure the CAN
263          * timing parameters are calculated based on the provided bitrate OR
264          * alternatively the CAN timing parameters (tq, prop_seg, etc.) are
265          * provided directly which are then checked and fixed up.
266          */
267         if (!bt->tq && bt->bitrate)
268                 err = can_calc_bittiming(dev, bt, btc);
269         else if (bt->tq && !bt->bitrate)
270                 err = can_fixup_bittiming(dev, bt, btc);
271         else
272                 err = -EINVAL;
273
274         return err;
275 }
276
277 static void can_update_state_error_stats(struct net_device *dev,
278                                          enum can_state new_state)
279 {
280         struct can_priv *priv = netdev_priv(dev);
281
282         if (new_state <= priv->state)
283                 return;
284
285         switch (new_state) {
286         case CAN_STATE_ERROR_WARNING:
287                 priv->can_stats.error_warning++;
288                 break;
289         case CAN_STATE_ERROR_PASSIVE:
290                 priv->can_stats.error_passive++;
291                 break;
292         case CAN_STATE_BUS_OFF:
293                 priv->can_stats.bus_off++;
294                 break;
295         default:
296                 break;
297         }
298 }
299
300 static int can_tx_state_to_frame(struct net_device *dev, enum can_state state)
301 {
302         switch (state) {
303         case CAN_STATE_ERROR_ACTIVE:
304                 return CAN_ERR_CRTL_ACTIVE;
305         case CAN_STATE_ERROR_WARNING:
306                 return CAN_ERR_CRTL_TX_WARNING;
307         case CAN_STATE_ERROR_PASSIVE:
308                 return CAN_ERR_CRTL_TX_PASSIVE;
309         default:
310                 return 0;
311         }
312 }
313
314 static int can_rx_state_to_frame(struct net_device *dev, enum can_state state)
315 {
316         switch (state) {
317         case CAN_STATE_ERROR_ACTIVE:
318                 return CAN_ERR_CRTL_ACTIVE;
319         case CAN_STATE_ERROR_WARNING:
320                 return CAN_ERR_CRTL_RX_WARNING;
321         case CAN_STATE_ERROR_PASSIVE:
322                 return CAN_ERR_CRTL_RX_PASSIVE;
323         default:
324                 return 0;
325         }
326 }
327
328 void can_change_state(struct net_device *dev, struct can_frame *cf,
329                       enum can_state tx_state, enum can_state rx_state)
330 {
331         struct can_priv *priv = netdev_priv(dev);
332         enum can_state new_state = max(tx_state, rx_state);
333
334         if (unlikely(new_state == priv->state)) {
335                 netdev_warn(dev, "%s: oops, state did not change", __func__);
336                 return;
337         }
338
339         netdev_dbg(dev, "New error state: %d\n", new_state);
340
341         can_update_state_error_stats(dev, new_state);
342         priv->state = new_state;
343
344         if (unlikely(new_state == CAN_STATE_BUS_OFF)) {
345                 cf->can_id |= CAN_ERR_BUSOFF;
346                 return;
347         }
348
349         cf->can_id |= CAN_ERR_CRTL;
350         cf->data[1] |= tx_state >= rx_state ?
351                        can_tx_state_to_frame(dev, tx_state) : 0;
352         cf->data[1] |= tx_state <= rx_state ?
353                        can_rx_state_to_frame(dev, rx_state) : 0;
354 }
355 EXPORT_SYMBOL_GPL(can_change_state);
356
357 /*
358  * Local echo of CAN messages
359  *
360  * CAN network devices *should* support a local echo functionality
361  * (see Documentation/networking/can.txt). To test the handling of CAN
362  * interfaces that do not support the local echo both driver types are
363  * implemented. In the case that the driver does not support the echo
364  * the IFF_ECHO remains clear in dev->flags. This causes the PF_CAN core
365  * to perform the echo as a fallback solution.
366  */
367 static void can_flush_echo_skb(struct net_device *dev)
368 {
369         struct can_priv *priv = netdev_priv(dev);
370         struct net_device_stats *stats = &dev->stats;
371         int i;
372
373         for (i = 0; i < priv->echo_skb_max; i++) {
374                 if (priv->echo_skb[i]) {
375                         kfree_skb(priv->echo_skb[i]);
376                         priv->echo_skb[i] = NULL;
377                         stats->tx_dropped++;
378                         stats->tx_aborted_errors++;
379                 }
380         }
381 }
382
383 /*
384  * Put the skb on the stack to be looped backed locally lateron
385  *
386  * The function is typically called in the start_xmit function
387  * of the device driver. The driver must protect access to
388  * priv->echo_skb, if necessary.
389  */
390 void can_put_echo_skb(struct sk_buff *skb, struct net_device *dev,
391                       unsigned int idx)
392 {
393         struct can_priv *priv = netdev_priv(dev);
394
395         BUG_ON(idx >= priv->echo_skb_max);
396
397         /* check flag whether this packet has to be looped back */
398         if (!(dev->flags & IFF_ECHO) || skb->pkt_type != PACKET_LOOPBACK ||
399             (skb->protocol != htons(ETH_P_CAN) &&
400              skb->protocol != htons(ETH_P_CANFD))) {
401                 kfree_skb(skb);
402                 return;
403         }
404
405         if (!priv->echo_skb[idx]) {
406
407                 skb = can_create_echo_skb(skb);
408                 if (!skb)
409                         return;
410
411                 /* make settings for echo to reduce code in irq context */
412                 skb->pkt_type = PACKET_BROADCAST;
413                 skb->ip_summed = CHECKSUM_UNNECESSARY;
414                 skb->dev = dev;
415
416                 /* save this skb for tx interrupt echo handling */
417                 priv->echo_skb[idx] = skb;
418         } else {
419                 /* locking problem with netif_stop_queue() ?? */
420                 netdev_err(dev, "%s: BUG! echo_skb is occupied!\n", __func__);
421                 kfree_skb(skb);
422         }
423 }
424 EXPORT_SYMBOL_GPL(can_put_echo_skb);
425
426 /*
427  * Get the skb from the stack and loop it back locally
428  *
429  * The function is typically called when the TX done interrupt
430  * is handled in the device driver. The driver must protect
431  * access to priv->echo_skb, if necessary.
432  */
433 unsigned int can_get_echo_skb(struct net_device *dev, unsigned int idx)
434 {
435         struct can_priv *priv = netdev_priv(dev);
436
437         BUG_ON(idx >= priv->echo_skb_max);
438
439         if (priv->echo_skb[idx]) {
440                 struct sk_buff *skb = priv->echo_skb[idx];
441                 struct can_frame *cf = (struct can_frame *)skb->data;
442                 u8 dlc = cf->can_dlc;
443
444                 netif_rx(priv->echo_skb[idx]);
445                 priv->echo_skb[idx] = NULL;
446
447                 return dlc;
448         }
449
450         return 0;
451 }
452 EXPORT_SYMBOL_GPL(can_get_echo_skb);
453
454 /*
455   * Remove the skb from the stack and free it.
456   *
457   * The function is typically called when TX failed.
458   */
459 void can_free_echo_skb(struct net_device *dev, unsigned int idx)
460 {
461         struct can_priv *priv = netdev_priv(dev);
462
463         BUG_ON(idx >= priv->echo_skb_max);
464
465         if (priv->echo_skb[idx]) {
466                 dev_kfree_skb_any(priv->echo_skb[idx]);
467                 priv->echo_skb[idx] = NULL;
468         }
469 }
470 EXPORT_SYMBOL_GPL(can_free_echo_skb);
471
472 /*
473  * CAN device restart for bus-off recovery
474  */
475 static void can_restart(struct net_device *dev)
476 {
477         struct can_priv *priv = netdev_priv(dev);
478         struct net_device_stats *stats = &dev->stats;
479         struct sk_buff *skb;
480         struct can_frame *cf;
481         int err;
482
483         BUG_ON(netif_carrier_ok(dev));
484
485         /*
486          * No synchronization needed because the device is bus-off and
487          * no messages can come in or go out.
488          */
489         can_flush_echo_skb(dev);
490
491         /* send restart message upstream */
492         skb = alloc_can_err_skb(dev, &cf);
493         if (skb == NULL) {
494                 err = -ENOMEM;
495                 goto restart;
496         }
497         cf->can_id |= CAN_ERR_RESTARTED;
498
499         netif_rx(skb);
500
501         stats->rx_packets++;
502         stats->rx_bytes += cf->can_dlc;
503
504 restart:
505         netdev_dbg(dev, "restarted\n");
506         priv->can_stats.restarts++;
507
508         /* Now restart the device */
509         err = priv->do_set_mode(dev, CAN_MODE_START);
510
511         netif_carrier_on(dev);
512         if (err)
513                 netdev_err(dev, "Error %d during restart", err);
514 }
515
516 static void can_restart_work(struct work_struct *work)
517 {
518         struct delayed_work *dwork = to_delayed_work(work);
519         struct can_priv *priv = container_of(dwork, struct can_priv, restart_work);
520
521         can_restart(priv->dev);
522 }
523
524 int can_restart_now(struct net_device *dev)
525 {
526         struct can_priv *priv = netdev_priv(dev);
527
528         /*
529          * A manual restart is only permitted if automatic restart is
530          * disabled and the device is in the bus-off state
531          */
532         if (priv->restart_ms)
533                 return -EINVAL;
534         if (priv->state != CAN_STATE_BUS_OFF)
535                 return -EBUSY;
536
537         cancel_delayed_work_sync(&priv->restart_work);
538         can_restart(dev);
539
540         return 0;
541 }
542
543 /*
544  * CAN bus-off
545  *
546  * This functions should be called when the device goes bus-off to
547  * tell the netif layer that no more packets can be sent or received.
548  * If enabled, a timer is started to trigger bus-off recovery.
549  */
550 void can_bus_off(struct net_device *dev)
551 {
552         struct can_priv *priv = netdev_priv(dev);
553
554         netdev_dbg(dev, "bus-off\n");
555
556         netif_carrier_off(dev);
557
558         if (priv->restart_ms)
559                 schedule_delayed_work(&priv->restart_work,
560                                       msecs_to_jiffies(priv->restart_ms));
561 }
562 EXPORT_SYMBOL_GPL(can_bus_off);
563
564 static void can_setup(struct net_device *dev)
565 {
566         dev->type = ARPHRD_CAN;
567         dev->mtu = CAN_MTU;
568         dev->hard_header_len = 0;
569         dev->addr_len = 0;
570         dev->tx_queue_len = 10;
571
572         /* New-style flags. */
573         dev->flags = IFF_NOARP;
574         dev->features = NETIF_F_HW_CSUM;
575 }
576
577 struct sk_buff *alloc_can_skb(struct net_device *dev, struct can_frame **cf)
578 {
579         struct sk_buff *skb;
580
581         skb = netdev_alloc_skb(dev, sizeof(struct can_skb_priv) +
582                                sizeof(struct can_frame));
583         if (unlikely(!skb))
584                 return NULL;
585
586         skb->protocol = htons(ETH_P_CAN);
587         skb->pkt_type = PACKET_BROADCAST;
588         skb->ip_summed = CHECKSUM_UNNECESSARY;
589
590         skb_reset_mac_header(skb);
591         skb_reset_network_header(skb);
592         skb_reset_transport_header(skb);
593
594         can_skb_reserve(skb);
595         can_skb_prv(skb)->ifindex = dev->ifindex;
596         can_skb_prv(skb)->skbcnt = 0;
597
598         *cf = (struct can_frame *)skb_put(skb, sizeof(struct can_frame));
599         memset(*cf, 0, sizeof(struct can_frame));
600
601         return skb;
602 }
603 EXPORT_SYMBOL_GPL(alloc_can_skb);
604
605 struct sk_buff *alloc_canfd_skb(struct net_device *dev,
606                                 struct canfd_frame **cfd)
607 {
608         struct sk_buff *skb;
609
610         skb = netdev_alloc_skb(dev, sizeof(struct can_skb_priv) +
611                                sizeof(struct canfd_frame));
612         if (unlikely(!skb))
613                 return NULL;
614
615         skb->protocol = htons(ETH_P_CANFD);
616         skb->pkt_type = PACKET_BROADCAST;
617         skb->ip_summed = CHECKSUM_UNNECESSARY;
618
619         skb_reset_mac_header(skb);
620         skb_reset_network_header(skb);
621         skb_reset_transport_header(skb);
622
623         can_skb_reserve(skb);
624         can_skb_prv(skb)->ifindex = dev->ifindex;
625         can_skb_prv(skb)->skbcnt = 0;
626
627         *cfd = (struct canfd_frame *)skb_put(skb, sizeof(struct canfd_frame));
628         memset(*cfd, 0, sizeof(struct canfd_frame));
629
630         return skb;
631 }
632 EXPORT_SYMBOL_GPL(alloc_canfd_skb);
633
634 struct sk_buff *alloc_can_err_skb(struct net_device *dev, struct can_frame **cf)
635 {
636         struct sk_buff *skb;
637
638         skb = alloc_can_skb(dev, cf);
639         if (unlikely(!skb))
640                 return NULL;
641
642         (*cf)->can_id = CAN_ERR_FLAG;
643         (*cf)->can_dlc = CAN_ERR_DLC;
644
645         return skb;
646 }
647 EXPORT_SYMBOL_GPL(alloc_can_err_skb);
648
649 /*
650  * Allocate and setup space for the CAN network device
651  */
652 struct net_device *alloc_candev(int sizeof_priv, unsigned int echo_skb_max)
653 {
654         struct net_device *dev;
655         struct can_priv *priv;
656         int size;
657
658         if (echo_skb_max)
659                 size = ALIGN(sizeof_priv, sizeof(struct sk_buff *)) +
660                         echo_skb_max * sizeof(struct sk_buff *);
661         else
662                 size = sizeof_priv;
663
664         dev = alloc_netdev(size, "can%d", NET_NAME_UNKNOWN, can_setup);
665         if (!dev)
666                 return NULL;
667
668         priv = netdev_priv(dev);
669         priv->dev = dev;
670
671         if (echo_skb_max) {
672                 priv->echo_skb_max = echo_skb_max;
673                 priv->echo_skb = (void *)priv +
674                         ALIGN(sizeof_priv, sizeof(struct sk_buff *));
675         }
676
677         priv->state = CAN_STATE_STOPPED;
678
679         INIT_DELAYED_WORK(&priv->restart_work, can_restart_work);
680
681         return dev;
682 }
683 EXPORT_SYMBOL_GPL(alloc_candev);
684
685 /*
686  * Free space of the CAN network device
687  */
688 void free_candev(struct net_device *dev)
689 {
690         free_netdev(dev);
691 }
692 EXPORT_SYMBOL_GPL(free_candev);
693
694 /*
695  * changing MTU and control mode for CAN/CANFD devices
696  */
697 int can_change_mtu(struct net_device *dev, int new_mtu)
698 {
699         struct can_priv *priv = netdev_priv(dev);
700
701         /* Do not allow changing the MTU while running */
702         if (dev->flags & IFF_UP)
703                 return -EBUSY;
704
705         /* allow change of MTU according to the CANFD ability of the device */
706         switch (new_mtu) {
707         case CAN_MTU:
708                 /* 'CANFD-only' controllers can not switch to CAN_MTU */
709                 if (priv->ctrlmode_static & CAN_CTRLMODE_FD)
710                         return -EINVAL;
711
712                 priv->ctrlmode &= ~CAN_CTRLMODE_FD;
713                 break;
714
715         case CANFD_MTU:
716                 /* check for potential CANFD ability */
717                 if (!(priv->ctrlmode_supported & CAN_CTRLMODE_FD) &&
718                     !(priv->ctrlmode_static & CAN_CTRLMODE_FD))
719                         return -EINVAL;
720
721                 priv->ctrlmode |= CAN_CTRLMODE_FD;
722                 break;
723
724         default:
725                 return -EINVAL;
726         }
727
728         dev->mtu = new_mtu;
729         return 0;
730 }
731 EXPORT_SYMBOL_GPL(can_change_mtu);
732
733 /*
734  * Common open function when the device gets opened.
735  *
736  * This function should be called in the open function of the device
737  * driver.
738  */
739 int open_candev(struct net_device *dev)
740 {
741         struct can_priv *priv = netdev_priv(dev);
742
743         if (!priv->bittiming.bitrate) {
744                 netdev_err(dev, "bit-timing not yet defined\n");
745                 return -EINVAL;
746         }
747
748         /* For CAN FD the data bitrate has to be >= the arbitration bitrate */
749         if ((priv->ctrlmode & CAN_CTRLMODE_FD) &&
750             (!priv->data_bittiming.bitrate ||
751              (priv->data_bittiming.bitrate < priv->bittiming.bitrate))) {
752                 netdev_err(dev, "incorrect/missing data bit-timing\n");
753                 return -EINVAL;
754         }
755
756         /* Switch carrier on if device was stopped while in bus-off state */
757         if (!netif_carrier_ok(dev))
758                 netif_carrier_on(dev);
759
760         return 0;
761 }
762 EXPORT_SYMBOL_GPL(open_candev);
763
764 /*
765  * Common close function for cleanup before the device gets closed.
766  *
767  * This function should be called in the close function of the device
768  * driver.
769  */
770 void close_candev(struct net_device *dev)
771 {
772         struct can_priv *priv = netdev_priv(dev);
773
774         cancel_delayed_work_sync(&priv->restart_work);
775         can_flush_echo_skb(dev);
776 }
777 EXPORT_SYMBOL_GPL(close_candev);
778
779 /*
780  * CAN netlink interface
781  */
782 static const struct nla_policy can_policy[IFLA_CAN_MAX + 1] = {
783         [IFLA_CAN_STATE]        = { .type = NLA_U32 },
784         [IFLA_CAN_CTRLMODE]     = { .len = sizeof(struct can_ctrlmode) },
785         [IFLA_CAN_RESTART_MS]   = { .type = NLA_U32 },
786         [IFLA_CAN_RESTART]      = { .type = NLA_U32 },
787         [IFLA_CAN_BITTIMING]    = { .len = sizeof(struct can_bittiming) },
788         [IFLA_CAN_BITTIMING_CONST]
789                                 = { .len = sizeof(struct can_bittiming_const) },
790         [IFLA_CAN_CLOCK]        = { .len = sizeof(struct can_clock) },
791         [IFLA_CAN_BERR_COUNTER] = { .len = sizeof(struct can_berr_counter) },
792         [IFLA_CAN_DATA_BITTIMING]
793                                 = { .len = sizeof(struct can_bittiming) },
794         [IFLA_CAN_DATA_BITTIMING_CONST]
795                                 = { .len = sizeof(struct can_bittiming_const) },
796 };
797
798 static int can_validate(struct nlattr *tb[], struct nlattr *data[])
799 {
800         bool is_can_fd = false;
801
802         /* Make sure that valid CAN FD configurations always consist of
803          * - nominal/arbitration bittiming
804          * - data bittiming
805          * - control mode with CAN_CTRLMODE_FD set
806          */
807
808         if (!data)
809                 return 0;
810
811         if (data[IFLA_CAN_CTRLMODE]) {
812                 struct can_ctrlmode *cm = nla_data(data[IFLA_CAN_CTRLMODE]);
813
814                 is_can_fd = cm->flags & cm->mask & CAN_CTRLMODE_FD;
815         }
816
817         if (is_can_fd) {
818                 if (!data[IFLA_CAN_BITTIMING] || !data[IFLA_CAN_DATA_BITTIMING])
819                         return -EOPNOTSUPP;
820         }
821
822         if (data[IFLA_CAN_DATA_BITTIMING]) {
823                 if (!is_can_fd || !data[IFLA_CAN_BITTIMING])
824                         return -EOPNOTSUPP;
825         }
826
827         return 0;
828 }
829
830 static int can_changelink(struct net_device *dev,
831                           struct nlattr *tb[], struct nlattr *data[])
832 {
833         struct can_priv *priv = netdev_priv(dev);
834         int err;
835
836         /* We need synchronization with dev->stop() */
837         ASSERT_RTNL();
838
839         if (data[IFLA_CAN_BITTIMING]) {
840                 struct can_bittiming bt;
841
842                 /* Do not allow changing bittiming while running */
843                 if (dev->flags & IFF_UP)
844                         return -EBUSY;
845                 memcpy(&bt, nla_data(data[IFLA_CAN_BITTIMING]), sizeof(bt));
846                 err = can_get_bittiming(dev, &bt, priv->bittiming_const);
847                 if (err)
848                         return err;
849                 memcpy(&priv->bittiming, &bt, sizeof(bt));
850
851                 if (priv->do_set_bittiming) {
852                         /* Finally, set the bit-timing registers */
853                         err = priv->do_set_bittiming(dev);
854                         if (err)
855                                 return err;
856                 }
857         }
858
859         if (data[IFLA_CAN_CTRLMODE]) {
860                 struct can_ctrlmode *cm;
861                 u32 ctrlstatic;
862                 u32 maskedflags;
863
864                 /* Do not allow changing controller mode while running */
865                 if (dev->flags & IFF_UP)
866                         return -EBUSY;
867                 cm = nla_data(data[IFLA_CAN_CTRLMODE]);
868                 ctrlstatic = priv->ctrlmode_static;
869                 maskedflags = cm->flags & cm->mask;
870
871                 /* check whether provided bits are allowed to be passed */
872                 if (cm->mask & ~(priv->ctrlmode_supported | ctrlstatic))
873                         return -EOPNOTSUPP;
874
875                 /* do not check for static fd-non-iso if 'fd' is disabled */
876                 if (!(maskedflags & CAN_CTRLMODE_FD))
877                         ctrlstatic &= ~CAN_CTRLMODE_FD_NON_ISO;
878
879                 /* make sure static options are provided by configuration */
880                 if ((maskedflags & ctrlstatic) != ctrlstatic)
881                         return -EOPNOTSUPP;
882
883                 /* clear bits to be modified and copy the flag values */
884                 priv->ctrlmode &= ~cm->mask;
885                 priv->ctrlmode |= maskedflags;
886
887                 /* CAN_CTRLMODE_FD can only be set when driver supports FD */
888                 if (priv->ctrlmode & CAN_CTRLMODE_FD)
889                         dev->mtu = CANFD_MTU;
890                 else
891                         dev->mtu = CAN_MTU;
892         }
893
894         if (data[IFLA_CAN_RESTART_MS]) {
895                 /* Do not allow changing restart delay while running */
896                 if (dev->flags & IFF_UP)
897                         return -EBUSY;
898                 priv->restart_ms = nla_get_u32(data[IFLA_CAN_RESTART_MS]);
899         }
900
901         if (data[IFLA_CAN_RESTART]) {
902                 /* Do not allow a restart while not running */
903                 if (!(dev->flags & IFF_UP))
904                         return -EINVAL;
905                 err = can_restart_now(dev);
906                 if (err)
907                         return err;
908         }
909
910         if (data[IFLA_CAN_DATA_BITTIMING]) {
911                 struct can_bittiming dbt;
912
913                 /* Do not allow changing bittiming while running */
914                 if (dev->flags & IFF_UP)
915                         return -EBUSY;
916                 memcpy(&dbt, nla_data(data[IFLA_CAN_DATA_BITTIMING]),
917                        sizeof(dbt));
918                 err = can_get_bittiming(dev, &dbt, priv->data_bittiming_const);
919                 if (err)
920                         return err;
921                 memcpy(&priv->data_bittiming, &dbt, sizeof(dbt));
922
923                 if (priv->do_set_data_bittiming) {
924                         /* Finally, set the bit-timing registers */
925                         err = priv->do_set_data_bittiming(dev);
926                         if (err)
927                                 return err;
928                 }
929         }
930
931         return 0;
932 }
933
934 static size_t can_get_size(const struct net_device *dev)
935 {
936         struct can_priv *priv = netdev_priv(dev);
937         size_t size = 0;
938
939         if (priv->bittiming.bitrate)                            /* IFLA_CAN_BITTIMING */
940                 size += nla_total_size(sizeof(struct can_bittiming));
941         if (priv->bittiming_const)                              /* IFLA_CAN_BITTIMING_CONST */
942                 size += nla_total_size(sizeof(struct can_bittiming_const));
943         size += nla_total_size(sizeof(struct can_clock));       /* IFLA_CAN_CLOCK */
944         size += nla_total_size(sizeof(u32));                    /* IFLA_CAN_STATE */
945         size += nla_total_size(sizeof(struct can_ctrlmode));    /* IFLA_CAN_CTRLMODE */
946         size += nla_total_size(sizeof(u32));                    /* IFLA_CAN_RESTART_MS */
947         if (priv->do_get_berr_counter)                          /* IFLA_CAN_BERR_COUNTER */
948                 size += nla_total_size(sizeof(struct can_berr_counter));
949         if (priv->data_bittiming.bitrate)                       /* IFLA_CAN_DATA_BITTIMING */
950                 size += nla_total_size(sizeof(struct can_bittiming));
951         if (priv->data_bittiming_const)                         /* IFLA_CAN_DATA_BITTIMING_CONST */
952                 size += nla_total_size(sizeof(struct can_bittiming_const));
953
954         return size;
955 }
956
957 static int can_fill_info(struct sk_buff *skb, const struct net_device *dev)
958 {
959         struct can_priv *priv = netdev_priv(dev);
960         struct can_ctrlmode cm = {.flags = priv->ctrlmode};
961         struct can_berr_counter bec;
962         enum can_state state = priv->state;
963
964         if (priv->do_get_state)
965                 priv->do_get_state(dev, &state);
966
967         if ((priv->bittiming.bitrate &&
968              nla_put(skb, IFLA_CAN_BITTIMING,
969                      sizeof(priv->bittiming), &priv->bittiming)) ||
970
971             (priv->bittiming_const &&
972              nla_put(skb, IFLA_CAN_BITTIMING_CONST,
973                      sizeof(*priv->bittiming_const), priv->bittiming_const)) ||
974
975             nla_put(skb, IFLA_CAN_CLOCK, sizeof(priv->clock), &priv->clock) ||
976             nla_put_u32(skb, IFLA_CAN_STATE, state) ||
977             nla_put(skb, IFLA_CAN_CTRLMODE, sizeof(cm), &cm) ||
978             nla_put_u32(skb, IFLA_CAN_RESTART_MS, priv->restart_ms) ||
979
980             (priv->do_get_berr_counter &&
981              !priv->do_get_berr_counter(dev, &bec) &&
982              nla_put(skb, IFLA_CAN_BERR_COUNTER, sizeof(bec), &bec)) ||
983
984             (priv->data_bittiming.bitrate &&
985              nla_put(skb, IFLA_CAN_DATA_BITTIMING,
986                      sizeof(priv->data_bittiming), &priv->data_bittiming)) ||
987
988             (priv->data_bittiming_const &&
989              nla_put(skb, IFLA_CAN_DATA_BITTIMING_CONST,
990                      sizeof(*priv->data_bittiming_const),
991                      priv->data_bittiming_const)))
992                 return -EMSGSIZE;
993
994         return 0;
995 }
996
997 static size_t can_get_xstats_size(const struct net_device *dev)
998 {
999         return sizeof(struct can_device_stats);
1000 }
1001
1002 static int can_fill_xstats(struct sk_buff *skb, const struct net_device *dev)
1003 {
1004         struct can_priv *priv = netdev_priv(dev);
1005
1006         if (nla_put(skb, IFLA_INFO_XSTATS,
1007                     sizeof(priv->can_stats), &priv->can_stats))
1008                 goto nla_put_failure;
1009         return 0;
1010
1011 nla_put_failure:
1012         return -EMSGSIZE;
1013 }
1014
1015 static int can_newlink(struct net *src_net, struct net_device *dev,
1016                        struct nlattr *tb[], struct nlattr *data[])
1017 {
1018         return -EOPNOTSUPP;
1019 }
1020
1021 static void can_dellink(struct net_device *dev, struct list_head *head)
1022 {
1023         return;
1024 }
1025
1026 static struct rtnl_link_ops can_link_ops __read_mostly = {
1027         .kind           = "can",
1028         .maxtype        = IFLA_CAN_MAX,
1029         .policy         = can_policy,
1030         .setup          = can_setup,
1031         .validate       = can_validate,
1032         .newlink        = can_newlink,
1033         .changelink     = can_changelink,
1034         .dellink        = can_dellink,
1035         .get_size       = can_get_size,
1036         .fill_info      = can_fill_info,
1037         .get_xstats_size = can_get_xstats_size,
1038         .fill_xstats    = can_fill_xstats,
1039 };
1040
1041 /*
1042  * Register the CAN network device
1043  */
1044 int register_candev(struct net_device *dev)
1045 {
1046         dev->rtnl_link_ops = &can_link_ops;
1047         return register_netdev(dev);
1048 }
1049 EXPORT_SYMBOL_GPL(register_candev);
1050
1051 /*
1052  * Unregister the CAN network device
1053  */
1054 void unregister_candev(struct net_device *dev)
1055 {
1056         unregister_netdev(dev);
1057 }
1058 EXPORT_SYMBOL_GPL(unregister_candev);
1059
1060 /*
1061  * Test if a network device is a candev based device
1062  * and return the can_priv* if so.
1063  */
1064 struct can_priv *safe_candev_priv(struct net_device *dev)
1065 {
1066         if ((dev->type != ARPHRD_CAN) || (dev->rtnl_link_ops != &can_link_ops))
1067                 return NULL;
1068
1069         return netdev_priv(dev);
1070 }
1071 EXPORT_SYMBOL_GPL(safe_candev_priv);
1072
1073 static __init int can_dev_init(void)
1074 {
1075         int err;
1076
1077         can_led_notifier_init();
1078
1079         err = rtnl_link_register(&can_link_ops);
1080         if (!err)
1081                 printk(KERN_INFO MOD_DESC "\n");
1082
1083         return err;
1084 }
1085 module_init(can_dev_init);
1086
1087 static __exit void can_dev_exit(void)
1088 {
1089         rtnl_link_unregister(&can_link_ops);
1090
1091         can_led_notifier_exit();
1092 }
1093 module_exit(can_dev_exit);
1094
1095 MODULE_ALIAS_RTNL_LINK("can");