v4l2-framework.txt 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160
  1. Overview of the V4L2 driver framework
  2. =====================================
  3. This text documents the various structures provided by the V4L2 framework and
  4. their relationships.
  5. Introduction
  6. ------------
  7. The V4L2 drivers tend to be very complex due to the complexity of the
  8. hardware: most devices have multiple ICs, export multiple device nodes in
  9. /dev, and create also non-V4L2 devices such as DVB, ALSA, FB, I2C and input
  10. (IR) devices.
  11. Especially the fact that V4L2 drivers have to setup supporting ICs to
  12. do audio/video muxing/encoding/decoding makes it more complex than most.
  13. Usually these ICs are connected to the main bridge driver through one or
  14. more I2C busses, but other busses can also be used. Such devices are
  15. called 'sub-devices'.
  16. For a long time the framework was limited to the video_device struct for
  17. creating V4L device nodes and video_buf for handling the video buffers
  18. (note that this document does not discuss the video_buf framework).
  19. This meant that all drivers had to do the setup of device instances and
  20. connecting to sub-devices themselves. Some of this is quite complicated
  21. to do right and many drivers never did do it correctly.
  22. There is also a lot of common code that could never be refactored due to
  23. the lack of a framework.
  24. So this framework sets up the basic building blocks that all drivers
  25. need and this same framework should make it much easier to refactor
  26. common code into utility functions shared by all drivers.
  27. A good example to look at as a reference is the v4l2-pci-skeleton.c
  28. source that is available in this directory. It is a skeleton driver for
  29. a PCI capture card, and demonstrates how to use the V4L2 driver
  30. framework. It can be used as a template for real PCI video capture driver.
  31. Structure of a driver
  32. ---------------------
  33. All drivers have the following structure:
  34. 1) A struct for each device instance containing the device state.
  35. 2) A way of initializing and commanding sub-devices (if any).
  36. 3) Creating V4L2 device nodes (/dev/videoX, /dev/vbiX and /dev/radioX)
  37. and keeping track of device-node specific data.
  38. 4) Filehandle-specific structs containing per-filehandle data;
  39. 5) video buffer handling.
  40. This is a rough schematic of how it all relates:
  41. device instances
  42. |
  43. +-sub-device instances
  44. |
  45. \-V4L2 device nodes
  46. |
  47. \-filehandle instances
  48. Structure of the framework
  49. --------------------------
  50. The framework closely resembles the driver structure: it has a v4l2_device
  51. struct for the device instance data, a v4l2_subdev struct to refer to
  52. sub-device instances, the video_device struct stores V4L2 device node data
  53. and the v4l2_fh struct keeps track of filehandle instances.
  54. The V4L2 framework also optionally integrates with the media framework. If a
  55. driver sets the struct v4l2_device mdev field, sub-devices and video nodes
  56. will automatically appear in the media framework as entities.
  57. struct v4l2_device
  58. ------------------
  59. Each device instance is represented by a struct v4l2_device (v4l2-device.h).
  60. Very simple devices can just allocate this struct, but most of the time you
  61. would embed this struct inside a larger struct.
  62. You must register the device instance:
  63. v4l2_device_register(struct device *dev, struct v4l2_device *v4l2_dev);
  64. Registration will initialize the v4l2_device struct. If the dev->driver_data
  65. field is NULL, it will be linked to v4l2_dev.
  66. Drivers that want integration with the media device framework need to set
  67. dev->driver_data manually to point to the driver-specific device structure
  68. that embed the struct v4l2_device instance. This is achieved by a
  69. dev_set_drvdata() call before registering the V4L2 device instance. They must
  70. also set the struct v4l2_device mdev field to point to a properly initialized
  71. and registered media_device instance.
  72. If v4l2_dev->name is empty then it will be set to a value derived from dev
  73. (driver name followed by the bus_id, to be precise). If you set it up before
  74. calling v4l2_device_register then it will be untouched. If dev is NULL, then
  75. you *must* setup v4l2_dev->name before calling v4l2_device_register.
  76. You can use v4l2_device_set_name() to set the name based on a driver name and
  77. a driver-global atomic_t instance. This will generate names like ivtv0, ivtv1,
  78. etc. If the name ends with a digit, then it will insert a dash: cx18-0,
  79. cx18-1, etc. This function returns the instance number.
  80. The first 'dev' argument is normally the struct device pointer of a pci_dev,
  81. usb_interface or platform_device. It is rare for dev to be NULL, but it happens
  82. with ISA devices or when one device creates multiple PCI devices, thus making
  83. it impossible to associate v4l2_dev with a particular parent.
  84. You can also supply a notify() callback that can be called by sub-devices to
  85. notify you of events. Whether you need to set this depends on the sub-device.
  86. Any notifications a sub-device supports must be defined in a header in
  87. include/media/<subdevice>.h.
  88. You unregister with:
  89. v4l2_device_unregister(struct v4l2_device *v4l2_dev);
  90. If the dev->driver_data field points to v4l2_dev, it will be reset to NULL.
  91. Unregistering will also automatically unregister all subdevs from the device.
  92. If you have a hotpluggable device (e.g. a USB device), then when a disconnect
  93. happens the parent device becomes invalid. Since v4l2_device has a pointer to
  94. that parent device it has to be cleared as well to mark that the parent is
  95. gone. To do this call:
  96. v4l2_device_disconnect(struct v4l2_device *v4l2_dev);
  97. This does *not* unregister the subdevs, so you still need to call the
  98. v4l2_device_unregister() function for that. If your driver is not hotpluggable,
  99. then there is no need to call v4l2_device_disconnect().
  100. Sometimes you need to iterate over all devices registered by a specific
  101. driver. This is usually the case if multiple device drivers use the same
  102. hardware. E.g. the ivtvfb driver is a framebuffer driver that uses the ivtv
  103. hardware. The same is true for alsa drivers for example.
  104. You can iterate over all registered devices as follows:
  105. static int callback(struct device *dev, void *p)
  106. {
  107. struct v4l2_device *v4l2_dev = dev_get_drvdata(dev);
  108. /* test if this device was inited */
  109. if (v4l2_dev == NULL)
  110. return 0;
  111. ...
  112. return 0;
  113. }
  114. int iterate(void *p)
  115. {
  116. struct device_driver *drv;
  117. int err;
  118. /* Find driver 'ivtv' on the PCI bus.
  119. pci_bus_type is a global. For USB busses use usb_bus_type. */
  120. drv = driver_find("ivtv", &pci_bus_type);
  121. /* iterate over all ivtv device instances */
  122. err = driver_for_each_device(drv, NULL, p, callback);
  123. put_driver(drv);
  124. return err;
  125. }
  126. Sometimes you need to keep a running counter of the device instance. This is
  127. commonly used to map a device instance to an index of a module option array.
  128. The recommended approach is as follows:
  129. static atomic_t drv_instance = ATOMIC_INIT(0);
  130. static int drv_probe(struct pci_dev *pdev, const struct pci_device_id *pci_id)
  131. {
  132. ...
  133. state->instance = atomic_inc_return(&drv_instance) - 1;
  134. }
  135. If you have multiple device nodes then it can be difficult to know when it is
  136. safe to unregister v4l2_device for hotpluggable devices. For this purpose
  137. v4l2_device has refcounting support. The refcount is increased whenever
  138. video_register_device is called and it is decreased whenever that device node
  139. is released. When the refcount reaches zero, then the v4l2_device release()
  140. callback is called. You can do your final cleanup there.
  141. If other device nodes (e.g. ALSA) are created, then you can increase and
  142. decrease the refcount manually as well by calling:
  143. void v4l2_device_get(struct v4l2_device *v4l2_dev);
  144. or:
  145. int v4l2_device_put(struct v4l2_device *v4l2_dev);
  146. Since the initial refcount is 1 you also need to call v4l2_device_put in the
  147. disconnect() callback (for USB devices) or in the remove() callback (for e.g.
  148. PCI devices), otherwise the refcount will never reach 0.
  149. struct v4l2_subdev
  150. ------------------
  151. Many drivers need to communicate with sub-devices. These devices can do all
  152. sort of tasks, but most commonly they handle audio and/or video muxing,
  153. encoding or decoding. For webcams common sub-devices are sensors and camera
  154. controllers.
  155. Usually these are I2C devices, but not necessarily. In order to provide the
  156. driver with a consistent interface to these sub-devices the v4l2_subdev struct
  157. (v4l2-subdev.h) was created.
  158. Each sub-device driver must have a v4l2_subdev struct. This struct can be
  159. stand-alone for simple sub-devices or it might be embedded in a larger struct
  160. if more state information needs to be stored. Usually there is a low-level
  161. device struct (e.g. i2c_client) that contains the device data as setup
  162. by the kernel. It is recommended to store that pointer in the private
  163. data of v4l2_subdev using v4l2_set_subdevdata(). That makes it easy to go
  164. from a v4l2_subdev to the actual low-level bus-specific device data.
  165. You also need a way to go from the low-level struct to v4l2_subdev. For the
  166. common i2c_client struct the i2c_set_clientdata() call is used to store a
  167. v4l2_subdev pointer, for other busses you may have to use other methods.
  168. Bridges might also need to store per-subdev private data, such as a pointer to
  169. bridge-specific per-subdev private data. The v4l2_subdev structure provides
  170. host private data for that purpose that can be accessed with
  171. v4l2_get_subdev_hostdata() and v4l2_set_subdev_hostdata().
  172. From the bridge driver perspective you load the sub-device module and somehow
  173. obtain the v4l2_subdev pointer. For i2c devices this is easy: you call
  174. i2c_get_clientdata(). For other busses something similar needs to be done.
  175. Helper functions exists for sub-devices on an I2C bus that do most of this
  176. tricky work for you.
  177. Each v4l2_subdev contains function pointers that sub-device drivers can
  178. implement (or leave NULL if it is not applicable). Since sub-devices can do
  179. so many different things and you do not want to end up with a huge ops struct
  180. of which only a handful of ops are commonly implemented, the function pointers
  181. are sorted according to category and each category has its own ops struct.
  182. The top-level ops struct contains pointers to the category ops structs, which
  183. may be NULL if the subdev driver does not support anything from that category.
  184. It looks like this:
  185. struct v4l2_subdev_core_ops {
  186. int (*log_status)(struct v4l2_subdev *sd);
  187. int (*init)(struct v4l2_subdev *sd, u32 val);
  188. ...
  189. };
  190. struct v4l2_subdev_tuner_ops {
  191. ...
  192. };
  193. struct v4l2_subdev_audio_ops {
  194. ...
  195. };
  196. struct v4l2_subdev_video_ops {
  197. ...
  198. };
  199. struct v4l2_subdev_pad_ops {
  200. ...
  201. };
  202. struct v4l2_subdev_ops {
  203. const struct v4l2_subdev_core_ops *core;
  204. const struct v4l2_subdev_tuner_ops *tuner;
  205. const struct v4l2_subdev_audio_ops *audio;
  206. const struct v4l2_subdev_video_ops *video;
  207. const struct v4l2_subdev_pad_ops *video;
  208. };
  209. The core ops are common to all subdevs, the other categories are implemented
  210. depending on the sub-device. E.g. a video device is unlikely to support the
  211. audio ops and vice versa.
  212. This setup limits the number of function pointers while still making it easy
  213. to add new ops and categories.
  214. A sub-device driver initializes the v4l2_subdev struct using:
  215. v4l2_subdev_init(sd, &ops);
  216. Afterwards you need to initialize subdev->name with a unique name and set the
  217. module owner. This is done for you if you use the i2c helper functions.
  218. If integration with the media framework is needed, you must initialize the
  219. media_entity struct embedded in the v4l2_subdev struct (entity field) by
  220. calling media_entity_init():
  221. struct media_pad *pads = &my_sd->pads;
  222. int err;
  223. err = media_entity_init(&sd->entity, npads, pads, 0);
  224. The pads array must have been previously initialized. There is no need to
  225. manually set the struct media_entity type and name fields, but the revision
  226. field must be initialized if needed.
  227. A reference to the entity will be automatically acquired/released when the
  228. subdev device node (if any) is opened/closed.
  229. Don't forget to cleanup the media entity before the sub-device is destroyed:
  230. media_entity_cleanup(&sd->entity);
  231. If the subdev driver intends to process video and integrate with the media
  232. framework, it must implement format related functionality using
  233. v4l2_subdev_pad_ops instead of v4l2_subdev_video_ops.
  234. In that case, the subdev driver may set the link_validate field to provide
  235. its own link validation function. The link validation function is called for
  236. every link in the pipeline where both of the ends of the links are V4L2
  237. sub-devices. The driver is still responsible for validating the correctness
  238. of the format configuration between sub-devices and video nodes.
  239. If link_validate op is not set, the default function
  240. v4l2_subdev_link_validate_default() is used instead. This function ensures
  241. that width, height and the media bus pixel code are equal on both source and
  242. sink of the link. Subdev drivers are also free to use this function to
  243. perform the checks mentioned above in addition to their own checks.
  244. There are currently two ways to register subdevices with the V4L2 core. The
  245. first (traditional) possibility is to have subdevices registered by bridge
  246. drivers. This can be done when the bridge driver has the complete information
  247. about subdevices connected to it and knows exactly when to register them. This
  248. is typically the case for internal subdevices, like video data processing units
  249. within SoCs or complex PCI(e) boards, camera sensors in USB cameras or connected
  250. to SoCs, which pass information about them to bridge drivers, usually in their
  251. platform data.
  252. There are however also situations where subdevices have to be registered
  253. asynchronously to bridge devices. An example of such a configuration is a Device
  254. Tree based system where information about subdevices is made available to the
  255. system independently from the bridge devices, e.g. when subdevices are defined
  256. in DT as I2C device nodes. The API used in this second case is described further
  257. below.
  258. Using one or the other registration method only affects the probing process, the
  259. run-time bridge-subdevice interaction is in both cases the same.
  260. In the synchronous case a device (bridge) driver needs to register the
  261. v4l2_subdev with the v4l2_device:
  262. int err = v4l2_device_register_subdev(v4l2_dev, sd);
  263. This can fail if the subdev module disappeared before it could be registered.
  264. After this function was called successfully the subdev->dev field points to
  265. the v4l2_device.
  266. If the v4l2_device parent device has a non-NULL mdev field, the sub-device
  267. entity will be automatically registered with the media device.
  268. You can unregister a sub-device using:
  269. v4l2_device_unregister_subdev(sd);
  270. Afterwards the subdev module can be unloaded and sd->dev == NULL.
  271. You can call an ops function either directly:
  272. err = sd->ops->core->g_std(sd, &norm);
  273. but it is better and easier to use this macro:
  274. err = v4l2_subdev_call(sd, core, g_std, &norm);
  275. The macro will to the right NULL pointer checks and returns -ENODEV if subdev
  276. is NULL, -ENOIOCTLCMD if either subdev->core or subdev->core->g_std is
  277. NULL, or the actual result of the subdev->ops->core->g_std ops.
  278. It is also possible to call all or a subset of the sub-devices:
  279. v4l2_device_call_all(v4l2_dev, 0, core, g_std, &norm);
  280. Any subdev that does not support this ops is skipped and error results are
  281. ignored. If you want to check for errors use this:
  282. err = v4l2_device_call_until_err(v4l2_dev, 0, core, g_std, &norm);
  283. Any error except -ENOIOCTLCMD will exit the loop with that error. If no
  284. errors (except -ENOIOCTLCMD) occurred, then 0 is returned.
  285. The second argument to both calls is a group ID. If 0, then all subdevs are
  286. called. If non-zero, then only those whose group ID match that value will
  287. be called. Before a bridge driver registers a subdev it can set sd->grp_id
  288. to whatever value it wants (it's 0 by default). This value is owned by the
  289. bridge driver and the sub-device driver will never modify or use it.
  290. The group ID gives the bridge driver more control how callbacks are called.
  291. For example, there may be multiple audio chips on a board, each capable of
  292. changing the volume. But usually only one will actually be used when the
  293. user want to change the volume. You can set the group ID for that subdev to
  294. e.g. AUDIO_CONTROLLER and specify that as the group ID value when calling
  295. v4l2_device_call_all(). That ensures that it will only go to the subdev
  296. that needs it.
  297. If the sub-device needs to notify its v4l2_device parent of an event, then
  298. it can call v4l2_subdev_notify(sd, notification, arg). This macro checks
  299. whether there is a notify() callback defined and returns -ENODEV if not.
  300. Otherwise the result of the notify() call is returned.
  301. The advantage of using v4l2_subdev is that it is a generic struct and does
  302. not contain any knowledge about the underlying hardware. So a driver might
  303. contain several subdevs that use an I2C bus, but also a subdev that is
  304. controlled through GPIO pins. This distinction is only relevant when setting
  305. up the device, but once the subdev is registered it is completely transparent.
  306. In the asynchronous case subdevice probing can be invoked independently of the
  307. bridge driver availability. The subdevice driver then has to verify whether all
  308. the requirements for a successful probing are satisfied. This can include a
  309. check for a master clock availability. If any of the conditions aren't satisfied
  310. the driver might decide to return -EPROBE_DEFER to request further reprobing
  311. attempts. Once all conditions are met the subdevice shall be registered using
  312. the v4l2_async_register_subdev() function. Unregistration is performed using
  313. the v4l2_async_unregister_subdev() call. Subdevices registered this way are
  314. stored in a global list of subdevices, ready to be picked up by bridge drivers.
  315. Bridge drivers in turn have to register a notifier object with an array of
  316. subdevice descriptors that the bridge device needs for its operation. This is
  317. performed using the v4l2_async_notifier_register() call. To unregister the
  318. notifier the driver has to call v4l2_async_notifier_unregister(). The former of
  319. the two functions takes two arguments: a pointer to struct v4l2_device and a
  320. pointer to struct v4l2_async_notifier. The latter contains a pointer to an array
  321. of pointers to subdevice descriptors of type struct v4l2_async_subdev type. The
  322. V4L2 core will then use these descriptors to match asynchronously registered
  323. subdevices to them. If a match is detected the .bound() notifier callback is
  324. called. After all subdevices have been located the .complete() callback is
  325. called. When a subdevice is removed from the system the .unbind() method is
  326. called. All three callbacks are optional.
  327. V4L2 sub-device userspace API
  328. -----------------------------
  329. Beside exposing a kernel API through the v4l2_subdev_ops structure, V4L2
  330. sub-devices can also be controlled directly by userspace applications.
  331. Device nodes named v4l-subdevX can be created in /dev to access sub-devices
  332. directly. If a sub-device supports direct userspace configuration it must set
  333. the V4L2_SUBDEV_FL_HAS_DEVNODE flag before being registered.
  334. After registering sub-devices, the v4l2_device driver can create device nodes
  335. for all registered sub-devices marked with V4L2_SUBDEV_FL_HAS_DEVNODE by calling
  336. v4l2_device_register_subdev_nodes(). Those device nodes will be automatically
  337. removed when sub-devices are unregistered.
  338. The device node handles a subset of the V4L2 API.
  339. VIDIOC_QUERYCTRL
  340. VIDIOC_QUERYMENU
  341. VIDIOC_G_CTRL
  342. VIDIOC_S_CTRL
  343. VIDIOC_G_EXT_CTRLS
  344. VIDIOC_S_EXT_CTRLS
  345. VIDIOC_TRY_EXT_CTRLS
  346. The controls ioctls are identical to the ones defined in V4L2. They
  347. behave identically, with the only exception that they deal only with
  348. controls implemented in the sub-device. Depending on the driver, those
  349. controls can be also be accessed through one (or several) V4L2 device
  350. nodes.
  351. VIDIOC_DQEVENT
  352. VIDIOC_SUBSCRIBE_EVENT
  353. VIDIOC_UNSUBSCRIBE_EVENT
  354. The events ioctls are identical to the ones defined in V4L2. They
  355. behave identically, with the only exception that they deal only with
  356. events generated by the sub-device. Depending on the driver, those
  357. events can also be reported by one (or several) V4L2 device nodes.
  358. Sub-device drivers that want to use events need to set the
  359. V4L2_SUBDEV_USES_EVENTS v4l2_subdev::flags and initialize
  360. v4l2_subdev::nevents to events queue depth before registering the
  361. sub-device. After registration events can be queued as usual on the
  362. v4l2_subdev::devnode device node.
  363. To properly support events, the poll() file operation is also
  364. implemented.
  365. Private ioctls
  366. All ioctls not in the above list are passed directly to the sub-device
  367. driver through the core::ioctl operation.
  368. I2C sub-device drivers
  369. ----------------------
  370. Since these drivers are so common, special helper functions are available to
  371. ease the use of these drivers (v4l2-common.h).
  372. The recommended method of adding v4l2_subdev support to an I2C driver is to
  373. embed the v4l2_subdev struct into the state struct that is created for each
  374. I2C device instance. Very simple devices have no state struct and in that case
  375. you can just create a v4l2_subdev directly.
  376. A typical state struct would look like this (where 'chipname' is replaced by
  377. the name of the chip):
  378. struct chipname_state {
  379. struct v4l2_subdev sd;
  380. ... /* additional state fields */
  381. };
  382. Initialize the v4l2_subdev struct as follows:
  383. v4l2_i2c_subdev_init(&state->sd, client, subdev_ops);
  384. This function will fill in all the fields of v4l2_subdev and ensure that the
  385. v4l2_subdev and i2c_client both point to one another.
  386. You should also add a helper inline function to go from a v4l2_subdev pointer
  387. to a chipname_state struct:
  388. static inline struct chipname_state *to_state(struct v4l2_subdev *sd)
  389. {
  390. return container_of(sd, struct chipname_state, sd);
  391. }
  392. Use this to go from the v4l2_subdev struct to the i2c_client struct:
  393. struct i2c_client *client = v4l2_get_subdevdata(sd);
  394. And this to go from an i2c_client to a v4l2_subdev struct:
  395. struct v4l2_subdev *sd = i2c_get_clientdata(client);
  396. Make sure to call v4l2_device_unregister_subdev(sd) when the remove() callback
  397. is called. This will unregister the sub-device from the bridge driver. It is
  398. safe to call this even if the sub-device was never registered.
  399. You need to do this because when the bridge driver destroys the i2c adapter
  400. the remove() callbacks are called of the i2c devices on that adapter.
  401. After that the corresponding v4l2_subdev structures are invalid, so they
  402. have to be unregistered first. Calling v4l2_device_unregister_subdev(sd)
  403. from the remove() callback ensures that this is always done correctly.
  404. The bridge driver also has some helper functions it can use:
  405. struct v4l2_subdev *sd = v4l2_i2c_new_subdev(v4l2_dev, adapter,
  406. "module_foo", "chipid", 0x36, NULL);
  407. This loads the given module (can be NULL if no module needs to be loaded) and
  408. calls i2c_new_device() with the given i2c_adapter and chip/address arguments.
  409. If all goes well, then it registers the subdev with the v4l2_device.
  410. You can also use the last argument of v4l2_i2c_new_subdev() to pass an array
  411. of possible I2C addresses that it should probe. These probe addresses are
  412. only used if the previous argument is 0. A non-zero argument means that you
  413. know the exact i2c address so in that case no probing will take place.
  414. Both functions return NULL if something went wrong.
  415. Note that the chipid you pass to v4l2_i2c_new_subdev() is usually
  416. the same as the module name. It allows you to specify a chip variant, e.g.
  417. "saa7114" or "saa7115". In general though the i2c driver autodetects this.
  418. The use of chipid is something that needs to be looked at more closely at a
  419. later date. It differs between i2c drivers and as such can be confusing.
  420. To see which chip variants are supported you can look in the i2c driver code
  421. for the i2c_device_id table. This lists all the possibilities.
  422. There are two more helper functions:
  423. v4l2_i2c_new_subdev_cfg: this function adds new irq and platform_data
  424. arguments and has both 'addr' and 'probed_addrs' arguments: if addr is not
  425. 0 then that will be used (non-probing variant), otherwise the probed_addrs
  426. are probed.
  427. For example: this will probe for address 0x10:
  428. struct v4l2_subdev *sd = v4l2_i2c_new_subdev_cfg(v4l2_dev, adapter,
  429. "module_foo", "chipid", 0, NULL, 0, I2C_ADDRS(0x10));
  430. v4l2_i2c_new_subdev_board uses an i2c_board_info struct which is passed
  431. to the i2c driver and replaces the irq, platform_data and addr arguments.
  432. If the subdev supports the s_config core ops, then that op is called with
  433. the irq and platform_data arguments after the subdev was setup. The older
  434. v4l2_i2c_new_(probed_)subdev functions will call s_config as well, but with
  435. irq set to 0 and platform_data set to NULL.
  436. struct video_device
  437. -------------------
  438. The actual device nodes in the /dev directory are created using the
  439. video_device struct (v4l2-dev.h). This struct can either be allocated
  440. dynamically or embedded in a larger struct.
  441. To allocate it dynamically use:
  442. struct video_device *vdev = video_device_alloc();
  443. if (vdev == NULL)
  444. return -ENOMEM;
  445. vdev->release = video_device_release;
  446. If you embed it in a larger struct, then you must set the release()
  447. callback to your own function:
  448. struct video_device *vdev = &my_vdev->vdev;
  449. vdev->release = my_vdev_release;
  450. The release callback must be set and it is called when the last user
  451. of the video device exits.
  452. The default video_device_release() callback just calls kfree to free the
  453. allocated memory.
  454. There is also a video_device_release_empty() function that does nothing
  455. (is empty) and can be used if the struct is embedded and there is nothing
  456. to do when it is released.
  457. You should also set these fields:
  458. - v4l2_dev: must be set to the v4l2_device parent device.
  459. - name: set to something descriptive and unique.
  460. - vfl_dir: set this to VFL_DIR_RX for capture devices (VFL_DIR_RX has value 0,
  461. so this is normally already the default), set to VFL_DIR_TX for output
  462. devices and VFL_DIR_M2M for mem2mem (codec) devices.
  463. - fops: set to the v4l2_file_operations struct.
  464. - ioctl_ops: if you use the v4l2_ioctl_ops to simplify ioctl maintenance
  465. (highly recommended to use this and it might become compulsory in the
  466. future!), then set this to your v4l2_ioctl_ops struct. The vfl_type and
  467. vfl_dir fields are used to disable ops that do not match the type/dir
  468. combination. E.g. VBI ops are disabled for non-VBI nodes, and output ops
  469. are disabled for a capture device. This makes it possible to provide
  470. just one v4l2_ioctl_ops struct for both vbi and video nodes.
  471. - lock: leave to NULL if you want to do all the locking in the driver.
  472. Otherwise you give it a pointer to a struct mutex_lock and before the
  473. unlocked_ioctl file operation is called this lock will be taken by the
  474. core and released afterwards. See the next section for more details.
  475. - queue: a pointer to the struct vb2_queue associated with this device node.
  476. If queue is non-NULL, and queue->lock is non-NULL, then queue->lock is
  477. used for the queuing ioctls (VIDIOC_REQBUFS, CREATE_BUFS, QBUF, DQBUF,
  478. QUERYBUF, PREPARE_BUF, STREAMON and STREAMOFF) instead of the lock above.
  479. That way the vb2 queuing framework does not have to wait for other ioctls.
  480. This queue pointer is also used by the vb2 helper functions to check for
  481. queuing ownership (i.e. is the filehandle calling it allowed to do the
  482. operation).
  483. - prio: keeps track of the priorities. Used to implement VIDIOC_G/S_PRIORITY.
  484. If left to NULL, then it will use the struct v4l2_prio_state in v4l2_device.
  485. If you want to have a separate priority state per (group of) device node(s),
  486. then you can point it to your own struct v4l2_prio_state.
  487. - dev_parent: you only set this if v4l2_device was registered with NULL as
  488. the parent device struct. This only happens in cases where one hardware
  489. device has multiple PCI devices that all share the same v4l2_device core.
  490. The cx88 driver is an example of this: one core v4l2_device struct, but
  491. it is used by both a raw video PCI device (cx8800) and a MPEG PCI device
  492. (cx8802). Since the v4l2_device cannot be associated with two PCI devices
  493. at the same time it is setup without a parent device. But when the struct
  494. video_device is initialized you *do* know which parent PCI device to use and
  495. so you set dev_device to the correct PCI device.
  496. If you use v4l2_ioctl_ops, then you should set .unlocked_ioctl to video_ioctl2
  497. in your v4l2_file_operations struct.
  498. Do not use .ioctl! This is deprecated and will go away in the future.
  499. In some cases you want to tell the core that a function you had specified in
  500. your v4l2_ioctl_ops should be ignored. You can mark such ioctls by calling this
  501. function before video_device_register is called:
  502. void v4l2_disable_ioctl(struct video_device *vdev, unsigned int cmd);
  503. This tends to be needed if based on external factors (e.g. which card is
  504. being used) you want to turns off certain features in v4l2_ioctl_ops without
  505. having to make a new struct.
  506. The v4l2_file_operations struct is a subset of file_operations. The main
  507. difference is that the inode argument is omitted since it is never used.
  508. If integration with the media framework is needed, you must initialize the
  509. media_entity struct embedded in the video_device struct (entity field) by
  510. calling media_entity_init():
  511. struct media_pad *pad = &my_vdev->pad;
  512. int err;
  513. err = media_entity_init(&vdev->entity, 1, pad, 0);
  514. The pads array must have been previously initialized. There is no need to
  515. manually set the struct media_entity type and name fields.
  516. A reference to the entity will be automatically acquired/released when the
  517. video device is opened/closed.
  518. ioctls and locking
  519. ------------------
  520. The V4L core provides optional locking services. The main service is the
  521. lock field in struct video_device, which is a pointer to a mutex. If you set
  522. this pointer, then that will be used by unlocked_ioctl to serialize all ioctls.
  523. If you are using the videobuf2 framework, then there is a second lock that you
  524. can set: video_device->queue->lock. If set, then this lock will be used instead
  525. of video_device->lock to serialize all queuing ioctls (see the previous section
  526. for the full list of those ioctls).
  527. The advantage of using a different lock for the queuing ioctls is that for some
  528. drivers (particularly USB drivers) certain commands such as setting controls
  529. can take a long time, so you want to use a separate lock for the buffer queuing
  530. ioctls. That way your VIDIOC_DQBUF doesn't stall because the driver is busy
  531. changing the e.g. exposure of the webcam.
  532. Of course, you can always do all the locking yourself by leaving both lock
  533. pointers at NULL.
  534. If you use the old videobuf then you must pass the video_device lock to the
  535. videobuf queue initialize function: if videobuf has to wait for a frame to
  536. arrive, then it will temporarily unlock the lock and relock it afterwards. If
  537. your driver also waits in the code, then you should do the same to allow other
  538. processes to access the device node while the first process is waiting for
  539. something.
  540. In the case of videobuf2 you will need to implement the wait_prepare and
  541. wait_finish callbacks to unlock/lock if applicable. If you use the queue->lock
  542. pointer, then you can use the helper functions vb2_ops_wait_prepare/finish.
  543. The implementation of a hotplug disconnect should also take the lock from
  544. video_device before calling v4l2_device_disconnect. If you are also using
  545. video_device->queue->lock, then you have to first lock video_device->queue->lock
  546. followed by video_device->lock. That way you can be sure no ioctl is running
  547. when you call v4l2_device_disconnect.
  548. video_device registration
  549. -------------------------
  550. Next you register the video device: this will create the character device
  551. for you.
  552. err = video_register_device(vdev, VFL_TYPE_GRABBER, -1);
  553. if (err) {
  554. video_device_release(vdev); /* or kfree(my_vdev); */
  555. return err;
  556. }
  557. If the v4l2_device parent device has a non-NULL mdev field, the video device
  558. entity will be automatically registered with the media device.
  559. Which device is registered depends on the type argument. The following
  560. types exist:
  561. VFL_TYPE_GRABBER: videoX for video input/output devices
  562. VFL_TYPE_VBI: vbiX for vertical blank data (i.e. closed captions, teletext)
  563. VFL_TYPE_RADIO: radioX for radio tuners
  564. VFL_TYPE_SDR: swradioX for Software Defined Radio tuners
  565. The last argument gives you a certain amount of control over the device
  566. device node number used (i.e. the X in videoX). Normally you will pass -1
  567. to let the v4l2 framework pick the first free number. But sometimes users
  568. want to select a specific node number. It is common that drivers allow
  569. the user to select a specific device node number through a driver module
  570. option. That number is then passed to this function and video_register_device
  571. will attempt to select that device node number. If that number was already
  572. in use, then the next free device node number will be selected and it
  573. will send a warning to the kernel log.
  574. Another use-case is if a driver creates many devices. In that case it can
  575. be useful to place different video devices in separate ranges. For example,
  576. video capture devices start at 0, video output devices start at 16.
  577. So you can use the last argument to specify a minimum device node number
  578. and the v4l2 framework will try to pick the first free number that is equal
  579. or higher to what you passed. If that fails, then it will just pick the
  580. first free number.
  581. Since in this case you do not care about a warning about not being able
  582. to select the specified device node number, you can call the function
  583. video_register_device_no_warn() instead.
  584. Whenever a device node is created some attributes are also created for you.
  585. If you look in /sys/class/video4linux you see the devices. Go into e.g.
  586. video0 and you will see 'name', 'dev_debug' and 'index' attributes. The 'name'
  587. attribute is the 'name' field of the video_device struct. The 'dev_debug' attribute
  588. can be used to enable core debugging. See the next section for more detailed
  589. information on this.
  590. The 'index' attribute is the index of the device node: for each call to
  591. video_register_device() the index is just increased by 1. The first video
  592. device node you register always starts with index 0.
  593. Users can setup udev rules that utilize the index attribute to make fancy
  594. device names (e.g. 'mpegX' for MPEG video capture device nodes).
  595. After the device was successfully registered, then you can use these fields:
  596. - vfl_type: the device type passed to video_register_device.
  597. - minor: the assigned device minor number.
  598. - num: the device node number (i.e. the X in videoX).
  599. - index: the device index number.
  600. If the registration failed, then you need to call video_device_release()
  601. to free the allocated video_device struct, or free your own struct if the
  602. video_device was embedded in it. The vdev->release() callback will never
  603. be called if the registration failed, nor should you ever attempt to
  604. unregister the device if the registration failed.
  605. video device debugging
  606. ----------------------
  607. The 'dev_debug' attribute that is created for each video, vbi, radio or swradio
  608. device in /sys/class/video4linux/<devX>/ allows you to enable logging of
  609. file operations.
  610. It is a bitmask and the following bits can be set:
  611. 0x01: Log the ioctl name and error code. VIDIOC_(D)QBUF ioctls are only logged
  612. if bit 0x08 is also set.
  613. 0x02: Log the ioctl name arguments and error code. VIDIOC_(D)QBUF ioctls are
  614. only logged if bit 0x08 is also set.
  615. 0x04: Log the file operations open, release, read, write, mmap and
  616. get_unmapped_area. The read and write operations are only logged if
  617. bit 0x08 is also set.
  618. 0x08: Log the read and write file operations and the VIDIOC_QBUF and
  619. VIDIOC_DQBUF ioctls.
  620. 0x10: Log the poll file operation.
  621. video_device cleanup
  622. --------------------
  623. When the video device nodes have to be removed, either during the unload
  624. of the driver or because the USB device was disconnected, then you should
  625. unregister them:
  626. video_unregister_device(vdev);
  627. This will remove the device nodes from sysfs (causing udev to remove them
  628. from /dev).
  629. After video_unregister_device() returns no new opens can be done. However,
  630. in the case of USB devices some application might still have one of these
  631. device nodes open. So after the unregister all file operations (except
  632. release, of course) will return an error as well.
  633. When the last user of the video device node exits, then the vdev->release()
  634. callback is called and you can do the final cleanup there.
  635. Don't forget to cleanup the media entity associated with the video device if
  636. it has been initialized:
  637. media_entity_cleanup(&vdev->entity);
  638. This can be done from the release callback.
  639. video_device helper functions
  640. -----------------------------
  641. There are a few useful helper functions:
  642. - file/video_device private data
  643. You can set/get driver private data in the video_device struct using:
  644. void *video_get_drvdata(struct video_device *vdev);
  645. void video_set_drvdata(struct video_device *vdev, void *data);
  646. Note that you can safely call video_set_drvdata() before calling
  647. video_register_device().
  648. And this function:
  649. struct video_device *video_devdata(struct file *file);
  650. returns the video_device belonging to the file struct.
  651. The video_drvdata function combines video_get_drvdata with video_devdata:
  652. void *video_drvdata(struct file *file);
  653. You can go from a video_device struct to the v4l2_device struct using:
  654. struct v4l2_device *v4l2_dev = vdev->v4l2_dev;
  655. - Device node name
  656. The video_device node kernel name can be retrieved using
  657. const char *video_device_node_name(struct video_device *vdev);
  658. The name is used as a hint by userspace tools such as udev. The function
  659. should be used where possible instead of accessing the video_device::num and
  660. video_device::minor fields.
  661. video buffer helper functions
  662. -----------------------------
  663. The v4l2 core API provides a set of standard methods (called "videobuf")
  664. for dealing with video buffers. Those methods allow a driver to implement
  665. read(), mmap() and overlay() in a consistent way. There are currently
  666. methods for using video buffers on devices that supports DMA with
  667. scatter/gather method (videobuf-dma-sg), DMA with linear access
  668. (videobuf-dma-contig), and vmalloced buffers, mostly used on USB drivers
  669. (videobuf-vmalloc).
  670. Please see Documentation/video4linux/videobuf for more information on how
  671. to use the videobuf layer.
  672. struct v4l2_fh
  673. --------------
  674. struct v4l2_fh provides a way to easily keep file handle specific data
  675. that is used by the V4L2 framework. New drivers must use struct v4l2_fh
  676. since it is also used to implement priority handling (VIDIOC_G/S_PRIORITY).
  677. The users of v4l2_fh (in the V4L2 framework, not the driver) know
  678. whether a driver uses v4l2_fh as its file->private_data pointer by
  679. testing the V4L2_FL_USES_V4L2_FH bit in video_device->flags. This bit is
  680. set whenever v4l2_fh_init() is called.
  681. struct v4l2_fh is allocated as a part of the driver's own file handle
  682. structure and file->private_data is set to it in the driver's open
  683. function by the driver.
  684. In many cases the struct v4l2_fh will be embedded in a larger structure.
  685. In that case you should call v4l2_fh_init+v4l2_fh_add in open() and
  686. v4l2_fh_del+v4l2_fh_exit in release().
  687. Drivers can extract their own file handle structure by using the container_of
  688. macro. Example:
  689. struct my_fh {
  690. int blah;
  691. struct v4l2_fh fh;
  692. };
  693. ...
  694. int my_open(struct file *file)
  695. {
  696. struct my_fh *my_fh;
  697. struct video_device *vfd;
  698. int ret;
  699. ...
  700. my_fh = kzalloc(sizeof(*my_fh), GFP_KERNEL);
  701. ...
  702. v4l2_fh_init(&my_fh->fh, vfd);
  703. ...
  704. file->private_data = &my_fh->fh;
  705. v4l2_fh_add(&my_fh->fh);
  706. return 0;
  707. }
  708. int my_release(struct file *file)
  709. {
  710. struct v4l2_fh *fh = file->private_data;
  711. struct my_fh *my_fh = container_of(fh, struct my_fh, fh);
  712. ...
  713. v4l2_fh_del(&my_fh->fh);
  714. v4l2_fh_exit(&my_fh->fh);
  715. kfree(my_fh);
  716. return 0;
  717. }
  718. Below is a short description of the v4l2_fh functions used:
  719. void v4l2_fh_init(struct v4l2_fh *fh, struct video_device *vdev)
  720. Initialise the file handle. This *MUST* be performed in the driver's
  721. v4l2_file_operations->open() handler.
  722. void v4l2_fh_add(struct v4l2_fh *fh)
  723. Add a v4l2_fh to video_device file handle list. Must be called once the
  724. file handle is completely initialized.
  725. void v4l2_fh_del(struct v4l2_fh *fh)
  726. Unassociate the file handle from video_device(). The file handle
  727. exit function may now be called.
  728. void v4l2_fh_exit(struct v4l2_fh *fh)
  729. Uninitialise the file handle. After uninitialisation the v4l2_fh
  730. memory can be freed.
  731. If struct v4l2_fh is not embedded, then you can use these helper functions:
  732. int v4l2_fh_open(struct file *filp)
  733. This allocates a struct v4l2_fh, initializes it and adds it to the struct
  734. video_device associated with the file struct.
  735. int v4l2_fh_release(struct file *filp)
  736. This deletes it from the struct video_device associated with the file
  737. struct, uninitialised the v4l2_fh and frees it.
  738. These two functions can be plugged into the v4l2_file_operation's open() and
  739. release() ops.
  740. Several drivers need to do something when the first file handle is opened and
  741. when the last file handle closes. Two helper functions were added to check
  742. whether the v4l2_fh struct is the only open filehandle of the associated
  743. device node:
  744. int v4l2_fh_is_singular(struct v4l2_fh *fh)
  745. Returns 1 if the file handle is the only open file handle, else 0.
  746. int v4l2_fh_is_singular_file(struct file *filp)
  747. Same, but it calls v4l2_fh_is_singular with filp->private_data.
  748. V4L2 events
  749. -----------
  750. The V4L2 events provide a generic way to pass events to user space.
  751. The driver must use v4l2_fh to be able to support V4L2 events.
  752. Events are defined by a type and an optional ID. The ID may refer to a V4L2
  753. object such as a control ID. If unused, then the ID is 0.
  754. When the user subscribes to an event the driver will allocate a number of
  755. kevent structs for that event. So every (type, ID) event tuple will have
  756. its own set of kevent structs. This guarantees that if a driver is generating
  757. lots of events of one type in a short time, then that will not overwrite
  758. events of another type.
  759. But if you get more events of one type than the number of kevents that were
  760. reserved, then the oldest event will be dropped and the new one added.
  761. Furthermore, the internal struct v4l2_subscribed_event has merge() and
  762. replace() callbacks which drivers can set. These callbacks are called when
  763. a new event is raised and there is no more room. The replace() callback
  764. allows you to replace the payload of the old event with that of the new event,
  765. merging any relevant data from the old payload into the new payload that
  766. replaces it. It is called when this event type has only one kevent struct
  767. allocated. The merge() callback allows you to merge the oldest event payload
  768. into that of the second-oldest event payload. It is called when there are two
  769. or more kevent structs allocated.
  770. This way no status information is lost, just the intermediate steps leading
  771. up to that state.
  772. A good example of these replace/merge callbacks is in v4l2-event.c:
  773. ctrls_replace() and ctrls_merge() callbacks for the control event.
  774. Note: these callbacks can be called from interrupt context, so they must be
  775. fast.
  776. Useful functions:
  777. void v4l2_event_queue(struct video_device *vdev, const struct v4l2_event *ev)
  778. Queue events to video device. The driver's only responsibility is to fill
  779. in the type and the data fields. The other fields will be filled in by
  780. V4L2.
  781. int v4l2_event_subscribe(struct v4l2_fh *fh,
  782. struct v4l2_event_subscription *sub, unsigned elems,
  783. const struct v4l2_subscribed_event_ops *ops)
  784. The video_device->ioctl_ops->vidioc_subscribe_event must check the driver
  785. is able to produce events with specified event id. Then it calls
  786. v4l2_event_subscribe() to subscribe the event.
  787. The elems argument is the size of the event queue for this event. If it is 0,
  788. then the framework will fill in a default value (this depends on the event
  789. type).
  790. The ops argument allows the driver to specify a number of callbacks:
  791. * add: called when a new listener gets added (subscribing to the same
  792. event twice will only cause this callback to get called once)
  793. * del: called when a listener stops listening
  794. * replace: replace event 'old' with event 'new'.
  795. * merge: merge event 'old' into event 'new'.
  796. All 4 callbacks are optional, if you don't want to specify any callbacks
  797. the ops argument itself maybe NULL.
  798. int v4l2_event_unsubscribe(struct v4l2_fh *fh,
  799. struct v4l2_event_subscription *sub)
  800. vidioc_unsubscribe_event in struct v4l2_ioctl_ops. A driver may use
  801. v4l2_event_unsubscribe() directly unless it wants to be involved in
  802. unsubscription process.
  803. The special type V4L2_EVENT_ALL may be used to unsubscribe all events. The
  804. drivers may want to handle this in a special way.
  805. int v4l2_event_pending(struct v4l2_fh *fh)
  806. Returns the number of pending events. Useful when implementing poll.
  807. Events are delivered to user space through the poll system call. The driver
  808. can use v4l2_fh->wait (a wait_queue_head_t) as the argument for poll_wait().
  809. There are standard and private events. New standard events must use the
  810. smallest available event type. The drivers must allocate their events from
  811. their own class starting from class base. Class base is
  812. V4L2_EVENT_PRIVATE_START + n * 1000 where n is the lowest available number.
  813. The first event type in the class is reserved for future use, so the first
  814. available event type is 'class base + 1'.
  815. An example on how the V4L2 events may be used can be found in the OMAP
  816. 3 ISP driver (drivers/media/platform/omap3isp).
  817. A subdev can directly send an event to the v4l2_device notify function with
  818. V4L2_DEVICE_NOTIFY_EVENT. This allows the bridge to map the subdev that sends
  819. the event to the video node(s) associated with the subdev that need to be
  820. informed about such an event.
  821. V4L2 clocks
  822. -----------
  823. Many subdevices, like camera sensors, TV decoders and encoders, need a clock
  824. signal to be supplied by the system. Often this clock is supplied by the
  825. respective bridge device. The Linux kernel provides a Common Clock Framework for
  826. this purpose. However, it is not (yet) available on all architectures. Besides,
  827. the nature of the multi-functional (clock, data + synchronisation, I2C control)
  828. connection of subdevices to the system might impose special requirements on the
  829. clock API usage. E.g. V4L2 has to support clock provider driver unregistration
  830. while a subdevice driver is holding a reference to the clock. For these reasons
  831. a V4L2 clock helper API has been developed and is provided to bridge and
  832. subdevice drivers.
  833. The API consists of two parts: two functions to register and unregister a V4L2
  834. clock source: v4l2_clk_register() and v4l2_clk_unregister() and calls to control
  835. a clock object, similar to the respective generic clock API calls:
  836. v4l2_clk_get(), v4l2_clk_put(), v4l2_clk_enable(), v4l2_clk_disable(),
  837. v4l2_clk_get_rate(), and v4l2_clk_set_rate(). Clock suppliers have to provide
  838. clock operations that will be called when clock users invoke respective API
  839. methods.
  840. It is expected that once the CCF becomes available on all relevant
  841. architectures this API will be removed.