1 // SPDX-License-Identifier: GPL-2.0-only 2 /* Copyright (C) 2012, 2020 Oliver Hartkopp <socketcan@hartkopp.net> 3 */ 4 5 #include <linux/can/dev.h> 6 7 /* CAN DLC to real data length conversion helpers */ 8 9 static const u8 dlc2len[] = { 10 0, 1, 2, 3, 4, 5, 6, 7, 11 8, 12, 16, 20, 24, 32, 48, 64 12 }; 13 14 /* get data length from raw data length code (DLC) */ 15 u8 can_fd_dlc2len(u8 dlc) 16 { 17 return dlc2len[dlc & 0x0F]; 18 } 19 EXPORT_SYMBOL_GPL(can_fd_dlc2len); 20 21 static const u8 len2dlc[] = { 22 0, 1, 2, 3, 4, 5, 6, 7, 8, /* 0 - 8 */ 23 9, 9, 9, 9, /* 9 - 12 */ 24 10, 10, 10, 10, /* 13 - 16 */ 25 11, 11, 11, 11, /* 17 - 20 */ 26 12, 12, 12, 12, /* 21 - 24 */ 27 13, 13, 13, 13, 13, 13, 13, 13, /* 25 - 32 */ 28 14, 14, 14, 14, 14, 14, 14, 14, /* 33 - 40 */ 29 14, 14, 14, 14, 14, 14, 14, 14, /* 41 - 48 */ 30 }; 31 32 /* map the sanitized data length to an appropriate data length code */ 33 u8 can_fd_len2dlc(u8 len) 34 { 35 if (len >= ARRAY_SIZE(len2dlc)) 36 return CANFD_MAX_DLC; 37 38 return len2dlc[len]; 39 } 40 EXPORT_SYMBOL_GPL(can_fd_len2dlc); 41 42 /** 43 * can_skb_get_frame_len() - Calculate the CAN Frame length in bytes 44 * of a given skb. 45 * @skb: socket buffer of a CAN message. 46 * 47 * Do a rough calculation: bit stuffing is ignored and length in bits 48 * is rounded up to a length in bytes. 49 * 50 * Rationale: this function is to be used for the BQL functions 51 * (netdev_sent_queue() and netdev_completed_queue()) which expect a 52 * value in bytes. Just using skb->len is insufficient because it will 53 * return the constant value of CAN(FD)_MTU. Doing the bit stuffing 54 * calculation would be too expensive in term of computing resources 55 * for no noticeable gain. 56 * 57 * Remarks: The payload of CAN FD frames with BRS flag are sent at a 58 * different bitrate. Currently, the can-utils canbusload tool does 59 * not support CAN-FD yet and so we could not run any benchmark to 60 * measure the impact. There might be possible improvement here. 61 * 62 * Return: length in bytes. 63 */ 64 unsigned int can_skb_get_frame_len(const struct sk_buff *skb) 65 { 66 const struct canfd_frame *cf = (const struct canfd_frame *)skb->data; 67 u8 len; 68 69 if (can_is_canfd_skb(skb)) 70 len = canfd_sanitize_len(cf->len); 71 else if (cf->can_id & CAN_RTR_FLAG) 72 len = 0; 73 else 74 len = cf->len; 75 76 if (can_is_canfd_skb(skb)) { 77 if (cf->can_id & CAN_EFF_FLAG) 78 len += CANFD_FRAME_OVERHEAD_EFF; 79 else 80 len += CANFD_FRAME_OVERHEAD_SFF; 81 } else { 82 if (cf->can_id & CAN_EFF_FLAG) 83 len += CAN_FRAME_OVERHEAD_EFF; 84 else 85 len += CAN_FRAME_OVERHEAD_SFF; 86 } 87 88 return len; 89 } 90 EXPORT_SYMBOL_GPL(can_skb_get_frame_len); 91