writing-clients 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619
  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).
  3. To set up a driver, you need to do several things. Some are optional, and
  4. some things can be done slightly or completely different. Use this as a
  5. guide, not as a rule book!
  6. General remarks
  7. ===============
  8. Try to keep the kernel namespace as clean as possible. The best way to
  9. do this is to use a unique prefix for all global symbols. This is
  10. especially important for exported symbols, but it is a good idea to do
  11. it for non-exported symbols too. We will use the prefix `foo_' in this
  12. tutorial, and `FOO_' for preprocessor variables.
  13. The driver structure
  14. ====================
  15. Usually, you will implement a single driver structure, and instantiate
  16. all clients from it. Remember, a driver structure contains general access
  17. routines, and should be zero-initialized except for fields with data you
  18. provide. A client structure holds device-specific information like the
  19. driver model device node, and its I2C address.
  20. /* iff driver uses driver model ("new style") binding model: */
  21. static struct i2c_device_id foo_idtable[] = {
  22. { "foo", my_id_for_foo },
  23. { "bar", my_id_for_bar },
  24. { }
  25. };
  26. MODULE_DEVICE_TABLE(i2c, foo_idtable);
  27. static struct i2c_driver foo_driver = {
  28. .driver = {
  29. .name = "foo",
  30. },
  31. /* iff driver uses driver model ("new style") binding model: */
  32. .id_table = foo_ids,
  33. .probe = foo_probe,
  34. .remove = foo_remove,
  35. /* else, driver uses "legacy" binding model: */
  36. .attach_adapter = foo_attach_adapter,
  37. .detach_client = foo_detach_client,
  38. /* these may be used regardless of the driver binding model */
  39. .shutdown = foo_shutdown, /* optional */
  40. .suspend = foo_suspend, /* optional */
  41. .resume = foo_resume, /* optional */
  42. .command = foo_command, /* optional */
  43. }
  44. The name field is the driver name, and must not contain spaces. It
  45. should match the module name (if the driver can be compiled as a module),
  46. although you can use MODULE_ALIAS (passing "foo" in this example) to add
  47. another name for the module. If the driver name doesn't match the module
  48. name, the module won't be automatically loaded (hotplug/coldplug).
  49. All other fields are for call-back functions which will be explained
  50. below.
  51. Extra client data
  52. =================
  53. Each client structure has a special `data' field that can point to any
  54. structure at all. You should use this to keep device-specific data,
  55. especially in drivers that handle multiple I2C or SMBUS devices. You
  56. do not always need this, but especially for `sensors' drivers, it can
  57. be very useful.
  58. /* store the value */
  59. void i2c_set_clientdata(struct i2c_client *client, void *data);
  60. /* retrieve the value */
  61. void *i2c_get_clientdata(struct i2c_client *client);
  62. An example structure is below.
  63. struct foo_data {
  64. struct i2c_client client;
  65. enum chips type; /* To keep the chips type for `sensors' drivers. */
  66. /* Because the i2c bus is slow, it is often useful to cache the read
  67. information of a chip for some time (for example, 1 or 2 seconds).
  68. It depends of course on the device whether this is really worthwhile
  69. or even sensible. */
  70. struct mutex update_lock; /* When we are reading lots of information,
  71. another process should not update the
  72. below information */
  73. char valid; /* != 0 if the following fields are valid. */
  74. unsigned long last_updated; /* In jiffies */
  75. /* Add the read information here too */
  76. };
  77. Accessing the client
  78. ====================
  79. Let's say we have a valid client structure. At some time, we will need
  80. to gather information from the client, or write new information to the
  81. client. How we will export this information to user-space is less
  82. important at this moment (perhaps we do not need to do this at all for
  83. some obscure clients). But we need generic reading and writing routines.
  84. I have found it useful to define foo_read and foo_write function for this.
  85. For some cases, it will be easier to call the i2c functions directly,
  86. but many chips have some kind of register-value idea that can easily
  87. be encapsulated.
  88. The below functions are simple examples, and should not be copied
  89. literally.
  90. int foo_read_value(struct i2c_client *client, u8 reg)
  91. {
  92. if (reg < 0x10) /* byte-sized register */
  93. return i2c_smbus_read_byte_data(client,reg);
  94. else /* word-sized register */
  95. return i2c_smbus_read_word_data(client,reg);
  96. }
  97. int foo_write_value(struct i2c_client *client, u8 reg, u16 value)
  98. {
  99. if (reg == 0x10) /* Impossible to write - driver error! */ {
  100. return -1;
  101. else if (reg < 0x10) /* byte-sized register */
  102. return i2c_smbus_write_byte_data(client,reg,value);
  103. else /* word-sized register */
  104. return i2c_smbus_write_word_data(client,reg,value);
  105. }
  106. Probing and attaching
  107. =====================
  108. The Linux I2C stack was originally written to support access to hardware
  109. monitoring chips on PC motherboards, and thus it embeds some assumptions
  110. that are more appropriate to SMBus (and PCs) than to I2C. One of these
  111. assumptions is that most adapters and devices drivers support the SMBUS_QUICK
  112. protocol to probe device presence. Another is that devices and their drivers
  113. can be sufficiently configured using only such probe primitives.
  114. As Linux and its I2C stack became more widely used in embedded systems
  115. and complex components such as DVB adapters, those assumptions became more
  116. problematic. Drivers for I2C devices that issue interrupts need more (and
  117. different) configuration information, as do drivers handling chip variants
  118. that can't be distinguished by protocol probing, or which need some board
  119. specific information to operate correctly.
  120. Accordingly, the I2C stack now has two models for associating I2C devices
  121. with their drivers: the original "legacy" model, and a newer one that's
  122. fully compatible with the Linux 2.6 driver model. These models do not mix,
  123. since the "legacy" model requires drivers to create "i2c_client" device
  124. objects after SMBus style probing, while the Linux driver model expects
  125. drivers to be given such device objects in their probe() routines.
  126. Standard Driver Model Binding ("New Style")
  127. -------------------------------------------
  128. System infrastructure, typically board-specific initialization code or
  129. boot firmware, reports what I2C devices exist. For example, there may be
  130. a table, in the kernel or from the boot loader, identifying I2C devices
  131. and linking them to board-specific configuration information about IRQs
  132. and other wiring artifacts, chip type, and so on. That could be used to
  133. create i2c_client objects for each I2C device.
  134. I2C device drivers using this binding model work just like any other
  135. kind of driver in Linux: they provide a probe() method to bind to
  136. those devices, and a remove() method to unbind.
  137. static int foo_probe(struct i2c_client *client,
  138. const struct i2c_device_id *id);
  139. static int foo_remove(struct i2c_client *client);
  140. Remember that the i2c_driver does not create those client handles. The
  141. handle may be used during foo_probe(). If foo_probe() reports success
  142. (zero not a negative status code) it may save the handle and use it until
  143. foo_remove() returns. That binding model is used by most Linux drivers.
  144. The probe function is called when an entry in the id_table name field
  145. matches the device's name. It is passed the entry that was matched so
  146. the driver knows which one in the table matched.
  147. Device Creation (Standard driver model)
  148. ---------------------------------------
  149. If you know for a fact that an I2C device is connected to a given I2C bus,
  150. you can instantiate that device by simply filling an i2c_board_info
  151. structure with the device address and driver name, and calling
  152. i2c_new_device(). This will create the device, then the driver core will
  153. take care of finding the right driver and will call its probe() method.
  154. If a driver supports different device types, you can specify the type you
  155. want using the type field. You can also specify an IRQ and platform data
  156. if needed.
  157. Sometimes you know that a device is connected to a given I2C bus, but you
  158. don't know the exact address it uses. This happens on TV adapters for
  159. example, where the same driver supports dozens of slightly different
  160. models, and I2C device addresses change from one model to the next. In
  161. that case, you can use the i2c_new_probed_device() variant, which is
  162. similar to i2c_new_device(), except that it takes an additional list of
  163. possible I2C addresses to probe. A device is created for the first
  164. responsive address in the list. If you expect more than one device to be
  165. present in the address range, simply call i2c_new_probed_device() that
  166. many times.
  167. The call to i2c_new_device() or i2c_new_probed_device() typically happens
  168. in the I2C bus driver. You may want to save the returned i2c_client
  169. reference for later use.
  170. Device Deletion (Standard driver model)
  171. ---------------------------------------
  172. Each I2C device which has been created using i2c_new_device() or
  173. i2c_new_probed_device() can be unregistered by calling
  174. i2c_unregister_device(). If you don't call it explicitly, it will be
  175. called automatically before the underlying I2C bus itself is removed, as a
  176. device can't survive its parent in the device driver model.
  177. Legacy Driver Binding Model
  178. ---------------------------
  179. Most i2c devices can be present on several i2c addresses; for some this
  180. is determined in hardware (by soldering some chip pins to Vcc or Ground),
  181. for others this can be changed in software (by writing to specific client
  182. registers). Some devices are usually on a specific address, but not always;
  183. and some are even more tricky. So you will probably need to scan several
  184. i2c addresses for your clients, and do some sort of detection to see
  185. whether it is actually a device supported by your driver.
  186. To give the user a maximum of possibilities, some default module parameters
  187. are defined to help determine what addresses are scanned. Several macros
  188. are defined in i2c.h to help you support them, as well as a generic
  189. detection algorithm.
  190. You do not have to use this parameter interface; but don't try to use
  191. function i2c_probe() if you don't.
  192. Probing classes (Legacy model)
  193. ------------------------------
  194. All parameters are given as lists of unsigned 16-bit integers. Lists are
  195. terminated by I2C_CLIENT_END.
  196. The following lists are used internally:
  197. normal_i2c: filled in by the module writer.
  198. A list of I2C addresses which should normally be examined.
  199. probe: insmod parameter.
  200. A list of pairs. The first value is a bus number (-1 for any I2C bus),
  201. the second is the address. These addresses are also probed, as if they
  202. were in the 'normal' list.
  203. ignore: insmod parameter.
  204. A list of pairs. The first value is a bus number (-1 for any I2C bus),
  205. the second is the I2C address. These addresses are never probed.
  206. This parameter overrules the 'normal_i2c' list only.
  207. force: insmod parameter.
  208. A list of pairs. The first value is a bus number (-1 for any I2C bus),
  209. the second is the I2C address. A device is blindly assumed to be on
  210. the given address, no probing is done.
  211. Additionally, kind-specific force lists may optionally be defined if
  212. the driver supports several chip kinds. They are grouped in a
  213. NULL-terminated list of pointers named forces, those first element if the
  214. generic force list mentioned above. Each additional list correspond to an
  215. insmod parameter of the form force_<kind>.
  216. Fortunately, as a module writer, you just have to define the `normal_i2c'
  217. parameter. The complete declaration could look like this:
  218. /* Scan 0x4c to 0x4f */
  219. static const unsigned short normal_i2c[] = { 0x4c, 0x4d, 0x4e, 0x4f,
  220. I2C_CLIENT_END };
  221. /* Magic definition of all other variables and things */
  222. I2C_CLIENT_INSMOD;
  223. /* Or, if your driver supports, say, 2 kind of devices: */
  224. I2C_CLIENT_INSMOD_2(foo, bar);
  225. If you use the multi-kind form, an enum will be defined for you:
  226. enum chips { any_chip, foo, bar, ... }
  227. You can then (and certainly should) use it in the driver code.
  228. Note that you *have* to call the defined variable `normal_i2c',
  229. without any prefix!
  230. Attaching to an adapter (Legacy model)
  231. --------------------------------------
  232. Whenever a new adapter is inserted, or for all adapters if the driver is
  233. being registered, the callback attach_adapter() is called. Now is the
  234. time to determine what devices are present on the adapter, and to register
  235. a client for each of them.
  236. The attach_adapter callback is really easy: we just call the generic
  237. detection function. This function will scan the bus for us, using the
  238. information as defined in the lists explained above. If a device is
  239. detected at a specific address, another callback is called.
  240. int foo_attach_adapter(struct i2c_adapter *adapter)
  241. {
  242. return i2c_probe(adapter,&addr_data,&foo_detect_client);
  243. }
  244. Remember, structure `addr_data' is defined by the macros explained above,
  245. so you do not have to define it yourself.
  246. The i2c_probe function will call the foo_detect_client
  247. function only for those i2c addresses that actually have a device on
  248. them (unless a `force' parameter was used). In addition, addresses that
  249. are already in use (by some other registered client) are skipped.
  250. The detect client function (Legacy model)
  251. -----------------------------------------
  252. The detect client function is called by i2c_probe. The `kind' parameter
  253. contains -1 for a probed detection, 0 for a forced detection, or a positive
  254. number for a forced detection with a chip type forced.
  255. Returning an error different from -ENODEV in a detect function will cause
  256. the detection to stop: other addresses and adapters won't be scanned.
  257. This should only be done on fatal or internal errors, such as a memory
  258. shortage or i2c_attach_client failing.
  259. For now, you can ignore the `flags' parameter. It is there for future use.
  260. int foo_detect_client(struct i2c_adapter *adapter, int address,
  261. int kind)
  262. {
  263. int err = 0;
  264. int i;
  265. struct i2c_client *client;
  266. struct foo_data *data;
  267. const char *name = "";
  268. /* Let's see whether this adapter can support what we need.
  269. Please substitute the things you need here! */
  270. if (!i2c_check_functionality(adapter,I2C_FUNC_SMBUS_WORD_DATA |
  271. I2C_FUNC_SMBUS_WRITE_BYTE))
  272. goto ERROR0;
  273. /* OK. For now, we presume we have a valid client. We now create the
  274. client structure, even though we cannot fill it completely yet.
  275. But it allows us to access several i2c functions safely */
  276. if (!(data = kzalloc(sizeof(struct foo_data), GFP_KERNEL))) {
  277. err = -ENOMEM;
  278. goto ERROR0;
  279. }
  280. client = &data->client;
  281. i2c_set_clientdata(client, data);
  282. client->addr = address;
  283. client->adapter = adapter;
  284. client->driver = &foo_driver;
  285. /* Now, we do the remaining detection. If no `force' parameter is used. */
  286. /* First, the generic detection (if any), that is skipped if any force
  287. parameter was used. */
  288. if (kind < 0) {
  289. /* The below is of course bogus */
  290. if (foo_read(client, FOO_REG_GENERIC) != FOO_GENERIC_VALUE)
  291. goto ERROR1;
  292. }
  293. /* Next, specific detection. This is especially important for `sensors'
  294. devices. */
  295. /* Determine the chip type. Not needed if a `force_CHIPTYPE' parameter
  296. was used. */
  297. if (kind <= 0) {
  298. i = foo_read(client, FOO_REG_CHIPTYPE);
  299. if (i == FOO_TYPE_1)
  300. kind = chip1; /* As defined in the enum */
  301. else if (i == FOO_TYPE_2)
  302. kind = chip2;
  303. else {
  304. printk("foo: Ignoring 'force' parameter for unknown chip at "
  305. "adapter %d, address 0x%02x\n",i2c_adapter_id(adapter),address);
  306. goto ERROR1;
  307. }
  308. }
  309. /* Now set the type and chip names */
  310. if (kind == chip1) {
  311. name = "chip1";
  312. } else if (kind == chip2) {
  313. name = "chip2";
  314. }
  315. /* Fill in the remaining client fields. */
  316. strlcpy(client->name, name, I2C_NAME_SIZE);
  317. data->type = kind;
  318. mutex_init(&data->update_lock); /* Only if you use this field */
  319. /* Any other initializations in data must be done here too. */
  320. /* This function can write default values to the client registers, if
  321. needed. */
  322. foo_init_client(client);
  323. /* Tell the i2c layer a new client has arrived */
  324. if ((err = i2c_attach_client(client)))
  325. goto ERROR1;
  326. return 0;
  327. /* OK, this is not exactly good programming practice, usually. But it is
  328. very code-efficient in this case. */
  329. ERROR1:
  330. kfree(data);
  331. ERROR0:
  332. return err;
  333. }
  334. Removing the client (Legacy model)
  335. ==================================
  336. The detach_client call back function is called when a client should be
  337. removed. It may actually fail, but only when panicking. This code is
  338. much simpler than the attachment code, fortunately!
  339. int foo_detach_client(struct i2c_client *client)
  340. {
  341. int err;
  342. /* Try to detach the client from i2c space */
  343. if ((err = i2c_detach_client(client)))
  344. return err;
  345. kfree(i2c_get_clientdata(client));
  346. return 0;
  347. }
  348. Initializing the module or kernel
  349. =================================
  350. When the kernel is booted, or when your foo driver module is inserted,
  351. you have to do some initializing. Fortunately, just attaching (registering)
  352. the driver module is usually enough.
  353. static int __init foo_init(void)
  354. {
  355. int res;
  356. if ((res = i2c_add_driver(&foo_driver))) {
  357. printk("foo: Driver registration failed, module not inserted.\n");
  358. return res;
  359. }
  360. return 0;
  361. }
  362. static void __exit foo_cleanup(void)
  363. {
  364. i2c_del_driver(&foo_driver);
  365. }
  366. /* Substitute your own name and email address */
  367. MODULE_AUTHOR("Frodo Looijaard <frodol@dds.nl>"
  368. MODULE_DESCRIPTION("Driver for Barf Inc. Foo I2C devices");
  369. /* a few non-GPL license types are also allowed */
  370. MODULE_LICENSE("GPL");
  371. module_init(foo_init);
  372. module_exit(foo_cleanup);
  373. Note that some functions are marked by `__init', and some data structures
  374. by `__initdata'. These functions and structures can be removed after
  375. kernel booting (or module loading) is completed.
  376. Power Management
  377. ================
  378. If your I2C device needs special handling when entering a system low
  379. power state -- like putting a transceiver into a low power mode, or
  380. activating a system wakeup mechanism -- do that in the suspend() method.
  381. The resume() method should reverse what the suspend() method does.
  382. These are standard driver model calls, and they work just like they
  383. would for any other driver stack. The calls can sleep, and can use
  384. I2C messaging to the device being suspended or resumed (since their
  385. parent I2C adapter is active when these calls are issued, and IRQs
  386. are still enabled).
  387. System Shutdown
  388. ===============
  389. If your I2C device needs special handling when the system shuts down
  390. or reboots (including kexec) -- like turning something off -- use a
  391. shutdown() method.
  392. Again, this is a standard driver model call, working just like it
  393. would for any other driver stack: the calls can sleep, and can use
  394. I2C messaging.
  395. Command function
  396. ================
  397. A generic ioctl-like function call back is supported. You will seldom
  398. need this, and its use is deprecated anyway, so newer design should not
  399. use it. Set it to NULL.
  400. Sending and receiving
  401. =====================
  402. If you want to communicate with your device, there are several functions
  403. to do this. You can find all of them in i2c.h.
  404. If you can choose between plain i2c communication and SMBus level
  405. communication, please use the last. All adapters understand SMBus level
  406. commands, but only some of them understand plain i2c!
  407. Plain i2c communication
  408. -----------------------
  409. extern int i2c_master_send(struct i2c_client *,const char* ,int);
  410. extern int i2c_master_recv(struct i2c_client *,char* ,int);
  411. These routines read and write some bytes from/to a client. The client
  412. contains the i2c address, so you do not have to include it. The second
  413. parameter contains the bytes the read/write, the third the length of the
  414. buffer. Returned is the actual number of bytes read/written.
  415. extern int i2c_transfer(struct i2c_adapter *adap, struct i2c_msg *msg,
  416. int num);
  417. This sends a series of messages. Each message can be a read or write,
  418. and they can be mixed in any way. The transactions are combined: no
  419. stop bit is sent between transaction. The i2c_msg structure contains
  420. for each message the client address, the number of bytes of the message
  421. and the message data itself.
  422. You can read the file `i2c-protocol' for more information about the
  423. actual i2c protocol.
  424. SMBus communication
  425. -------------------
  426. extern s32 i2c_smbus_xfer (struct i2c_adapter * adapter, u16 addr,
  427. unsigned short flags,
  428. char read_write, u8 command, int size,
  429. union i2c_smbus_data * data);
  430. This is the generic SMBus function. All functions below are implemented
  431. in terms of it. Never use this function directly!
  432. extern s32 i2c_smbus_write_quick(struct i2c_client * client, u8 value);
  433. extern s32 i2c_smbus_read_byte(struct i2c_client * client);
  434. extern s32 i2c_smbus_write_byte(struct i2c_client * client, u8 value);
  435. extern s32 i2c_smbus_read_byte_data(struct i2c_client * client, u8 command);
  436. extern s32 i2c_smbus_write_byte_data(struct i2c_client * client,
  437. u8 command, u8 value);
  438. extern s32 i2c_smbus_read_word_data(struct i2c_client * client, u8 command);
  439. extern s32 i2c_smbus_write_word_data(struct i2c_client * client,
  440. u8 command, u16 value);
  441. extern s32 i2c_smbus_write_block_data(struct i2c_client * client,
  442. u8 command, u8 length,
  443. u8 *values);
  444. extern s32 i2c_smbus_read_i2c_block_data(struct i2c_client * client,
  445. u8 command, u8 length, u8 *values);
  446. These ones were removed in Linux 2.6.10 because they had no users, but could
  447. be added back later if needed:
  448. extern s32 i2c_smbus_read_block_data(struct i2c_client * client,
  449. u8 command, u8 *values);
  450. extern s32 i2c_smbus_write_i2c_block_data(struct i2c_client * client,
  451. u8 command, u8 length,
  452. u8 *values);
  453. extern s32 i2c_smbus_process_call(struct i2c_client * client,
  454. u8 command, u16 value);
  455. extern s32 i2c_smbus_block_process_call(struct i2c_client *client,
  456. u8 command, u8 length,
  457. u8 *values)
  458. All these transactions return -1 on failure. The 'write' transactions
  459. return 0 on success; the 'read' transactions return the read value, except
  460. for read_block, which returns the number of values read. The block buffers
  461. need not be longer than 32 bytes.
  462. You can read the file `smbus-protocol' for more information about the
  463. actual SMBus protocol.
  464. General purpose routines
  465. ========================
  466. Below all general purpose routines are listed, that were not mentioned
  467. before.
  468. /* This call returns a unique low identifier for each registered adapter.
  469. */
  470. extern int i2c_adapter_id(struct i2c_adapter *adap);