xref: /linux-6.15/include/linux/can/length.h (revision bdd2e413)
1 /* SPDX-License-Identifier: GPL-2.0 */
2 /* Copyright (C) 2020 Oliver Hartkopp <[email protected]>
3  */
4 
5 #ifndef _CAN_LENGTH_H
6 #define _CAN_LENGTH_H
7 
8 /*
9  * can_cc_dlc2len(value) - convert a given data length code (dlc) of a
10  * Classical CAN frame into a valid data length of max. 8 bytes.
11  *
12  * To be used in the CAN netdriver receive path to ensure conformance with
13  * ISO 11898-1 Chapter 8.4.2.3 (DLC field)
14  */
15 #define can_cc_dlc2len(dlc)	(min_t(u8, (dlc), CAN_MAX_DLEN))
16 
17 /* helper to get the data length code (DLC) for Classical CAN raw DLC access */
18 static inline u8 can_get_cc_dlc(const struct can_frame *cf, const u32 ctrlmode)
19 {
20 	/* return len8_dlc as dlc value only if all conditions apply */
21 	if ((ctrlmode & CAN_CTRLMODE_CC_LEN8_DLC) &&
22 	    (cf->len == CAN_MAX_DLEN) &&
23 	    (cf->len8_dlc > CAN_MAX_DLEN && cf->len8_dlc <= CAN_MAX_RAW_DLC))
24 		return cf->len8_dlc;
25 
26 	/* return the payload length as dlc value */
27 	return cf->len;
28 }
29 
30 /* helper to set len and len8_dlc value for Classical CAN raw DLC access */
31 static inline void can_frame_set_cc_len(struct can_frame *cf, const u8 dlc,
32 					const u32 ctrlmode)
33 {
34 	/* the caller already ensured that dlc is a value from 0 .. 15 */
35 	if (ctrlmode & CAN_CTRLMODE_CC_LEN8_DLC && dlc > CAN_MAX_DLEN)
36 		cf->len8_dlc = dlc;
37 
38 	/* limit the payload length 'len' to CAN_MAX_DLEN */
39 	cf->len = can_cc_dlc2len(dlc);
40 }
41 
42 /* get data length from raw data length code (DLC) */
43 u8 can_fd_dlc2len(u8 dlc);
44 
45 /* map the sanitized data length to an appropriate data length code */
46 u8 can_fd_len2dlc(u8 len);
47 
48 #endif /* !_CAN_LENGTH_H */
49