1 /**
2  * @file
3  *
4  * @brief Public APIs for the I2C drivers.
5  */
6 
7 /*
8  * Copyright (c) 2015 Intel Corporation
9  *
10  * SPDX-License-Identifier: Apache-2.0
11  */
12 #ifndef ZEPHYR_INCLUDE_DRIVERS_I2C_H_
13 #define ZEPHYR_INCLUDE_DRIVERS_I2C_H_
14 
15 /**
16  * @brief I2C Interface
17  * @defgroup i2c_interface I2C Interface
18  * @since 1.0
19  * @version 1.0.0
20  * @ingroup io_interfaces
21  * @{
22  */
23 
24 #include <errno.h>
25 
26 #include <zephyr/types.h>
27 #include <zephyr/device.h>
28 #include <zephyr/kernel.h>
29 #include <zephyr/sys/slist.h>
30 #include <zephyr/rtio/rtio.h>
31 
32 #ifdef __cplusplus
33 extern "C" {
34 #endif
35 
36 /*
37  * The following #defines are used to configure the I2C controller.
38  */
39 
40 /** I2C Standard Speed: 100 kHz */
41 #define I2C_SPEED_STANDARD		(0x1U)
42 
43 /** I2C Fast Speed: 400 kHz */
44 #define I2C_SPEED_FAST			(0x2U)
45 
46 /** I2C Fast Plus Speed: 1 MHz */
47 #define I2C_SPEED_FAST_PLUS		(0x3U)
48 
49 /** I2C High Speed: 3.4 MHz */
50 #define I2C_SPEED_HIGH			(0x4U)
51 
52 /** I2C Ultra Fast Speed: 5 MHz */
53 #define I2C_SPEED_ULTRA			(0x5U)
54 
55 /** Device Tree specified speed */
56 #define I2C_SPEED_DT			(0x7U)
57 
58 #define I2C_SPEED_SHIFT			(1U)
59 #define I2C_SPEED_SET(speed)		(((speed) << I2C_SPEED_SHIFT) \
60 						& I2C_SPEED_MASK)
61 #define I2C_SPEED_MASK			(0x7U << I2C_SPEED_SHIFT) /* 3 bits */
62 #define I2C_SPEED_GET(cfg) 		(((cfg) & I2C_SPEED_MASK) \
63 						>> I2C_SPEED_SHIFT)
64 
65 /** Use 10-bit addressing. DEPRECATED - Use I2C_MSG_ADDR_10_BITS instead. */
66 #define I2C_ADDR_10_BITS		BIT(0)
67 
68 /** Peripheral to act as Controller. */
69 #define I2C_MODE_CONTROLLER		BIT(4)
70 
71 /**
72  * @brief Complete I2C DT information
73  *
74  * @param bus is the I2C bus
75  * @param addr is the target address
76  */
77 struct i2c_dt_spec {
78 	const struct device *bus;
79 	uint16_t addr;
80 };
81 
82 /**
83  * @brief Structure initializer for i2c_dt_spec from devicetree (on I3C bus)
84  *
85  * This helper macro expands to a static initializer for a <tt>struct
86  * i2c_dt_spec</tt> by reading the relevant bus and address data from
87  * the devicetree.
88  *
89  * @param node_id Devicetree node identifier for the I2C device whose
90  *                struct i2c_dt_spec to create an initializer for
91  */
92 #define I2C_DT_SPEC_GET_ON_I3C(node_id)					\
93 	.bus = DEVICE_DT_GET(DT_BUS(node_id)),				\
94 	.addr = DT_PROP_BY_IDX(node_id, reg, 0)
95 
96 /**
97  * @brief Structure initializer for i2c_dt_spec from devicetree (on I2C bus)
98  *
99  * This helper macro expands to a static initializer for a <tt>struct
100  * i2c_dt_spec</tt> by reading the relevant bus and address data from
101  * the devicetree.
102  *
103  * @param node_id Devicetree node identifier for the I2C device whose
104  *                struct i2c_dt_spec to create an initializer for
105  */
106 #define I2C_DT_SPEC_GET_ON_I2C(node_id)					\
107 	.bus = DEVICE_DT_GET(DT_BUS(node_id)),				\
108 	.addr = DT_REG_ADDR(node_id)
109 
110 /**
111  * @brief Structure initializer for i2c_dt_spec from devicetree
112  *
113  * This helper macro expands to a static initializer for a <tt>struct
114  * i2c_dt_spec</tt> by reading the relevant bus and address data from
115  * the devicetree.
116  *
117  * @param node_id Devicetree node identifier for the I2C device whose
118  *                struct i2c_dt_spec to create an initializer for
119  */
120 #define I2C_DT_SPEC_GET(node_id)					\
121 	{								\
122 		COND_CODE_1(DT_ON_BUS(node_id, i3c),			\
123 			    (I2C_DT_SPEC_GET_ON_I3C(node_id)),		\
124 			    (I2C_DT_SPEC_GET_ON_I2C(node_id)))		\
125 	}
126 
127 /**
128  * @brief Structure initializer for i2c_dt_spec from devicetree instance
129  *
130  * This is equivalent to
131  * <tt>I2C_DT_SPEC_GET(DT_DRV_INST(inst))</tt>.
132  *
133  * @param inst Devicetree instance number
134  */
135 #define I2C_DT_SPEC_INST_GET(inst) \
136 	I2C_DT_SPEC_GET(DT_DRV_INST(inst))
137 
138 
139 /*
140  * I2C_MSG_* are I2C Message flags.
141  */
142 
143 /** Write message to I2C bus. */
144 #define I2C_MSG_WRITE			(0U << 0U)
145 
146 /** Read message from I2C bus. */
147 #define I2C_MSG_READ			BIT(0)
148 
149 /** @cond INTERNAL_HIDDEN */
150 #define I2C_MSG_RW_MASK			BIT(0)
151 /** @endcond  */
152 
153 /** Send STOP after this message. */
154 #define I2C_MSG_STOP			BIT(1)
155 
156 /** RESTART I2C transaction for this message.
157  *
158  * @note Not all I2C drivers have or require explicit support for this
159  * feature. Some drivers require this be present on a read message
160  * that follows a write, or vice-versa.  Some drivers will merge
161  * adjacent fragments into a single transaction using this flag; some
162  * will not. */
163 #define I2C_MSG_RESTART			BIT(2)
164 
165 /** Use 10-bit addressing for this message.
166  *
167  * @note Not all SoC I2C implementations support this feature. */
168 #define I2C_MSG_ADDR_10_BITS		BIT(3)
169 
170 /**
171  * @brief One I2C Message.
172  *
173  * This defines one I2C message to transact on the I2C bus.
174  *
175  * @note Some of the configurations supported by this API may not be
176  * supported by specific SoC I2C hardware implementations, in
177  * particular features related to bus transactions intended to read or
178  * write data from different buffers within a single transaction.
179  * Invocations of i2c_transfer() may not indicate an error when an
180  * unsupported configuration is encountered.  In some cases drivers
181  * will generate separate transactions for each message fragment, with
182  * or without presence of @ref I2C_MSG_RESTART in #flags.
183  */
184 struct i2c_msg {
185 	/** Data buffer in bytes */
186 	uint8_t		*buf;
187 
188 	/** Length of buffer in bytes */
189 	uint32_t	len;
190 
191 	/** Flags for this message */
192 	uint8_t		flags;
193 };
194 
195 /**
196  * @brief I2C callback for asynchronous transfer requests
197  *
198  * @param dev I2C device which is notifying of transfer completion or error
199  * @param result Result code of the transfer request. 0 is success, -errno for failure.
200  * @param data Transfer requester supplied data which is passed along to the callback.
201  */
202 typedef void (*i2c_callback_t)(const struct device *dev, int result, void *data);
203 
204 /**
205  * @cond INTERNAL_HIDDEN
206  *
207  * These are for internal use only, so skip these in
208  * public documentation.
209  */
210 struct i2c_target_config;
211 
212 typedef int (*i2c_api_configure_t)(const struct device *dev,
213 				   uint32_t dev_config);
214 typedef int (*i2c_api_get_config_t)(const struct device *dev,
215 				    uint32_t *dev_config);
216 typedef int (*i2c_api_full_io_t)(const struct device *dev,
217 				 struct i2c_msg *msgs,
218 				 uint8_t num_msgs,
219 				 uint16_t addr);
220 typedef int (*i2c_api_target_register_t)(const struct device *dev,
221 					struct i2c_target_config *cfg);
222 typedef int (*i2c_api_target_unregister_t)(const struct device *dev,
223 					  struct i2c_target_config *cfg);
224 #ifdef CONFIG_I2C_CALLBACK
225 typedef int (*i2c_api_transfer_cb_t)(const struct device *dev,
226 				 struct i2c_msg *msgs,
227 				 uint8_t num_msgs,
228 				 uint16_t addr,
229 				 i2c_callback_t cb,
230 				 void *userdata);
231 #endif /* CONFIG_I2C_CALLBACK */
232 #if defined(CONFIG_I2C_RTIO) || defined(__DOXYGEN__)
233 
234 /**
235  * @typedef i2c_api_iodev_submit
236  * @brief Callback API for submitting work to a I2C device with RTIO
237  */
238 typedef void (*i2c_api_iodev_submit)(const struct device *dev,
239 				     struct rtio_iodev_sqe *iodev_sqe);
240 #endif /* CONFIG_I2C_RTIO */
241 
242 typedef int (*i2c_api_recover_bus_t)(const struct device *dev);
243 
244 __subsystem struct i2c_driver_api {
245 	i2c_api_configure_t configure;
246 	i2c_api_get_config_t get_config;
247 	i2c_api_full_io_t transfer;
248 	i2c_api_target_register_t target_register;
249 	i2c_api_target_unregister_t target_unregister;
250 #ifdef CONFIG_I2C_CALLBACK
251 	i2c_api_transfer_cb_t transfer_cb;
252 #endif
253 #ifdef CONFIG_I2C_RTIO
254 	i2c_api_iodev_submit iodev_submit;
255 #endif
256 	i2c_api_recover_bus_t recover_bus;
257 };
258 
259 typedef int (*i2c_target_api_register_t)(const struct device *dev);
260 typedef int (*i2c_target_api_unregister_t)(const struct device *dev);
261 
262 __subsystem struct i2c_target_driver_api {
263 	i2c_target_api_register_t driver_register;
264 	i2c_target_api_unregister_t driver_unregister;
265 };
266 
267 /**
268  * @endcond
269  */
270 
271 /** Target device responds to 10-bit addressing. */
272 #define I2C_TARGET_FLAGS_ADDR_10_BITS	BIT(0)
273 
274 /** @brief Function called when a write to the device is initiated.
275  *
276  * This function is invoked by the controller when the bus completes a
277  * start condition for a write operation to the address associated
278  * with a particular device.
279  *
280  * A success return shall cause the controller to ACK the next byte
281  * received.  An error return shall cause the controller to NACK the
282  * next byte received.
283  *
284  * @param config the configuration structure associated with the
285  * device to which the operation is addressed.
286  *
287  * @return 0 if the write is accepted, or a negative error code.
288  */
289 typedef int (*i2c_target_write_requested_cb_t)(
290 		struct i2c_target_config *config);
291 
292 /** @brief Function called when a write to the device is continued.
293  *
294  * This function is invoked by the controller when it completes
295  * reception of a byte of data in an ongoing write operation to the
296  * device.
297  *
298  * A success return shall cause the controller to ACK the next byte
299  * received.  An error return shall cause the controller to NACK the
300  * next byte received.
301  *
302  * @param config the configuration structure associated with the
303  * device to which the operation is addressed.
304  *
305  * @param val the byte received by the controller.
306  *
307  * @return 0 if more data can be accepted, or a negative error
308  * code.
309  */
310 typedef int (*i2c_target_write_received_cb_t)(
311 		struct i2c_target_config *config, uint8_t val);
312 
313 /** @brief Function called when a read from the device is initiated.
314  *
315  * This function is invoked by the controller when the bus completes a
316  * start condition for a read operation from the address associated
317  * with a particular device.
318  *
319  * The value returned in @p *val will be transmitted.  A success
320  * return shall cause the controller to react to additional read
321  * operations.  An error return shall cause the controller to ignore
322  * bus operations until a new start condition is received.
323  *
324  * @param config the configuration structure associated with the
325  * device to which the operation is addressed.
326  *
327  * @param val pointer to storage for the first byte of data to return
328  * for the read request.
329  *
330  * @return 0 if more data can be requested, or a negative error code.
331  */
332 typedef int (*i2c_target_read_requested_cb_t)(
333 		struct i2c_target_config *config, uint8_t *val);
334 
335 /** @brief Function called when a read from the device is continued.
336  *
337  * This function is invoked by the controller when the bus is ready to
338  * provide additional data for a read operation from the address
339  * associated with the device device.
340  *
341  * The value returned in @p *val will be transmitted.  A success
342  * return shall cause the controller to react to additional read
343  * operations.  An error return shall cause the controller to ignore
344  * bus operations until a new start condition is received.
345  *
346  * @param config the configuration structure associated with the
347  * device to which the operation is addressed.
348  *
349  * @param val pointer to storage for the next byte of data to return
350  * for the read request.
351  *
352  * @return 0 if data has been provided, or a negative error code.
353  */
354 typedef int (*i2c_target_read_processed_cb_t)(
355 		struct i2c_target_config *config, uint8_t *val);
356 
357 #ifdef CONFIG_I2C_TARGET_BUFFER_MODE
358 /** @brief Function called when a write to the device is completed.
359  *
360  * This function is invoked by the controller when it completes
361  * reception of data from the source buffer to the destination
362  * buffer in an ongoing write operation to the device.
363  *
364  * @param config the configuration structure associated with the
365  * device to which the operation is addressed.
366  *
367  * @param ptr pointer to the buffer that contains the data to be transferred.
368  *
369  * @param len the length of the data to be transferred.
370  */
371 typedef void (*i2c_target_buf_write_received_cb_t)(
372 		struct i2c_target_config *config, uint8_t *ptr, uint32_t len);
373 
374 /** @brief Function called when a read from the device is initiated.
375  *
376  * This function is invoked by the controller when the bus is ready to
377  * provide additional data by buffer for a read operation from the address
378  * associated with the device.
379  *
380  * The value returned in @p **ptr and @p *len will be transmitted. A success
381  * return shall cause the controller to react to additional read operations.
382  * An error return shall cause the controller to ignore bus operations until
383  * a new start condition is received.
384  *
385  * @param config the configuration structure associated with the
386  * device to which the operation is addressed.
387  *
388  * @param ptr pointer to storage for the address of data buffer to return
389  * for the read request.
390  *
391  * @param len pointer to storage for the length of the data to be transferred
392  * for the read request.
393  *
394  * @return 0 if data has been provided, or a negative error code.
395  */
396 typedef int (*i2c_target_buf_read_requested_cb_t)(
397 		struct i2c_target_config *config, uint8_t **ptr, uint32_t *len);
398 #endif
399 
400 /** @brief Function called when a stop condition is observed after a
401  * start condition addressed to a particular device.
402  *
403  * This function is invoked by the controller when the bus is ready to
404  * provide additional data for a read operation from the address
405  * associated with the device device.  After the function returns the
406  * controller shall enter a state where it is ready to react to new
407  * start conditions.
408  *
409  * @param config the configuration structure associated with the
410  * device to which the operation is addressed.
411  *
412  * @return Ignored.
413  */
414 typedef int (*i2c_target_stop_cb_t)(struct i2c_target_config *config);
415 
416 /** @brief Structure providing callbacks to be implemented for devices
417  * that supports the I2C target API.
418  *
419  * This structure may be shared by multiple devices that implement the
420  * same API at different addresses on the bus.
421  */
422 struct i2c_target_callbacks {
423 	i2c_target_write_requested_cb_t write_requested;
424 	i2c_target_read_requested_cb_t read_requested;
425 	i2c_target_write_received_cb_t write_received;
426 	i2c_target_read_processed_cb_t read_processed;
427 #ifdef CONFIG_I2C_TARGET_BUFFER_MODE
428 	i2c_target_buf_write_received_cb_t buf_write_received;
429 	i2c_target_buf_read_requested_cb_t buf_read_requested;
430 #endif
431 	i2c_target_stop_cb_t stop;
432 };
433 
434 /** @brief Structure describing a device that supports the I2C
435  * target API.
436  *
437  * Instances of this are passed to the i2c_target_register() and
438  * i2c_target_unregister() functions to indicate addition and removal
439  * of a target device, respective.
440  *
441  * Fields other than @c node must be initialized by the module that
442  * implements the device behavior prior to passing the object
443  * reference to i2c_target_register().
444  */
445 struct i2c_target_config {
446 	/** Private, do not modify */
447 	sys_snode_t node;
448 
449 	/** Flags for the target device defined by I2C_TARGET_FLAGS_* constants */
450 	uint8_t flags;
451 
452 	/** Address for this target device */
453 	uint16_t address;
454 
455 	/** Callback functions */
456 	const struct i2c_target_callbacks *callbacks;
457 };
458 
459 /**
460  * @brief Validate that I2C bus is ready.
461  *
462  * @param spec I2C specification from devicetree
463  *
464  * @retval true if the I2C bus is ready for use.
465  * @retval false if the I2C bus is not ready for use.
466  */
i2c_is_ready_dt(const struct i2c_dt_spec * spec)467 static inline bool i2c_is_ready_dt(const struct i2c_dt_spec *spec)
468 {
469 	/* Validate bus is ready */
470 	return device_is_ready(spec->bus);
471 }
472 
473 /**
474  * @brief Check if the current message is a read operation
475  *
476  * @param msg The message to check
477  * @return true if the I2C message is sa read operation
478  * @return false if the I2C message is a write operation
479  */
i2c_is_read_op(struct i2c_msg * msg)480 static inline bool i2c_is_read_op(struct i2c_msg *msg)
481 {
482 	return (msg->flags & I2C_MSG_READ) == I2C_MSG_READ;
483 }
484 
485 /**
486  * @brief Dump out an I2C message
487  *
488  * Dumps out a list of I2C messages. For any that are writes (W), the data is
489  * displayed in hex. Setting dump_read will dump the data for read messages too,
490  * which only makes sense when called after the messages have been processed.
491  *
492  * It looks something like this (with name "testing"):
493  *
494  * @code
495  * D: I2C msg: testing, addr=56
496  * D:    W len=01: 06
497  * D:    W len=0e:
498  * D: contents:
499  * D: 00 01 02 03 04 05 06 07 |........
500  * D: 08 09 0a 0b 0c 0d       |......
501  * D:    W len=01: 0f
502  * D:    R len=01: 6c
503  * @endcode
504  *
505  * @param dev Target for the messages being sent. Its name will be printed in the log.
506  * @param msgs Array of messages to dump.
507  * @param num_msgs Number of messages to dump.
508  * @param addr Address of the I2C target device.
509  * @param dump_read Dump data from I2C reads, otherwise only writes have data dumped.
510  */
511 void i2c_dump_msgs_rw(const struct device *dev, const struct i2c_msg *msgs, uint8_t num_msgs,
512 		      uint16_t addr, bool dump_read);
513 
514 /**
515  * @brief Dump out an I2C message, before it is executed.
516  *
517  * This is equivalent to:
518  *
519  *     i2c_dump_msgs_rw(dev, msgs, num_msgs, addr, false);
520  *
521  * The read messages' data isn't dumped.
522  *
523  * @param dev Target for the messages being sent. Its name will be printed in the log.
524  * @param msgs Array of messages to dump.
525  * @param num_msgs Number of messages to dump.
526  * @param addr Address of the I2C target device.
527  */
i2c_dump_msgs(const struct device * dev,const struct i2c_msg * msgs,uint8_t num_msgs,uint16_t addr)528 static inline void i2c_dump_msgs(const struct device *dev, const struct i2c_msg *msgs,
529 				 uint8_t num_msgs, uint16_t addr)
530 {
531 	i2c_dump_msgs_rw(dev, msgs, num_msgs, addr, false);
532 }
533 
534 #if defined(CONFIG_I2C_STATS) || defined(__DOXYGEN__)
535 
536 #include <zephyr/stats/stats.h>
537 
538 /** @cond INTERNAL_HIDDEN */
539 
540 STATS_SECT_START(i2c)
541 STATS_SECT_ENTRY32(bytes_read)
542 STATS_SECT_ENTRY32(bytes_written)
543 STATS_SECT_ENTRY32(message_count)
544 STATS_SECT_ENTRY32(transfer_call_count)
545 STATS_SECT_END;
546 
547 STATS_NAME_START(i2c)
548 STATS_NAME(i2c, bytes_read)
549 STATS_NAME(i2c, bytes_written)
550 STATS_NAME(i2c, message_count)
551 STATS_NAME(i2c, transfer_call_count)
552 STATS_NAME_END(i2c);
553 
554 /** @endcond */
555 
556 
557 /**
558  * @brief I2C specific device state which allows for i2c device class specific additions
559  */
560 struct i2c_device_state {
561 	struct device_state devstate;
562 	struct stats_i2c stats;
563 };
564 
565 /**
566  * @brief Updates the i2c stats for i2c transfers
567  *
568  * @param dev I2C device to update stats for
569  * @param msgs Array of struct i2c_msg
570  * @param num_msgs Number of i2c_msgs
571  */
i2c_xfer_stats(const struct device * dev,struct i2c_msg * msgs,uint8_t num_msgs)572 static inline void i2c_xfer_stats(const struct device *dev, struct i2c_msg *msgs,
573 				  uint8_t num_msgs)
574 {
575 	struct i2c_device_state *state =
576 		CONTAINER_OF(dev->state, struct i2c_device_state, devstate);
577 	uint32_t bytes_read = 0U;
578 	uint32_t bytes_written = 0U;
579 
580 	STATS_INC(state->stats, transfer_call_count);
581 	STATS_INCN(state->stats, message_count, num_msgs);
582 	for (uint8_t i = 0U; i < num_msgs; i++) {
583 		if (msgs[i].flags & I2C_MSG_READ) {
584 			bytes_read += msgs[i].len;
585 		} else {
586 			bytes_written += msgs[i].len;
587 		}
588 	}
589 	STATS_INCN(state->stats, bytes_read, bytes_read);
590 	STATS_INCN(state->stats, bytes_written, bytes_written);
591 }
592 
593 /** @cond INTERNAL_HIDDEN */
594 
595 /**
596  * @brief Define a statically allocated and section assigned i2c device state
597  */
598 #define Z_I2C_DEVICE_STATE_DEFINE(dev_id)				\
599 	static struct i2c_device_state Z_DEVICE_STATE_NAME(dev_id)	\
600 	__attribute__((__section__(".z_devstate")))
601 
602 /**
603  * @brief Define an i2c device init wrapper function
604  *
605  * This does device instance specific initialization of common data (such as stats)
606  * and calls the given init_fn
607  */
608 #define Z_I2C_INIT_FN(dev_id, init_fn)					\
609 	static inline int UTIL_CAT(dev_id, _init)(const struct device *dev) \
610 	{								\
611 		struct i2c_device_state *state =			\
612 			CONTAINER_OF(dev->state, struct i2c_device_state, devstate); \
613 		stats_init(&state->stats.s_hdr, STATS_SIZE_32, 4,	\
614 			   STATS_NAME_INIT_PARMS(i2c));			\
615 		stats_register(dev->name, &(state->stats.s_hdr));	\
616 		if (!is_null_no_warn(init_fn)) {			\
617 			return init_fn(dev);				\
618 		}							\
619 									\
620 		return 0;						\
621 	}
622 
623 /** @endcond */
624 
625 /**
626  * @brief Like DEVICE_DT_DEFINE() with I2C specifics.
627  *
628  * @details Defines a device which implements the I2C API. May
629  * generate a custom device_state container struct and init_fn
630  * wrapper when needed depending on I2C @kconfig{CONFIG_I2C_STATS}.
631  *
632  * @param node_id The devicetree node identifier.
633  *
634  * @param init_fn Name of the init function of the driver. Can be `NULL`.
635  *
636  * @param pm PM device resources reference (NULL if device does not use PM).
637  *
638  * @param data Pointer to the device's private data.
639  *
640  * @param config The address to the structure containing the
641  * configuration information for this instance of the driver.
642  *
643  * @param level The initialization level. See SYS_INIT() for
644  * details.
645  *
646  * @param prio Priority within the selected initialization level. See
647  * SYS_INIT() for details.
648  *
649  * @param api Provides an initial pointer to the API function struct
650  * used by the driver. Can be NULL.
651  */
652 #define I2C_DEVICE_DT_DEFINE(node_id, init_fn, pm, data, config, level,	\
653 			     prio, api, ...)				\
654 	Z_I2C_DEVICE_STATE_DEFINE(Z_DEVICE_DT_DEV_ID(node_id));		\
655 	Z_I2C_INIT_FN(Z_DEVICE_DT_DEV_ID(node_id), init_fn)		\
656 	Z_DEVICE_DEFINE(node_id, Z_DEVICE_DT_DEV_ID(node_id),		\
657 			DEVICE_DT_NAME(node_id),			\
658 			&UTIL_CAT(Z_DEVICE_DT_DEV_ID(node_id), _init),	\
659 			pm, data, config, level, prio, api,	\
660 			&(Z_DEVICE_STATE_NAME(Z_DEVICE_DT_DEV_ID(node_id)).devstate), \
661 			__VA_ARGS__)
662 
663 #else /* CONFIG_I2C_STATS */
664 
i2c_xfer_stats(const struct device * dev,struct i2c_msg * msgs,uint8_t num_msgs)665 static inline void i2c_xfer_stats(const struct device *dev, struct i2c_msg *msgs,
666 				  uint8_t num_msgs)
667 {
668 	ARG_UNUSED(dev);
669 	ARG_UNUSED(msgs);
670 	ARG_UNUSED(num_msgs);
671 }
672 
673 #define I2C_DEVICE_DT_DEFINE(node_id, init_fn, pm, data, config, level,	\
674 			     prio, api, ...)				\
675 	DEVICE_DT_DEFINE(node_id, init_fn, pm, data, config, level,	\
676 			 prio, api, __VA_ARGS__)
677 
678 #endif /* CONFIG_I2C_STATS */
679 
680 /**
681  * @brief Like I2C_DEVICE_DT_DEFINE() for an instance of a DT_DRV_COMPAT compatible
682  *
683  * @param inst instance number. This is replaced by
684  * <tt>DT_DRV_COMPAT(inst)</tt> in the call to I2C_DEVICE_DT_DEFINE().
685  *
686  * @param ... other parameters as expected by I2C_DEVICE_DT_DEFINE().
687  */
688 #define I2C_DEVICE_DT_INST_DEFINE(inst, ...)		\
689 	I2C_DEVICE_DT_DEFINE(DT_DRV_INST(inst), __VA_ARGS__)
690 
691 
692 /**
693  * @brief Configure operation of a host controller.
694  *
695  * @param dev Pointer to the device structure for the driver instance.
696  * @param dev_config Bit-packed 32-bit value to the device runtime configuration
697  * for the I2C controller.
698  *
699  * @retval 0 If successful.
700  * @retval -EIO General input / output error, failed to configure device.
701  */
702 __syscall int i2c_configure(const struct device *dev, uint32_t dev_config);
703 
z_impl_i2c_configure(const struct device * dev,uint32_t dev_config)704 static inline int z_impl_i2c_configure(const struct device *dev,
705 				       uint32_t dev_config)
706 {
707 	const struct i2c_driver_api *api =
708 		(const struct i2c_driver_api *)dev->api;
709 
710 	return api->configure(dev, dev_config);
711 }
712 
713 /**
714  * @brief Get configuration of a host controller.
715  *
716  * This routine provides a way to get current configuration. It is allowed to
717  * call the function before i2c_configure, because some I2C ports can be
718  * configured during init process. However, if the I2C port is not configured,
719  * i2c_get_config returns an error.
720  *
721  * i2c_get_config can return cached config or probe hardware, but it has to be
722  * up to date with current configuration.
723  *
724  * @param dev Pointer to the device structure for the driver instance.
725  * @param dev_config Pointer to return bit-packed 32-bit value of
726  * the I2C controller configuration.
727  *
728  * @retval 0 If successful.
729  * @retval -EIO General input / output error.
730  * @retval -ERANGE Configured I2C frequency is invalid.
731  * @retval -ENOSYS If get config is not implemented
732  */
733 __syscall int i2c_get_config(const struct device *dev, uint32_t *dev_config);
734 
z_impl_i2c_get_config(const struct device * dev,uint32_t * dev_config)735 static inline int z_impl_i2c_get_config(const struct device *dev, uint32_t *dev_config)
736 {
737 	const struct i2c_driver_api *api = (const struct i2c_driver_api *)dev->api;
738 
739 	if (api->get_config == NULL) {
740 		return -ENOSYS;
741 	}
742 
743 	return api->get_config(dev, dev_config);
744 }
745 
746 /**
747  * @brief Perform data transfer to another I2C device in controller mode.
748  *
749  * This routine provides a generic interface to perform data transfer
750  * to another I2C device synchronously. Use i2c_read()/i2c_write()
751  * for simple read or write.
752  *
753  * The array of message @a msgs must not be NULL.  The number of
754  * message @a num_msgs may be zero,in which case no transfer occurs.
755  *
756  * @note Not all scatter/gather transactions can be supported by all
757  * drivers.  As an example, a gather write (multiple consecutive
758  * `i2c_msg` buffers all configured for `I2C_MSG_WRITE`) may be packed
759  * into a single transaction by some drivers, but others may emit each
760  * fragment as a distinct write transaction, which will not produce
761  * the same behavior.  See the documentation of `struct i2c_msg` for
762  * limitations on support for multi-message bus transactions.
763  *
764  * @note The last message in the scatter/gather transaction implies a STOP
765  * whether or not it is explicitly set. This ensures the bus is in a good
766  * state for the next transaction which may be from a different call context.
767  *
768  * @param dev Pointer to the device structure for an I2C controller
769  * driver configured in controller mode.
770  * @param msgs Array of messages to transfer.
771  * @param num_msgs Number of messages to transfer.
772  * @param addr Address of the I2C target device.
773  *
774  * @retval 0 If successful.
775  * @retval -EIO General input / output error.
776  */
777 __syscall int i2c_transfer(const struct device *dev,
778 			   struct i2c_msg *msgs, uint8_t num_msgs,
779 			   uint16_t addr);
780 
z_impl_i2c_transfer(const struct device * dev,struct i2c_msg * msgs,uint8_t num_msgs,uint16_t addr)781 static inline int z_impl_i2c_transfer(const struct device *dev,
782 				      struct i2c_msg *msgs, uint8_t num_msgs,
783 				      uint16_t addr)
784 {
785 	const struct i2c_driver_api *api =
786 		(const struct i2c_driver_api *)dev->api;
787 
788 	if (!num_msgs) {
789 		return 0;
790 	}
791 
792 	msgs[num_msgs - 1].flags |= I2C_MSG_STOP;
793 
794 	int res =  api->transfer(dev, msgs, num_msgs, addr);
795 
796 	i2c_xfer_stats(dev, msgs, num_msgs);
797 
798 	if (IS_ENABLED(CONFIG_I2C_DUMP_MESSAGES)) {
799 		i2c_dump_msgs_rw(dev, msgs, num_msgs, addr, true);
800 	}
801 
802 	return res;
803 }
804 
805 #if defined(CONFIG_I2C_CALLBACK) || defined(__DOXYGEN__)
806 
807 /**
808  * @brief Perform data transfer to another I2C device in controller mode.
809  *
810  * This routine provides a generic interface to perform data transfer
811  * to another I2C device asynchronously with a callback completion.
812  *
813  * @see i2c_transfer()
814  * @funcprops \isr_ok
815  *
816  * @param dev Pointer to the device structure for an I2C controller
817  *            driver configured in controller mode.
818  * @param msgs Array of messages to transfer, must live until callback completes.
819  * @param num_msgs Number of messages to transfer.
820  * @param addr Address of the I2C target device.
821  * @param cb Function pointer for completion callback.
822  * @param userdata Userdata passed to callback.
823  *
824  * @retval 0 If successful.
825  * @retval -EIO General input / output error.
826  * @retval -ENOSYS If transfer async is not implemented
827  * @retval -EWOULDBLOCK If the device is temporarily busy doing another transfer
828  */
i2c_transfer_cb(const struct device * dev,struct i2c_msg * msgs,uint8_t num_msgs,uint16_t addr,i2c_callback_t cb,void * userdata)829 static inline int i2c_transfer_cb(const struct device *dev,
830 				  struct i2c_msg *msgs,
831 				  uint8_t num_msgs,
832 				  uint16_t addr,
833 				  i2c_callback_t cb,
834 				  void *userdata)
835 {
836 	const struct i2c_driver_api *api =
837 		(const struct i2c_driver_api *)dev->api;
838 
839 	if (api->transfer_cb == NULL) {
840 		return -ENOSYS;
841 	}
842 
843 	if (!num_msgs) {
844 		cb(dev, 0, userdata);
845 		return 0;
846 	}
847 
848 	msgs[num_msgs - 1].flags |= I2C_MSG_STOP;
849 
850 	return api->transfer_cb(dev, msgs, num_msgs, addr, cb, userdata);
851 }
852 
853 /**
854  * @brief Perform data transfer to another I2C device in master mode asynchronously.
855  *
856  * This is equivalent to:
857  *
858  *     i2c_transfer_cb(spec->bus, msgs, num_msgs, spec->addr, cb, userdata);
859  *
860  * @param spec I2C specification from devicetree.
861  * @param msgs Array of messages to transfer.
862  * @param num_msgs Number of messages to transfer.
863  * @param cb Function pointer for completion callback.
864  * @param userdata Userdata passed to callback.
865  *
866  * @return a value from i2c_transfer_cb()
867  */
i2c_transfer_cb_dt(const struct i2c_dt_spec * spec,struct i2c_msg * msgs,uint8_t num_msgs,i2c_callback_t cb,void * userdata)868 static inline int i2c_transfer_cb_dt(const struct i2c_dt_spec *spec,
869 				struct i2c_msg *msgs,
870 				uint8_t num_msgs,
871 				i2c_callback_t cb,
872 				void *userdata)
873 {
874 	return i2c_transfer_cb(spec->bus, msgs, num_msgs, spec->addr, cb, userdata);
875 }
876 
877 /**
878  * @brief Write then read data from an I2C device asynchronously.
879  *
880  * This supports the common operation "this is what I want", "now give
881  * it to me" transaction pair through a combined write-then-read bus
882  * transaction but using i2c_transfer_cb. This helper function expects
883  * caller to pass a message pointer with 2 and only 2 size.
884  *
885  * @param dev Pointer to the device structure for an I2C controller
886  * driver configured in master mode.
887  * @param msgs Array of messages to transfer.
888  * @param num_msgs Number of messages to transfer.
889  * @param addr Address of the I2C device
890  * @param write_buf Pointer to the data to be written
891  * @param num_write Number of bytes to write
892  * @param read_buf Pointer to storage for read data
893  * @param num_read Number of bytes to read
894  * @param cb Function pointer for completion callback.
895  * @param userdata Userdata passed to callback.
896  *
897  * @retval 0 if successful
898  * @retval negative on error.
899  */
i2c_write_read_cb(const struct device * dev,struct i2c_msg * msgs,uint8_t num_msgs,uint16_t addr,const void * write_buf,size_t num_write,void * read_buf,size_t num_read,i2c_callback_t cb,void * userdata)900 static inline int i2c_write_read_cb(const struct device *dev, struct i2c_msg *msgs,
901 				 uint8_t num_msgs, uint16_t addr, const void *write_buf,
902 				 size_t num_write, void *read_buf, size_t num_read,
903 				 i2c_callback_t cb, void *userdata)
904 {
905 	if ((msgs == NULL) || (num_msgs != 2)) {
906 		return -EINVAL;
907 	}
908 
909 	msgs[0].buf = (uint8_t *)write_buf;
910 	msgs[0].len = num_write;
911 	msgs[0].flags = I2C_MSG_WRITE;
912 
913 	msgs[1].buf = (uint8_t *)read_buf;
914 	msgs[1].len = num_read;
915 	msgs[1].flags = I2C_MSG_RESTART | I2C_MSG_READ | I2C_MSG_STOP;
916 
917 	return i2c_transfer_cb(dev, msgs, num_msgs, addr, cb, userdata);
918 }
919 
920 /**
921  * @brief Write then read data from an I2C device asynchronously.
922  *
923  * This is equivalent to:
924  *
925  *     i2c_write_read_cb(spec->bus, msgs, num_msgs,
926  *                    spec->addr, write_buf,
927  *                    num_write, read_buf, num_read);
928  *
929  * @param spec I2C specification from devicetree.
930  * @param msgs Array of messages to transfer.
931  * @param num_msgs Number of messages to transfer.
932  * @param write_buf Pointer to the data to be written
933  * @param num_write Number of bytes to write
934  * @param read_buf Pointer to storage for read data
935  * @param num_read Number of bytes to read
936  * @param cb Function pointer for completion callback.
937  * @param userdata Userdata passed to callback.
938  *
939  * @return a value from i2c_write_read_cb()
940  */
i2c_write_read_cb_dt(const struct i2c_dt_spec * spec,struct i2c_msg * msgs,uint8_t num_msgs,const void * write_buf,size_t num_write,void * read_buf,size_t num_read,i2c_callback_t cb,void * userdata)941 static inline int i2c_write_read_cb_dt(const struct i2c_dt_spec *spec, struct i2c_msg *msgs,
942 				       uint8_t num_msgs, const void *write_buf, size_t num_write,
943 				       void *read_buf, size_t num_read, i2c_callback_t cb,
944 				       void *userdata)
945 {
946 	return i2c_write_read_cb(spec->bus, msgs, num_msgs, spec->addr, write_buf, num_write,
947 				 read_buf, num_read, cb, userdata);
948 }
949 
950 #if defined(CONFIG_POLL) || defined(__DOXYGEN__)
951 
952 /** @cond INTERNAL_HIDDEN */
953 void z_i2c_transfer_signal_cb(const struct device *dev, int result, void *userdata);
954 /** @endcond */
955 
956 /**
957  * @brief Perform data transfer to another I2C device in controller mode.
958  *
959  * This routine provides a generic interface to perform data transfer
960  * to another I2C device asynchronously with a k_poll_signal completion.
961  *
962  * @see i2c_transfer_cb()
963  * @funcprops \isr_ok
964  *
965  * @param dev Pointer to the device structure for an I2C controller
966  *            driver configured in controller mode.
967  * @param msgs Array of messages to transfer, must live until callback completes.
968  * @param num_msgs Number of messages to transfer.
969  * @param addr Address of the I2C target device.
970  * @param sig Signal to notify of transfer completion.
971  *
972  * @retval 0 If successful.
973  * @retval -EIO General input / output error.
974  * @retval -ENOSYS If transfer async is not implemented
975  * @retval -EWOULDBLOCK If the device is temporarily busy doing another transfer
976  */
i2c_transfer_signal(const struct device * dev,struct i2c_msg * msgs,uint8_t num_msgs,uint16_t addr,struct k_poll_signal * sig)977 static inline int i2c_transfer_signal(const struct device *dev,
978 				 struct i2c_msg *msgs,
979 				 uint8_t num_msgs,
980 				 uint16_t addr,
981 				 struct k_poll_signal *sig)
982 {
983 	const struct i2c_driver_api *api = (const struct i2c_driver_api *)dev->api;
984 
985 	if (api->transfer_cb == NULL) {
986 		return -ENOSYS;
987 	}
988 
989 	return api->transfer_cb(dev, msgs, num_msgs, addr, z_i2c_transfer_signal_cb, sig);
990 }
991 
992 #endif /* CONFIG_POLL */
993 
994 #endif /* CONFIG_I2C_CALLBACK */
995 
996 
997 #if defined(CONFIG_I2C_RTIO) || defined(__DOXYGEN__)
998 
999 /**
1000  * @brief Submit request(s) to an I2C device with RTIO
1001  *
1002  * @param iodev_sqe Prepared submissions queue entry connected to an iodev
1003  *                  defined by I2C_DT_IODEV_DEFINE.
1004  */
i2c_iodev_submit(struct rtio_iodev_sqe * iodev_sqe)1005 static inline void i2c_iodev_submit(struct rtio_iodev_sqe *iodev_sqe)
1006 {
1007 	const struct i2c_dt_spec *dt_spec = (const struct i2c_dt_spec *)iodev_sqe->sqe.iodev->data;
1008 	const struct device *dev = dt_spec->bus;
1009 	const struct i2c_driver_api *api = (const struct i2c_driver_api *)dev->api;
1010 
1011 	api->iodev_submit(dt_spec->bus, iodev_sqe);
1012 }
1013 
1014 extern const struct rtio_iodev_api i2c_iodev_api;
1015 
1016 /**
1017  * @brief Define an iodev for a given dt node on the bus
1018  *
1019  * These do not need to be shared globally but doing so
1020  * will save a small amount of memory.
1021  *
1022  * @param name Symbolic name of the iodev to define
1023  * @param node_id Devicetree node identifier
1024  */
1025 #define I2C_DT_IODEV_DEFINE(name, node_id)					\
1026 	const struct i2c_dt_spec _i2c_dt_spec_##name =				\
1027 		I2C_DT_SPEC_GET(node_id);					\
1028 	RTIO_IODEV_DEFINE(name, &i2c_iodev_api, (void *)&_i2c_dt_spec_##name)
1029 
1030 /**
1031  * @brief Define an iodev for a given i2c device on a bus
1032  *
1033  * These do not need to be shared globally but doing so
1034  * will save a small amount of memory.
1035  *
1036  * @param name Symbolic name of the iodev to define
1037  * @param _bus Node ID for I2C bus
1038  * @param _addr I2C target address
1039  */
1040 #define I2C_IODEV_DEFINE(name, _bus, _addr)                                     \
1041 	const struct i2c_dt_spec _i2c_dt_spec_##name = {                        \
1042 		.bus = DEVICE_DT_GET(_bus),                                     \
1043 		.addr = _addr,                                                  \
1044 	};                                                                      \
1045 	RTIO_IODEV_DEFINE(name, &i2c_iodev_api, (void *)&_i2c_dt_spec_##name)
1046 
1047 /**
1048  * @brief Copy the i2c_msgs into a set of RTIO requests
1049  *
1050  * @param r RTIO context
1051  * @param iodev RTIO IODev to target for the submissions
1052  * @param msgs Array of messages
1053  * @param num_msgs Number of i2c msgs in array
1054  *
1055  * @retval sqe Last submission in the queue added
1056  * @retval NULL Not enough memory in the context to copy the requests
1057  */
1058 struct rtio_sqe *i2c_rtio_copy(struct rtio *r,
1059 			       struct rtio_iodev *iodev,
1060 			       const struct i2c_msg *msgs,
1061 			       uint8_t num_msgs);
1062 
1063 #endif /* CONFIG_I2C_RTIO */
1064 
1065 /**
1066  * @brief Perform data transfer to another I2C device in controller mode.
1067  *
1068  * This is equivalent to:
1069  *
1070  *     i2c_transfer(spec->bus, msgs, num_msgs, spec->addr);
1071  *
1072  * @param spec I2C specification from devicetree.
1073  * @param msgs Array of messages to transfer.
1074  * @param num_msgs Number of messages to transfer.
1075  *
1076  * @return a value from i2c_transfer()
1077  */
i2c_transfer_dt(const struct i2c_dt_spec * spec,struct i2c_msg * msgs,uint8_t num_msgs)1078 static inline int i2c_transfer_dt(const struct i2c_dt_spec *spec,
1079 				  struct i2c_msg *msgs, uint8_t num_msgs)
1080 {
1081 	return i2c_transfer(spec->bus, msgs, num_msgs, spec->addr);
1082 }
1083 
1084 /**
1085  * @brief Recover the I2C bus
1086  *
1087  * Attempt to recover the I2C bus.
1088  *
1089  * @param dev Pointer to the device structure for an I2C controller
1090  * driver configured in controller mode.
1091  * @retval 0 If successful
1092  * @retval -EBUSY If bus is not clear after recovery attempt.
1093  * @retval -EIO General input / output error.
1094  * @retval -ENOSYS If bus recovery is not implemented
1095  */
1096 __syscall int i2c_recover_bus(const struct device *dev);
1097 
z_impl_i2c_recover_bus(const struct device * dev)1098 static inline int z_impl_i2c_recover_bus(const struct device *dev)
1099 {
1100 	const struct i2c_driver_api *api =
1101 		(const struct i2c_driver_api *)dev->api;
1102 
1103 	if (api->recover_bus == NULL) {
1104 		return -ENOSYS;
1105 	}
1106 
1107 	return api->recover_bus(dev);
1108 }
1109 
1110 /**
1111  * @brief Registers the provided config as Target device of a controller.
1112  *
1113  * Enable I2C target mode for the 'dev' I2C bus driver using the provided
1114  * 'config' struct containing the functions and parameters to send bus
1115  * events. The I2C target will be registered at the address provided as 'address'
1116  * struct member. Addressing mode - 7 or 10 bit - depends on the 'flags'
1117  * struct member. Any I2C bus events related to the target mode will be passed
1118  * onto I2C target device driver via a set of callback functions provided in
1119  * the 'callbacks' struct member.
1120  *
1121  * Most of the existing hardware allows simultaneous support for controller
1122  * and target mode. This is however not guaranteed.
1123  *
1124  * @param dev Pointer to the device structure for an I2C controller
1125  * driver configured in target mode.
1126  * @param cfg Config struct with functions and parameters used by the I2C driver
1127  * to send bus events
1128  *
1129  * @retval 0 Is successful
1130  * @retval -EINVAL If parameters are invalid
1131  * @retval -EIO General input / output error.
1132  * @retval -ENOSYS If target mode is not implemented
1133  */
i2c_target_register(const struct device * dev,struct i2c_target_config * cfg)1134 static inline int i2c_target_register(const struct device *dev,
1135 				     struct i2c_target_config *cfg)
1136 {
1137 	const struct i2c_driver_api *api =
1138 		(const struct i2c_driver_api *)dev->api;
1139 
1140 	if (api->target_register == NULL) {
1141 		return -ENOSYS;
1142 	}
1143 
1144 	return api->target_register(dev, cfg);
1145 }
1146 
1147 /**
1148  * @brief Unregisters the provided config as Target device
1149  *
1150  * This routine disables I2C target mode for the 'dev' I2C bus driver using
1151  * the provided 'config' struct containing the functions and parameters
1152  * to send bus events.
1153  *
1154  * @param dev Pointer to the device structure for an I2C controller
1155  * driver configured in target mode.
1156  * @param cfg Config struct with functions and parameters used by the I2C driver
1157  * to send bus events
1158  *
1159  * @retval 0 Is successful
1160  * @retval -EINVAL If parameters are invalid
1161  * @retval -ENOSYS If target mode is not implemented
1162  */
i2c_target_unregister(const struct device * dev,struct i2c_target_config * cfg)1163 static inline int i2c_target_unregister(const struct device *dev,
1164 				       struct i2c_target_config *cfg)
1165 {
1166 	const struct i2c_driver_api *api =
1167 		(const struct i2c_driver_api *)dev->api;
1168 
1169 	if (api->target_unregister == NULL) {
1170 		return -ENOSYS;
1171 	}
1172 
1173 	return api->target_unregister(dev, cfg);
1174 }
1175 
1176 /**
1177  * @brief Instructs the I2C Target device to register itself to the I2C Controller
1178  *
1179  * This routine instructs the I2C Target device to register itself to the I2C
1180  * Controller via its parent controller's i2c_target_register() API.
1181  *
1182  * @param dev Pointer to the device structure for the I2C target
1183  * device (not itself an I2C controller).
1184  *
1185  * @retval 0 Is successful
1186  * @retval -EINVAL If parameters are invalid
1187  * @retval -EIO General input / output error.
1188  */
1189 __syscall int i2c_target_driver_register(const struct device *dev);
1190 
z_impl_i2c_target_driver_register(const struct device * dev)1191 static inline int z_impl_i2c_target_driver_register(const struct device *dev)
1192 {
1193 	const struct i2c_target_driver_api *api =
1194 		(const struct i2c_target_driver_api *)dev->api;
1195 
1196 	return api->driver_register(dev);
1197 }
1198 
1199 /**
1200  * @brief Instructs the I2C Target device to unregister itself from the I2C
1201  * Controller
1202  *
1203  * This routine instructs the I2C Target device to unregister itself from the I2C
1204  * Controller via its parent controller's i2c_target_register() API.
1205  *
1206  * @param dev Pointer to the device structure for the I2C target
1207  * device (not itself an I2C controller).
1208  *
1209  * @retval 0 Is successful
1210  * @retval -EINVAL If parameters are invalid
1211  */
1212 __syscall int i2c_target_driver_unregister(const struct device *dev);
1213 
z_impl_i2c_target_driver_unregister(const struct device * dev)1214 static inline int z_impl_i2c_target_driver_unregister(const struct device *dev)
1215 {
1216 	const struct i2c_target_driver_api *api =
1217 		(const struct i2c_target_driver_api *)dev->api;
1218 
1219 	return api->driver_unregister(dev);
1220 }
1221 
1222 /*
1223  * Derived i2c APIs -- all implemented in terms of i2c_transfer()
1224  */
1225 
1226 /**
1227  * @brief Write a set amount of data to an I2C device.
1228  *
1229  * This routine writes a set amount of data synchronously.
1230  *
1231  * @param dev Pointer to the device structure for an I2C controller
1232  * driver configured in controller mode.
1233  * @param buf Memory pool from which the data is transferred.
1234  * @param num_bytes Number of bytes to write.
1235  * @param addr Address to the target I2C device for writing.
1236  *
1237  * @retval 0 If successful.
1238  * @retval -EIO General input / output error.
1239  */
i2c_write(const struct device * dev,const uint8_t * buf,uint32_t num_bytes,uint16_t addr)1240 static inline int i2c_write(const struct device *dev, const uint8_t *buf,
1241 			    uint32_t num_bytes, uint16_t addr)
1242 {
1243 	struct i2c_msg msg;
1244 
1245 	msg.buf = (uint8_t *)buf;
1246 	msg.len = num_bytes;
1247 	msg.flags = I2C_MSG_WRITE | I2C_MSG_STOP;
1248 
1249 	return i2c_transfer(dev, &msg, 1, addr);
1250 }
1251 
1252 /**
1253  * @brief Write a set amount of data to an I2C device.
1254  *
1255  * This is equivalent to:
1256  *
1257  *     i2c_write(spec->bus, buf, num_bytes, spec->addr);
1258  *
1259  * @param spec I2C specification from devicetree.
1260  * @param buf Memory pool from which the data is transferred.
1261  * @param num_bytes Number of bytes to write.
1262  *
1263  * @return a value from i2c_write()
1264  */
i2c_write_dt(const struct i2c_dt_spec * spec,const uint8_t * buf,uint32_t num_bytes)1265 static inline int i2c_write_dt(const struct i2c_dt_spec *spec,
1266 			       const uint8_t *buf, uint32_t num_bytes)
1267 {
1268 	return i2c_write(spec->bus, buf, num_bytes, spec->addr);
1269 }
1270 
1271 /**
1272  * @brief Read a set amount of data from an I2C device.
1273  *
1274  * This routine reads a set amount of data synchronously.
1275  *
1276  * @param dev Pointer to the device structure for an I2C controller
1277  * driver configured in controller mode.
1278  * @param buf Memory pool that stores the retrieved data.
1279  * @param num_bytes Number of bytes to read.
1280  * @param addr Address of the I2C device being read.
1281  *
1282  * @retval 0 If successful.
1283  * @retval -EIO General input / output error.
1284  */
i2c_read(const struct device * dev,uint8_t * buf,uint32_t num_bytes,uint16_t addr)1285 static inline int i2c_read(const struct device *dev, uint8_t *buf,
1286 			   uint32_t num_bytes, uint16_t addr)
1287 {
1288 	struct i2c_msg msg;
1289 
1290 	msg.buf = buf;
1291 	msg.len = num_bytes;
1292 	msg.flags = I2C_MSG_READ | I2C_MSG_STOP;
1293 
1294 	return i2c_transfer(dev, &msg, 1, addr);
1295 }
1296 
1297 /**
1298  * @brief Read a set amount of data from an I2C device.
1299  *
1300  * This is equivalent to:
1301  *
1302  *     i2c_read(spec->bus, buf, num_bytes, spec->addr);
1303  *
1304  * @param spec I2C specification from devicetree.
1305  * @param buf Memory pool that stores the retrieved data.
1306  * @param num_bytes Number of bytes to read.
1307  *
1308  * @return a value from i2c_read()
1309  */
i2c_read_dt(const struct i2c_dt_spec * spec,uint8_t * buf,uint32_t num_bytes)1310 static inline int i2c_read_dt(const struct i2c_dt_spec *spec,
1311 			      uint8_t *buf, uint32_t num_bytes)
1312 {
1313 	return i2c_read(spec->bus, buf, num_bytes, spec->addr);
1314 }
1315 
1316 /**
1317  * @brief Write then read data from an I2C device.
1318  *
1319  * This supports the common operation "this is what I want", "now give
1320  * it to me" transaction pair through a combined write-then-read bus
1321  * transaction.
1322  *
1323  * @param dev Pointer to the device structure for an I2C controller
1324  * driver configured in controller mode.
1325  * @param addr Address of the I2C device
1326  * @param write_buf Pointer to the data to be written
1327  * @param num_write Number of bytes to write
1328  * @param read_buf Pointer to storage for read data
1329  * @param num_read Number of bytes to read
1330  *
1331  * @retval 0 if successful
1332  * @retval negative on error.
1333  */
i2c_write_read(const struct device * dev,uint16_t addr,const void * write_buf,size_t num_write,void * read_buf,size_t num_read)1334 static inline int i2c_write_read(const struct device *dev, uint16_t addr,
1335 				 const void *write_buf, size_t num_write,
1336 				 void *read_buf, size_t num_read)
1337 {
1338 	struct i2c_msg msg[2];
1339 
1340 	msg[0].buf = (uint8_t *)write_buf;
1341 	msg[0].len = num_write;
1342 	msg[0].flags = I2C_MSG_WRITE;
1343 
1344 	msg[1].buf = (uint8_t *)read_buf;
1345 	msg[1].len = num_read;
1346 	msg[1].flags = I2C_MSG_RESTART | I2C_MSG_READ | I2C_MSG_STOP;
1347 
1348 	return i2c_transfer(dev, msg, 2, addr);
1349 }
1350 
1351 /**
1352  * @brief Write then read data from an I2C device.
1353  *
1354  * This is equivalent to:
1355  *
1356  *     i2c_write_read(spec->bus, spec->addr,
1357  *                    write_buf, num_write,
1358  *                    read_buf, num_read);
1359  *
1360  * @param spec I2C specification from devicetree.
1361  * @param write_buf Pointer to the data to be written
1362  * @param num_write Number of bytes to write
1363  * @param read_buf Pointer to storage for read data
1364  * @param num_read Number of bytes to read
1365  *
1366  * @return a value from i2c_write_read()
1367  */
i2c_write_read_dt(const struct i2c_dt_spec * spec,const void * write_buf,size_t num_write,void * read_buf,size_t num_read)1368 static inline int i2c_write_read_dt(const struct i2c_dt_spec *spec,
1369 				    const void *write_buf, size_t num_write,
1370 				    void *read_buf, size_t num_read)
1371 {
1372 	return i2c_write_read(spec->bus, spec->addr,
1373 			      write_buf, num_write,
1374 			      read_buf, num_read);
1375 }
1376 
1377 /**
1378  * @brief Read multiple bytes from an internal address of an I2C device.
1379  *
1380  * This routine reads multiple bytes from an internal address of an
1381  * I2C device synchronously.
1382  *
1383  * Instances of this may be replaced by i2c_write_read().
1384  *
1385  * @param dev Pointer to the device structure for an I2C controller
1386  * driver configured in controller mode.
1387  * @param dev_addr Address of the I2C device for reading.
1388  * @param start_addr Internal address from which the data is being read.
1389  * @param buf Memory pool that stores the retrieved data.
1390  * @param num_bytes Number of bytes being read.
1391  *
1392  * @retval 0 If successful.
1393  * @retval -EIO General input / output error.
1394  */
i2c_burst_read(const struct device * dev,uint16_t dev_addr,uint8_t start_addr,uint8_t * buf,uint32_t num_bytes)1395 static inline int i2c_burst_read(const struct device *dev,
1396 				 uint16_t dev_addr,
1397 				 uint8_t start_addr,
1398 				 uint8_t *buf,
1399 				 uint32_t num_bytes)
1400 {
1401 	return i2c_write_read(dev, dev_addr,
1402 			      &start_addr, sizeof(start_addr),
1403 			      buf, num_bytes);
1404 }
1405 
1406 /**
1407  * @brief Read multiple bytes from an internal address of an I2C device.
1408  *
1409  * This is equivalent to:
1410  *
1411  *     i2c_burst_read(spec->bus, spec->addr, start_addr, buf, num_bytes);
1412  *
1413  * @param spec I2C specification from devicetree.
1414  * @param start_addr Internal address from which the data is being read.
1415  * @param buf Memory pool that stores the retrieved data.
1416  * @param num_bytes Number of bytes to read.
1417  *
1418  * @return a value from i2c_burst_read()
1419  */
i2c_burst_read_dt(const struct i2c_dt_spec * spec,uint8_t start_addr,uint8_t * buf,uint32_t num_bytes)1420 static inline int i2c_burst_read_dt(const struct i2c_dt_spec *spec,
1421 				    uint8_t start_addr,
1422 				    uint8_t *buf,
1423 				    uint32_t num_bytes)
1424 {
1425 	return i2c_burst_read(spec->bus, spec->addr,
1426 			      start_addr, buf, num_bytes);
1427 }
1428 
1429 /**
1430  * @brief Write multiple bytes to an internal address of an I2C device.
1431  *
1432  * This routine writes multiple bytes to an internal address of an
1433  * I2C device synchronously.
1434  *
1435  * @warning The combined write synthesized by this API may not be
1436  * supported on all I2C devices.  Uses of this API may be made more
1437  * portable by replacing them with calls to i2c_write() passing a
1438  * buffer containing the combined address and data.
1439  *
1440  * @param dev Pointer to the device structure for an I2C controller
1441  * driver configured in controller mode.
1442  * @param dev_addr Address of the I2C device for writing.
1443  * @param start_addr Internal address to which the data is being written.
1444  * @param buf Memory pool from which the data is transferred.
1445  * @param num_bytes Number of bytes being written.
1446  *
1447  * @retval 0 If successful.
1448  * @retval -EIO General input / output error.
1449  */
i2c_burst_write(const struct device * dev,uint16_t dev_addr,uint8_t start_addr,const uint8_t * buf,uint32_t num_bytes)1450 static inline int i2c_burst_write(const struct device *dev,
1451 				  uint16_t dev_addr,
1452 				  uint8_t start_addr,
1453 				  const uint8_t *buf,
1454 				  uint32_t num_bytes)
1455 {
1456 	struct i2c_msg msg[2];
1457 
1458 	msg[0].buf = &start_addr;
1459 	msg[0].len = 1U;
1460 	msg[0].flags = I2C_MSG_WRITE;
1461 
1462 	msg[1].buf = (uint8_t *)buf;
1463 	msg[1].len = num_bytes;
1464 	msg[1].flags = I2C_MSG_WRITE | I2C_MSG_STOP;
1465 
1466 	return i2c_transfer(dev, msg, 2, dev_addr);
1467 }
1468 
1469 /**
1470  * @brief Write multiple bytes to an internal address of an I2C device.
1471  *
1472  * This is equivalent to:
1473  *
1474  *     i2c_burst_write(spec->bus, spec->addr, start_addr, buf, num_bytes);
1475  *
1476  * @param spec I2C specification from devicetree.
1477  * @param start_addr Internal address to which the data is being written.
1478  * @param buf Memory pool from which the data is transferred.
1479  * @param num_bytes Number of bytes being written.
1480  *
1481  * @return a value from i2c_burst_write()
1482  */
i2c_burst_write_dt(const struct i2c_dt_spec * spec,uint8_t start_addr,const uint8_t * buf,uint32_t num_bytes)1483 static inline int i2c_burst_write_dt(const struct i2c_dt_spec *spec,
1484 				     uint8_t start_addr,
1485 				     const uint8_t *buf,
1486 				     uint32_t num_bytes)
1487 {
1488 	return i2c_burst_write(spec->bus, spec->addr,
1489 			       start_addr, buf, num_bytes);
1490 }
1491 
1492 /**
1493  * @brief Read internal register of an I2C device.
1494  *
1495  * This routine reads the value of an 8-bit internal register of an I2C
1496  * device synchronously.
1497  *
1498  * @param dev Pointer to the device structure for an I2C controller
1499  * driver configured in controller mode.
1500  * @param dev_addr Address of the I2C device for reading.
1501  * @param reg_addr Address of the internal register being read.
1502  * @param value Memory pool that stores the retrieved register value.
1503  *
1504  * @retval 0 If successful.
1505  * @retval -EIO General input / output error.
1506  */
i2c_reg_read_byte(const struct device * dev,uint16_t dev_addr,uint8_t reg_addr,uint8_t * value)1507 static inline int i2c_reg_read_byte(const struct device *dev,
1508 				    uint16_t dev_addr,
1509 				    uint8_t reg_addr, uint8_t *value)
1510 {
1511 	return i2c_write_read(dev, dev_addr,
1512 			      &reg_addr, sizeof(reg_addr),
1513 			      value, sizeof(*value));
1514 }
1515 
1516 /**
1517  * @brief Read internal register of an I2C device.
1518  *
1519  * This is equivalent to:
1520  *
1521  *     i2c_reg_read_byte(spec->bus, spec->addr, reg_addr, value);
1522  *
1523  * @param spec I2C specification from devicetree.
1524  * @param reg_addr Address of the internal register being read.
1525  * @param value Memory pool that stores the retrieved register value.
1526  *
1527  * @return a value from i2c_reg_read_byte()
1528  */
i2c_reg_read_byte_dt(const struct i2c_dt_spec * spec,uint8_t reg_addr,uint8_t * value)1529 static inline int i2c_reg_read_byte_dt(const struct i2c_dt_spec *spec,
1530 				       uint8_t reg_addr, uint8_t *value)
1531 {
1532 	return i2c_reg_read_byte(spec->bus, spec->addr, reg_addr, value);
1533 }
1534 
1535 /**
1536  * @brief Write internal register of an I2C device.
1537  *
1538  * This routine writes a value to an 8-bit internal register of an I2C
1539  * device synchronously.
1540  *
1541  * @note This function internally combines the register and value into
1542  * a single bus transaction.
1543  *
1544  * @param dev Pointer to the device structure for an I2C controller
1545  * driver configured in controller mode.
1546  * @param dev_addr Address of the I2C device for writing.
1547  * @param reg_addr Address of the internal register being written.
1548  * @param value Value to be written to internal register.
1549  *
1550  * @retval 0 If successful.
1551  * @retval -EIO General input / output error.
1552  */
i2c_reg_write_byte(const struct device * dev,uint16_t dev_addr,uint8_t reg_addr,uint8_t value)1553 static inline int i2c_reg_write_byte(const struct device *dev,
1554 				     uint16_t dev_addr,
1555 				     uint8_t reg_addr, uint8_t value)
1556 {
1557 	uint8_t tx_buf[2] = {reg_addr, value};
1558 
1559 	return i2c_write(dev, tx_buf, 2, dev_addr);
1560 }
1561 
1562 /**
1563  * @brief Write internal register of an I2C device.
1564  *
1565  * This is equivalent to:
1566  *
1567  *     i2c_reg_write_byte(spec->bus, spec->addr, reg_addr, value);
1568  *
1569  * @param spec I2C specification from devicetree.
1570  * @param reg_addr Address of the internal register being written.
1571  * @param value Value to be written to internal register.
1572  *
1573  * @return a value from i2c_reg_write_byte()
1574  */
i2c_reg_write_byte_dt(const struct i2c_dt_spec * spec,uint8_t reg_addr,uint8_t value)1575 static inline int i2c_reg_write_byte_dt(const struct i2c_dt_spec *spec,
1576 					uint8_t reg_addr, uint8_t value)
1577 {
1578 	return i2c_reg_write_byte(spec->bus, spec->addr, reg_addr, value);
1579 }
1580 
1581 /**
1582  * @brief Update internal register of an I2C device.
1583  *
1584  * This routine updates the value of a set of bits from an 8-bit internal
1585  * register of an I2C device synchronously.
1586  *
1587  * @note If the calculated new register value matches the value that
1588  * was read this function will not generate a write operation.
1589  *
1590  * @param dev Pointer to the device structure for an I2C controller
1591  * driver configured in controller mode.
1592  * @param dev_addr Address of the I2C device for updating.
1593  * @param reg_addr Address of the internal register being updated.
1594  * @param mask Bitmask for updating internal register.
1595  * @param value Value for updating internal register.
1596  *
1597  * @retval 0 If successful.
1598  * @retval -EIO General input / output error.
1599  */
i2c_reg_update_byte(const struct device * dev,uint8_t dev_addr,uint8_t reg_addr,uint8_t mask,uint8_t value)1600 static inline int i2c_reg_update_byte(const struct device *dev,
1601 				      uint8_t dev_addr,
1602 				      uint8_t reg_addr, uint8_t mask,
1603 				      uint8_t value)
1604 {
1605 	uint8_t old_value, new_value;
1606 	int rc;
1607 
1608 	rc = i2c_reg_read_byte(dev, dev_addr, reg_addr, &old_value);
1609 	if (rc != 0) {
1610 		return rc;
1611 	}
1612 
1613 	new_value = (old_value & ~mask) | (value & mask);
1614 	if (new_value == old_value) {
1615 		return 0;
1616 	}
1617 
1618 	return i2c_reg_write_byte(dev, dev_addr, reg_addr, new_value);
1619 }
1620 
1621 /**
1622  * @brief Update internal register of an I2C device.
1623  *
1624  * This is equivalent to:
1625  *
1626  *     i2c_reg_update_byte(spec->bus, spec->addr, reg_addr, mask, value);
1627  *
1628  * @param spec I2C specification from devicetree.
1629  * @param reg_addr Address of the internal register being updated.
1630  * @param mask Bitmask for updating internal register.
1631  * @param value Value for updating internal register.
1632  *
1633  * @return a value from i2c_reg_update_byte()
1634  */
i2c_reg_update_byte_dt(const struct i2c_dt_spec * spec,uint8_t reg_addr,uint8_t mask,uint8_t value)1635 static inline int i2c_reg_update_byte_dt(const struct i2c_dt_spec *spec,
1636 					 uint8_t reg_addr, uint8_t mask,
1637 					 uint8_t value)
1638 {
1639 	return i2c_reg_update_byte(spec->bus, spec->addr,
1640 				   reg_addr, mask, value);
1641 }
1642 
1643 #ifdef __cplusplus
1644 }
1645 #endif
1646 
1647 /**
1648  * @}
1649  */
1650 
1651 #include <zephyr/syscalls/i2c.h>
1652 
1653 #endif /* ZEPHYR_INCLUDE_DRIVERS_I2C_H_ */
1654