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