1 This is a small guide for those who want to write kernel drivers for I2C
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, a client structure specific information like the actual I2C
27 static struct i2c_driver foo_driver = {
32 .attach_adapter = &foo_attach_adapter,
33 .detach_client = &foo_detach_client,
34 .command = &foo_command /* may be NULL */
37 The name field must match the driver name, including the case. It must not
38 contain spaces, and may be up to 31 characters long.
40 All other fields are for call-back functions which will be explained
47 The client structure has a special `data' field that can point to any
48 structure at all. You can use this to keep client-specific data. You
49 do not always need this, but especially for `sensors' drivers, it can
52 An example structure is below.
55 struct i2c_client client;
56 struct semaphore lock; /* For ISA access in `sensors' drivers. */
57 int sysctl_id; /* To keep the /proc directory entry for
59 enum chips type; /* To keep the chips type for `sensors' drivers. */
61 /* Because the i2c bus is slow, it is often useful to cache the read
62 information of a chip for some time (for example, 1 or 2 seconds).
63 It depends of course on the device whether this is really worthwhile
65 struct semaphore update_lock; /* When we are reading lots of information,
66 another process should not update the
68 char valid; /* != 0 if the following fields are valid. */
69 unsigned long last_updated; /* In jiffies */
70 /* Add the read information here too */
77 Let's say we have a valid client structure. At some time, we will need
78 to gather information from the client, or write new information to the
79 client. How we will export this information to user-space is less
80 important at this moment (perhaps we do not need to do this at all for
81 some obscure clients). But we need generic reading and writing routines.
83 I have found it useful to define foo_read and foo_write function for this.
84 For some cases, it will be easier to call the i2c functions directly,
85 but many chips have some kind of register-value idea that can easily
86 be encapsulated. Also, some chips have both ISA and I2C interfaces, and
87 it useful to abstract from this (only for `sensors' drivers).
89 The below functions are simple examples, and should not be copied
92 int foo_read_value(struct i2c_client *client, u8 reg)
94 if (reg < 0x10) /* byte-sized register */
95 return i2c_smbus_read_byte_data(client,reg);
96 else /* word-sized register */
97 return i2c_smbus_read_word_data(client,reg);
100 int foo_write_value(struct i2c_client *client, u8 reg, u16 value)
102 if (reg == 0x10) /* Impossible to write - driver error! */ {
104 else if (reg < 0x10) /* byte-sized register */
105 return i2c_smbus_write_byte_data(client,reg,value);
106 else /* word-sized register */
107 return i2c_smbus_write_word_data(client,reg,value);
110 For sensors code, you may have to cope with ISA registers too. Something
111 like the below often works. Note the locking!
113 int foo_read_value(struct i2c_client *client, u8 reg)
116 if (i2c_is_isa_client(client)) {
117 down(&(((struct foo_data *) (client->data)) -> lock));
118 outb_p(reg,client->addr + FOO_ADDR_REG_OFFSET);
119 res = inb_p(client->addr + FOO_DATA_REG_OFFSET);
120 up(&(((struct foo_data *) (client->data)) -> lock));
123 return i2c_smbus_read_byte_data(client,reg);
126 Writing is done the same way.
129 Probing and attaching
130 =====================
132 Most i2c devices can be present on several i2c addresses; for some this
133 is determined in hardware (by soldering some chip pins to Vcc or Ground),
134 for others this can be changed in software (by writing to specific client
135 registers). Some devices are usually on a specific address, but not always;
136 and some are even more tricky. So you will probably need to scan several
137 i2c addresses for your clients, and do some sort of detection to see
138 whether it is actually a device supported by your driver.
140 To give the user a maximum of possibilities, some default module parameters
141 are defined to help determine what addresses are scanned. Several macros
142 are defined in i2c.h to help you support them, as well as a generic
145 You do not have to use this parameter interface; but don't try to use
146 function i2c_probe() if you don't.
148 NOTE: If you want to write a `sensors' driver, the interface is slightly
149 different! See below.
156 All parameters are given as lists of unsigned 16-bit integers. Lists are
157 terminated by I2C_CLIENT_END.
158 The following lists are used internally:
160 normal_i2c: filled in by the module writer.
161 A list of I2C addresses which should normally be examined.
162 probe: insmod parameter.
163 A list of pairs. The first value is a bus number (-1 for any I2C bus),
164 the second is the address. These addresses are also probed, as if they
165 were in the 'normal' list.
166 ignore: insmod parameter.
167 A list of pairs. The first value is a bus number (-1 for any I2C bus),
168 the second is the I2C address. These addresses are never probed.
169 This parameter overrules the 'normal_i2c' list only.
170 force: insmod parameter.
171 A list of pairs. The first value is a bus number (-1 for any I2C bus),
172 the second is the I2C address. A device is blindly assumed to be on
173 the given address, no probing is done.
175 Additionally, kind-specific force lists may optionally be defined if
176 the driver supports several chip kinds. They are grouped in a
177 NULL-terminated list of pointers named forces, those first element if the
178 generic force list mentioned above. Each additional list correspond to an
179 insmod parameter of the form force_<kind>.
181 Fortunately, as a module writer, you just have to define the `normal_i2c'
182 parameter. The complete declaration could look like this:
184 /* Scan 0x37, and 0x48 to 0x4f */
185 static unsigned short normal_i2c[] = { 0x37, 0x48, 0x49, 0x4a, 0x4b, 0x4c,
186 0x4d, 0x4e, 0x4f, I2C_CLIENT_END };
188 /* Magic definition of all other variables and things */
190 /* Or, if your driver supports, say, 2 kind of devices: */
191 I2C_CLIENT_INSMOD_2(foo, bar);
193 If you use the multi-kind form, an enum will be defined for you:
194 enum chips { any_chip, foo, bar, ... }
195 You can then (and certainly should) use it in the driver code.
197 Note that you *have* to call the defined variable `normal_i2c',
201 Attaching to an adapter
202 -----------------------
204 Whenever a new adapter is inserted, or for all adapters if the driver is
205 being registered, the callback attach_adapter() is called. Now is the
206 time to determine what devices are present on the adapter, and to register
207 a client for each of them.
209 The attach_adapter callback is really easy: we just call the generic
210 detection function. This function will scan the bus for us, using the
211 information as defined in the lists explained above. If a device is
212 detected at a specific address, another callback is called.
214 int foo_attach_adapter(struct i2c_adapter *adapter)
216 return i2c_probe(adapter,&addr_data,&foo_detect_client);
219 Remember, structure `addr_data' is defined by the macros explained above,
220 so you do not have to define it yourself.
222 The i2c_probe function will call the foo_detect_client
223 function only for those i2c addresses that actually have a device on
224 them (unless a `force' parameter was used). In addition, addresses that
225 are already in use (by some other registered client) are skipped.
228 The detect client function
229 --------------------------
231 The detect client function is called by i2c_probe. The `kind' parameter
232 contains -1 for a probed detection, 0 for a forced detection, or a positive
233 number for a forced detection with a chip type forced.
235 Below, some things are only needed if this is a `sensors' driver. Those
236 parts are between /* SENSORS ONLY START */ and /* SENSORS ONLY END */
239 Returning an error different from -ENODEV in a detect function will cause
240 the detection to stop: other addresses and adapters won't be scanned.
241 This should only be done on fatal or internal errors, such as a memory
242 shortage or i2c_attach_client failing.
244 For now, you can ignore the `flags' parameter. It is there for future use.
246 int foo_detect_client(struct i2c_adapter *adapter, int address,
247 unsigned short flags, int kind)
251 struct i2c_client *new_client;
252 struct foo_data *data;
253 const char *client_name = ""; /* For non-`sensors' drivers, put the real
256 /* Let's see whether this adapter can support what we need.
257 Please substitute the things you need here!
258 For `sensors' drivers, add `! is_isa &&' to the if statement */
259 if (!i2c_check_functionality(adapter,I2C_FUNC_SMBUS_WORD_DATA |
260 I2C_FUNC_SMBUS_WRITE_BYTE))
263 /* SENSORS ONLY START */
264 const char *type_name = "";
265 int is_isa = i2c_is_isa_adapter(adapter);
267 /* Do this only if the chip can additionally be found on the ISA bus
272 /* Discard immediately if this ISA range is already used */
273 /* FIXME: never use check_region(), only request_region() */
274 if (check_region(address,FOO_EXTENT))
277 /* Probe whether there is anything on this address.
278 Some example code is below, but you will have to adapt this
279 for your own driver */
281 if (kind < 0) /* Only if no force parameter was used */ {
282 /* We may need long timeouts at least for some chips. */
283 #define REALLY_SLOW_IO
284 i = inb_p(address + 1);
285 if (inb_p(address + 2) != i)
287 if (inb_p(address + 3) != i)
289 if (inb_p(address + 7) != i)
291 #undef REALLY_SLOW_IO
293 /* Let's just hope nothing breaks here */
294 i = inb_p(address + 5) & 0x7f;
295 outb_p(~i & 0x7f,address+5);
296 if ((inb_p(address + 5) & 0x7f) != (~i & 0x7f)) {
303 /* SENSORS ONLY END */
305 /* OK. For now, we presume we have a valid client. We now create the
306 client structure, even though we cannot fill it completely yet.
307 But it allows us to access several i2c functions safely */
309 if (!(data = kzalloc(sizeof(struct foo_data), GFP_KERNEL))) {
314 new_client = &data->client;
315 i2c_set_clientdata(new_client, data);
317 new_client->addr = address;
318 new_client->adapter = adapter;
319 new_client->driver = &foo_driver;
320 new_client->flags = 0;
322 /* Now, we do the remaining detection. If no `force' parameter is used. */
324 /* First, the generic detection (if any), that is skipped if any force
325 parameter was used. */
327 /* The below is of course bogus */
328 if (foo_read(new_client,FOO_REG_GENERIC) != FOO_GENERIC_VALUE)
332 /* SENSORS ONLY START */
334 /* Next, specific detection. This is especially important for `sensors'
337 /* Determine the chip type. Not needed if a `force_CHIPTYPE' parameter
340 i = foo_read(new_client,FOO_REG_CHIPTYPE);
342 kind = chip1; /* As defined in the enum */
343 else if (i == FOO_TYPE_2)
346 printk("foo: Ignoring 'force' parameter for unknown chip at "
347 "adapter %d, address 0x%02x\n",i2c_adapter_id(adapter),address);
352 /* Now set the type and chip names */
354 type_name = "chip1"; /* For /proc entry */
355 client_name = "CHIP 1";
356 } else if (kind == chip2) {
357 type_name = "chip2"; /* For /proc entry */
358 client_name = "CHIP 2";
361 /* Reserve the ISA region */
363 request_region(address,FOO_EXTENT,type_name);
365 /* SENSORS ONLY END */
367 /* Fill in the remaining client fields. */
368 strcpy(new_client->name,client_name);
370 /* SENSORS ONLY BEGIN */
372 /* SENSORS ONLY END */
374 data->valid = 0; /* Only if you use this field */
375 init_MUTEX(&data->update_lock); /* Only if you use this field */
377 /* Any other initializations in data must be done here too. */
379 /* Tell the i2c layer a new client has arrived */
380 if ((err = i2c_attach_client(new_client)))
383 /* SENSORS ONLY BEGIN */
384 /* Register a new directory entry with module sensors. See below for
385 the `template' structure. */
386 if ((i = i2c_register_entry(new_client, type_name,
387 foo_dir_table_template,THIS_MODULE)) < 0) {
393 /* SENSORS ONLY END */
395 /* This function can write default values to the client registers, if
397 foo_init_client(new_client);
400 /* OK, this is not exactly good programming practice, usually. But it is
401 very code-efficient in this case. */
404 i2c_detach_client(new_client);
407 /* SENSORS ONLY START */
409 release_region(address,FOO_EXTENT);
410 /* SENSORS ONLY END */
421 The detach_client call back function is called when a client should be
422 removed. It may actually fail, but only when panicking. This code is
423 much simpler than the attachment code, fortunately!
425 int foo_detach_client(struct i2c_client *client)
429 /* SENSORS ONLY START */
430 /* Deregister with the `i2c-proc' module. */
431 i2c_deregister_entry(((struct lm78_data *)(client->data))->sysctl_id);
432 /* SENSORS ONLY END */
434 /* Try to detach the client from i2c space */
435 if ((err = i2c_detach_client(client)))
438 /* HYBRID SENSORS CHIP ONLY START */
439 if i2c_is_isa_client(client)
440 release_region(client->addr,LM78_EXTENT);
441 /* HYBRID SENSORS CHIP ONLY END */
443 kfree(i2c_get_clientdata(client));
448 Initializing the module or kernel
449 =================================
451 When the kernel is booted, or when your foo driver module is inserted,
452 you have to do some initializing. Fortunately, just attaching (registering)
453 the driver module is usually enough.
455 /* Keep track of how far we got in the initialization process. If several
456 things have to initialized, and we fail halfway, only those things
457 have to be cleaned up! */
458 static int __initdata foo_initialized = 0;
460 static int __init foo_init(void)
463 printk("foo version %s (%s)\n",FOO_VERSION,FOO_DATE);
465 if ((res = i2c_add_driver(&foo_driver))) {
466 printk("foo: Driver registration failed, module not inserted.\n");
474 void foo_cleanup(void)
476 if (foo_initialized == 1) {
477 if ((res = i2c_del_driver(&foo_driver))) {
478 printk("foo: Driver registration failed, module not removed.\n");
485 /* Substitute your own name and email address */
486 MODULE_AUTHOR("Frodo Looijaard <frodol@dds.nl>"
487 MODULE_DESCRIPTION("Driver for Barf Inc. Foo I2C devices");
489 module_init(foo_init);
490 module_exit(foo_cleanup);
492 Note that some functions are marked by `__init', and some data structures
493 by `__init_data'. Hose functions and structures can be removed after
494 kernel booting (or module loading) is completed.
499 A generic ioctl-like function call back is supported. You will seldom
500 need this. You may even set it to NULL.
502 /* No commands defined */
503 int foo_command(struct i2c_client *client, unsigned int cmd, void *arg)
509 Sending and receiving
510 =====================
512 If you want to communicate with your device, there are several functions
513 to do this. You can find all of them in i2c.h.
515 If you can choose between plain i2c communication and SMBus level
516 communication, please use the last. All adapters understand SMBus level
517 commands, but only some of them understand plain i2c!
520 Plain i2c communication
521 -----------------------
523 extern int i2c_master_send(struct i2c_client *,const char* ,int);
524 extern int i2c_master_recv(struct i2c_client *,char* ,int);
526 These routines read and write some bytes from/to a client. The client
527 contains the i2c address, so you do not have to include it. The second
528 parameter contains the bytes the read/write, the third the length of the
529 buffer. Returned is the actual number of bytes read/written.
531 extern int i2c_transfer(struct i2c_adapter *adap, struct i2c_msg *msg,
534 This sends a series of messages. Each message can be a read or write,
535 and they can be mixed in any way. The transactions are combined: no
536 stop bit is sent between transaction. The i2c_msg structure contains
537 for each message the client address, the number of bytes of the message
538 and the message data itself.
540 You can read the file `i2c-protocol' for more information about the
547 extern s32 i2c_smbus_xfer (struct i2c_adapter * adapter, u16 addr,
548 unsigned short flags,
549 char read_write, u8 command, int size,
550 union i2c_smbus_data * data);
552 This is the generic SMBus function. All functions below are implemented
553 in terms of it. Never use this function directly!
556 extern s32 i2c_smbus_write_quick(struct i2c_client * client, u8 value);
557 extern s32 i2c_smbus_read_byte(struct i2c_client * client);
558 extern s32 i2c_smbus_write_byte(struct i2c_client * client, u8 value);
559 extern s32 i2c_smbus_read_byte_data(struct i2c_client * client, u8 command);
560 extern s32 i2c_smbus_write_byte_data(struct i2c_client * client,
561 u8 command, u8 value);
562 extern s32 i2c_smbus_read_word_data(struct i2c_client * client, u8 command);
563 extern s32 i2c_smbus_write_word_data(struct i2c_client * client,
564 u8 command, u16 value);
565 extern s32 i2c_smbus_write_block_data(struct i2c_client * client,
566 u8 command, u8 length,
568 extern s32 i2c_smbus_read_i2c_block_data(struct i2c_client * client,
569 u8 command, u8 *values);
571 These ones were removed in Linux 2.6.10 because they had no users, but could
572 be added back later if needed:
574 extern s32 i2c_smbus_read_block_data(struct i2c_client * client,
575 u8 command, u8 *values);
576 extern s32 i2c_smbus_write_i2c_block_data(struct i2c_client * client,
577 u8 command, u8 length,
579 extern s32 i2c_smbus_process_call(struct i2c_client * client,
580 u8 command, u16 value);
581 extern s32 i2c_smbus_block_process_call(struct i2c_client *client,
582 u8 command, u8 length,
585 All these transactions return -1 on failure. The 'write' transactions
586 return 0 on success; the 'read' transactions return the read value, except
587 for read_block, which returns the number of values read. The block buffers
588 need not be longer than 32 bytes.
590 You can read the file `smbus-protocol' for more information about the
591 actual SMBus protocol.
594 General purpose routines
595 ========================
597 Below all general purpose routines are listed, that were not mentioned
600 /* This call returns a unique low identifier for each registered adapter,
601 * or -1 if the adapter was not registered.
603 extern int i2c_adapter_id(struct i2c_adapter *adap);
606 The sensors sysctl/proc interface
607 =================================
609 This section only applies if you write `sensors' drivers.
611 Each sensors driver creates a directory in /proc/sys/dev/sensors for each
612 registered client. The directory is called something like foo-i2c-4-65.
613 The sensors module helps you to do this as easily as possible.
618 You will need to define a ctl_table template. This template will automatically
619 be copied to a newly allocated structure and filled in where necessary when
620 you call sensors_register_entry.
622 First, I will give an example definition.
623 static ctl_table foo_dir_table_template[] = {
624 { FOO_SYSCTL_FUNC1, "func1", NULL, 0, 0644, NULL, &i2c_proc_real,
625 &i2c_sysctl_real,NULL,&foo_func },
626 { FOO_SYSCTL_FUNC2, "func2", NULL, 0, 0644, NULL, &i2c_proc_real,
627 &i2c_sysctl_real,NULL,&foo_func },
628 { FOO_SYSCTL_DATA, "data", NULL, 0, 0644, NULL, &i2c_proc_real,
629 &i2c_sysctl_real,NULL,&foo_data },
633 In the above example, three entries are defined. They can either be
634 accessed through the /proc interface, in the /proc/sys/dev/sensors/*
635 directories, as files named func1, func2 and data, or alternatively
636 through the sysctl interface, in the appropriate table, with identifiers
637 FOO_SYSCTL_FUNC1, FOO_SYSCTL_FUNC2 and FOO_SYSCTL_DATA.
639 The third, sixth and ninth parameters should always be NULL, and the
640 fourth should always be 0. The fifth is the mode of the /proc file;
641 0644 is safe, as the file will be owned by root:root.
643 The seventh and eighth parameters should be &i2c_proc_real and
644 &i2c_sysctl_real if you want to export lists of reals (scaled
645 integers). You can also use your own function for them, as usual.
646 Finally, the last parameter is the call-back to gather the data
647 (see below) if you use the *_proc_real functions.
653 The call back functions (foo_func and foo_data in the above example)
654 can be called in several ways; the operation parameter determines
657 * If operation == SENSORS_PROC_REAL_INFO, you must return the
658 magnitude (scaling) in nrels_mag;
659 * If operation == SENSORS_PROC_REAL_READ, you must read information
660 from the chip and return it in results. The number of integers
661 to display should be put in nrels_mag;
662 * If operation == SENSORS_PROC_REAL_WRITE, you must write the
663 supplied information to the chip. nrels_mag will contain the number
664 of integers, results the integers themselves.
666 The *_proc_real functions will display the elements as reals for the
667 /proc interface. If you set the magnitude to 2, and supply 345 for
668 SENSORS_PROC_REAL_READ, it would display 3.45; and if the user would
669 write 45.6 to the /proc file, it would be returned as 4560 for
670 SENSORS_PROC_REAL_WRITE. A magnitude may even be negative!
674 /* FOO_FROM_REG and FOO_TO_REG translate between scaled values and
675 register values. Note the use of the read cache. */
676 void foo_in(struct i2c_client *client, int operation, int ctl_name,
677 int *nrels_mag, long *results)
679 struct foo_data *data = client->data;
680 int nr = ctl_name - FOO_SYSCTL_FUNC1; /* reduce to 0 upwards */
682 if (operation == SENSORS_PROC_REAL_INFO)
684 else if (operation == SENSORS_PROC_REAL_READ) {
685 /* Update the readings cache (if necessary) */
686 foo_update_client(client);
687 /* Get the readings from the cache */
688 results[0] = FOO_FROM_REG(data->foo_func_base[nr]);
689 results[1] = FOO_FROM_REG(data->foo_func_more[nr]);
690 results[2] = FOO_FROM_REG(data->foo_func_readonly[nr]);
692 } else if (operation == SENSORS_PROC_REAL_WRITE) {
693 if (*nrels_mag >= 1) {
694 /* Update the cache */
695 data->foo_base[nr] = FOO_TO_REG(results[0]);
696 /* Update the chip */
697 foo_write_value(client,FOO_REG_FUNC_BASE(nr),data->foo_base[nr]);
699 if (*nrels_mag >= 2) {
700 /* Update the cache */
701 data->foo_more[nr] = FOO_TO_REG(results[1]);
702 /* Update the chip */
703 foo_write_value(client,FOO_REG_FUNC_MORE(nr),data->foo_more[nr]);