1 This is a small guide for those who want to write kernel drivers for I2C
2 or SMBus devices, using Linux as the protocol host/master (not slave).
4 To set up a driver, you need to do several things. Some are optional, and
5 some things can be done slightly or completely different. Use this as a
6 guide, not as a rule book!
12 Try to keep the kernel namespace as clean as possible. The best way to
13 do this is to use a unique prefix for all global symbols. This is
14 especially important for exported symbols, but it is a good idea to do
15 it for non-exported symbols too. We will use the prefix `foo_' in this
16 tutorial, and `FOO_' for preprocessor variables.
22 Usually, you will implement a single driver structure, and instantiate
23 all clients from it. Remember, a driver structure contains general access
24 routines, and should be zero-initialized except for fields with data you
25 provide. A client structure holds device-specific information like the
26 driver model device node, and its I2C address.
28 static struct i2c_driver foo_driver = {
33 /* iff driver uses driver model ("new style") binding model: */
37 /* else, driver uses "legacy" binding model: */
38 .attach_adapter = foo_attach_adapter,
39 .detach_client = foo_detach_client,
41 /* these may be used regardless of the driver binding model */
42 .shutdown = foo_shutdown, /* optional */
43 .suspend = foo_suspend, /* optional */
44 .resume = foo_resume, /* optional */
45 .command = foo_command, /* optional */
48 The name field is the driver name, and must not contain spaces. It
49 should match the module name (if the driver can be compiled as a module),
50 although you can use MODULE_ALIAS (passing "foo" in this example) to add
51 another name for the module. If the driver name doesn't match the module
52 name, the module won't be automatically loaded (hotplug/coldplug).
54 All other fields are for call-back functions which will be explained
61 Each client structure has a special `data' field that can point to any
62 structure at all. You should use this to keep device-specific data,
63 especially in drivers that handle multiple I2C or SMBUS devices. You
64 do not always need this, but especially for `sensors' drivers, it can
68 void i2c_set_clientdata(struct i2c_client *client, void *data);
70 /* retrieve the value */
71 void *i2c_get_clientdata(struct i2c_client *client);
73 An example structure is below.
76 struct i2c_client client;
77 enum chips type; /* To keep the chips type for `sensors' drivers. */
79 /* Because the i2c bus is slow, it is often useful to cache the read
80 information of a chip for some time (for example, 1 or 2 seconds).
81 It depends of course on the device whether this is really worthwhile
83 struct mutex update_lock; /* When we are reading lots of information,
84 another process should not update the
86 char valid; /* != 0 if the following fields are valid. */
87 unsigned long last_updated; /* In jiffies */
88 /* Add the read information here too */
95 Let's say we have a valid client structure. At some time, we will need
96 to gather information from the client, or write new information to the
97 client. How we will export this information to user-space is less
98 important at this moment (perhaps we do not need to do this at all for
99 some obscure clients). But we need generic reading and writing routines.
101 I have found it useful to define foo_read and foo_write function for this.
102 For some cases, it will be easier to call the i2c functions directly,
103 but many chips have some kind of register-value idea that can easily
106 The below functions are simple examples, and should not be copied
109 int foo_read_value(struct i2c_client *client, u8 reg)
111 if (reg < 0x10) /* byte-sized register */
112 return i2c_smbus_read_byte_data(client,reg);
113 else /* word-sized register */
114 return i2c_smbus_read_word_data(client,reg);
117 int foo_write_value(struct i2c_client *client, u8 reg, u16 value)
119 if (reg == 0x10) /* Impossible to write - driver error! */ {
121 else if (reg < 0x10) /* byte-sized register */
122 return i2c_smbus_write_byte_data(client,reg,value);
123 else /* word-sized register */
124 return i2c_smbus_write_word_data(client,reg,value);
128 Probing and attaching
129 =====================
131 The Linux I2C stack was originally written to support access to hardware
132 monitoring chips on PC motherboards, and thus it embeds some assumptions
133 that are more appropriate to SMBus (and PCs) than to I2C. One of these
134 assumptions is that most adapters and devices drivers support the SMBUS_QUICK
135 protocol to probe device presence. Another is that devices and their drivers
136 can be sufficiently configured using only such probe primitives.
138 As Linux and its I2C stack became more widely used in embedded systems
139 and complex components such as DVB adapters, those assumptions became more
140 problematic. Drivers for I2C devices that issue interrupts need more (and
141 different) configuration information, as do drivers handling chip variants
142 that can't be distinguished by protocol probing, or which need some board
143 specific information to operate correctly.
145 Accordingly, the I2C stack now has two models for associating I2C devices
146 with their drivers: the original "legacy" model, and a newer one that's
147 fully compatible with the Linux 2.6 driver model. These models do not mix,
148 since the "legacy" model requires drivers to create "i2c_client" device
149 objects after SMBus style probing, while the Linux driver model expects
150 drivers to be given such device objects in their probe() routines.
153 Standard Driver Model Binding ("New Style")
154 -------------------------------------------
156 System infrastructure, typically board-specific initialization code or
157 boot firmware, reports what I2C devices exist. For example, there may be
158 a table, in the kernel or from the boot loader, identifying I2C devices
159 and linking them to board-specific configuration information about IRQs
160 and other wiring artifacts, chip type, and so on. That could be used to
161 create i2c_client objects for each I2C device.
163 I2C device drivers using this binding model work just like any other
164 kind of driver in Linux: they provide a probe() method to bind to
165 those devices, and a remove() method to unbind.
167 static int foo_probe(struct i2c_client *client);
168 static int foo_remove(struct i2c_client *client);
170 Remember that the i2c_driver does not create those client handles. The
171 handle may be used during foo_probe(). If foo_probe() reports success
172 (zero not a negative status code) it may save the handle and use it until
173 foo_remove() returns. That binding model is used by most Linux drivers.
175 Drivers match devices when i2c_client.driver_name and the driver name are
176 the same; this approach is used in several other busses that don't have
177 device typing support in the hardware. The driver and module name should
178 match, so hotplug/coldplug mechanisms will modprobe the driver.
181 Device Creation (Standard driver model)
182 ---------------------------------------
184 If you know for a fact that an I2C device is connected to a given I2C bus,
185 you can instantiate that device by simply filling an i2c_board_info
186 structure with the device address and driver name, and calling
187 i2c_new_device(). This will create the device, then the driver core will
188 take care of finding the right driver and will call its probe() method.
189 If a driver supports different device types, you can specify the type you
190 want using the type field. You can also specify an IRQ and platform data
193 Sometimes you know that a device is connected to a given I2C bus, but you
194 don't know the exact address it uses. This happens on TV adapters for
195 example, where the same driver supports dozens of slightly different
196 models, and I2C device addresses change from one model to the next. In
197 that case, you can use the i2c_new_probed_device() variant, which is
198 similar to i2c_new_device(), except that it takes an additional list of
199 possible I2C addresses to probe. A device is created for the first
200 responsive address in the list. If you expect more than one device to be
201 present in the address range, simply call i2c_new_probed_device() that
204 The call to i2c_new_device() or i2c_new_probed_device() typically happens
205 in the I2C bus driver. You may want to save the returned i2c_client
206 reference for later use.
209 Device Deletion (Standard driver model)
210 ---------------------------------------
212 Each I2C device which has been created using i2c_new_device() or
213 i2c_new_probed_device() can be unregistered by calling
214 i2c_unregister_device(). If you don't call it explicitly, it will be
215 called automatically before the underlying I2C bus itself is removed, as a
216 device can't survive its parent in the device driver model.
219 Legacy Driver Binding Model
220 ---------------------------
222 Most i2c devices can be present on several i2c addresses; for some this
223 is determined in hardware (by soldering some chip pins to Vcc or Ground),
224 for others this can be changed in software (by writing to specific client
225 registers). Some devices are usually on a specific address, but not always;
226 and some are even more tricky. So you will probably need to scan several
227 i2c addresses for your clients, and do some sort of detection to see
228 whether it is actually a device supported by your driver.
230 To give the user a maximum of possibilities, some default module parameters
231 are defined to help determine what addresses are scanned. Several macros
232 are defined in i2c.h to help you support them, as well as a generic
235 You do not have to use this parameter interface; but don't try to use
236 function i2c_probe() if you don't.
239 Probing classes (Legacy model)
240 ------------------------------
242 All parameters are given as lists of unsigned 16-bit integers. Lists are
243 terminated by I2C_CLIENT_END.
244 The following lists are used internally:
246 normal_i2c: filled in by the module writer.
247 A list of I2C addresses which should normally be examined.
248 probe: insmod parameter.
249 A list of pairs. The first value is a bus number (-1 for any I2C bus),
250 the second is the address. These addresses are also probed, as if they
251 were in the 'normal' list.
252 ignore: insmod parameter.
253 A list of pairs. The first value is a bus number (-1 for any I2C bus),
254 the second is the I2C address. These addresses are never probed.
255 This parameter overrules the 'normal_i2c' list only.
256 force: insmod parameter.
257 A list of pairs. The first value is a bus number (-1 for any I2C bus),
258 the second is the I2C address. A device is blindly assumed to be on
259 the given address, no probing is done.
261 Additionally, kind-specific force lists may optionally be defined if
262 the driver supports several chip kinds. They are grouped in a
263 NULL-terminated list of pointers named forces, those first element if the
264 generic force list mentioned above. Each additional list correspond to an
265 insmod parameter of the form force_<kind>.
267 Fortunately, as a module writer, you just have to define the `normal_i2c'
268 parameter. The complete declaration could look like this:
270 /* Scan 0x37, and 0x48 to 0x4f */
271 static unsigned short normal_i2c[] = { 0x37, 0x48, 0x49, 0x4a, 0x4b, 0x4c,
272 0x4d, 0x4e, 0x4f, I2C_CLIENT_END };
274 /* Magic definition of all other variables and things */
276 /* Or, if your driver supports, say, 2 kind of devices: */
277 I2C_CLIENT_INSMOD_2(foo, bar);
279 If you use the multi-kind form, an enum will be defined for you:
280 enum chips { any_chip, foo, bar, ... }
281 You can then (and certainly should) use it in the driver code.
283 Note that you *have* to call the defined variable `normal_i2c',
287 Attaching to an adapter (Legacy model)
288 --------------------------------------
290 Whenever a new adapter is inserted, or for all adapters if the driver is
291 being registered, the callback attach_adapter() is called. Now is the
292 time to determine what devices are present on the adapter, and to register
293 a client for each of them.
295 The attach_adapter callback is really easy: we just call the generic
296 detection function. This function will scan the bus for us, using the
297 information as defined in the lists explained above. If a device is
298 detected at a specific address, another callback is called.
300 int foo_attach_adapter(struct i2c_adapter *adapter)
302 return i2c_probe(adapter,&addr_data,&foo_detect_client);
305 Remember, structure `addr_data' is defined by the macros explained above,
306 so you do not have to define it yourself.
308 The i2c_probe function will call the foo_detect_client
309 function only for those i2c addresses that actually have a device on
310 them (unless a `force' parameter was used). In addition, addresses that
311 are already in use (by some other registered client) are skipped.
314 The detect client function (Legacy model)
315 -----------------------------------------
317 The detect client function is called by i2c_probe. The `kind' parameter
318 contains -1 for a probed detection, 0 for a forced detection, or a positive
319 number for a forced detection with a chip type forced.
321 Returning an error different from -ENODEV in a detect function will cause
322 the detection to stop: other addresses and adapters won't be scanned.
323 This should only be done on fatal or internal errors, such as a memory
324 shortage or i2c_attach_client failing.
326 For now, you can ignore the `flags' parameter. It is there for future use.
328 int foo_detect_client(struct i2c_adapter *adapter, int address,
333 struct i2c_client *client;
334 struct foo_data *data;
335 const char *name = "";
337 /* Let's see whether this adapter can support what we need.
338 Please substitute the things you need here! */
339 if (!i2c_check_functionality(adapter,I2C_FUNC_SMBUS_WORD_DATA |
340 I2C_FUNC_SMBUS_WRITE_BYTE))
343 /* OK. For now, we presume we have a valid client. We now create the
344 client structure, even though we cannot fill it completely yet.
345 But it allows us to access several i2c functions safely */
347 if (!(data = kzalloc(sizeof(struct foo_data), GFP_KERNEL))) {
352 client = &data->client;
353 i2c_set_clientdata(client, data);
355 client->addr = address;
356 client->adapter = adapter;
357 client->driver = &foo_driver;
359 /* Now, we do the remaining detection. If no `force' parameter is used. */
361 /* First, the generic detection (if any), that is skipped if any force
362 parameter was used. */
364 /* The below is of course bogus */
365 if (foo_read(client, FOO_REG_GENERIC) != FOO_GENERIC_VALUE)
369 /* Next, specific detection. This is especially important for `sensors'
372 /* Determine the chip type. Not needed if a `force_CHIPTYPE' parameter
375 i = foo_read(client, FOO_REG_CHIPTYPE);
377 kind = chip1; /* As defined in the enum */
378 else if (i == FOO_TYPE_2)
381 printk("foo: Ignoring 'force' parameter for unknown chip at "
382 "adapter %d, address 0x%02x\n",i2c_adapter_id(adapter),address);
387 /* Now set the type and chip names */
390 } else if (kind == chip2) {
394 /* Fill in the remaining client fields. */
395 strlcpy(client->name, name, I2C_NAME_SIZE);
397 mutex_init(&data->update_lock); /* Only if you use this field */
399 /* Any other initializations in data must be done here too. */
401 /* This function can write default values to the client registers, if
403 foo_init_client(client);
405 /* Tell the i2c layer a new client has arrived */
406 if ((err = i2c_attach_client(client)))
411 /* OK, this is not exactly good programming practice, usually. But it is
412 very code-efficient in this case. */
421 Removing the client (Legacy model)
422 ==================================
424 The detach_client call back function is called when a client should be
425 removed. It may actually fail, but only when panicking. This code is
426 much simpler than the attachment code, fortunately!
428 int foo_detach_client(struct i2c_client *client)
432 /* Try to detach the client from i2c space */
433 if ((err = i2c_detach_client(client)))
436 kfree(i2c_get_clientdata(client));
441 Initializing the module or kernel
442 =================================
444 When the kernel is booted, or when your foo driver module is inserted,
445 you have to do some initializing. Fortunately, just attaching (registering)
446 the driver module is usually enough.
448 static int __init foo_init(void)
452 if ((res = i2c_add_driver(&foo_driver))) {
453 printk("foo: Driver registration failed, module not inserted.\n");
459 static void __exit foo_cleanup(void)
461 i2c_del_driver(&foo_driver);
464 /* Substitute your own name and email address */
465 MODULE_AUTHOR("Frodo Looijaard <frodol@dds.nl>"
466 MODULE_DESCRIPTION("Driver for Barf Inc. Foo I2C devices");
468 /* a few non-GPL license types are also allowed */
469 MODULE_LICENSE("GPL");
471 module_init(foo_init);
472 module_exit(foo_cleanup);
474 Note that some functions are marked by `__init', and some data structures
475 by `__initdata'. These functions and structures can be removed after
476 kernel booting (or module loading) is completed.
482 If your I2C device needs special handling when entering a system low
483 power state -- like putting a transceiver into a low power mode, or
484 activating a system wakeup mechanism -- do that in the suspend() method.
485 The resume() method should reverse what the suspend() method does.
487 These are standard driver model calls, and they work just like they
488 would for any other driver stack. The calls can sleep, and can use
489 I2C messaging to the device being suspended or resumed (since their
490 parent I2C adapter is active when these calls are issued, and IRQs
497 If your I2C device needs special handling when the system shuts down
498 or reboots (including kexec) -- like turning something off -- use a
501 Again, this is a standard driver model call, working just like it
502 would for any other driver stack: the calls can sleep, and can use
509 A generic ioctl-like function call back is supported. You will seldom
510 need this, and its use is deprecated anyway, so newer design should not
511 use it. Set it to NULL.
514 Sending and receiving
515 =====================
517 If you want to communicate with your device, there are several functions
518 to do this. You can find all of them in i2c.h.
520 If you can choose between plain i2c communication and SMBus level
521 communication, please use the last. All adapters understand SMBus level
522 commands, but only some of them understand plain i2c!
525 Plain i2c communication
526 -----------------------
528 extern int i2c_master_send(struct i2c_client *,const char* ,int);
529 extern int i2c_master_recv(struct i2c_client *,char* ,int);
531 These routines read and write some bytes from/to a client. The client
532 contains the i2c address, so you do not have to include it. The second
533 parameter contains the bytes the read/write, the third the length of the
534 buffer. Returned is the actual number of bytes read/written.
536 extern int i2c_transfer(struct i2c_adapter *adap, struct i2c_msg *msg,
539 This sends a series of messages. Each message can be a read or write,
540 and they can be mixed in any way. The transactions are combined: no
541 stop bit is sent between transaction. The i2c_msg structure contains
542 for each message the client address, the number of bytes of the message
543 and the message data itself.
545 You can read the file `i2c-protocol' for more information about the
552 extern s32 i2c_smbus_xfer (struct i2c_adapter * adapter, u16 addr,
553 unsigned short flags,
554 char read_write, u8 command, int size,
555 union i2c_smbus_data * data);
557 This is the generic SMBus function. All functions below are implemented
558 in terms of it. Never use this function directly!
561 extern s32 i2c_smbus_write_quick(struct i2c_client * client, u8 value);
562 extern s32 i2c_smbus_read_byte(struct i2c_client * client);
563 extern s32 i2c_smbus_write_byte(struct i2c_client * client, u8 value);
564 extern s32 i2c_smbus_read_byte_data(struct i2c_client * client, u8 command);
565 extern s32 i2c_smbus_write_byte_data(struct i2c_client * client,
566 u8 command, u8 value);
567 extern s32 i2c_smbus_read_word_data(struct i2c_client * client, u8 command);
568 extern s32 i2c_smbus_write_word_data(struct i2c_client * client,
569 u8 command, u16 value);
570 extern s32 i2c_smbus_write_block_data(struct i2c_client * client,
571 u8 command, u8 length,
573 extern s32 i2c_smbus_read_i2c_block_data(struct i2c_client * client,
574 u8 command, u8 *values);
576 These ones were removed in Linux 2.6.10 because they had no users, but could
577 be added back later if needed:
579 extern s32 i2c_smbus_read_block_data(struct i2c_client * client,
580 u8 command, u8 *values);
581 extern s32 i2c_smbus_write_i2c_block_data(struct i2c_client * client,
582 u8 command, u8 length,
584 extern s32 i2c_smbus_process_call(struct i2c_client * client,
585 u8 command, u16 value);
586 extern s32 i2c_smbus_block_process_call(struct i2c_client *client,
587 u8 command, u8 length,
590 All these transactions return -1 on failure. The 'write' transactions
591 return 0 on success; the 'read' transactions return the read value, except
592 for read_block, which returns the number of values read. The block buffers
593 need not be longer than 32 bytes.
595 You can read the file `smbus-protocol' for more information about the
596 actual SMBus protocol.
599 General purpose routines
600 ========================
602 Below all general purpose routines are listed, that were not mentioned
605 /* This call returns a unique low identifier for each registered adapter.
607 extern int i2c_adapter_id(struct i2c_adapter *adap);