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 a read operation
478  * @return false if the I2C message is a write operation
479  */
i2c_is_read_op(const struct i2c_msg * msg)480 static inline bool i2c_is_read_op(const struct i2c_msg *msg)
481 {
482 	return (msg->flags & I2C_MSG_READ) == I2C_MSG_READ;
483 }
484 
485 /**
486  * @brief Check if the current message includes a stop.
487  *
488  * @param msg The message to check
489  * @return true if the I2C message includes a stop
490  * @return false if the I2C message includes a stop
491  */
i2c_is_stop_op(const struct i2c_msg * msg)492 static inline bool i2c_is_stop_op(const struct i2c_msg *msg)
493 {
494 	return (msg->flags & I2C_MSG_STOP) == I2C_MSG_STOP;
495 }
496 
497 /**
498  * @brief Dump out an I2C message
499  *
500  * Dumps out a list of I2C messages. For any that are writes (W), the data is
501  * displayed in hex. Setting dump_read will dump the data for read messages too,
502  * which only makes sense when called after the messages have been processed.
503  *
504  * It looks something like this (with name "testing"):
505  *
506  * @code
507  * D: I2C msg: testing, addr=56
508  * D:    W len=01: 06
509  * D:    W len=0e:
510  * D: contents:
511  * D: 00 01 02 03 04 05 06 07 |........
512  * D: 08 09 0a 0b 0c 0d       |......
513  * D:    W len=01: 0f
514  * D:    R len=01: 6c
515  * @endcode
516  *
517  * @param dev Target for the messages being sent. Its name will be printed in the log.
518  * @param msgs Array of messages to dump.
519  * @param num_msgs Number of messages to dump.
520  * @param addr Address of the I2C target device.
521  * @param dump_read Dump data from I2C reads, otherwise only writes have data dumped.
522  */
523 void i2c_dump_msgs_rw(const struct device *dev, const struct i2c_msg *msgs, uint8_t num_msgs,
524 		      uint16_t addr, bool dump_read);
525 
526 /**
527  * @brief Dump out an I2C message, before it is executed.
528  *
529  * This is equivalent to:
530  *
531  *     i2c_dump_msgs_rw(dev, msgs, num_msgs, addr, false);
532  *
533  * The read messages' data isn't dumped.
534  *
535  * @param dev Target for the messages being sent. Its name will be printed in the log.
536  * @param msgs Array of messages to dump.
537  * @param num_msgs Number of messages to dump.
538  * @param addr Address of the I2C target device.
539  */
i2c_dump_msgs(const struct device * dev,const struct i2c_msg * msgs,uint8_t num_msgs,uint16_t addr)540 static inline void i2c_dump_msgs(const struct device *dev, const struct i2c_msg *msgs,
541 				 uint8_t num_msgs, uint16_t addr)
542 {
543 	i2c_dump_msgs_rw(dev, msgs, num_msgs, addr, false);
544 }
545 
546 #if defined(CONFIG_I2C_STATS) || defined(__DOXYGEN__)
547 
548 #include <zephyr/stats/stats.h>
549 
550 /** @cond INTERNAL_HIDDEN */
551 
552 STATS_SECT_START(i2c)
553 STATS_SECT_ENTRY32(bytes_read)
554 STATS_SECT_ENTRY32(bytes_written)
555 STATS_SECT_ENTRY32(message_count)
556 STATS_SECT_ENTRY32(transfer_call_count)
557 STATS_SECT_END;
558 
559 STATS_NAME_START(i2c)
560 STATS_NAME(i2c, bytes_read)
561 STATS_NAME(i2c, bytes_written)
562 STATS_NAME(i2c, message_count)
563 STATS_NAME(i2c, transfer_call_count)
564 STATS_NAME_END(i2c);
565 
566 /** @endcond */
567 
568 
569 /**
570  * @brief I2C specific device state which allows for i2c device class specific additions
571  */
572 struct i2c_device_state {
573 	struct device_state devstate;
574 	struct stats_i2c stats;
575 };
576 
577 /**
578  * @brief Updates the i2c stats for i2c transfers
579  *
580  * @param dev I2C device to update stats for
581  * @param msgs Array of struct i2c_msg
582  * @param num_msgs Number of i2c_msgs
583  */
i2c_xfer_stats(const struct device * dev,struct i2c_msg * msgs,uint8_t num_msgs)584 static inline void i2c_xfer_stats(const struct device *dev, struct i2c_msg *msgs,
585 				  uint8_t num_msgs)
586 {
587 	struct i2c_device_state *state =
588 		CONTAINER_OF(dev->state, struct i2c_device_state, devstate);
589 	uint32_t bytes_read = 0U;
590 	uint32_t bytes_written = 0U;
591 
592 	STATS_INC(state->stats, transfer_call_count);
593 	STATS_INCN(state->stats, message_count, num_msgs);
594 	for (uint8_t i = 0U; i < num_msgs; i++) {
595 		if (msgs[i].flags & I2C_MSG_READ) {
596 			bytes_read += msgs[i].len;
597 		} else {
598 			bytes_written += msgs[i].len;
599 		}
600 	}
601 	STATS_INCN(state->stats, bytes_read, bytes_read);
602 	STATS_INCN(state->stats, bytes_written, bytes_written);
603 }
604 
605 /** @cond INTERNAL_HIDDEN */
606 
607 /**
608  * @brief Define a statically allocated and section assigned i2c device state
609  */
610 #define Z_I2C_DEVICE_STATE_DEFINE(dev_id)				\
611 	static struct i2c_device_state Z_DEVICE_STATE_NAME(dev_id)	\
612 	__attribute__((__section__(".z_devstate")))
613 
614 /**
615  * @brief Define an i2c device init wrapper function
616  *
617  * This does device instance specific initialization of common data (such as stats)
618  * and calls the given init_fn
619  */
620 #define Z_I2C_INIT_FN(dev_id, init_fn)					\
621 	static inline int UTIL_CAT(dev_id, _init)(const struct device *dev) \
622 	{								\
623 		struct i2c_device_state *state =			\
624 			CONTAINER_OF(dev->state, struct i2c_device_state, devstate); \
625 		stats_init(&state->stats.s_hdr, STATS_SIZE_32, 4,	\
626 			   STATS_NAME_INIT_PARMS(i2c));			\
627 		stats_register(dev->name, &(state->stats.s_hdr));	\
628 		if (!is_null_no_warn(init_fn)) {			\
629 			return init_fn(dev);				\
630 		}							\
631 									\
632 		return 0;						\
633 	}
634 
635 /** @endcond */
636 
637 /**
638  * @brief Like DEVICE_DT_DEFINE() with I2C specifics.
639  *
640  * @details Defines a device which implements the I2C API. May
641  * generate a custom device_state container struct and init_fn
642  * wrapper when needed depending on I2C @kconfig{CONFIG_I2C_STATS}.
643  *
644  * @param node_id The devicetree node identifier.
645  *
646  * @param init_fn Name of the init function of the driver. Can be `NULL`.
647  *
648  * @param pm PM device resources reference (NULL if device does not use PM).
649  *
650  * @param data Pointer to the device's private data.
651  *
652  * @param config The address to the structure containing the
653  * configuration information for this instance of the driver.
654  *
655  * @param level The initialization level. See SYS_INIT() for
656  * details.
657  *
658  * @param prio Priority within the selected initialization level. See
659  * SYS_INIT() for details.
660  *
661  * @param api Provides an initial pointer to the API function struct
662  * used by the driver. Can be NULL.
663  */
664 #define I2C_DEVICE_DT_DEFINE(node_id, init_fn, pm, data, config, level,	\
665 			     prio, api, ...)				\
666 	Z_I2C_DEVICE_STATE_DEFINE(Z_DEVICE_DT_DEV_ID(node_id));		\
667 	Z_I2C_INIT_FN(Z_DEVICE_DT_DEV_ID(node_id), init_fn)		\
668 	Z_DEVICE_DEFINE(node_id, Z_DEVICE_DT_DEV_ID(node_id),		\
669 			DEVICE_DT_NAME(node_id),			\
670 			&UTIL_CAT(Z_DEVICE_DT_DEV_ID(node_id), _init),	\
671 			NULL, Z_DEVICE_DT_FLAGS(node_id), pm, data,	\
672 			config,	level, prio, api,			\
673 			&(Z_DEVICE_STATE_NAME(Z_DEVICE_DT_DEV_ID(node_id)).devstate), \
674 			__VA_ARGS__)
675 
676 #else /* CONFIG_I2C_STATS */
677 
i2c_xfer_stats(const struct device * dev,struct i2c_msg * msgs,uint8_t num_msgs)678 static inline void i2c_xfer_stats(const struct device *dev, struct i2c_msg *msgs,
679 				  uint8_t num_msgs)
680 {
681 	ARG_UNUSED(dev);
682 	ARG_UNUSED(msgs);
683 	ARG_UNUSED(num_msgs);
684 }
685 
686 #define I2C_DEVICE_DT_DEFINE(node_id, init_fn, pm, data, config, level,	\
687 			     prio, api, ...)				\
688 	DEVICE_DT_DEFINE(node_id, init_fn, pm, data, config, level,	\
689 			 prio, api, __VA_ARGS__)
690 
691 #endif /* CONFIG_I2C_STATS */
692 
693 /**
694  * @brief Like I2C_DEVICE_DT_DEFINE() for an instance of a DT_DRV_COMPAT compatible
695  *
696  * @param inst instance number. This is replaced by
697  * <tt>DT_DRV_COMPAT(inst)</tt> in the call to I2C_DEVICE_DT_DEFINE().
698  *
699  * @param ... other parameters as expected by I2C_DEVICE_DT_DEFINE().
700  */
701 #define I2C_DEVICE_DT_INST_DEFINE(inst, ...)		\
702 	I2C_DEVICE_DT_DEFINE(DT_DRV_INST(inst), __VA_ARGS__)
703 
704 
705 /**
706  * @brief Configure operation of a host controller.
707  *
708  * @param dev Pointer to the device structure for the driver instance.
709  * @param dev_config Bit-packed 32-bit value to the device runtime configuration
710  * for the I2C controller.
711  *
712  * @retval 0 If successful.
713  * @retval -EIO General input / output error, failed to configure device.
714  */
715 __syscall int i2c_configure(const struct device *dev, uint32_t dev_config);
716 
z_impl_i2c_configure(const struct device * dev,uint32_t dev_config)717 static inline int z_impl_i2c_configure(const struct device *dev,
718 				       uint32_t dev_config)
719 {
720 	const struct i2c_driver_api *api =
721 		(const struct i2c_driver_api *)dev->api;
722 
723 	return api->configure(dev, dev_config);
724 }
725 
726 /**
727  * @brief Get configuration of a host controller.
728  *
729  * This routine provides a way to get current configuration. It is allowed to
730  * call the function before i2c_configure, because some I2C ports can be
731  * configured during init process. However, if the I2C port is not configured,
732  * i2c_get_config returns an error.
733  *
734  * i2c_get_config can return cached config or probe hardware, but it has to be
735  * up to date with current configuration.
736  *
737  * @param dev Pointer to the device structure for the driver instance.
738  * @param dev_config Pointer to return bit-packed 32-bit value of
739  * the I2C controller configuration.
740  *
741  * @retval 0 If successful.
742  * @retval -EIO General input / output error.
743  * @retval -ERANGE Configured I2C frequency is invalid.
744  * @retval -ENOSYS If get config is not implemented
745  */
746 __syscall int i2c_get_config(const struct device *dev, uint32_t *dev_config);
747 
z_impl_i2c_get_config(const struct device * dev,uint32_t * dev_config)748 static inline int z_impl_i2c_get_config(const struct device *dev, uint32_t *dev_config)
749 {
750 	const struct i2c_driver_api *api = (const struct i2c_driver_api *)dev->api;
751 
752 	if (api->get_config == NULL) {
753 		return -ENOSYS;
754 	}
755 
756 	return api->get_config(dev, dev_config);
757 }
758 
759 /**
760  * @brief Perform data transfer to another I2C device in controller mode.
761  *
762  * This routine provides a generic interface to perform data transfer
763  * to another I2C device synchronously. Use i2c_read()/i2c_write()
764  * for simple read or write.
765  *
766  * The array of message @a msgs must not be NULL.  The number of
767  * message @a num_msgs may be zero,in which case no transfer occurs.
768  *
769  * @note Not all scatter/gather transactions can be supported by all
770  * drivers.  As an example, a gather write (multiple consecutive
771  * `i2c_msg` buffers all configured for `I2C_MSG_WRITE`) may be packed
772  * into a single transaction by some drivers, but others may emit each
773  * fragment as a distinct write transaction, which will not produce
774  * the same behavior.  See the documentation of `struct i2c_msg` for
775  * limitations on support for multi-message bus transactions.
776  *
777  * @note The last message in the scatter/gather transaction implies a STOP
778  * whether or not it is explicitly set. This ensures the bus is in a good
779  * state for the next transaction which may be from a different call context.
780  *
781  * @param dev Pointer to the device structure for an I2C controller
782  * driver configured in controller mode.
783  * @param msgs Array of messages to transfer.
784  * @param num_msgs Number of messages to transfer.
785  * @param addr Address of the I2C target device.
786  *
787  * @retval 0 If successful.
788  * @retval -EIO General input / output error.
789  */
790 __syscall int i2c_transfer(const struct device *dev,
791 			   struct i2c_msg *msgs, uint8_t num_msgs,
792 			   uint16_t addr);
793 
z_impl_i2c_transfer(const struct device * dev,struct i2c_msg * msgs,uint8_t num_msgs,uint16_t addr)794 static inline int z_impl_i2c_transfer(const struct device *dev,
795 				      struct i2c_msg *msgs, uint8_t num_msgs,
796 				      uint16_t addr)
797 {
798 	const struct i2c_driver_api *api =
799 		(const struct i2c_driver_api *)dev->api;
800 
801 	if (!num_msgs) {
802 		return 0;
803 	}
804 
805 	if (!IS_ENABLED(CONFIG_I2C_ALLOW_NO_STOP_TRANSACTIONS)) {
806 		msgs[num_msgs - 1].flags |= I2C_MSG_STOP;
807 	}
808 
809 	int res =  api->transfer(dev, msgs, num_msgs, addr);
810 
811 	i2c_xfer_stats(dev, msgs, num_msgs);
812 
813 	if (IS_ENABLED(CONFIG_I2C_DUMP_MESSAGES)) {
814 		i2c_dump_msgs_rw(dev, msgs, num_msgs, addr, true);
815 	}
816 
817 	return res;
818 }
819 
820 #if defined(CONFIG_I2C_CALLBACK) || defined(__DOXYGEN__)
821 
822 /**
823  * @brief Perform data transfer to another I2C device in controller mode.
824  *
825  * This routine provides a generic interface to perform data transfer
826  * to another I2C device asynchronously with a callback completion.
827  *
828  * @see i2c_transfer()
829  * @funcprops \isr_ok
830  *
831  * @param dev Pointer to the device structure for an I2C controller
832  *            driver configured in controller mode.
833  * @param msgs Array of messages to transfer, must live until callback completes.
834  * @param num_msgs Number of messages to transfer.
835  * @param addr Address of the I2C target device.
836  * @param cb Function pointer for completion callback.
837  * @param userdata Userdata passed to callback.
838  *
839  * @retval 0 If successful.
840  * @retval -EIO General input / output error.
841  * @retval -ENOSYS If transfer async is not implemented
842  * @retval -EWOULDBLOCK If the device is temporarily busy doing another transfer
843  */
i2c_transfer_cb(const struct device * dev,struct i2c_msg * msgs,uint8_t num_msgs,uint16_t addr,i2c_callback_t cb,void * userdata)844 static inline int i2c_transfer_cb(const struct device *dev,
845 				  struct i2c_msg *msgs,
846 				  uint8_t num_msgs,
847 				  uint16_t addr,
848 				  i2c_callback_t cb,
849 				  void *userdata)
850 {
851 	const struct i2c_driver_api *api =
852 		(const struct i2c_driver_api *)dev->api;
853 
854 	if (api->transfer_cb == NULL) {
855 		return -ENOSYS;
856 	}
857 
858 	if (!num_msgs) {
859 		cb(dev, 0, userdata);
860 		return 0;
861 	}
862 
863 	if (!IS_ENABLED(CONFIG_I2C_ALLOW_NO_STOP_TRANSACTIONS)) {
864 		msgs[num_msgs - 1].flags |= I2C_MSG_STOP;
865 	}
866 
867 	return api->transfer_cb(dev, msgs, num_msgs, addr, cb, userdata);
868 }
869 
870 /**
871  * @brief Perform data transfer to another I2C device in master mode asynchronously.
872  *
873  * This is equivalent to:
874  *
875  *     i2c_transfer_cb(spec->bus, msgs, num_msgs, spec->addr, cb, userdata);
876  *
877  * @param spec I2C specification from devicetree.
878  * @param msgs Array of messages to transfer.
879  * @param num_msgs Number of messages to transfer.
880  * @param cb Function pointer for completion callback.
881  * @param userdata Userdata passed to callback.
882  *
883  * @return a value from i2c_transfer_cb()
884  */
i2c_transfer_cb_dt(const struct i2c_dt_spec * spec,struct i2c_msg * msgs,uint8_t num_msgs,i2c_callback_t cb,void * userdata)885 static inline int i2c_transfer_cb_dt(const struct i2c_dt_spec *spec,
886 				struct i2c_msg *msgs,
887 				uint8_t num_msgs,
888 				i2c_callback_t cb,
889 				void *userdata)
890 {
891 	return i2c_transfer_cb(spec->bus, msgs, num_msgs, spec->addr, cb, userdata);
892 }
893 
894 /**
895  * @brief Write then read data from an I2C device asynchronously.
896  *
897  * This supports the common operation "this is what I want", "now give
898  * it to me" transaction pair through a combined write-then-read bus
899  * transaction but using i2c_transfer_cb. This helper function expects
900  * caller to pass a message pointer with 2 and only 2 size.
901  *
902  * @param dev Pointer to the device structure for an I2C controller
903  * driver configured in master mode.
904  * @param msgs Array of messages to transfer.
905  * @param num_msgs Number of messages to transfer.
906  * @param addr Address of the I2C device
907  * @param write_buf Pointer to the data to be written
908  * @param num_write Number of bytes to write
909  * @param read_buf Pointer to storage for read data
910  * @param num_read Number of bytes to read
911  * @param cb Function pointer for completion callback.
912  * @param userdata Userdata passed to callback.
913  *
914  * @retval 0 if successful
915  * @retval negative on error.
916  */
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)917 static inline int i2c_write_read_cb(const struct device *dev, struct i2c_msg *msgs,
918 				 uint8_t num_msgs, uint16_t addr, const void *write_buf,
919 				 size_t num_write, void *read_buf, size_t num_read,
920 				 i2c_callback_t cb, void *userdata)
921 {
922 	if ((msgs == NULL) || (num_msgs != 2)) {
923 		return -EINVAL;
924 	}
925 
926 	msgs[0].buf = (uint8_t *)write_buf;
927 	msgs[0].len = num_write;
928 	msgs[0].flags = I2C_MSG_WRITE;
929 
930 	msgs[1].buf = (uint8_t *)read_buf;
931 	msgs[1].len = num_read;
932 	msgs[1].flags = I2C_MSG_RESTART | I2C_MSG_READ | I2C_MSG_STOP;
933 
934 	return i2c_transfer_cb(dev, msgs, num_msgs, addr, cb, userdata);
935 }
936 
937 /**
938  * @brief Write then read data from an I2C device asynchronously.
939  *
940  * This is equivalent to:
941  *
942  *     i2c_write_read_cb(spec->bus, msgs, num_msgs,
943  *                    spec->addr, write_buf,
944  *                    num_write, read_buf, num_read);
945  *
946  * @param spec I2C specification from devicetree.
947  * @param msgs Array of messages to transfer.
948  * @param num_msgs Number of messages to transfer.
949  * @param write_buf Pointer to the data to be written
950  * @param num_write Number of bytes to write
951  * @param read_buf Pointer to storage for read data
952  * @param num_read Number of bytes to read
953  * @param cb Function pointer for completion callback.
954  * @param userdata Userdata passed to callback.
955  *
956  * @return a value from i2c_write_read_cb()
957  */
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)958 static inline int i2c_write_read_cb_dt(const struct i2c_dt_spec *spec, struct i2c_msg *msgs,
959 				       uint8_t num_msgs, const void *write_buf, size_t num_write,
960 				       void *read_buf, size_t num_read, i2c_callback_t cb,
961 				       void *userdata)
962 {
963 	return i2c_write_read_cb(spec->bus, msgs, num_msgs, spec->addr, write_buf, num_write,
964 				 read_buf, num_read, cb, userdata);
965 }
966 
967 #if defined(CONFIG_POLL) || defined(__DOXYGEN__)
968 
969 /** @cond INTERNAL_HIDDEN */
970 void z_i2c_transfer_signal_cb(const struct device *dev, int result, void *userdata);
971 /** @endcond */
972 
973 /**
974  * @brief Perform data transfer to another I2C device in controller mode.
975  *
976  * This routine provides a generic interface to perform data transfer
977  * to another I2C device asynchronously with a k_poll_signal completion.
978  *
979  * @see i2c_transfer_cb()
980  * @funcprops \isr_ok
981  *
982  * @param dev Pointer to the device structure for an I2C controller
983  *            driver configured in controller mode.
984  * @param msgs Array of messages to transfer, must live until callback completes.
985  * @param num_msgs Number of messages to transfer.
986  * @param addr Address of the I2C target device.
987  * @param sig Signal to notify of transfer completion.
988  *
989  * @retval 0 If successful.
990  * @retval -EIO General input / output error.
991  * @retval -ENOSYS If transfer async is not implemented
992  * @retval -EWOULDBLOCK If the device is temporarily busy doing another transfer
993  */
i2c_transfer_signal(const struct device * dev,struct i2c_msg * msgs,uint8_t num_msgs,uint16_t addr,struct k_poll_signal * sig)994 static inline int i2c_transfer_signal(const struct device *dev,
995 				 struct i2c_msg *msgs,
996 				 uint8_t num_msgs,
997 				 uint16_t addr,
998 				 struct k_poll_signal *sig)
999 {
1000 	const struct i2c_driver_api *api = (const struct i2c_driver_api *)dev->api;
1001 
1002 	if (api->transfer_cb == NULL) {
1003 		return -ENOSYS;
1004 	}
1005 
1006 	return api->transfer_cb(dev, msgs, num_msgs, addr, z_i2c_transfer_signal_cb, sig);
1007 }
1008 
1009 #endif /* CONFIG_POLL */
1010 
1011 #endif /* CONFIG_I2C_CALLBACK */
1012 
1013 
1014 #if defined(CONFIG_I2C_RTIO) || defined(__DOXYGEN__)
1015 
1016 /**
1017  * @brief Fallback submit implementation
1018  *
1019  * This implementation will schedule a blocking I2C transaction on the bus via the RTIO work
1020  * queue. It is only used if the I2C driver did not implement the iodev_submit function.
1021  *
1022  * @param dev Pointer to the device structure for an I2C controller driver.
1023  * @param iodev_sqe Prepared submissions queue entry connected to an iodev
1024  *                  defined by I2C_DT_IODEV_DEFINE.
1025  */
1026 void i2c_iodev_submit_fallback(const struct device *dev, struct rtio_iodev_sqe *iodev_sqe);
1027 
1028 /**
1029  * @brief Submit request(s) to an I2C device with RTIO
1030  *
1031  * @param iodev_sqe Prepared submissions queue entry connected to an iodev
1032  *                  defined by I2C_DT_IODEV_DEFINE.
1033  */
i2c_iodev_submit(struct rtio_iodev_sqe * iodev_sqe)1034 static inline void i2c_iodev_submit(struct rtio_iodev_sqe *iodev_sqe)
1035 {
1036 	const struct i2c_dt_spec *dt_spec = (const struct i2c_dt_spec *)iodev_sqe->sqe.iodev->data;
1037 	const struct device *dev = dt_spec->bus;
1038 	const struct i2c_driver_api *api = (const struct i2c_driver_api *)dev->api;
1039 
1040 	if (api->iodev_submit == NULL) {
1041 		rtio_iodev_sqe_err(iodev_sqe, -ENOSYS);
1042 		return;
1043 	}
1044 	api->iodev_submit(dt_spec->bus, iodev_sqe);
1045 }
1046 
1047 extern const struct rtio_iodev_api i2c_iodev_api;
1048 
1049 /**
1050  * @brief Define an iodev for a given dt node on the bus
1051  *
1052  * These do not need to be shared globally but doing so
1053  * will save a small amount of memory.
1054  *
1055  * @param name Symbolic name of the iodev to define
1056  * @param node_id Devicetree node identifier
1057  */
1058 #define I2C_DT_IODEV_DEFINE(name, node_id)					\
1059 	const struct i2c_dt_spec _i2c_dt_spec_##name =				\
1060 		I2C_DT_SPEC_GET(node_id);					\
1061 	RTIO_IODEV_DEFINE(name, &i2c_iodev_api, (void *)&_i2c_dt_spec_##name)
1062 
1063 /**
1064  * @brief Define an iodev for a given i2c device on a bus
1065  *
1066  * These do not need to be shared globally but doing so
1067  * will save a small amount of memory.
1068  *
1069  * @param name Symbolic name of the iodev to define
1070  * @param _bus Node ID for I2C bus
1071  * @param _addr I2C target address
1072  */
1073 #define I2C_IODEV_DEFINE(name, _bus, _addr)                                     \
1074 	const struct i2c_dt_spec _i2c_dt_spec_##name = {                        \
1075 		.bus = DEVICE_DT_GET(_bus),                                     \
1076 		.addr = _addr,                                                  \
1077 	};                                                                      \
1078 	RTIO_IODEV_DEFINE(name, &i2c_iodev_api, (void *)&_i2c_dt_spec_##name)
1079 
1080 /**
1081  * @brief Copy the i2c_msgs into a set of RTIO requests
1082  *
1083  * @param r RTIO context
1084  * @param iodev RTIO IODev to target for the submissions
1085  * @param msgs Array of messages
1086  * @param num_msgs Number of i2c msgs in array
1087  *
1088  * @retval sqe Last submission in the queue added
1089  * @retval NULL Not enough memory in the context to copy the requests
1090  */
1091 struct rtio_sqe *i2c_rtio_copy(struct rtio *r,
1092 			       struct rtio_iodev *iodev,
1093 			       const struct i2c_msg *msgs,
1094 			       uint8_t num_msgs);
1095 
1096 /**
1097  * @brief Copy the register address and data to a SQE
1098  *
1099  * @param r RTIO context
1100  * @param iodev RTIO IODev to target for the submissions
1101  * @param reg_addr target register address
1102  * @param data data to be written
1103  *
1104  * @retval sqe Last submission in the queue added
1105  * @retval NULL Not enough memory in the context to copy the requests
1106  */
1107 struct rtio_sqe *i2c_rtio_copy_reg_write_byte(struct rtio *r, struct rtio_iodev *iodev,
1108 					      uint8_t reg_addr, uint8_t data);
1109 
1110 /**
1111  * @brief acquire and configure a i2c burst read transmission
1112  *
1113  * @param r RTIO context
1114  * @param iodev RTIO IODev to target for the submissions
1115  * @param start_addr target register address
1116  * @param buf Memory pool that stores the retrieved data.
1117  * @param num_bytes Number of bytes to read.
1118  *
1119  * @retval sqe Last submission in the queue added
1120  * @retval NULL Not enough memory in the context to copy the requests
1121  */
1122 struct rtio_sqe *i2c_rtio_copy_reg_burst_read(struct rtio *r, struct rtio_iodev *iodev,
1123 					      uint8_t start_addr, void *buf, size_t num_bytes);
1124 
1125 #endif /* CONFIG_I2C_RTIO */
1126 
1127 /**
1128  * @brief Perform data transfer to another I2C device in controller mode.
1129  *
1130  * This is equivalent to:
1131  *
1132  *     i2c_transfer(spec->bus, msgs, num_msgs, spec->addr);
1133  *
1134  * @param spec I2C specification from devicetree.
1135  * @param msgs Array of messages to transfer.
1136  * @param num_msgs Number of messages to transfer.
1137  *
1138  * @return a value from i2c_transfer()
1139  */
i2c_transfer_dt(const struct i2c_dt_spec * spec,struct i2c_msg * msgs,uint8_t num_msgs)1140 static inline int i2c_transfer_dt(const struct i2c_dt_spec *spec,
1141 				  struct i2c_msg *msgs, uint8_t num_msgs)
1142 {
1143 	return i2c_transfer(spec->bus, msgs, num_msgs, spec->addr);
1144 }
1145 
1146 /**
1147  * @brief Recover the I2C bus
1148  *
1149  * Attempt to recover the I2C bus.
1150  *
1151  * @param dev Pointer to the device structure for an I2C controller
1152  * driver configured in controller mode.
1153  * @retval 0 If successful
1154  * @retval -EBUSY If bus is not clear after recovery attempt.
1155  * @retval -EIO General input / output error.
1156  * @retval -ENOSYS If bus recovery is not implemented
1157  */
1158 __syscall int i2c_recover_bus(const struct device *dev);
1159 
z_impl_i2c_recover_bus(const struct device * dev)1160 static inline int z_impl_i2c_recover_bus(const struct device *dev)
1161 {
1162 	const struct i2c_driver_api *api =
1163 		(const struct i2c_driver_api *)dev->api;
1164 
1165 	if (api->recover_bus == NULL) {
1166 		return -ENOSYS;
1167 	}
1168 
1169 	return api->recover_bus(dev);
1170 }
1171 
1172 /**
1173  * @brief Registers the provided config as Target device of a controller.
1174  *
1175  * Enable I2C target mode for the 'dev' I2C bus driver using the provided
1176  * 'config' struct containing the functions and parameters to send bus
1177  * events. The I2C target will be registered at the address provided as 'address'
1178  * struct member. Addressing mode - 7 or 10 bit - depends on the 'flags'
1179  * struct member. Any I2C bus events related to the target mode will be passed
1180  * onto I2C target device driver via a set of callback functions provided in
1181  * the 'callbacks' struct member.
1182  *
1183  * Most of the existing hardware allows simultaneous support for controller
1184  * and target mode. This is however not guaranteed.
1185  *
1186  * @param dev Pointer to the device structure for an I2C controller
1187  * driver configured in target mode.
1188  * @param cfg Config struct with functions and parameters used by the I2C driver
1189  * to send bus events
1190  *
1191  * @retval 0 Is successful
1192  * @retval -EINVAL If parameters are invalid
1193  * @retval -EIO General input / output error.
1194  * @retval -ENOSYS If target mode is not implemented
1195  */
i2c_target_register(const struct device * dev,struct i2c_target_config * cfg)1196 static inline int i2c_target_register(const struct device *dev,
1197 				     struct i2c_target_config *cfg)
1198 {
1199 	const struct i2c_driver_api *api =
1200 		(const struct i2c_driver_api *)dev->api;
1201 
1202 	if (api->target_register == NULL) {
1203 		return -ENOSYS;
1204 	}
1205 
1206 	return api->target_register(dev, cfg);
1207 }
1208 
1209 /**
1210  * @brief Unregisters the provided config as Target device
1211  *
1212  * This routine disables I2C target mode for the 'dev' I2C bus driver using
1213  * the provided 'config' struct containing the functions and parameters
1214  * to send bus events.
1215  *
1216  * @param dev Pointer to the device structure for an I2C controller
1217  * driver configured in target mode.
1218  * @param cfg Config struct with functions and parameters used by the I2C driver
1219  * to send bus events
1220  *
1221  * @retval 0 Is successful
1222  * @retval -EINVAL If parameters are invalid
1223  * @retval -ENOSYS If target mode is not implemented
1224  */
i2c_target_unregister(const struct device * dev,struct i2c_target_config * cfg)1225 static inline int i2c_target_unregister(const struct device *dev,
1226 				       struct i2c_target_config *cfg)
1227 {
1228 	const struct i2c_driver_api *api =
1229 		(const struct i2c_driver_api *)dev->api;
1230 
1231 	if (api->target_unregister == NULL) {
1232 		return -ENOSYS;
1233 	}
1234 
1235 	return api->target_unregister(dev, cfg);
1236 }
1237 
1238 /**
1239  * @brief Instructs the I2C Target device to register itself to the I2C Controller
1240  *
1241  * This routine instructs the I2C Target device to register itself to the I2C
1242  * Controller via its parent controller's i2c_target_register() API.
1243  *
1244  * @param dev Pointer to the device structure for the I2C target
1245  * device (not itself an I2C controller).
1246  *
1247  * @retval 0 Is successful
1248  * @retval -EINVAL If parameters are invalid
1249  * @retval -EIO General input / output error.
1250  */
1251 __syscall int i2c_target_driver_register(const struct device *dev);
1252 
z_impl_i2c_target_driver_register(const struct device * dev)1253 static inline int z_impl_i2c_target_driver_register(const struct device *dev)
1254 {
1255 	const struct i2c_target_driver_api *api =
1256 		(const struct i2c_target_driver_api *)dev->api;
1257 
1258 	return api->driver_register(dev);
1259 }
1260 
1261 /**
1262  * @brief Instructs the I2C Target device to unregister itself from the I2C
1263  * Controller
1264  *
1265  * This routine instructs the I2C Target device to unregister itself from the I2C
1266  * Controller via its parent controller's i2c_target_register() API.
1267  *
1268  * @param dev Pointer to the device structure for the I2C target
1269  * device (not itself an I2C controller).
1270  *
1271  * @retval 0 Is successful
1272  * @retval -EINVAL If parameters are invalid
1273  */
1274 __syscall int i2c_target_driver_unregister(const struct device *dev);
1275 
z_impl_i2c_target_driver_unregister(const struct device * dev)1276 static inline int z_impl_i2c_target_driver_unregister(const struct device *dev)
1277 {
1278 	const struct i2c_target_driver_api *api =
1279 		(const struct i2c_target_driver_api *)dev->api;
1280 
1281 	return api->driver_unregister(dev);
1282 }
1283 
1284 /*
1285  * Derived i2c APIs -- all implemented in terms of i2c_transfer()
1286  */
1287 
1288 /**
1289  * @brief Write a set amount of data to an I2C device.
1290  *
1291  * This routine writes a set amount of data synchronously.
1292  *
1293  * @param dev Pointer to the device structure for an I2C controller
1294  * driver configured in controller mode.
1295  * @param buf Memory pool from which the data is transferred.
1296  * @param num_bytes Number of bytes to write.
1297  * @param addr Address to the target I2C device for writing.
1298  *
1299  * @retval 0 If successful.
1300  * @retval -EIO General input / output error.
1301  */
i2c_write(const struct device * dev,const uint8_t * buf,uint32_t num_bytes,uint16_t addr)1302 static inline int i2c_write(const struct device *dev, const uint8_t *buf,
1303 			    uint32_t num_bytes, uint16_t addr)
1304 {
1305 	struct i2c_msg msg;
1306 
1307 	msg.buf = (uint8_t *)buf;
1308 	msg.len = num_bytes;
1309 	msg.flags = I2C_MSG_WRITE | I2C_MSG_STOP;
1310 
1311 	return i2c_transfer(dev, &msg, 1, addr);
1312 }
1313 
1314 /**
1315  * @brief Write a set amount of data to an I2C device.
1316  *
1317  * This is equivalent to:
1318  *
1319  *     i2c_write(spec->bus, buf, num_bytes, spec->addr);
1320  *
1321  * @param spec I2C specification from devicetree.
1322  * @param buf Memory pool from which the data is transferred.
1323  * @param num_bytes Number of bytes to write.
1324  *
1325  * @return a value from i2c_write()
1326  */
i2c_write_dt(const struct i2c_dt_spec * spec,const uint8_t * buf,uint32_t num_bytes)1327 static inline int i2c_write_dt(const struct i2c_dt_spec *spec,
1328 			       const uint8_t *buf, uint32_t num_bytes)
1329 {
1330 	return i2c_write(spec->bus, buf, num_bytes, spec->addr);
1331 }
1332 
1333 /**
1334  * @brief Read a set amount of data from an I2C device.
1335  *
1336  * This routine reads a set amount of data synchronously.
1337  *
1338  * @param dev Pointer to the device structure for an I2C controller
1339  * driver configured in controller mode.
1340  * @param buf Memory pool that stores the retrieved data.
1341  * @param num_bytes Number of bytes to read.
1342  * @param addr Address of the I2C device being read.
1343  *
1344  * @retval 0 If successful.
1345  * @retval -EIO General input / output error.
1346  */
i2c_read(const struct device * dev,uint8_t * buf,uint32_t num_bytes,uint16_t addr)1347 static inline int i2c_read(const struct device *dev, uint8_t *buf,
1348 			   uint32_t num_bytes, uint16_t addr)
1349 {
1350 	struct i2c_msg msg;
1351 
1352 	msg.buf = buf;
1353 	msg.len = num_bytes;
1354 	msg.flags = I2C_MSG_READ | I2C_MSG_STOP;
1355 
1356 	return i2c_transfer(dev, &msg, 1, addr);
1357 }
1358 
1359 /**
1360  * @brief Read a set amount of data from an I2C device.
1361  *
1362  * This is equivalent to:
1363  *
1364  *     i2c_read(spec->bus, buf, num_bytes, spec->addr);
1365  *
1366  * @param spec I2C specification from devicetree.
1367  * @param buf Memory pool that stores the retrieved data.
1368  * @param num_bytes Number of bytes to read.
1369  *
1370  * @return a value from i2c_read()
1371  */
i2c_read_dt(const struct i2c_dt_spec * spec,uint8_t * buf,uint32_t num_bytes)1372 static inline int i2c_read_dt(const struct i2c_dt_spec *spec,
1373 			      uint8_t *buf, uint32_t num_bytes)
1374 {
1375 	return i2c_read(spec->bus, buf, num_bytes, spec->addr);
1376 }
1377 
1378 /**
1379  * @brief Write then read data from an I2C device.
1380  *
1381  * This supports the common operation "this is what I want", "now give
1382  * it to me" transaction pair through a combined write-then-read bus
1383  * transaction.
1384  *
1385  * @param dev Pointer to the device structure for an I2C controller
1386  * driver configured in controller mode.
1387  * @param addr Address of the I2C device
1388  * @param write_buf Pointer to the data to be written
1389  * @param num_write Number of bytes to write
1390  * @param read_buf Pointer to storage for read data
1391  * @param num_read Number of bytes to read
1392  *
1393  * @retval 0 if successful
1394  * @retval negative on error.
1395  */
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)1396 static inline int i2c_write_read(const struct device *dev, uint16_t addr,
1397 				 const void *write_buf, size_t num_write,
1398 				 void *read_buf, size_t num_read)
1399 {
1400 	struct i2c_msg msg[2];
1401 
1402 	msg[0].buf = (uint8_t *)write_buf;
1403 	msg[0].len = num_write;
1404 	msg[0].flags = I2C_MSG_WRITE;
1405 
1406 	msg[1].buf = (uint8_t *)read_buf;
1407 	msg[1].len = num_read;
1408 	msg[1].flags = I2C_MSG_RESTART | I2C_MSG_READ | I2C_MSG_STOP;
1409 
1410 	return i2c_transfer(dev, msg, 2, addr);
1411 }
1412 
1413 /**
1414  * @brief Write then read data from an I2C device.
1415  *
1416  * This is equivalent to:
1417  *
1418  *     i2c_write_read(spec->bus, spec->addr,
1419  *                    write_buf, num_write,
1420  *                    read_buf, num_read);
1421  *
1422  * @param spec I2C specification from devicetree.
1423  * @param write_buf Pointer to the data to be written
1424  * @param num_write Number of bytes to write
1425  * @param read_buf Pointer to storage for read data
1426  * @param num_read Number of bytes to read
1427  *
1428  * @return a value from i2c_write_read()
1429  */
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)1430 static inline int i2c_write_read_dt(const struct i2c_dt_spec *spec,
1431 				    const void *write_buf, size_t num_write,
1432 				    void *read_buf, size_t num_read)
1433 {
1434 	return i2c_write_read(spec->bus, spec->addr,
1435 			      write_buf, num_write,
1436 			      read_buf, num_read);
1437 }
1438 
1439 /**
1440  * @brief Read multiple bytes from an internal address of an I2C device.
1441  *
1442  * This routine reads multiple bytes from an internal address of an
1443  * I2C device synchronously.
1444  *
1445  * Instances of this may be replaced by i2c_write_read().
1446  *
1447  * @param dev Pointer to the device structure for an I2C controller
1448  * driver configured in controller mode.
1449  * @param dev_addr Address of the I2C device for reading.
1450  * @param start_addr Internal address from which the data is being read.
1451  * @param buf Memory pool that stores the retrieved data.
1452  * @param num_bytes Number of bytes being read.
1453  *
1454  * @retval 0 If successful.
1455  * @retval -EIO General input / output error.
1456  */
i2c_burst_read(const struct device * dev,uint16_t dev_addr,uint8_t start_addr,uint8_t * buf,uint32_t num_bytes)1457 static inline int i2c_burst_read(const struct device *dev,
1458 				 uint16_t dev_addr,
1459 				 uint8_t start_addr,
1460 				 uint8_t *buf,
1461 				 uint32_t num_bytes)
1462 {
1463 	return i2c_write_read(dev, dev_addr,
1464 			      &start_addr, sizeof(start_addr),
1465 			      buf, num_bytes);
1466 }
1467 
1468 /**
1469  * @brief Read multiple bytes from an internal address of an I2C device.
1470  *
1471  * This is equivalent to:
1472  *
1473  *     i2c_burst_read(spec->bus, spec->addr, start_addr, buf, num_bytes);
1474  *
1475  * @param spec I2C specification from devicetree.
1476  * @param start_addr Internal address from which the data is being read.
1477  * @param buf Memory pool that stores the retrieved data.
1478  * @param num_bytes Number of bytes to read.
1479  *
1480  * @return a value from i2c_burst_read()
1481  */
i2c_burst_read_dt(const struct i2c_dt_spec * spec,uint8_t start_addr,uint8_t * buf,uint32_t num_bytes)1482 static inline int i2c_burst_read_dt(const struct i2c_dt_spec *spec,
1483 				    uint8_t start_addr,
1484 				    uint8_t *buf,
1485 				    uint32_t num_bytes)
1486 {
1487 	return i2c_burst_read(spec->bus, spec->addr,
1488 			      start_addr, buf, num_bytes);
1489 }
1490 
1491 /**
1492  * @brief Write multiple bytes to an internal address of an I2C device.
1493  *
1494  * This routine writes multiple bytes to an internal address of an
1495  * I2C device synchronously.
1496  *
1497  * @warning The combined write synthesized by this API may not be
1498  * supported on all I2C devices.  Uses of this API may be made more
1499  * portable by replacing them with calls to i2c_write() passing a
1500  * buffer containing the combined address and data.
1501  *
1502  * @param dev Pointer to the device structure for an I2C controller
1503  * driver configured in controller mode.
1504  * @param dev_addr Address of the I2C device for writing.
1505  * @param start_addr Internal address to which the data is being written.
1506  * @param buf Memory pool from which the data is transferred.
1507  * @param num_bytes Number of bytes being written.
1508  *
1509  * @retval 0 If successful.
1510  * @retval -EIO General input / output error.
1511  */
i2c_burst_write(const struct device * dev,uint16_t dev_addr,uint8_t start_addr,const uint8_t * buf,uint32_t num_bytes)1512 static inline int i2c_burst_write(const struct device *dev,
1513 				  uint16_t dev_addr,
1514 				  uint8_t start_addr,
1515 				  const uint8_t *buf,
1516 				  uint32_t num_bytes)
1517 {
1518 	struct i2c_msg msg[2];
1519 
1520 	msg[0].buf = &start_addr;
1521 	msg[0].len = 1U;
1522 	msg[0].flags = I2C_MSG_WRITE;
1523 
1524 	msg[1].buf = (uint8_t *)buf;
1525 	msg[1].len = num_bytes;
1526 	msg[1].flags = I2C_MSG_WRITE | I2C_MSG_STOP;
1527 
1528 	return i2c_transfer(dev, msg, 2, dev_addr);
1529 }
1530 
1531 /**
1532  * @brief Write multiple bytes to an internal address of an I2C device.
1533  *
1534  * This is equivalent to:
1535  *
1536  *     i2c_burst_write(spec->bus, spec->addr, start_addr, buf, num_bytes);
1537  *
1538  * @param spec I2C specification from devicetree.
1539  * @param start_addr Internal address to which the data is being written.
1540  * @param buf Memory pool from which the data is transferred.
1541  * @param num_bytes Number of bytes being written.
1542  *
1543  * @return a value from i2c_burst_write()
1544  */
i2c_burst_write_dt(const struct i2c_dt_spec * spec,uint8_t start_addr,const uint8_t * buf,uint32_t num_bytes)1545 static inline int i2c_burst_write_dt(const struct i2c_dt_spec *spec,
1546 				     uint8_t start_addr,
1547 				     const uint8_t *buf,
1548 				     uint32_t num_bytes)
1549 {
1550 	return i2c_burst_write(spec->bus, spec->addr,
1551 			       start_addr, buf, num_bytes);
1552 }
1553 
1554 /**
1555  * @brief Read internal register of an I2C device.
1556  *
1557  * This routine reads the value of an 8-bit internal register of an I2C
1558  * device synchronously.
1559  *
1560  * @param dev Pointer to the device structure for an I2C controller
1561  * driver configured in controller mode.
1562  * @param dev_addr Address of the I2C device for reading.
1563  * @param reg_addr Address of the internal register being read.
1564  * @param value Memory pool that stores the retrieved register value.
1565  *
1566  * @retval 0 If successful.
1567  * @retval -EIO General input / output error.
1568  */
i2c_reg_read_byte(const struct device * dev,uint16_t dev_addr,uint8_t reg_addr,uint8_t * value)1569 static inline int i2c_reg_read_byte(const struct device *dev,
1570 				    uint16_t dev_addr,
1571 				    uint8_t reg_addr, uint8_t *value)
1572 {
1573 	return i2c_write_read(dev, dev_addr,
1574 			      &reg_addr, sizeof(reg_addr),
1575 			      value, sizeof(*value));
1576 }
1577 
1578 /**
1579  * @brief Read internal register of an I2C device.
1580  *
1581  * This is equivalent to:
1582  *
1583  *     i2c_reg_read_byte(spec->bus, spec->addr, reg_addr, value);
1584  *
1585  * @param spec I2C specification from devicetree.
1586  * @param reg_addr Address of the internal register being read.
1587  * @param value Memory pool that stores the retrieved register value.
1588  *
1589  * @return a value from i2c_reg_read_byte()
1590  */
i2c_reg_read_byte_dt(const struct i2c_dt_spec * spec,uint8_t reg_addr,uint8_t * value)1591 static inline int i2c_reg_read_byte_dt(const struct i2c_dt_spec *spec,
1592 				       uint8_t reg_addr, uint8_t *value)
1593 {
1594 	return i2c_reg_read_byte(spec->bus, spec->addr, reg_addr, value);
1595 }
1596 
1597 /**
1598  * @brief Write internal register of an I2C device.
1599  *
1600  * This routine writes a value to an 8-bit internal register of an I2C
1601  * device synchronously.
1602  *
1603  * @note This function internally combines the register and value into
1604  * a single bus transaction.
1605  *
1606  * @param dev Pointer to the device structure for an I2C controller
1607  * driver configured in controller mode.
1608  * @param dev_addr Address of the I2C device for writing.
1609  * @param reg_addr Address of the internal register being written.
1610  * @param value Value to be written to internal register.
1611  *
1612  * @retval 0 If successful.
1613  * @retval -EIO General input / output error.
1614  */
i2c_reg_write_byte(const struct device * dev,uint16_t dev_addr,uint8_t reg_addr,uint8_t value)1615 static inline int i2c_reg_write_byte(const struct device *dev,
1616 				     uint16_t dev_addr,
1617 				     uint8_t reg_addr, uint8_t value)
1618 {
1619 	uint8_t tx_buf[2] = {reg_addr, value};
1620 
1621 	return i2c_write(dev, tx_buf, 2, dev_addr);
1622 }
1623 
1624 /**
1625  * @brief Write internal register of an I2C device.
1626  *
1627  * This is equivalent to:
1628  *
1629  *     i2c_reg_write_byte(spec->bus, spec->addr, reg_addr, value);
1630  *
1631  * @param spec I2C specification from devicetree.
1632  * @param reg_addr Address of the internal register being written.
1633  * @param value Value to be written to internal register.
1634  *
1635  * @return a value from i2c_reg_write_byte()
1636  */
i2c_reg_write_byte_dt(const struct i2c_dt_spec * spec,uint8_t reg_addr,uint8_t value)1637 static inline int i2c_reg_write_byte_dt(const struct i2c_dt_spec *spec,
1638 					uint8_t reg_addr, uint8_t value)
1639 {
1640 	return i2c_reg_write_byte(spec->bus, spec->addr, reg_addr, value);
1641 }
1642 
1643 /**
1644  * @brief Update internal register of an I2C device.
1645  *
1646  * This routine updates the value of a set of bits from an 8-bit internal
1647  * register of an I2C device synchronously.
1648  *
1649  * @note If the calculated new register value matches the value that
1650  * was read this function will not generate a write operation.
1651  *
1652  * @param dev Pointer to the device structure for an I2C controller
1653  * driver configured in controller mode.
1654  * @param dev_addr Address of the I2C device for updating.
1655  * @param reg_addr Address of the internal register being updated.
1656  * @param mask Bitmask for updating internal register.
1657  * @param value Value for updating internal register.
1658  *
1659  * @retval 0 If successful.
1660  * @retval -EIO General input / output error.
1661  */
i2c_reg_update_byte(const struct device * dev,uint8_t dev_addr,uint8_t reg_addr,uint8_t mask,uint8_t value)1662 static inline int i2c_reg_update_byte(const struct device *dev,
1663 				      uint8_t dev_addr,
1664 				      uint8_t reg_addr, uint8_t mask,
1665 				      uint8_t value)
1666 {
1667 	uint8_t old_value, new_value;
1668 	int rc;
1669 
1670 	rc = i2c_reg_read_byte(dev, dev_addr, reg_addr, &old_value);
1671 	if (rc != 0) {
1672 		return rc;
1673 	}
1674 
1675 	new_value = (old_value & ~mask) | (value & mask);
1676 	if (new_value == old_value) {
1677 		return 0;
1678 	}
1679 
1680 	return i2c_reg_write_byte(dev, dev_addr, reg_addr, new_value);
1681 }
1682 
1683 /**
1684  * @brief Update internal register of an I2C device.
1685  *
1686  * This is equivalent to:
1687  *
1688  *     i2c_reg_update_byte(spec->bus, spec->addr, reg_addr, mask, value);
1689  *
1690  * @param spec I2C specification from devicetree.
1691  * @param reg_addr Address of the internal register being updated.
1692  * @param mask Bitmask for updating internal register.
1693  * @param value Value for updating internal register.
1694  *
1695  * @return a value from i2c_reg_update_byte()
1696  */
i2c_reg_update_byte_dt(const struct i2c_dt_spec * spec,uint8_t reg_addr,uint8_t mask,uint8_t value)1697 static inline int i2c_reg_update_byte_dt(const struct i2c_dt_spec *spec,
1698 					 uint8_t reg_addr, uint8_t mask,
1699 					 uint8_t value)
1700 {
1701 	return i2c_reg_update_byte(spec->bus, spec->addr,
1702 				   reg_addr, mask, value);
1703 }
1704 
1705 #ifdef __cplusplus
1706 }
1707 #endif
1708 
1709 /**
1710  * @}
1711  */
1712 
1713 #include <zephyr/syscalls/i2c.h>
1714 
1715 #endif /* ZEPHYR_INCLUDE_DRIVERS_I2C_H_ */
1716