blob: e62fbfa1282ded6610519255975dff229b714e3f [file] [log] [blame]
Linus Torvalds1da177e2005-04-16 15:20:36 -07001This is a small guide for those who want to write kernel drivers for I2C
David Brownell4298cfc2007-05-01 23:26:31 +02002or SMBus devices, using Linux as the protocol host/master (not slave).
Linus Torvalds1da177e2005-04-16 15:20:36 -07003
4To set up a driver, you need to do several things. Some are optional, and
5some things can be done slightly or completely different. Use this as a
6guide, not as a rule book!
7
8
9General remarks
10===============
11
12Try to keep the kernel namespace as clean as possible. The best way to
13do this is to use a unique prefix for all global symbols. This is
14especially important for exported symbols, but it is a good idea to do
15it for non-exported symbols too. We will use the prefix `foo_' in this
16tutorial, and `FOO_' for preprocessor variables.
17
18
19The driver structure
20====================
21
22Usually, you will implement a single driver structure, and instantiate
23all clients from it. Remember, a driver structure contains general access
David Brownellf37dd802007-02-13 22:09:00 +010024routines, and should be zero-initialized except for fields with data you
25provide. A client structure holds device-specific information like the
26driver model device node, and its I2C address.
Linus Torvalds1da177e2005-04-16 15:20:36 -070027
28static struct i2c_driver foo_driver = {
Jean Delvared45d2042005-11-26 20:55:35 +010029 .driver = {
Jean Delvared45d2042005-11-26 20:55:35 +010030 .name = "foo",
31 },
David Brownell4298cfc2007-05-01 23:26:31 +020032
33 /* iff driver uses driver model ("new style") binding model: */
34 .probe = foo_probe,
35 .remove = foo_remove,
36
37 /* else, driver uses "legacy" binding model: */
David Brownellf37dd802007-02-13 22:09:00 +010038 .attach_adapter = foo_attach_adapter,
39 .detach_client = foo_detach_client,
David Brownell4298cfc2007-05-01 23:26:31 +020040
41 /* these may be used regardless of the driver binding model */
David Brownellf37dd802007-02-13 22:09:00 +010042 .shutdown = foo_shutdown, /* optional */
43 .suspend = foo_suspend, /* optional */
44 .resume = foo_resume, /* optional */
45 .command = foo_command, /* optional */
Linus Torvalds1da177e2005-04-16 15:20:36 -070046}
47
David Brownellf37dd802007-02-13 22:09:00 +010048The name field is the driver name, and must not contain spaces. It
49should match the module name (if the driver can be compiled as a module),
50although you can use MODULE_ALIAS (passing "foo" in this example) to add
David Brownell4298cfc2007-05-01 23:26:31 +020051another name for the module. If the driver name doesn't match the module
52name, the module won't be automatically loaded (hotplug/coldplug).
Linus Torvalds1da177e2005-04-16 15:20:36 -070053
Linus Torvalds1da177e2005-04-16 15:20:36 -070054All other fields are for call-back functions which will be explained
55below.
56
Linus Torvalds1da177e2005-04-16 15:20:36 -070057
58Extra client data
59=================
60
David Brownellf37dd802007-02-13 22:09:00 +010061Each client structure has a special `data' field that can point to any
62structure at all. You should use this to keep device-specific data,
63especially in drivers that handle multiple I2C or SMBUS devices. You
Linus Torvalds1da177e2005-04-16 15:20:36 -070064do not always need this, but especially for `sensors' drivers, it can
65be very useful.
66
David Brownellf37dd802007-02-13 22:09:00 +010067 /* store the value */
68 void i2c_set_clientdata(struct i2c_client *client, void *data);
69
70 /* retrieve the value */
71 void *i2c_get_clientdata(struct i2c_client *client);
72
Linus Torvalds1da177e2005-04-16 15:20:36 -070073An example structure is below.
74
75 struct foo_data {
Jean Delvare2445eb62005-10-17 23:16:25 +020076 struct i2c_client client;
Linus Torvalds1da177e2005-04-16 15:20:36 -070077 struct semaphore lock; /* For ISA access in `sensors' drivers. */
78 int sysctl_id; /* To keep the /proc directory entry for
79 `sensors' drivers. */
80 enum chips type; /* To keep the chips type for `sensors' drivers. */
81
82 /* Because the i2c bus is slow, it is often useful to cache the read
83 information of a chip for some time (for example, 1 or 2 seconds).
84 It depends of course on the device whether this is really worthwhile
85 or even sensible. */
86 struct semaphore update_lock; /* When we are reading lots of information,
87 another process should not update the
88 below information */
89 char valid; /* != 0 if the following fields are valid. */
90 unsigned long last_updated; /* In jiffies */
91 /* Add the read information here too */
92 };
93
94
95Accessing the client
96====================
97
98Let's say we have a valid client structure. At some time, we will need
99to gather information from the client, or write new information to the
100client. How we will export this information to user-space is less
101important at this moment (perhaps we do not need to do this at all for
102some obscure clients). But we need generic reading and writing routines.
103
104I have found it useful to define foo_read and foo_write function for this.
105For some cases, it will be easier to call the i2c functions directly,
106but many chips have some kind of register-value idea that can easily
107be encapsulated. Also, some chips have both ISA and I2C interfaces, and
108it useful to abstract from this (only for `sensors' drivers).
109
110The below functions are simple examples, and should not be copied
111literally.
112
113 int foo_read_value(struct i2c_client *client, u8 reg)
114 {
115 if (reg < 0x10) /* byte-sized register */
116 return i2c_smbus_read_byte_data(client,reg);
117 else /* word-sized register */
118 return i2c_smbus_read_word_data(client,reg);
119 }
120
121 int foo_write_value(struct i2c_client *client, u8 reg, u16 value)
122 {
123 if (reg == 0x10) /* Impossible to write - driver error! */ {
124 return -1;
125 else if (reg < 0x10) /* byte-sized register */
126 return i2c_smbus_write_byte_data(client,reg,value);
127 else /* word-sized register */
128 return i2c_smbus_write_word_data(client,reg,value);
129 }
130
131For sensors code, you may have to cope with ISA registers too. Something
132like the below often works. Note the locking!
133
134 int foo_read_value(struct i2c_client *client, u8 reg)
135 {
136 int res;
137 if (i2c_is_isa_client(client)) {
138 down(&(((struct foo_data *) (client->data)) -> lock));
139 outb_p(reg,client->addr + FOO_ADDR_REG_OFFSET);
140 res = inb_p(client->addr + FOO_DATA_REG_OFFSET);
141 up(&(((struct foo_data *) (client->data)) -> lock));
142 return res;
143 } else
144 return i2c_smbus_read_byte_data(client,reg);
145 }
146
147Writing is done the same way.
148
149
150Probing and attaching
151=====================
152
David Brownell4298cfc2007-05-01 23:26:31 +0200153The Linux I2C stack was originally written to support access to hardware
154monitoring chips on PC motherboards, and thus it embeds some assumptions
155that are more appropriate to SMBus (and PCs) than to I2C. One of these
156assumptions is that most adapters and devices drivers support the SMBUS_QUICK
157protocol to probe device presence. Another is that devices and their drivers
158can be sufficiently configured using only such probe primitives.
159
160As Linux and its I2C stack became more widely used in embedded systems
161and complex components such as DVB adapters, those assumptions became more
162problematic. Drivers for I2C devices that issue interrupts need more (and
163different) configuration information, as do drivers handling chip variants
164that can't be distinguished by protocol probing, or which need some board
165specific information to operate correctly.
166
167Accordingly, the I2C stack now has two models for associating I2C devices
168with their drivers: the original "legacy" model, and a newer one that's
169fully compatible with the Linux 2.6 driver model. These models do not mix,
170since the "legacy" model requires drivers to create "i2c_client" device
171objects after SMBus style probing, while the Linux driver model expects
172drivers to be given such device objects in their probe() routines.
173
174
175Standard Driver Model Binding ("New Style")
176-------------------------------------------
177
178System infrastructure, typically board-specific initialization code or
179boot firmware, reports what I2C devices exist. For example, there may be
180a table, in the kernel or from the boot loader, identifying I2C devices
181and linking them to board-specific configuration information about IRQs
182and other wiring artifacts, chip type, and so on. That could be used to
183create i2c_client objects for each I2C device.
184
185I2C device drivers using this binding model work just like any other
186kind of driver in Linux: they provide a probe() method to bind to
187those devices, and a remove() method to unbind.
188
189 static int foo_probe(struct i2c_client *client);
190 static int foo_remove(struct i2c_client *client);
191
192Remember that the i2c_driver does not create those client handles. The
193handle may be used during foo_probe(). If foo_probe() reports success
194(zero not a negative status code) it may save the handle and use it until
195foo_remove() returns. That binding model is used by most Linux drivers.
196
197Drivers match devices when i2c_client.driver_name and the driver name are
198the same; this approach is used in several other busses that don't have
199device typing support in the hardware. The driver and module name should
200match, so hotplug/coldplug mechanisms will modprobe the driver.
201
202
Jean Delvarece9e0792007-05-01 23:26:32 +0200203Device Creation (Standard driver model)
204---------------------------------------
205
206If you know for a fact that an I2C device is connected to a given I2C bus,
207you can instantiate that device by simply filling an i2c_board_info
208structure with the device address and driver name, and calling
209i2c_new_device(). This will create the device, then the driver core will
210take care of finding the right driver and will call its probe() method.
211If a driver supports different device types, you can specify the type you
212want using the type field. You can also specify an IRQ and platform data
213if needed.
214
215Sometimes you know that a device is connected to a given I2C bus, but you
216don't know the exact address it uses. This happens on TV adapters for
217example, where the same driver supports dozens of slightly different
218models, and I2C device addresses change from one model to the next. In
219that case, you can use the i2c_new_probed_device() variant, which is
220similar to i2c_new_device(), except that it takes an additional list of
221possible I2C addresses to probe. A device is created for the first
222responsive address in the list. If you expect more than one device to be
223present in the address range, simply call i2c_new_probed_device() that
224many times.
225
226The call to i2c_new_device() or i2c_new_probed_device() typically happens
227in the I2C bus driver. You may want to save the returned i2c_client
228reference for later use.
229
230
231Device Deletion (Standard driver model)
232---------------------------------------
233
234Each I2C device which has been created using i2c_new_device() or
235i2c_new_probed_device() can be unregistered by calling
236i2c_unregister_device(). If you don't call it explicitly, it will be
237called automatically before the underlying I2C bus itself is removed, as a
238device can't survive its parent in the device driver model.
239
240
David Brownell4298cfc2007-05-01 23:26:31 +0200241Legacy Driver Binding Model
242---------------------------
243
Linus Torvalds1da177e2005-04-16 15:20:36 -0700244Most i2c devices can be present on several i2c addresses; for some this
245is determined in hardware (by soldering some chip pins to Vcc or Ground),
246for others this can be changed in software (by writing to specific client
247registers). Some devices are usually on a specific address, but not always;
248and some are even more tricky. So you will probably need to scan several
249i2c addresses for your clients, and do some sort of detection to see
250whether it is actually a device supported by your driver.
251
252To give the user a maximum of possibilities, some default module parameters
253are defined to help determine what addresses are scanned. Several macros
254are defined in i2c.h to help you support them, as well as a generic
255detection algorithm.
256
257You do not have to use this parameter interface; but don't try to use
Jean Delvare2ed2dc32005-07-31 21:42:02 +0200258function i2c_probe() if you don't.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700259
260NOTE: If you want to write a `sensors' driver, the interface is slightly
261 different! See below.
262
263
264
David Brownell4298cfc2007-05-01 23:26:31 +0200265Probing classes (Legacy model)
266------------------------------
Linus Torvalds1da177e2005-04-16 15:20:36 -0700267
268All parameters are given as lists of unsigned 16-bit integers. Lists are
269terminated by I2C_CLIENT_END.
270The following lists are used internally:
271
272 normal_i2c: filled in by the module writer.
273 A list of I2C addresses which should normally be examined.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700274 probe: insmod parameter.
275 A list of pairs. The first value is a bus number (-1 for any I2C bus),
276 the second is the address. These addresses are also probed, as if they
277 were in the 'normal' list.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700278 ignore: insmod parameter.
279 A list of pairs. The first value is a bus number (-1 for any I2C bus),
280 the second is the I2C address. These addresses are never probed.
Jean Delvaref4b50262005-07-31 21:49:03 +0200281 This parameter overrules the 'normal_i2c' list only.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700282 force: insmod parameter.
283 A list of pairs. The first value is a bus number (-1 for any I2C bus),
284 the second is the I2C address. A device is blindly assumed to be on
285 the given address, no probing is done.
286
Jean Delvaref4b50262005-07-31 21:49:03 +0200287Additionally, kind-specific force lists may optionally be defined if
288the driver supports several chip kinds. They are grouped in a
289NULL-terminated list of pointers named forces, those first element if the
290generic force list mentioned above. Each additional list correspond to an
291insmod parameter of the form force_<kind>.
292
Jean Delvareb3d54962005-04-02 20:31:02 +0200293Fortunately, as a module writer, you just have to define the `normal_i2c'
294parameter. The complete declaration could look like this:
Linus Torvalds1da177e2005-04-16 15:20:36 -0700295
Jean Delvareb3d54962005-04-02 20:31:02 +0200296 /* Scan 0x37, and 0x48 to 0x4f */
297 static unsigned short normal_i2c[] = { 0x37, 0x48, 0x49, 0x4a, 0x4b, 0x4c,
298 0x4d, 0x4e, 0x4f, I2C_CLIENT_END };
Linus Torvalds1da177e2005-04-16 15:20:36 -0700299
300 /* Magic definition of all other variables and things */
301 I2C_CLIENT_INSMOD;
Jean Delvaref4b50262005-07-31 21:49:03 +0200302 /* Or, if your driver supports, say, 2 kind of devices: */
303 I2C_CLIENT_INSMOD_2(foo, bar);
304
305If you use the multi-kind form, an enum will be defined for you:
306 enum chips { any_chip, foo, bar, ... }
307You can then (and certainly should) use it in the driver code.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700308
Jean Delvareb3d54962005-04-02 20:31:02 +0200309Note that you *have* to call the defined variable `normal_i2c',
310without any prefix!
Linus Torvalds1da177e2005-04-16 15:20:36 -0700311
312
David Brownell4298cfc2007-05-01 23:26:31 +0200313Attaching to an adapter (Legacy model)
314--------------------------------------
Linus Torvalds1da177e2005-04-16 15:20:36 -0700315
316Whenever a new adapter is inserted, or for all adapters if the driver is
317being registered, the callback attach_adapter() is called. Now is the
318time to determine what devices are present on the adapter, and to register
319a client for each of them.
320
321The attach_adapter callback is really easy: we just call the generic
322detection function. This function will scan the bus for us, using the
323information as defined in the lists explained above. If a device is
324detected at a specific address, another callback is called.
325
326 int foo_attach_adapter(struct i2c_adapter *adapter)
327 {
328 return i2c_probe(adapter,&addr_data,&foo_detect_client);
329 }
330
Linus Torvalds1da177e2005-04-16 15:20:36 -0700331Remember, structure `addr_data' is defined by the macros explained above,
332so you do not have to define it yourself.
333
Jean Delvare2ed2dc32005-07-31 21:42:02 +0200334The i2c_probe function will call the foo_detect_client
Linus Torvalds1da177e2005-04-16 15:20:36 -0700335function only for those i2c addresses that actually have a device on
336them (unless a `force' parameter was used). In addition, addresses that
337are already in use (by some other registered client) are skipped.
338
339
David Brownell4298cfc2007-05-01 23:26:31 +0200340The detect client function (Legacy model)
341-----------------------------------------
Linus Torvalds1da177e2005-04-16 15:20:36 -0700342
Jean Delvare2ed2dc32005-07-31 21:42:02 +0200343The detect client function is called by i2c_probe. The `kind' parameter
344contains -1 for a probed detection, 0 for a forced detection, or a positive
345number for a forced detection with a chip type forced.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700346
347Below, some things are only needed if this is a `sensors' driver. Those
348parts are between /* SENSORS ONLY START */ and /* SENSORS ONLY END */
349markers.
350
Jean Delvarea89ba0b2005-08-09 20:17:55 +0200351Returning an error different from -ENODEV in a detect function will cause
352the detection to stop: other addresses and adapters won't be scanned.
353This should only be done on fatal or internal errors, such as a memory
354shortage or i2c_attach_client failing.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700355
356For now, you can ignore the `flags' parameter. It is there for future use.
357
358 int foo_detect_client(struct i2c_adapter *adapter, int address,
359 unsigned short flags, int kind)
360 {
361 int err = 0;
362 int i;
363 struct i2c_client *new_client;
364 struct foo_data *data;
365 const char *client_name = ""; /* For non-`sensors' drivers, put the real
366 name here! */
367
368 /* Let's see whether this adapter can support what we need.
369 Please substitute the things you need here!
370 For `sensors' drivers, add `! is_isa &&' to the if statement */
371 if (!i2c_check_functionality(adapter,I2C_FUNC_SMBUS_WORD_DATA |
372 I2C_FUNC_SMBUS_WRITE_BYTE))
373 goto ERROR0;
374
375 /* SENSORS ONLY START */
376 const char *type_name = "";
377 int is_isa = i2c_is_isa_adapter(adapter);
378
Jean Delvare02ff9822005-07-20 00:05:33 +0200379 /* Do this only if the chip can additionally be found on the ISA bus
380 (hybrid chip). */
Linus Torvalds1da177e2005-04-16 15:20:36 -0700381
Jean Delvare02ff9822005-07-20 00:05:33 +0200382 if (is_isa) {
Linus Torvalds1da177e2005-04-16 15:20:36 -0700383
384 /* Discard immediately if this ISA range is already used */
Jeff Garzikd61780c2005-10-30 15:01:51 -0800385 /* FIXME: never use check_region(), only request_region() */
Linus Torvalds1da177e2005-04-16 15:20:36 -0700386 if (check_region(address,FOO_EXTENT))
387 goto ERROR0;
388
389 /* Probe whether there is anything on this address.
390 Some example code is below, but you will have to adapt this
391 for your own driver */
392
393 if (kind < 0) /* Only if no force parameter was used */ {
394 /* We may need long timeouts at least for some chips. */
395 #define REALLY_SLOW_IO
396 i = inb_p(address + 1);
397 if (inb_p(address + 2) != i)
398 goto ERROR0;
399 if (inb_p(address + 3) != i)
400 goto ERROR0;
401 if (inb_p(address + 7) != i)
402 goto ERROR0;
403 #undef REALLY_SLOW_IO
404
405 /* Let's just hope nothing breaks here */
406 i = inb_p(address + 5) & 0x7f;
407 outb_p(~i & 0x7f,address+5);
408 if ((inb_p(address + 5) & 0x7f) != (~i & 0x7f)) {
409 outb_p(i,address+5);
410 return 0;
411 }
412 }
413 }
414
415 /* SENSORS ONLY END */
416
417 /* OK. For now, we presume we have a valid client. We now create the
418 client structure, even though we cannot fill it completely yet.
419 But it allows us to access several i2c functions safely */
420
Jean Delvare2445eb62005-10-17 23:16:25 +0200421 if (!(data = kzalloc(sizeof(struct foo_data), GFP_KERNEL))) {
Linus Torvalds1da177e2005-04-16 15:20:36 -0700422 err = -ENOMEM;
423 goto ERROR0;
424 }
425
Jean Delvare2445eb62005-10-17 23:16:25 +0200426 new_client = &data->client;
427 i2c_set_clientdata(new_client, data);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700428
429 new_client->addr = address;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700430 new_client->adapter = adapter;
431 new_client->driver = &foo_driver;
432 new_client->flags = 0;
433
434 /* Now, we do the remaining detection. If no `force' parameter is used. */
435
436 /* First, the generic detection (if any), that is skipped if any force
437 parameter was used. */
438 if (kind < 0) {
439 /* The below is of course bogus */
440 if (foo_read(new_client,FOO_REG_GENERIC) != FOO_GENERIC_VALUE)
441 goto ERROR1;
442 }
443
444 /* SENSORS ONLY START */
445
446 /* Next, specific detection. This is especially important for `sensors'
447 devices. */
448
449 /* Determine the chip type. Not needed if a `force_CHIPTYPE' parameter
450 was used. */
451 if (kind <= 0) {
452 i = foo_read(new_client,FOO_REG_CHIPTYPE);
453 if (i == FOO_TYPE_1)
454 kind = chip1; /* As defined in the enum */
455 else if (i == FOO_TYPE_2)
456 kind = chip2;
457 else {
458 printk("foo: Ignoring 'force' parameter for unknown chip at "
459 "adapter %d, address 0x%02x\n",i2c_adapter_id(adapter),address);
460 goto ERROR1;
461 }
462 }
463
464 /* Now set the type and chip names */
465 if (kind == chip1) {
466 type_name = "chip1"; /* For /proc entry */
467 client_name = "CHIP 1";
468 } else if (kind == chip2) {
469 type_name = "chip2"; /* For /proc entry */
470 client_name = "CHIP 2";
471 }
472
473 /* Reserve the ISA region */
474 if (is_isa)
475 request_region(address,FOO_EXTENT,type_name);
476
477 /* SENSORS ONLY END */
478
479 /* Fill in the remaining client fields. */
480 strcpy(new_client->name,client_name);
481
482 /* SENSORS ONLY BEGIN */
483 data->type = kind;
484 /* SENSORS ONLY END */
485
486 data->valid = 0; /* Only if you use this field */
487 init_MUTEX(&data->update_lock); /* Only if you use this field */
488
489 /* Any other initializations in data must be done here too. */
490
491 /* Tell the i2c layer a new client has arrived */
492 if ((err = i2c_attach_client(new_client)))
493 goto ERROR3;
494
495 /* SENSORS ONLY BEGIN */
496 /* Register a new directory entry with module sensors. See below for
497 the `template' structure. */
498 if ((i = i2c_register_entry(new_client, type_name,
499 foo_dir_table_template,THIS_MODULE)) < 0) {
500 err = i;
501 goto ERROR4;
502 }
503 data->sysctl_id = i;
504
505 /* SENSORS ONLY END */
506
507 /* This function can write default values to the client registers, if
508 needed. */
509 foo_init_client(new_client);
510 return 0;
511
512 /* OK, this is not exactly good programming practice, usually. But it is
513 very code-efficient in this case. */
514
515 ERROR4:
516 i2c_detach_client(new_client);
517 ERROR3:
518 ERROR2:
519 /* SENSORS ONLY START */
520 if (is_isa)
521 release_region(address,FOO_EXTENT);
522 /* SENSORS ONLY END */
523 ERROR1:
Jean Delvarea852daa2005-11-02 21:42:48 +0100524 kfree(data);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700525 ERROR0:
526 return err;
527 }
528
529
David Brownell4298cfc2007-05-01 23:26:31 +0200530Removing the client (Legacy model)
531==================================
Linus Torvalds1da177e2005-04-16 15:20:36 -0700532
533The detach_client call back function is called when a client should be
534removed. It may actually fail, but only when panicking. This code is
535much simpler than the attachment code, fortunately!
536
537 int foo_detach_client(struct i2c_client *client)
538 {
539 int err,i;
540
541 /* SENSORS ONLY START */
542 /* Deregister with the `i2c-proc' module. */
543 i2c_deregister_entry(((struct lm78_data *)(client->data))->sysctl_id);
544 /* SENSORS ONLY END */
545
546 /* Try to detach the client from i2c space */
Jean Delvare7bef5592005-07-27 22:14:49 +0200547 if ((err = i2c_detach_client(client)))
Linus Torvalds1da177e2005-04-16 15:20:36 -0700548 return err;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700549
Jean Delvare02ff9822005-07-20 00:05:33 +0200550 /* HYBRID SENSORS CHIP ONLY START */
Linus Torvalds1da177e2005-04-16 15:20:36 -0700551 if i2c_is_isa_client(client)
552 release_region(client->addr,LM78_EXTENT);
Jean Delvare02ff9822005-07-20 00:05:33 +0200553 /* HYBRID SENSORS CHIP ONLY END */
Linus Torvalds1da177e2005-04-16 15:20:36 -0700554
Jean Delvarea852daa2005-11-02 21:42:48 +0100555 kfree(i2c_get_clientdata(client));
Linus Torvalds1da177e2005-04-16 15:20:36 -0700556 return 0;
557 }
558
559
560Initializing the module or kernel
561=================================
562
563When the kernel is booted, or when your foo driver module is inserted,
564you have to do some initializing. Fortunately, just attaching (registering)
565the driver module is usually enough.
566
567 /* Keep track of how far we got in the initialization process. If several
568 things have to initialized, and we fail halfway, only those things
569 have to be cleaned up! */
570 static int __initdata foo_initialized = 0;
571
572 static int __init foo_init(void)
573 {
574 int res;
575 printk("foo version %s (%s)\n",FOO_VERSION,FOO_DATE);
576
577 if ((res = i2c_add_driver(&foo_driver))) {
578 printk("foo: Driver registration failed, module not inserted.\n");
579 foo_cleanup();
580 return res;
581 }
582 foo_initialized ++;
583 return 0;
584 }
585
586 void foo_cleanup(void)
587 {
588 if (foo_initialized == 1) {
589 if ((res = i2c_del_driver(&foo_driver))) {
590 printk("foo: Driver registration failed, module not removed.\n");
591 return;
592 }
593 foo_initialized --;
594 }
595 }
596
597 /* Substitute your own name and email address */
598 MODULE_AUTHOR("Frodo Looijaard <frodol@dds.nl>"
599 MODULE_DESCRIPTION("Driver for Barf Inc. Foo I2C devices");
600
601 module_init(foo_init);
602 module_exit(foo_cleanup);
603
604Note that some functions are marked by `__init', and some data structures
605by `__init_data'. Hose functions and structures can be removed after
606kernel booting (or module loading) is completed.
607
Jean Delvarefb687d72005-12-18 16:51:55 +0100608
David Brownellf37dd802007-02-13 22:09:00 +0100609Power Management
610================
611
612If your I2C device needs special handling when entering a system low
613power state -- like putting a transceiver into a low power mode, or
614activating a system wakeup mechanism -- do that in the suspend() method.
615The resume() method should reverse what the suspend() method does.
616
617These are standard driver model calls, and they work just like they
618would for any other driver stack. The calls can sleep, and can use
619I2C messaging to the device being suspended or resumed (since their
620parent I2C adapter is active when these calls are issued, and IRQs
621are still enabled).
622
623
624System Shutdown
625===============
626
627If your I2C device needs special handling when the system shuts down
628or reboots (including kexec) -- like turning something off -- use a
629shutdown() method.
630
631Again, this is a standard driver model call, working just like it
632would for any other driver stack: the calls can sleep, and can use
633I2C messaging.
634
635
Linus Torvalds1da177e2005-04-16 15:20:36 -0700636Command function
637================
638
639A generic ioctl-like function call back is supported. You will seldom
Jean Delvarefb687d72005-12-18 16:51:55 +0100640need this, and its use is deprecated anyway, so newer design should not
641use it. Set it to NULL.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700642
643
644Sending and receiving
645=====================
646
647If you want to communicate with your device, there are several functions
648to do this. You can find all of them in i2c.h.
649
650If you can choose between plain i2c communication and SMBus level
651communication, please use the last. All adapters understand SMBus level
652commands, but only some of them understand plain i2c!
653
654
655Plain i2c communication
656-----------------------
657
658 extern int i2c_master_send(struct i2c_client *,const char* ,int);
659 extern int i2c_master_recv(struct i2c_client *,char* ,int);
660
661These routines read and write some bytes from/to a client. The client
662contains the i2c address, so you do not have to include it. The second
663parameter contains the bytes the read/write, the third the length of the
664buffer. Returned is the actual number of bytes read/written.
665
666 extern int i2c_transfer(struct i2c_adapter *adap, struct i2c_msg *msg,
667 int num);
668
669This sends a series of messages. Each message can be a read or write,
670and they can be mixed in any way. The transactions are combined: no
671stop bit is sent between transaction. The i2c_msg structure contains
672for each message the client address, the number of bytes of the message
673and the message data itself.
674
675You can read the file `i2c-protocol' for more information about the
676actual i2c protocol.
677
678
679SMBus communication
680-------------------
681
682 extern s32 i2c_smbus_xfer (struct i2c_adapter * adapter, u16 addr,
683 unsigned short flags,
684 char read_write, u8 command, int size,
685 union i2c_smbus_data * data);
686
687 This is the generic SMBus function. All functions below are implemented
688 in terms of it. Never use this function directly!
689
690
691 extern s32 i2c_smbus_write_quick(struct i2c_client * client, u8 value);
692 extern s32 i2c_smbus_read_byte(struct i2c_client * client);
693 extern s32 i2c_smbus_write_byte(struct i2c_client * client, u8 value);
694 extern s32 i2c_smbus_read_byte_data(struct i2c_client * client, u8 command);
695 extern s32 i2c_smbus_write_byte_data(struct i2c_client * client,
696 u8 command, u8 value);
697 extern s32 i2c_smbus_read_word_data(struct i2c_client * client, u8 command);
698 extern s32 i2c_smbus_write_word_data(struct i2c_client * client,
699 u8 command, u16 value);
700 extern s32 i2c_smbus_write_block_data(struct i2c_client * client,
701 u8 command, u8 length,
702 u8 *values);
Jean Delvare7865e242005-10-08 00:00:31 +0200703 extern s32 i2c_smbus_read_i2c_block_data(struct i2c_client * client,
704 u8 command, u8 *values);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700705
706These ones were removed in Linux 2.6.10 because they had no users, but could
707be added back later if needed:
708
Linus Torvalds1da177e2005-04-16 15:20:36 -0700709 extern s32 i2c_smbus_read_block_data(struct i2c_client * client,
710 u8 command, u8 *values);
711 extern s32 i2c_smbus_write_i2c_block_data(struct i2c_client * client,
712 u8 command, u8 length,
713 u8 *values);
714 extern s32 i2c_smbus_process_call(struct i2c_client * client,
715 u8 command, u16 value);
716 extern s32 i2c_smbus_block_process_call(struct i2c_client *client,
717 u8 command, u8 length,
718 u8 *values)
719
720All these transactions return -1 on failure. The 'write' transactions
721return 0 on success; the 'read' transactions return the read value, except
722for read_block, which returns the number of values read. The block buffers
723need not be longer than 32 bytes.
724
725You can read the file `smbus-protocol' for more information about the
726actual SMBus protocol.
727
728
729General purpose routines
730========================
731
732Below all general purpose routines are listed, that were not mentioned
733before.
734
735 /* This call returns a unique low identifier for each registered adapter,
736 * or -1 if the adapter was not registered.
737 */
738 extern int i2c_adapter_id(struct i2c_adapter *adap);
739
740
741The sensors sysctl/proc interface
742=================================
743
744This section only applies if you write `sensors' drivers.
745
746Each sensors driver creates a directory in /proc/sys/dev/sensors for each
747registered client. The directory is called something like foo-i2c-4-65.
748The sensors module helps you to do this as easily as possible.
749
750The template
751------------
752
753You will need to define a ctl_table template. This template will automatically
754be copied to a newly allocated structure and filled in where necessary when
755you call sensors_register_entry.
756
757First, I will give an example definition.
758 static ctl_table foo_dir_table_template[] = {
759 { FOO_SYSCTL_FUNC1, "func1", NULL, 0, 0644, NULL, &i2c_proc_real,
760 &i2c_sysctl_real,NULL,&foo_func },
761 { FOO_SYSCTL_FUNC2, "func2", NULL, 0, 0644, NULL, &i2c_proc_real,
762 &i2c_sysctl_real,NULL,&foo_func },
763 { FOO_SYSCTL_DATA, "data", NULL, 0, 0644, NULL, &i2c_proc_real,
764 &i2c_sysctl_real,NULL,&foo_data },
765 { 0 }
766 };
767
768In the above example, three entries are defined. They can either be
769accessed through the /proc interface, in the /proc/sys/dev/sensors/*
770directories, as files named func1, func2 and data, or alternatively
771through the sysctl interface, in the appropriate table, with identifiers
772FOO_SYSCTL_FUNC1, FOO_SYSCTL_FUNC2 and FOO_SYSCTL_DATA.
773
774The third, sixth and ninth parameters should always be NULL, and the
775fourth should always be 0. The fifth is the mode of the /proc file;
7760644 is safe, as the file will be owned by root:root.
777
778The seventh and eighth parameters should be &i2c_proc_real and
779&i2c_sysctl_real if you want to export lists of reals (scaled
780integers). You can also use your own function for them, as usual.
781Finally, the last parameter is the call-back to gather the data
782(see below) if you use the *_proc_real functions.
783
784
785Gathering the data
786------------------
787
788The call back functions (foo_func and foo_data in the above example)
789can be called in several ways; the operation parameter determines
790what should be done:
791
792 * If operation == SENSORS_PROC_REAL_INFO, you must return the
793 magnitude (scaling) in nrels_mag;
794 * If operation == SENSORS_PROC_REAL_READ, you must read information
795 from the chip and return it in results. The number of integers
796 to display should be put in nrels_mag;
797 * If operation == SENSORS_PROC_REAL_WRITE, you must write the
798 supplied information to the chip. nrels_mag will contain the number
799 of integers, results the integers themselves.
800
801The *_proc_real functions will display the elements as reals for the
802/proc interface. If you set the magnitude to 2, and supply 345 for
803SENSORS_PROC_REAL_READ, it would display 3.45; and if the user would
804write 45.6 to the /proc file, it would be returned as 4560 for
805SENSORS_PROC_REAL_WRITE. A magnitude may even be negative!
806
807An example function:
808
809 /* FOO_FROM_REG and FOO_TO_REG translate between scaled values and
810 register values. Note the use of the read cache. */
811 void foo_in(struct i2c_client *client, int operation, int ctl_name,
812 int *nrels_mag, long *results)
813 {
814 struct foo_data *data = client->data;
815 int nr = ctl_name - FOO_SYSCTL_FUNC1; /* reduce to 0 upwards */
816
817 if (operation == SENSORS_PROC_REAL_INFO)
818 *nrels_mag = 2;
819 else if (operation == SENSORS_PROC_REAL_READ) {
820 /* Update the readings cache (if necessary) */
821 foo_update_client(client);
822 /* Get the readings from the cache */
823 results[0] = FOO_FROM_REG(data->foo_func_base[nr]);
824 results[1] = FOO_FROM_REG(data->foo_func_more[nr]);
825 results[2] = FOO_FROM_REG(data->foo_func_readonly[nr]);
826 *nrels_mag = 2;
827 } else if (operation == SENSORS_PROC_REAL_WRITE) {
828 if (*nrels_mag >= 1) {
829 /* Update the cache */
830 data->foo_base[nr] = FOO_TO_REG(results[0]);
831 /* Update the chip */
832 foo_write_value(client,FOO_REG_FUNC_BASE(nr),data->foo_base[nr]);
833 }
834 if (*nrels_mag >= 2) {
835 /* Update the cache */
836 data->foo_more[nr] = FOO_TO_REG(results[1]);
837 /* Update the chip */
838 foo_write_value(client,FOO_REG_FUNC_MORE(nr),data->foo_more[nr]);
839 }
840 }
841 }