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 /* iff driver uses driver model ("new style") binding model: */
30 static struct i2c_device_id foo_idtable[] = {
31 { "foo", my_id_for_foo },
32 { "bar", my_id_for_bar },
36 MODULE_DEVICE_TABLE(i2c, foo_idtable);
38 static struct i2c_driver foo_driver = {
43 /* iff driver uses driver model ("new style") binding model: */
47 /* if device autodetection is needed: */
48 .class = I2C_CLASS_SOMETHING,
50 .address_data = &addr_data,
52 /* else, driver uses "legacy" binding model: */
53 .attach_adapter = foo_attach_adapter,
54 .detach_client = foo_detach_client,
56 /* these may be used regardless of the driver binding model */
57 .shutdown = foo_shutdown, /* optional */
58 .suspend = foo_suspend, /* optional */
59 .resume = foo_resume, /* optional */
60 .command = foo_command, /* optional */
63 The name field is the driver name, and must not contain spaces. It
64 should match the module name (if the driver can be compiled as a module),
65 although you can use MODULE_ALIAS (passing "foo" in this example) to add
66 another name for the module. If the driver name doesn't match the module
67 name, the module won't be automatically loaded (hotplug/coldplug).
69 All other fields are for call-back functions which will be explained
76 Each client structure has a special `data' field that can point to any
77 structure at all. You should use this to keep device-specific data,
78 especially in drivers that handle multiple I2C or SMBUS devices. You
79 do not always need this, but especially for `sensors' drivers, it can
83 void i2c_set_clientdata(struct i2c_client *client, void *data);
85 /* retrieve the value */
86 void *i2c_get_clientdata(struct i2c_client *client);
88 An example structure is below.
91 struct i2c_client client;
92 enum chips type; /* To keep the chips type for `sensors' drivers. */
94 /* Because the i2c bus is slow, it is often useful to cache the read
95 information of a chip for some time (for example, 1 or 2 seconds).
96 It depends of course on the device whether this is really worthwhile
98 struct mutex update_lock; /* When we are reading lots of information,
99 another process should not update the
101 char valid; /* != 0 if the following fields are valid. */
102 unsigned long last_updated; /* In jiffies */
103 /* Add the read information here too */
110 Let's say we have a valid client structure. At some time, we will need
111 to gather information from the client, or write new information to the
112 client. How we will export this information to user-space is less
113 important at this moment (perhaps we do not need to do this at all for
114 some obscure clients). But we need generic reading and writing routines.
116 I have found it useful to define foo_read and foo_write function for this.
117 For some cases, it will be easier to call the i2c functions directly,
118 but many chips have some kind of register-value idea that can easily
121 The below functions are simple examples, and should not be copied
124 int foo_read_value(struct i2c_client *client, u8 reg)
126 if (reg < 0x10) /* byte-sized register */
127 return i2c_smbus_read_byte_data(client,reg);
128 else /* word-sized register */
129 return i2c_smbus_read_word_data(client,reg);
132 int foo_write_value(struct i2c_client *client, u8 reg, u16 value)
134 if (reg == 0x10) /* Impossible to write - driver error! */ {
136 else if (reg < 0x10) /* byte-sized register */
137 return i2c_smbus_write_byte_data(client,reg,value);
138 else /* word-sized register */
139 return i2c_smbus_write_word_data(client,reg,value);
143 Probing and attaching
144 =====================
146 The Linux I2C stack was originally written to support access to hardware
147 monitoring chips on PC motherboards, and thus it embeds some assumptions
148 that are more appropriate to SMBus (and PCs) than to I2C. One of these
149 assumptions is that most adapters and devices drivers support the SMBUS_QUICK
150 protocol to probe device presence. Another is that devices and their drivers
151 can be sufficiently configured using only such probe primitives.
153 As Linux and its I2C stack became more widely used in embedded systems
154 and complex components such as DVB adapters, those assumptions became more
155 problematic. Drivers for I2C devices that issue interrupts need more (and
156 different) configuration information, as do drivers handling chip variants
157 that can't be distinguished by protocol probing, or which need some board
158 specific information to operate correctly.
160 Accordingly, the I2C stack now has two models for associating I2C devices
161 with their drivers: the original "legacy" model, and a newer one that's
162 fully compatible with the Linux 2.6 driver model. These models do not mix,
163 since the "legacy" model requires drivers to create "i2c_client" device
164 objects after SMBus style probing, while the Linux driver model expects
165 drivers to be given such device objects in their probe() routines.
168 Standard Driver Model Binding ("New Style")
169 -------------------------------------------
171 System infrastructure, typically board-specific initialization code or
172 boot firmware, reports what I2C devices exist. For example, there may be
173 a table, in the kernel or from the boot loader, identifying I2C devices
174 and linking them to board-specific configuration information about IRQs
175 and other wiring artifacts, chip type, and so on. That could be used to
176 create i2c_client objects for each I2C device.
178 I2C device drivers using this binding model work just like any other
179 kind of driver in Linux: they provide a probe() method to bind to
180 those devices, and a remove() method to unbind.
182 static int foo_probe(struct i2c_client *client,
183 const struct i2c_device_id *id);
184 static int foo_remove(struct i2c_client *client);
186 Remember that the i2c_driver does not create those client handles. The
187 handle may be used during foo_probe(). If foo_probe() reports success
188 (zero not a negative status code) it may save the handle and use it until
189 foo_remove() returns. That binding model is used by most Linux drivers.
191 The probe function is called when an entry in the id_table name field
192 matches the device's name. It is passed the entry that was matched so
193 the driver knows which one in the table matched.
196 Device Creation (Standard driver model)
197 ---------------------------------------
199 If you know for a fact that an I2C device is connected to a given I2C bus,
200 you can instantiate that device by simply filling an i2c_board_info
201 structure with the device address and driver name, and calling
202 i2c_new_device(). This will create the device, then the driver core will
203 take care of finding the right driver and will call its probe() method.
204 If a driver supports different device types, you can specify the type you
205 want using the type field. You can also specify an IRQ and platform data
208 Sometimes you know that a device is connected to a given I2C bus, but you
209 don't know the exact address it uses. This happens on TV adapters for
210 example, where the same driver supports dozens of slightly different
211 models, and I2C device addresses change from one model to the next. In
212 that case, you can use the i2c_new_probed_device() variant, which is
213 similar to i2c_new_device(), except that it takes an additional list of
214 possible I2C addresses to probe. A device is created for the first
215 responsive address in the list. If you expect more than one device to be
216 present in the address range, simply call i2c_new_probed_device() that
219 The call to i2c_new_device() or i2c_new_probed_device() typically happens
220 in the I2C bus driver. You may want to save the returned i2c_client
221 reference for later use.
224 Device Detection (Standard driver model)
225 ----------------------------------------
227 Sometimes you do not know in advance which I2C devices are connected to
228 a given I2C bus. This is for example the case of hardware monitoring
229 devices on a PC's SMBus. In that case, you may want to let your driver
230 detect supported devices automatically. This is how the legacy model
231 was working, and is now available as an extension to the standard
232 driver model (so that we can finally get rid of the legacy model.)
234 You simply have to define a detect callback which will attempt to
235 identify supported devices (returning 0 for supported ones and -ENODEV
236 for unsupported ones), a list of addresses to probe, and a device type
237 (or class) so that only I2C buses which may have that type of device
238 connected (and not otherwise enumerated) will be probed. The i2c
239 core will then call you back as needed and will instantiate a device
240 for you for every successful detection.
242 Note that this mechanism is purely optional and not suitable for all
243 devices. You need some reliable way to identify the supported devices
244 (typically using device-specific, dedicated identification registers),
245 otherwise misdetections are likely to occur and things can get wrong
249 Device Deletion (Standard driver model)
250 ---------------------------------------
252 Each I2C device which has been created using i2c_new_device() or
253 i2c_new_probed_device() can be unregistered by calling
254 i2c_unregister_device(). If you don't call it explicitly, it will be
255 called automatically before the underlying I2C bus itself is removed, as a
256 device can't survive its parent in the device driver model.
259 Legacy Driver Binding Model
260 ---------------------------
262 Most i2c devices can be present on several i2c addresses; for some this
263 is determined in hardware (by soldering some chip pins to Vcc or Ground),
264 for others this can be changed in software (by writing to specific client
265 registers). Some devices are usually on a specific address, but not always;
266 and some are even more tricky. So you will probably need to scan several
267 i2c addresses for your clients, and do some sort of detection to see
268 whether it is actually a device supported by your driver.
270 To give the user a maximum of possibilities, some default module parameters
271 are defined to help determine what addresses are scanned. Several macros
272 are defined in i2c.h to help you support them, as well as a generic
275 You do not have to use this parameter interface; but don't try to use
276 function i2c_probe() if you don't.
279 Probing classes (Legacy model)
280 ------------------------------
282 All parameters are given as lists of unsigned 16-bit integers. Lists are
283 terminated by I2C_CLIENT_END.
284 The following lists are used internally:
286 normal_i2c: filled in by the module writer.
287 A list of I2C addresses which should normally be examined.
288 probe: insmod parameter.
289 A list of pairs. The first value is a bus number (-1 for any I2C bus),
290 the second is the address. These addresses are also probed, as if they
291 were in the 'normal' list.
292 ignore: insmod parameter.
293 A list of pairs. The first value is a bus number (-1 for any I2C bus),
294 the second is the I2C address. These addresses are never probed.
295 This parameter overrules the 'normal_i2c' list only.
296 force: insmod parameter.
297 A list of pairs. The first value is a bus number (-1 for any I2C bus),
298 the second is the I2C address. A device is blindly assumed to be on
299 the given address, no probing is done.
301 Additionally, kind-specific force lists may optionally be defined if
302 the driver supports several chip kinds. They are grouped in a
303 NULL-terminated list of pointers named forces, those first element if the
304 generic force list mentioned above. Each additional list correspond to an
305 insmod parameter of the form force_<kind>.
307 Fortunately, as a module writer, you just have to define the `normal_i2c'
308 parameter. The complete declaration could look like this:
310 /* Scan 0x4c to 0x4f */
311 static const unsigned short normal_i2c[] = { 0x4c, 0x4d, 0x4e, 0x4f,
314 /* Magic definition of all other variables and things */
316 /* Or, if your driver supports, say, 2 kind of devices: */
317 I2C_CLIENT_INSMOD_2(foo, bar);
319 If you use the multi-kind form, an enum will be defined for you:
320 enum chips { any_chip, foo, bar, ... }
321 You can then (and certainly should) use it in the driver code.
323 Note that you *have* to call the defined variable `normal_i2c',
327 Attaching to an adapter (Legacy model)
328 --------------------------------------
330 Whenever a new adapter is inserted, or for all adapters if the driver is
331 being registered, the callback attach_adapter() is called. Now is the
332 time to determine what devices are present on the adapter, and to register
333 a client for each of them.
335 The attach_adapter callback is really easy: we just call the generic
336 detection function. This function will scan the bus for us, using the
337 information as defined in the lists explained above. If a device is
338 detected at a specific address, another callback is called.
340 int foo_attach_adapter(struct i2c_adapter *adapter)
342 return i2c_probe(adapter,&addr_data,&foo_detect_client);
345 Remember, structure `addr_data' is defined by the macros explained above,
346 so you do not have to define it yourself.
348 The i2c_probe function will call the foo_detect_client
349 function only for those i2c addresses that actually have a device on
350 them (unless a `force' parameter was used). In addition, addresses that
351 are already in use (by some other registered client) are skipped.
354 The detect client function (Legacy model)
355 -----------------------------------------
357 The detect client function is called by i2c_probe. The `kind' parameter
358 contains -1 for a probed detection, 0 for a forced detection, or a positive
359 number for a forced detection with a chip type forced.
361 Returning an error different from -ENODEV in a detect function will cause
362 the detection to stop: other addresses and adapters won't be scanned.
363 This should only be done on fatal or internal errors, such as a memory
364 shortage or i2c_attach_client failing.
366 For now, you can ignore the `flags' parameter. It is there for future use.
368 int foo_detect_client(struct i2c_adapter *adapter, int address,
373 struct i2c_client *client;
374 struct foo_data *data;
375 const char *name = "";
377 /* Let's see whether this adapter can support what we need.
378 Please substitute the things you need here! */
379 if (!i2c_check_functionality(adapter,I2C_FUNC_SMBUS_WORD_DATA |
380 I2C_FUNC_SMBUS_WRITE_BYTE))
383 /* OK. For now, we presume we have a valid client. We now create the
384 client structure, even though we cannot fill it completely yet.
385 But it allows us to access several i2c functions safely */
387 if (!(data = kzalloc(sizeof(struct foo_data), GFP_KERNEL))) {
392 client = &data->client;
393 i2c_set_clientdata(client, data);
395 client->addr = address;
396 client->adapter = adapter;
397 client->driver = &foo_driver;
399 /* Now, we do the remaining detection. If no `force' parameter is used. */
401 /* First, the generic detection (if any), that is skipped if any force
402 parameter was used. */
404 /* The below is of course bogus */
405 if (foo_read(client, FOO_REG_GENERIC) != FOO_GENERIC_VALUE)
409 /* Next, specific detection. This is especially important for `sensors'
412 /* Determine the chip type. Not needed if a `force_CHIPTYPE' parameter
415 i = foo_read(client, FOO_REG_CHIPTYPE);
417 kind = chip1; /* As defined in the enum */
418 else if (i == FOO_TYPE_2)
421 printk("foo: Ignoring 'force' parameter for unknown chip at "
422 "adapter %d, address 0x%02x\n",i2c_adapter_id(adapter),address);
427 /* Now set the type and chip names */
430 } else if (kind == chip2) {
434 /* Fill in the remaining client fields. */
435 strlcpy(client->name, name, I2C_NAME_SIZE);
437 mutex_init(&data->update_lock); /* Only if you use this field */
439 /* Any other initializations in data must be done here too. */
441 /* This function can write default values to the client registers, if
443 foo_init_client(client);
445 /* Tell the i2c layer a new client has arrived */
446 if ((err = i2c_attach_client(client)))
451 /* OK, this is not exactly good programming practice, usually. But it is
452 very code-efficient in this case. */
461 Removing the client (Legacy model)
462 ==================================
464 The detach_client call back function is called when a client should be
465 removed. It may actually fail, but only when panicking. This code is
466 much simpler than the attachment code, fortunately!
468 int foo_detach_client(struct i2c_client *client)
472 /* Try to detach the client from i2c space */
473 if ((err = i2c_detach_client(client)))
476 kfree(i2c_get_clientdata(client));
481 Initializing the module or kernel
482 =================================
484 When the kernel is booted, or when your foo driver module is inserted,
485 you have to do some initializing. Fortunately, just attaching (registering)
486 the driver module is usually enough.
488 static int __init foo_init(void)
492 if ((res = i2c_add_driver(&foo_driver))) {
493 printk("foo: Driver registration failed, module not inserted.\n");
499 static void __exit foo_cleanup(void)
501 i2c_del_driver(&foo_driver);
504 /* Substitute your own name and email address */
505 MODULE_AUTHOR("Frodo Looijaard <frodol@dds.nl>"
506 MODULE_DESCRIPTION("Driver for Barf Inc. Foo I2C devices");
508 /* a few non-GPL license types are also allowed */
509 MODULE_LICENSE("GPL");
511 module_init(foo_init);
512 module_exit(foo_cleanup);
514 Note that some functions are marked by `__init', and some data structures
515 by `__initdata'. These functions and structures can be removed after
516 kernel booting (or module loading) is completed.
522 If your I2C device needs special handling when entering a system low
523 power state -- like putting a transceiver into a low power mode, or
524 activating a system wakeup mechanism -- do that in the suspend() method.
525 The resume() method should reverse what the suspend() method does.
527 These are standard driver model calls, and they work just like they
528 would for any other driver stack. The calls can sleep, and can use
529 I2C messaging to the device being suspended or resumed (since their
530 parent I2C adapter is active when these calls are issued, and IRQs
537 If your I2C device needs special handling when the system shuts down
538 or reboots (including kexec) -- like turning something off -- use a
541 Again, this is a standard driver model call, working just like it
542 would for any other driver stack: the calls can sleep, and can use
549 A generic ioctl-like function call back is supported. You will seldom
550 need this, and its use is deprecated anyway, so newer design should not
551 use it. Set it to NULL.
554 Sending and receiving
555 =====================
557 If you want to communicate with your device, there are several functions
558 to do this. You can find all of them in i2c.h.
560 If you can choose between plain i2c communication and SMBus level
561 communication, please use the last. All adapters understand SMBus level
562 commands, but only some of them understand plain i2c!
565 Plain i2c communication
566 -----------------------
568 extern int i2c_master_send(struct i2c_client *,const char* ,int);
569 extern int i2c_master_recv(struct i2c_client *,char* ,int);
571 These routines read and write some bytes from/to a client. The client
572 contains the i2c address, so you do not have to include it. The second
573 parameter contains the bytes the read/write, the third the length of the
574 buffer. Returned is the actual number of bytes read/written.
576 extern int i2c_transfer(struct i2c_adapter *adap, struct i2c_msg *msg,
579 This sends a series of messages. Each message can be a read or write,
580 and they can be mixed in any way. The transactions are combined: no
581 stop bit is sent between transaction. The i2c_msg structure contains
582 for each message the client address, the number of bytes of the message
583 and the message data itself.
585 You can read the file `i2c-protocol' for more information about the
592 extern s32 i2c_smbus_xfer (struct i2c_adapter * adapter, u16 addr,
593 unsigned short flags,
594 char read_write, u8 command, int size,
595 union i2c_smbus_data * data);
597 This is the generic SMBus function. All functions below are implemented
598 in terms of it. Never use this function directly!
601 extern s32 i2c_smbus_read_byte(struct i2c_client * client);
602 extern s32 i2c_smbus_write_byte(struct i2c_client * client, u8 value);
603 extern s32 i2c_smbus_read_byte_data(struct i2c_client * client, u8 command);
604 extern s32 i2c_smbus_write_byte_data(struct i2c_client * client,
605 u8 command, u8 value);
606 extern s32 i2c_smbus_read_word_data(struct i2c_client * client, u8 command);
607 extern s32 i2c_smbus_write_word_data(struct i2c_client * client,
608 u8 command, u16 value);
609 extern s32 i2c_smbus_read_block_data(struct i2c_client * client,
610 u8 command, u8 *values);
611 extern s32 i2c_smbus_write_block_data(struct i2c_client * client,
612 u8 command, u8 length,
614 extern s32 i2c_smbus_read_i2c_block_data(struct i2c_client * client,
615 u8 command, u8 length, u8 *values);
616 extern s32 i2c_smbus_write_i2c_block_data(struct i2c_client * client,
617 u8 command, u8 length,
620 These ones were removed from i2c-core because they had no users, but could
621 be added back later if needed:
623 extern s32 i2c_smbus_write_quick(struct i2c_client * client, u8 value);
624 extern s32 i2c_smbus_process_call(struct i2c_client * client,
625 u8 command, u16 value);
626 extern s32 i2c_smbus_block_process_call(struct i2c_client *client,
627 u8 command, u8 length,
630 All these transactions return a negative errno value on failure. The 'write'
631 transactions return 0 on success; the 'read' transactions return the read
632 value, except for block transactions, which return the number of values
633 read. The block buffers need not be longer than 32 bytes.
635 You can read the file `smbus-protocol' for more information about the
636 actual SMBus protocol.
639 General purpose routines
640 ========================
642 Below all general purpose routines are listed, that were not mentioned
645 /* This call returns a unique low identifier for each registered adapter.
647 extern int i2c_adapter_id(struct i2c_adapter *adap);