writing-clients 23 KB

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