GNU Linux-libre 4.14.266-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 /* Checks the validity of predefined bitrate settings */
283 static int can_validate_bitrate(struct net_device *dev, struct can_bittiming *bt,
284                                 const u32 *bitrate_const,
285                                 const unsigned int bitrate_const_cnt)
286 {
287         struct can_priv *priv = netdev_priv(dev);
288         unsigned int i;
289
290         for (i = 0; i < bitrate_const_cnt; i++) {
291                 if (bt->bitrate == bitrate_const[i])
292                         break;
293         }
294
295         if (i >= priv->bitrate_const_cnt)
296                 return -EINVAL;
297
298         return 0;
299 }
300
301 static int can_get_bittiming(struct net_device *dev, struct can_bittiming *bt,
302                              const struct can_bittiming_const *btc,
303                              const u32 *bitrate_const,
304                              const unsigned int bitrate_const_cnt)
305 {
306         int err;
307
308         /*
309          * Depending on the given can_bittiming parameter structure the CAN
310          * timing parameters are calculated based on the provided bitrate OR
311          * alternatively the CAN timing parameters (tq, prop_seg, etc.) are
312          * provided directly which are then checked and fixed up.
313          */
314         if (!bt->tq && bt->bitrate && btc)
315                 err = can_calc_bittiming(dev, bt, btc);
316         else if (bt->tq && !bt->bitrate && btc)
317                 err = can_fixup_bittiming(dev, bt, btc);
318         else if (!bt->tq && bt->bitrate && bitrate_const)
319                 err = can_validate_bitrate(dev, bt, bitrate_const,
320                                            bitrate_const_cnt);
321         else
322                 err = -EINVAL;
323
324         return err;
325 }
326
327 static void can_update_state_error_stats(struct net_device *dev,
328                                          enum can_state new_state)
329 {
330         struct can_priv *priv = netdev_priv(dev);
331
332         if (new_state <= priv->state)
333                 return;
334
335         switch (new_state) {
336         case CAN_STATE_ERROR_WARNING:
337                 priv->can_stats.error_warning++;
338                 break;
339         case CAN_STATE_ERROR_PASSIVE:
340                 priv->can_stats.error_passive++;
341                 break;
342         case CAN_STATE_BUS_OFF:
343                 priv->can_stats.bus_off++;
344                 break;
345         default:
346                 break;
347         }
348 }
349
350 static int can_tx_state_to_frame(struct net_device *dev, enum can_state state)
351 {
352         switch (state) {
353         case CAN_STATE_ERROR_ACTIVE:
354                 return CAN_ERR_CRTL_ACTIVE;
355         case CAN_STATE_ERROR_WARNING:
356                 return CAN_ERR_CRTL_TX_WARNING;
357         case CAN_STATE_ERROR_PASSIVE:
358                 return CAN_ERR_CRTL_TX_PASSIVE;
359         default:
360                 return 0;
361         }
362 }
363
364 static int can_rx_state_to_frame(struct net_device *dev, enum can_state state)
365 {
366         switch (state) {
367         case CAN_STATE_ERROR_ACTIVE:
368                 return CAN_ERR_CRTL_ACTIVE;
369         case CAN_STATE_ERROR_WARNING:
370                 return CAN_ERR_CRTL_RX_WARNING;
371         case CAN_STATE_ERROR_PASSIVE:
372                 return CAN_ERR_CRTL_RX_PASSIVE;
373         default:
374                 return 0;
375         }
376 }
377
378 void can_change_state(struct net_device *dev, struct can_frame *cf,
379                       enum can_state tx_state, enum can_state rx_state)
380 {
381         struct can_priv *priv = netdev_priv(dev);
382         enum can_state new_state = max(tx_state, rx_state);
383
384         if (unlikely(new_state == priv->state)) {
385                 netdev_warn(dev, "%s: oops, state did not change", __func__);
386                 return;
387         }
388
389         netdev_dbg(dev, "New error state: %d\n", new_state);
390
391         can_update_state_error_stats(dev, new_state);
392         priv->state = new_state;
393
394         if (!cf)
395                 return;
396
397         if (unlikely(new_state == CAN_STATE_BUS_OFF)) {
398                 cf->can_id |= CAN_ERR_BUSOFF;
399                 return;
400         }
401
402         cf->can_id |= CAN_ERR_CRTL;
403         cf->data[1] |= tx_state >= rx_state ?
404                        can_tx_state_to_frame(dev, tx_state) : 0;
405         cf->data[1] |= tx_state <= rx_state ?
406                        can_rx_state_to_frame(dev, rx_state) : 0;
407 }
408 EXPORT_SYMBOL_GPL(can_change_state);
409
410 /*
411  * Local echo of CAN messages
412  *
413  * CAN network devices *should* support a local echo functionality
414  * (see Documentation/networking/can.txt). To test the handling of CAN
415  * interfaces that do not support the local echo both driver types are
416  * implemented. In the case that the driver does not support the echo
417  * the IFF_ECHO remains clear in dev->flags. This causes the PF_CAN core
418  * to perform the echo as a fallback solution.
419  */
420 static void can_flush_echo_skb(struct net_device *dev)
421 {
422         struct can_priv *priv = netdev_priv(dev);
423         struct net_device_stats *stats = &dev->stats;
424         int i;
425
426         for (i = 0; i < priv->echo_skb_max; i++) {
427                 if (priv->echo_skb[i]) {
428                         kfree_skb(priv->echo_skb[i]);
429                         priv->echo_skb[i] = NULL;
430                         stats->tx_dropped++;
431                         stats->tx_aborted_errors++;
432                 }
433         }
434 }
435
436 /*
437  * Put the skb on the stack to be looped backed locally lateron
438  *
439  * The function is typically called in the start_xmit function
440  * of the device driver. The driver must protect access to
441  * priv->echo_skb, if necessary.
442  */
443 void can_put_echo_skb(struct sk_buff *skb, struct net_device *dev,
444                       unsigned int idx)
445 {
446         struct can_priv *priv = netdev_priv(dev);
447
448         BUG_ON(idx >= priv->echo_skb_max);
449
450         /* check flag whether this packet has to be looped back */
451         if (!(dev->flags & IFF_ECHO) || skb->pkt_type != PACKET_LOOPBACK ||
452             (skb->protocol != htons(ETH_P_CAN) &&
453              skb->protocol != htons(ETH_P_CANFD))) {
454                 kfree_skb(skb);
455                 return;
456         }
457
458         if (!priv->echo_skb[idx]) {
459
460                 skb = can_create_echo_skb(skb);
461                 if (!skb)
462                         return;
463
464                 /* make settings for echo to reduce code in irq context */
465                 skb->pkt_type = PACKET_BROADCAST;
466                 skb->ip_summed = CHECKSUM_UNNECESSARY;
467                 skb->dev = dev;
468
469                 /* save this skb for tx interrupt echo handling */
470                 priv->echo_skb[idx] = skb;
471         } else {
472                 /* locking problem with netif_stop_queue() ?? */
473                 netdev_err(dev, "%s: BUG! echo_skb is occupied!\n", __func__);
474                 kfree_skb(skb);
475         }
476 }
477 EXPORT_SYMBOL_GPL(can_put_echo_skb);
478
479 struct sk_buff *__can_get_echo_skb(struct net_device *dev, unsigned int idx, u8 *len_ptr)
480 {
481         struct can_priv *priv = netdev_priv(dev);
482
483         if (idx >= priv->echo_skb_max) {
484                 netdev_err(dev, "%s: BUG! Trying to access can_priv::echo_skb out of bounds (%u/max %u)\n",
485                            __func__, idx, priv->echo_skb_max);
486                 return NULL;
487         }
488
489         if (priv->echo_skb[idx]) {
490                 /* Using "struct canfd_frame::len" for the frame
491                  * length is supported on both CAN and CANFD frames.
492                  */
493                 struct sk_buff *skb = priv->echo_skb[idx];
494                 struct canfd_frame *cf = (struct canfd_frame *)skb->data;
495
496                 /* get the real payload length for netdev statistics */
497                 if (cf->can_id & CAN_RTR_FLAG)
498                         *len_ptr = 0;
499                 else
500                         *len_ptr = cf->len;
501
502                 priv->echo_skb[idx] = NULL;
503
504                 return skb;
505         }
506
507         return NULL;
508 }
509
510 /*
511  * Get the skb from the stack and loop it back locally
512  *
513  * The function is typically called when the TX done interrupt
514  * is handled in the device driver. The driver must protect
515  * access to priv->echo_skb, if necessary.
516  */
517 unsigned int can_get_echo_skb(struct net_device *dev, unsigned int idx)
518 {
519         struct sk_buff *skb;
520         u8 len;
521
522         skb = __can_get_echo_skb(dev, idx, &len);
523         if (!skb)
524                 return 0;
525
526         skb_get(skb);
527         if (netif_rx(skb) == NET_RX_SUCCESS)
528                 dev_consume_skb_any(skb);
529         else
530                 dev_kfree_skb_any(skb);
531
532         return len;
533 }
534 EXPORT_SYMBOL_GPL(can_get_echo_skb);
535
536 /*
537   * Remove the skb from the stack and free it.
538   *
539   * The function is typically called when TX failed.
540   */
541 void can_free_echo_skb(struct net_device *dev, unsigned int idx)
542 {
543         struct can_priv *priv = netdev_priv(dev);
544
545         BUG_ON(idx >= priv->echo_skb_max);
546
547         if (priv->echo_skb[idx]) {
548                 dev_kfree_skb_any(priv->echo_skb[idx]);
549                 priv->echo_skb[idx] = NULL;
550         }
551 }
552 EXPORT_SYMBOL_GPL(can_free_echo_skb);
553
554 /*
555  * CAN device restart for bus-off recovery
556  */
557 static void can_restart(struct net_device *dev)
558 {
559         struct can_priv *priv = netdev_priv(dev);
560         struct net_device_stats *stats = &dev->stats;
561         struct sk_buff *skb;
562         struct can_frame *cf;
563         int err;
564
565         BUG_ON(netif_carrier_ok(dev));
566
567         /*
568          * No synchronization needed because the device is bus-off and
569          * no messages can come in or go out.
570          */
571         can_flush_echo_skb(dev);
572
573         /* send restart message upstream */
574         skb = alloc_can_err_skb(dev, &cf);
575         if (skb == NULL) {
576                 err = -ENOMEM;
577                 goto restart;
578         }
579         cf->can_id |= CAN_ERR_RESTARTED;
580
581         stats->rx_packets++;
582         stats->rx_bytes += cf->can_dlc;
583
584         netif_rx_ni(skb);
585
586 restart:
587         netdev_dbg(dev, "restarted\n");
588         priv->can_stats.restarts++;
589
590         /* Now restart the device */
591         err = priv->do_set_mode(dev, CAN_MODE_START);
592
593         netif_carrier_on(dev);
594         if (err)
595                 netdev_err(dev, "Error %d during restart", err);
596 }
597
598 static void can_restart_work(struct work_struct *work)
599 {
600         struct delayed_work *dwork = to_delayed_work(work);
601         struct can_priv *priv = container_of(dwork, struct can_priv, restart_work);
602
603         can_restart(priv->dev);
604 }
605
606 int can_restart_now(struct net_device *dev)
607 {
608         struct can_priv *priv = netdev_priv(dev);
609
610         /*
611          * A manual restart is only permitted if automatic restart is
612          * disabled and the device is in the bus-off state
613          */
614         if (priv->restart_ms)
615                 return -EINVAL;
616         if (priv->state != CAN_STATE_BUS_OFF)
617                 return -EBUSY;
618
619         cancel_delayed_work_sync(&priv->restart_work);
620         can_restart(dev);
621
622         return 0;
623 }
624
625 /*
626  * CAN bus-off
627  *
628  * This functions should be called when the device goes bus-off to
629  * tell the netif layer that no more packets can be sent or received.
630  * If enabled, a timer is started to trigger bus-off recovery.
631  */
632 void can_bus_off(struct net_device *dev)
633 {
634         struct can_priv *priv = netdev_priv(dev);
635
636         netdev_info(dev, "bus-off\n");
637
638         netif_carrier_off(dev);
639
640         if (priv->restart_ms)
641                 schedule_delayed_work(&priv->restart_work,
642                                       msecs_to_jiffies(priv->restart_ms));
643 }
644 EXPORT_SYMBOL_GPL(can_bus_off);
645
646 static void can_setup(struct net_device *dev)
647 {
648         dev->type = ARPHRD_CAN;
649         dev->mtu = CAN_MTU;
650         dev->hard_header_len = 0;
651         dev->addr_len = 0;
652         dev->tx_queue_len = 10;
653
654         /* New-style flags. */
655         dev->flags = IFF_NOARP;
656         dev->features = NETIF_F_HW_CSUM;
657 }
658
659 struct sk_buff *alloc_can_skb(struct net_device *dev, struct can_frame **cf)
660 {
661         struct sk_buff *skb;
662
663         skb = netdev_alloc_skb(dev, sizeof(struct can_skb_priv) +
664                                sizeof(struct can_frame));
665         if (unlikely(!skb))
666                 return NULL;
667
668         skb->protocol = htons(ETH_P_CAN);
669         skb->pkt_type = PACKET_BROADCAST;
670         skb->ip_summed = CHECKSUM_UNNECESSARY;
671
672         skb_reset_mac_header(skb);
673         skb_reset_network_header(skb);
674         skb_reset_transport_header(skb);
675
676         can_skb_reserve(skb);
677         can_skb_prv(skb)->ifindex = dev->ifindex;
678         can_skb_prv(skb)->skbcnt = 0;
679
680         *cf = skb_put(skb, sizeof(struct can_frame));
681         memset(*cf, 0, sizeof(struct can_frame));
682
683         return skb;
684 }
685 EXPORT_SYMBOL_GPL(alloc_can_skb);
686
687 struct sk_buff *alloc_canfd_skb(struct net_device *dev,
688                                 struct canfd_frame **cfd)
689 {
690         struct sk_buff *skb;
691
692         skb = netdev_alloc_skb(dev, sizeof(struct can_skb_priv) +
693                                sizeof(struct canfd_frame));
694         if (unlikely(!skb))
695                 return NULL;
696
697         skb->protocol = htons(ETH_P_CANFD);
698         skb->pkt_type = PACKET_BROADCAST;
699         skb->ip_summed = CHECKSUM_UNNECESSARY;
700
701         skb_reset_mac_header(skb);
702         skb_reset_network_header(skb);
703         skb_reset_transport_header(skb);
704
705         can_skb_reserve(skb);
706         can_skb_prv(skb)->ifindex = dev->ifindex;
707         can_skb_prv(skb)->skbcnt = 0;
708
709         *cfd = skb_put(skb, sizeof(struct canfd_frame));
710         memset(*cfd, 0, sizeof(struct canfd_frame));
711
712         return skb;
713 }
714 EXPORT_SYMBOL_GPL(alloc_canfd_skb);
715
716 struct sk_buff *alloc_can_err_skb(struct net_device *dev, struct can_frame **cf)
717 {
718         struct sk_buff *skb;
719
720         skb = alloc_can_skb(dev, cf);
721         if (unlikely(!skb))
722                 return NULL;
723
724         (*cf)->can_id = CAN_ERR_FLAG;
725         (*cf)->can_dlc = CAN_ERR_DLC;
726
727         return skb;
728 }
729 EXPORT_SYMBOL_GPL(alloc_can_err_skb);
730
731 /*
732  * Allocate and setup space for the CAN network device
733  */
734 struct net_device *alloc_candev(int sizeof_priv, unsigned int echo_skb_max)
735 {
736         struct net_device *dev;
737         struct can_priv *priv;
738         int size;
739
740         if (echo_skb_max)
741                 size = ALIGN(sizeof_priv, sizeof(struct sk_buff *)) +
742                         echo_skb_max * sizeof(struct sk_buff *);
743         else
744                 size = sizeof_priv;
745
746         dev = alloc_netdev(size, "can%d", NET_NAME_UNKNOWN, can_setup);
747         if (!dev)
748                 return NULL;
749
750         priv = netdev_priv(dev);
751         priv->dev = dev;
752
753         if (echo_skb_max) {
754                 priv->echo_skb_max = echo_skb_max;
755                 priv->echo_skb = (void *)priv +
756                         ALIGN(sizeof_priv, sizeof(struct sk_buff *));
757         }
758
759         priv->state = CAN_STATE_STOPPED;
760
761         INIT_DELAYED_WORK(&priv->restart_work, can_restart_work);
762
763         return dev;
764 }
765 EXPORT_SYMBOL_GPL(alloc_candev);
766
767 /*
768  * Free space of the CAN network device
769  */
770 void free_candev(struct net_device *dev)
771 {
772         free_netdev(dev);
773 }
774 EXPORT_SYMBOL_GPL(free_candev);
775
776 /*
777  * changing MTU and control mode for CAN/CANFD devices
778  */
779 int can_change_mtu(struct net_device *dev, int new_mtu)
780 {
781         struct can_priv *priv = netdev_priv(dev);
782
783         /* Do not allow changing the MTU while running */
784         if (dev->flags & IFF_UP)
785                 return -EBUSY;
786
787         /* allow change of MTU according to the CANFD ability of the device */
788         switch (new_mtu) {
789         case CAN_MTU:
790                 /* 'CANFD-only' controllers can not switch to CAN_MTU */
791                 if (priv->ctrlmode_static & CAN_CTRLMODE_FD)
792                         return -EINVAL;
793
794                 priv->ctrlmode &= ~CAN_CTRLMODE_FD;
795                 break;
796
797         case CANFD_MTU:
798                 /* check for potential CANFD ability */
799                 if (!(priv->ctrlmode_supported & CAN_CTRLMODE_FD) &&
800                     !(priv->ctrlmode_static & CAN_CTRLMODE_FD))
801                         return -EINVAL;
802
803                 priv->ctrlmode |= CAN_CTRLMODE_FD;
804                 break;
805
806         default:
807                 return -EINVAL;
808         }
809
810         dev->mtu = new_mtu;
811         return 0;
812 }
813 EXPORT_SYMBOL_GPL(can_change_mtu);
814
815 /*
816  * Common open function when the device gets opened.
817  *
818  * This function should be called in the open function of the device
819  * driver.
820  */
821 int open_candev(struct net_device *dev)
822 {
823         struct can_priv *priv = netdev_priv(dev);
824
825         if (!priv->bittiming.bitrate) {
826                 netdev_err(dev, "bit-timing not yet defined\n");
827                 return -EINVAL;
828         }
829
830         /* For CAN FD the data bitrate has to be >= the arbitration bitrate */
831         if ((priv->ctrlmode & CAN_CTRLMODE_FD) &&
832             (!priv->data_bittiming.bitrate ||
833              (priv->data_bittiming.bitrate < priv->bittiming.bitrate))) {
834                 netdev_err(dev, "incorrect/missing data bit-timing\n");
835                 return -EINVAL;
836         }
837
838         /* Switch carrier on if device was stopped while in bus-off state */
839         if (!netif_carrier_ok(dev))
840                 netif_carrier_on(dev);
841
842         return 0;
843 }
844 EXPORT_SYMBOL_GPL(open_candev);
845
846 /*
847  * Common close function for cleanup before the device gets closed.
848  *
849  * This function should be called in the close function of the device
850  * driver.
851  */
852 void close_candev(struct net_device *dev)
853 {
854         struct can_priv *priv = netdev_priv(dev);
855
856         cancel_delayed_work_sync(&priv->restart_work);
857         can_flush_echo_skb(dev);
858 }
859 EXPORT_SYMBOL_GPL(close_candev);
860
861 /*
862  * CAN netlink interface
863  */
864 static const struct nla_policy can_policy[IFLA_CAN_MAX + 1] = {
865         [IFLA_CAN_STATE]        = { .type = NLA_U32 },
866         [IFLA_CAN_CTRLMODE]     = { .len = sizeof(struct can_ctrlmode) },
867         [IFLA_CAN_RESTART_MS]   = { .type = NLA_U32 },
868         [IFLA_CAN_RESTART]      = { .type = NLA_U32 },
869         [IFLA_CAN_BITTIMING]    = { .len = sizeof(struct can_bittiming) },
870         [IFLA_CAN_BITTIMING_CONST]
871                                 = { .len = sizeof(struct can_bittiming_const) },
872         [IFLA_CAN_CLOCK]        = { .len = sizeof(struct can_clock) },
873         [IFLA_CAN_BERR_COUNTER] = { .len = sizeof(struct can_berr_counter) },
874         [IFLA_CAN_DATA_BITTIMING]
875                                 = { .len = sizeof(struct can_bittiming) },
876         [IFLA_CAN_DATA_BITTIMING_CONST]
877                                 = { .len = sizeof(struct can_bittiming_const) },
878         [IFLA_CAN_TERMINATION]  = { .type = NLA_U16 },
879 };
880
881 static int can_validate(struct nlattr *tb[], struct nlattr *data[],
882                         struct netlink_ext_ack *extack)
883 {
884         bool is_can_fd = false;
885
886         /* Make sure that valid CAN FD configurations always consist of
887          * - nominal/arbitration bittiming
888          * - data bittiming
889          * - control mode with CAN_CTRLMODE_FD set
890          */
891
892         if (!data)
893                 return 0;
894
895         if (data[IFLA_CAN_CTRLMODE]) {
896                 struct can_ctrlmode *cm = nla_data(data[IFLA_CAN_CTRLMODE]);
897
898                 is_can_fd = cm->flags & cm->mask & CAN_CTRLMODE_FD;
899         }
900
901         if (is_can_fd) {
902                 if (!data[IFLA_CAN_BITTIMING] || !data[IFLA_CAN_DATA_BITTIMING])
903                         return -EOPNOTSUPP;
904         }
905
906         if (data[IFLA_CAN_DATA_BITTIMING]) {
907                 if (!is_can_fd || !data[IFLA_CAN_BITTIMING])
908                         return -EOPNOTSUPP;
909         }
910
911         return 0;
912 }
913
914 static int can_changelink(struct net_device *dev, struct nlattr *tb[],
915                           struct nlattr *data[],
916                           struct netlink_ext_ack *extack)
917 {
918         struct can_priv *priv = netdev_priv(dev);
919         int err;
920
921         /* We need synchronization with dev->stop() */
922         ASSERT_RTNL();
923
924         if (data[IFLA_CAN_BITTIMING]) {
925                 struct can_bittiming bt;
926
927                 /* Do not allow changing bittiming while running */
928                 if (dev->flags & IFF_UP)
929                         return -EBUSY;
930
931                 /* Calculate bittiming parameters based on
932                  * bittiming_const if set, otherwise pass bitrate
933                  * directly via do_set_bitrate(). Bail out if neither
934                  * is given.
935                  */
936                 if (!priv->bittiming_const && !priv->do_set_bittiming)
937                         return -EOPNOTSUPP;
938
939                 memcpy(&bt, nla_data(data[IFLA_CAN_BITTIMING]), sizeof(bt));
940                 err = can_get_bittiming(dev, &bt,
941                                         priv->bittiming_const,
942                                         priv->bitrate_const,
943                                         priv->bitrate_const_cnt);
944                 if (err)
945                         return err;
946                 memcpy(&priv->bittiming, &bt, sizeof(bt));
947
948                 if (priv->do_set_bittiming) {
949                         /* Finally, set the bit-timing registers */
950                         err = priv->do_set_bittiming(dev);
951                         if (err)
952                                 return err;
953                 }
954         }
955
956         if (data[IFLA_CAN_CTRLMODE]) {
957                 struct can_ctrlmode *cm;
958                 u32 ctrlstatic;
959                 u32 maskedflags;
960
961                 /* Do not allow changing controller mode while running */
962                 if (dev->flags & IFF_UP)
963                         return -EBUSY;
964                 cm = nla_data(data[IFLA_CAN_CTRLMODE]);
965                 ctrlstatic = priv->ctrlmode_static;
966                 maskedflags = cm->flags & cm->mask;
967
968                 /* check whether provided bits are allowed to be passed */
969                 if (cm->mask & ~(priv->ctrlmode_supported | ctrlstatic))
970                         return -EOPNOTSUPP;
971
972                 /* do not check for static fd-non-iso if 'fd' is disabled */
973                 if (!(maskedflags & CAN_CTRLMODE_FD))
974                         ctrlstatic &= ~CAN_CTRLMODE_FD_NON_ISO;
975
976                 /* make sure static options are provided by configuration */
977                 if ((maskedflags & ctrlstatic) != ctrlstatic)
978                         return -EOPNOTSUPP;
979
980                 /* clear bits to be modified and copy the flag values */
981                 priv->ctrlmode &= ~cm->mask;
982                 priv->ctrlmode |= maskedflags;
983
984                 /* CAN_CTRLMODE_FD can only be set when driver supports FD */
985                 if (priv->ctrlmode & CAN_CTRLMODE_FD)
986                         dev->mtu = CANFD_MTU;
987                 else
988                         dev->mtu = CAN_MTU;
989         }
990
991         if (data[IFLA_CAN_RESTART_MS]) {
992                 /* Do not allow changing restart delay while running */
993                 if (dev->flags & IFF_UP)
994                         return -EBUSY;
995                 priv->restart_ms = nla_get_u32(data[IFLA_CAN_RESTART_MS]);
996         }
997
998         if (data[IFLA_CAN_RESTART]) {
999                 /* Do not allow a restart while not running */
1000                 if (!(dev->flags & IFF_UP))
1001                         return -EINVAL;
1002                 err = can_restart_now(dev);
1003                 if (err)
1004                         return err;
1005         }
1006
1007         if (data[IFLA_CAN_DATA_BITTIMING]) {
1008                 struct can_bittiming dbt;
1009
1010                 /* Do not allow changing bittiming while running */
1011                 if (dev->flags & IFF_UP)
1012                         return -EBUSY;
1013
1014                 /* Calculate bittiming parameters based on
1015                  * data_bittiming_const if set, otherwise pass bitrate
1016                  * directly via do_set_bitrate(). Bail out if neither
1017                  * is given.
1018                  */
1019                 if (!priv->data_bittiming_const && !priv->do_set_data_bittiming)
1020                         return -EOPNOTSUPP;
1021
1022                 memcpy(&dbt, nla_data(data[IFLA_CAN_DATA_BITTIMING]),
1023                        sizeof(dbt));
1024                 err = can_get_bittiming(dev, &dbt,
1025                                         priv->data_bittiming_const,
1026                                         priv->data_bitrate_const,
1027                                         priv->data_bitrate_const_cnt);
1028                 if (err)
1029                         return err;
1030                 memcpy(&priv->data_bittiming, &dbt, sizeof(dbt));
1031
1032                 if (priv->do_set_data_bittiming) {
1033                         /* Finally, set the bit-timing registers */
1034                         err = priv->do_set_data_bittiming(dev);
1035                         if (err)
1036                                 return err;
1037                 }
1038         }
1039
1040         if (data[IFLA_CAN_TERMINATION]) {
1041                 const u16 termval = nla_get_u16(data[IFLA_CAN_TERMINATION]);
1042                 const unsigned int num_term = priv->termination_const_cnt;
1043                 unsigned int i;
1044
1045                 if (!priv->do_set_termination)
1046                         return -EOPNOTSUPP;
1047
1048                 /* check whether given value is supported by the interface */
1049                 for (i = 0; i < num_term; i++) {
1050                         if (termval == priv->termination_const[i])
1051                                 break;
1052                 }
1053                 if (i >= num_term)
1054                         return -EINVAL;
1055
1056                 /* Finally, set the termination value */
1057                 err = priv->do_set_termination(dev, termval);
1058                 if (err)
1059                         return err;
1060
1061                 priv->termination = termval;
1062         }
1063
1064         return 0;
1065 }
1066
1067 static size_t can_get_size(const struct net_device *dev)
1068 {
1069         struct can_priv *priv = netdev_priv(dev);
1070         size_t size = 0;
1071
1072         if (priv->bittiming.bitrate)                            /* IFLA_CAN_BITTIMING */
1073                 size += nla_total_size(sizeof(struct can_bittiming));
1074         if (priv->bittiming_const)                              /* IFLA_CAN_BITTIMING_CONST */
1075                 size += nla_total_size(sizeof(struct can_bittiming_const));
1076         size += nla_total_size(sizeof(struct can_clock));       /* IFLA_CAN_CLOCK */
1077         size += nla_total_size(sizeof(u32));                    /* IFLA_CAN_STATE */
1078         size += nla_total_size(sizeof(struct can_ctrlmode));    /* IFLA_CAN_CTRLMODE */
1079         size += nla_total_size(sizeof(u32));                    /* IFLA_CAN_RESTART_MS */
1080         if (priv->do_get_berr_counter)                          /* IFLA_CAN_BERR_COUNTER */
1081                 size += nla_total_size(sizeof(struct can_berr_counter));
1082         if (priv->data_bittiming.bitrate)                       /* IFLA_CAN_DATA_BITTIMING */
1083                 size += nla_total_size(sizeof(struct can_bittiming));
1084         if (priv->data_bittiming_const)                         /* IFLA_CAN_DATA_BITTIMING_CONST */
1085                 size += nla_total_size(sizeof(struct can_bittiming_const));
1086         if (priv->termination_const) {
1087                 size += nla_total_size(sizeof(priv->termination));              /* IFLA_CAN_TERMINATION */
1088                 size += nla_total_size(sizeof(*priv->termination_const) *       /* IFLA_CAN_TERMINATION_CONST */
1089                                        priv->termination_const_cnt);
1090         }
1091         if (priv->bitrate_const)                                /* IFLA_CAN_BITRATE_CONST */
1092                 size += nla_total_size(sizeof(*priv->bitrate_const) *
1093                                        priv->bitrate_const_cnt);
1094         if (priv->data_bitrate_const)                           /* IFLA_CAN_DATA_BITRATE_CONST */
1095                 size += nla_total_size(sizeof(*priv->data_bitrate_const) *
1096                                        priv->data_bitrate_const_cnt);
1097
1098         return size;
1099 }
1100
1101 static int can_fill_info(struct sk_buff *skb, const struct net_device *dev)
1102 {
1103         struct can_priv *priv = netdev_priv(dev);
1104         struct can_ctrlmode cm = {.flags = priv->ctrlmode};
1105         struct can_berr_counter bec = { };
1106         enum can_state state = priv->state;
1107
1108         if (priv->do_get_state)
1109                 priv->do_get_state(dev, &state);
1110
1111         if ((priv->bittiming.bitrate &&
1112              nla_put(skb, IFLA_CAN_BITTIMING,
1113                      sizeof(priv->bittiming), &priv->bittiming)) ||
1114
1115             (priv->bittiming_const &&
1116              nla_put(skb, IFLA_CAN_BITTIMING_CONST,
1117                      sizeof(*priv->bittiming_const), priv->bittiming_const)) ||
1118
1119             nla_put(skb, IFLA_CAN_CLOCK, sizeof(priv->clock), &priv->clock) ||
1120             nla_put_u32(skb, IFLA_CAN_STATE, state) ||
1121             nla_put(skb, IFLA_CAN_CTRLMODE, sizeof(cm), &cm) ||
1122             nla_put_u32(skb, IFLA_CAN_RESTART_MS, priv->restart_ms) ||
1123
1124             (priv->do_get_berr_counter &&
1125              !priv->do_get_berr_counter(dev, &bec) &&
1126              nla_put(skb, IFLA_CAN_BERR_COUNTER, sizeof(bec), &bec)) ||
1127
1128             (priv->data_bittiming.bitrate &&
1129              nla_put(skb, IFLA_CAN_DATA_BITTIMING,
1130                      sizeof(priv->data_bittiming), &priv->data_bittiming)) ||
1131
1132             (priv->data_bittiming_const &&
1133              nla_put(skb, IFLA_CAN_DATA_BITTIMING_CONST,
1134                      sizeof(*priv->data_bittiming_const),
1135                      priv->data_bittiming_const)) ||
1136
1137             (priv->termination_const &&
1138              (nla_put_u16(skb, IFLA_CAN_TERMINATION, priv->termination) ||
1139               nla_put(skb, IFLA_CAN_TERMINATION_CONST,
1140                       sizeof(*priv->termination_const) *
1141                       priv->termination_const_cnt,
1142                       priv->termination_const))) ||
1143
1144             (priv->bitrate_const &&
1145              nla_put(skb, IFLA_CAN_BITRATE_CONST,
1146                      sizeof(*priv->bitrate_const) *
1147                      priv->bitrate_const_cnt,
1148                      priv->bitrate_const)) ||
1149
1150             (priv->data_bitrate_const &&
1151              nla_put(skb, IFLA_CAN_DATA_BITRATE_CONST,
1152                      sizeof(*priv->data_bitrate_const) *
1153                      priv->data_bitrate_const_cnt,
1154                      priv->data_bitrate_const))
1155             )
1156
1157                 return -EMSGSIZE;
1158
1159         return 0;
1160 }
1161
1162 static size_t can_get_xstats_size(const struct net_device *dev)
1163 {
1164         return sizeof(struct can_device_stats);
1165 }
1166
1167 static int can_fill_xstats(struct sk_buff *skb, const struct net_device *dev)
1168 {
1169         struct can_priv *priv = netdev_priv(dev);
1170
1171         if (nla_put(skb, IFLA_INFO_XSTATS,
1172                     sizeof(priv->can_stats), &priv->can_stats))
1173                 goto nla_put_failure;
1174         return 0;
1175
1176 nla_put_failure:
1177         return -EMSGSIZE;
1178 }
1179
1180 static int can_newlink(struct net *src_net, struct net_device *dev,
1181                        struct nlattr *tb[], struct nlattr *data[],
1182                        struct netlink_ext_ack *extack)
1183 {
1184         return -EOPNOTSUPP;
1185 }
1186
1187 static void can_dellink(struct net_device *dev, struct list_head *head)
1188 {
1189         return;
1190 }
1191
1192 static struct rtnl_link_ops can_link_ops __read_mostly = {
1193         .kind           = "can",
1194         .netns_refund   = true,
1195         .maxtype        = IFLA_CAN_MAX,
1196         .policy         = can_policy,
1197         .setup          = can_setup,
1198         .validate       = can_validate,
1199         .newlink        = can_newlink,
1200         .changelink     = can_changelink,
1201         .dellink        = can_dellink,
1202         .get_size       = can_get_size,
1203         .fill_info      = can_fill_info,
1204         .get_xstats_size = can_get_xstats_size,
1205         .fill_xstats    = can_fill_xstats,
1206 };
1207
1208 /*
1209  * Register the CAN network device
1210  */
1211 int register_candev(struct net_device *dev)
1212 {
1213         struct can_priv *priv = netdev_priv(dev);
1214
1215         /* Ensure termination_const, termination_const_cnt and
1216          * do_set_termination consistency. All must be either set or
1217          * unset.
1218          */
1219         if ((!priv->termination_const != !priv->termination_const_cnt) ||
1220             (!priv->termination_const != !priv->do_set_termination))
1221                 return -EINVAL;
1222
1223         if (!priv->bitrate_const != !priv->bitrate_const_cnt)
1224                 return -EINVAL;
1225
1226         if (!priv->data_bitrate_const != !priv->data_bitrate_const_cnt)
1227                 return -EINVAL;
1228
1229         dev->rtnl_link_ops = &can_link_ops;
1230         netif_carrier_off(dev);
1231
1232         return register_netdev(dev);
1233 }
1234 EXPORT_SYMBOL_GPL(register_candev);
1235
1236 /*
1237  * Unregister the CAN network device
1238  */
1239 void unregister_candev(struct net_device *dev)
1240 {
1241         unregister_netdev(dev);
1242 }
1243 EXPORT_SYMBOL_GPL(unregister_candev);
1244
1245 /*
1246  * Test if a network device is a candev based device
1247  * and return the can_priv* if so.
1248  */
1249 struct can_priv *safe_candev_priv(struct net_device *dev)
1250 {
1251         if ((dev->type != ARPHRD_CAN) || (dev->rtnl_link_ops != &can_link_ops))
1252                 return NULL;
1253
1254         return netdev_priv(dev);
1255 }
1256 EXPORT_SYMBOL_GPL(safe_candev_priv);
1257
1258 static __init int can_dev_init(void)
1259 {
1260         int err;
1261
1262         can_led_notifier_init();
1263
1264         err = rtnl_link_register(&can_link_ops);
1265         if (!err)
1266                 printk(KERN_INFO MOD_DESC "\n");
1267
1268         return err;
1269 }
1270 module_init(can_dev_init);
1271
1272 static __exit void can_dev_exit(void)
1273 {
1274         rtnl_link_unregister(&can_link_ops);
1275
1276         can_led_notifier_exit();
1277 }
1278 module_exit(can_dev_exit);
1279
1280 MODULE_ALIAS_RTNL_LINK("can");