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