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