uvc_video.c 63 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251
  1. // SPDX-License-Identifier: GPL-2.0-or-later
  2. /*
  3. * uvc_video.c -- USB Video Class driver - Video handling
  4. *
  5. * Copyright (C) 2005-2010
  6. * Laurent Pinchart ([email protected])
  7. */
  8. #include <linux/dma-mapping.h>
  9. #include <linux/highmem.h>
  10. #include <linux/kernel.h>
  11. #include <linux/list.h>
  12. #include <linux/module.h>
  13. #include <linux/slab.h>
  14. #include <linux/usb.h>
  15. #include <linux/usb/hcd.h>
  16. #include <linux/videodev2.h>
  17. #include <linux/vmalloc.h>
  18. #include <linux/wait.h>
  19. #include <linux/atomic.h>
  20. #include <asm/unaligned.h>
  21. #include <media/v4l2-common.h>
  22. #include "uvcvideo.h"
  23. /* ------------------------------------------------------------------------
  24. * UVC Controls
  25. */
  26. static int __uvc_query_ctrl(struct uvc_device *dev, u8 query, u8 unit,
  27. u8 intfnum, u8 cs, void *data, u16 size,
  28. int timeout)
  29. {
  30. u8 type = USB_TYPE_CLASS | USB_RECIP_INTERFACE;
  31. unsigned int pipe;
  32. pipe = (query & 0x80) ? usb_rcvctrlpipe(dev->udev, 0)
  33. : usb_sndctrlpipe(dev->udev, 0);
  34. type |= (query & 0x80) ? USB_DIR_IN : USB_DIR_OUT;
  35. return usb_control_msg(dev->udev, pipe, query, type, cs << 8,
  36. unit << 8 | intfnum, data, size, timeout);
  37. }
  38. static const char *uvc_query_name(u8 query)
  39. {
  40. switch (query) {
  41. case UVC_SET_CUR:
  42. return "SET_CUR";
  43. case UVC_GET_CUR:
  44. return "GET_CUR";
  45. case UVC_GET_MIN:
  46. return "GET_MIN";
  47. case UVC_GET_MAX:
  48. return "GET_MAX";
  49. case UVC_GET_RES:
  50. return "GET_RES";
  51. case UVC_GET_LEN:
  52. return "GET_LEN";
  53. case UVC_GET_INFO:
  54. return "GET_INFO";
  55. case UVC_GET_DEF:
  56. return "GET_DEF";
  57. default:
  58. return "<invalid>";
  59. }
  60. }
  61. int uvc_query_ctrl(struct uvc_device *dev, u8 query, u8 unit,
  62. u8 intfnum, u8 cs, void *data, u16 size)
  63. {
  64. int ret;
  65. u8 error;
  66. u8 tmp;
  67. ret = __uvc_query_ctrl(dev, query, unit, intfnum, cs, data, size,
  68. UVC_CTRL_CONTROL_TIMEOUT);
  69. if (likely(ret == size))
  70. return 0;
  71. dev_err(&dev->udev->dev,
  72. "Failed to query (%s) UVC control %u on unit %u: %d (exp. %u).\n",
  73. uvc_query_name(query), cs, unit, ret, size);
  74. if (ret != -EPIPE)
  75. return ret;
  76. tmp = *(u8 *)data;
  77. ret = __uvc_query_ctrl(dev, UVC_GET_CUR, 0, intfnum,
  78. UVC_VC_REQUEST_ERROR_CODE_CONTROL, data, 1,
  79. UVC_CTRL_CONTROL_TIMEOUT);
  80. error = *(u8 *)data;
  81. *(u8 *)data = tmp;
  82. if (ret != 1)
  83. return ret < 0 ? ret : -EPIPE;
  84. uvc_dbg(dev, CONTROL, "Control error %u\n", error);
  85. switch (error) {
  86. case 0:
  87. /* Cannot happen - we received a STALL */
  88. return -EPIPE;
  89. case 1: /* Not ready */
  90. return -EBUSY;
  91. case 2: /* Wrong state */
  92. return -EILSEQ;
  93. case 3: /* Power */
  94. return -EREMOTE;
  95. case 4: /* Out of range */
  96. return -ERANGE;
  97. case 5: /* Invalid unit */
  98. case 6: /* Invalid control */
  99. case 7: /* Invalid Request */
  100. /*
  101. * The firmware has not properly implemented
  102. * the control or there has been a HW error.
  103. */
  104. return -EIO;
  105. case 8: /* Invalid value within range */
  106. return -EINVAL;
  107. default: /* reserved or unknown */
  108. break;
  109. }
  110. return -EPIPE;
  111. }
  112. static void uvc_fixup_video_ctrl(struct uvc_streaming *stream,
  113. struct uvc_streaming_control *ctrl)
  114. {
  115. static const struct usb_device_id elgato_cam_link_4k = {
  116. USB_DEVICE(0x0fd9, 0x0066)
  117. };
  118. struct uvc_format *format = NULL;
  119. struct uvc_frame *frame = NULL;
  120. unsigned int i;
  121. /*
  122. * The response of the Elgato Cam Link 4K is incorrect: The second byte
  123. * contains bFormatIndex (instead of being the second byte of bmHint).
  124. * The first byte is always zero. The third byte is always 1.
  125. *
  126. * The UVC 1.5 class specification defines the first five bits in the
  127. * bmHint bitfield. The remaining bits are reserved and should be zero.
  128. * Therefore a valid bmHint will be less than 32.
  129. *
  130. * Latest Elgato Cam Link 4K firmware as of 2021-03-23 needs this fix.
  131. * MCU: 20.02.19, FPGA: 67
  132. */
  133. if (usb_match_one_id(stream->dev->intf, &elgato_cam_link_4k) &&
  134. ctrl->bmHint > 255) {
  135. u8 corrected_format_index = ctrl->bmHint >> 8;
  136. uvc_dbg(stream->dev, VIDEO,
  137. "Correct USB video probe response from {bmHint: 0x%04x, bFormatIndex: %u} to {bmHint: 0x%04x, bFormatIndex: %u}\n",
  138. ctrl->bmHint, ctrl->bFormatIndex,
  139. 1, corrected_format_index);
  140. ctrl->bmHint = 1;
  141. ctrl->bFormatIndex = corrected_format_index;
  142. }
  143. for (i = 0; i < stream->nformats; ++i) {
  144. if (stream->format[i].index == ctrl->bFormatIndex) {
  145. format = &stream->format[i];
  146. break;
  147. }
  148. }
  149. if (format == NULL)
  150. return;
  151. for (i = 0; i < format->nframes; ++i) {
  152. if (format->frame[i].bFrameIndex == ctrl->bFrameIndex) {
  153. frame = &format->frame[i];
  154. break;
  155. }
  156. }
  157. if (frame == NULL)
  158. return;
  159. if (!(format->flags & UVC_FMT_FLAG_COMPRESSED) ||
  160. (ctrl->dwMaxVideoFrameSize == 0 &&
  161. stream->dev->uvc_version < 0x0110))
  162. ctrl->dwMaxVideoFrameSize =
  163. frame->dwMaxVideoFrameBufferSize;
  164. /*
  165. * The "TOSHIBA Web Camera - 5M" Chicony device (04f2:b50b) seems to
  166. * compute the bandwidth on 16 bits and erroneously sign-extend it to
  167. * 32 bits, resulting in a huge bandwidth value. Detect and fix that
  168. * condition by setting the 16 MSBs to 0 when they're all equal to 1.
  169. */
  170. if ((ctrl->dwMaxPayloadTransferSize & 0xffff0000) == 0xffff0000)
  171. ctrl->dwMaxPayloadTransferSize &= ~0xffff0000;
  172. if (!(format->flags & UVC_FMT_FLAG_COMPRESSED) &&
  173. stream->dev->quirks & UVC_QUIRK_FIX_BANDWIDTH &&
  174. stream->intf->num_altsetting > 1) {
  175. u32 interval;
  176. u32 bandwidth;
  177. interval = (ctrl->dwFrameInterval > 100000)
  178. ? ctrl->dwFrameInterval
  179. : frame->dwFrameInterval[0];
  180. /*
  181. * Compute a bandwidth estimation by multiplying the frame
  182. * size by the number of video frames per second, divide the
  183. * result by the number of USB frames (or micro-frames for
  184. * high-speed devices) per second and add the UVC header size
  185. * (assumed to be 12 bytes long).
  186. */
  187. bandwidth = frame->wWidth * frame->wHeight / 8 * format->bpp;
  188. bandwidth *= 10000000 / interval + 1;
  189. bandwidth /= 1000;
  190. if (stream->dev->udev->speed == USB_SPEED_HIGH)
  191. bandwidth /= 8;
  192. bandwidth += 12;
  193. /*
  194. * The bandwidth estimate is too low for many cameras. Don't use
  195. * maximum packet sizes lower than 1024 bytes to try and work
  196. * around the problem. According to measurements done on two
  197. * different camera models, the value is high enough to get most
  198. * resolutions working while not preventing two simultaneous
  199. * VGA streams at 15 fps.
  200. */
  201. bandwidth = max_t(u32, bandwidth, 1024);
  202. ctrl->dwMaxPayloadTransferSize = bandwidth;
  203. }
  204. }
  205. static size_t uvc_video_ctrl_size(struct uvc_streaming *stream)
  206. {
  207. /*
  208. * Return the size of the video probe and commit controls, which depends
  209. * on the protocol version.
  210. */
  211. if (stream->dev->uvc_version < 0x0110)
  212. return 26;
  213. else if (stream->dev->uvc_version < 0x0150)
  214. return 34;
  215. else
  216. return 48;
  217. }
  218. static int uvc_get_video_ctrl(struct uvc_streaming *stream,
  219. struct uvc_streaming_control *ctrl, int probe, u8 query)
  220. {
  221. u16 size = uvc_video_ctrl_size(stream);
  222. u8 *data;
  223. int ret;
  224. if ((stream->dev->quirks & UVC_QUIRK_PROBE_DEF) &&
  225. query == UVC_GET_DEF)
  226. return -EIO;
  227. data = kmalloc(size, GFP_KERNEL);
  228. if (data == NULL)
  229. return -ENOMEM;
  230. ret = __uvc_query_ctrl(stream->dev, query, 0, stream->intfnum,
  231. probe ? UVC_VS_PROBE_CONTROL : UVC_VS_COMMIT_CONTROL, data,
  232. size, uvc_timeout_param);
  233. if ((query == UVC_GET_MIN || query == UVC_GET_MAX) && ret == 2) {
  234. /*
  235. * Some cameras, mostly based on Bison Electronics chipsets,
  236. * answer a GET_MIN or GET_MAX request with the wCompQuality
  237. * field only.
  238. */
  239. uvc_warn_once(stream->dev, UVC_WARN_MINMAX, "UVC non "
  240. "compliance - GET_MIN/MAX(PROBE) incorrectly "
  241. "supported. Enabling workaround.\n");
  242. memset(ctrl, 0, sizeof(*ctrl));
  243. ctrl->wCompQuality = le16_to_cpup((__le16 *)data);
  244. ret = 0;
  245. goto out;
  246. } else if (query == UVC_GET_DEF && probe == 1 && ret != size) {
  247. /*
  248. * Many cameras don't support the GET_DEF request on their
  249. * video probe control. Warn once and return, the caller will
  250. * fall back to GET_CUR.
  251. */
  252. uvc_warn_once(stream->dev, UVC_WARN_PROBE_DEF, "UVC non "
  253. "compliance - GET_DEF(PROBE) not supported. "
  254. "Enabling workaround.\n");
  255. ret = -EIO;
  256. goto out;
  257. } else if (ret != size) {
  258. dev_err(&stream->intf->dev,
  259. "Failed to query (%u) UVC %s control : %d (exp. %u).\n",
  260. query, probe ? "probe" : "commit", ret, size);
  261. ret = -EIO;
  262. goto out;
  263. }
  264. ctrl->bmHint = le16_to_cpup((__le16 *)&data[0]);
  265. ctrl->bFormatIndex = data[2];
  266. ctrl->bFrameIndex = data[3];
  267. ctrl->dwFrameInterval = le32_to_cpup((__le32 *)&data[4]);
  268. ctrl->wKeyFrameRate = le16_to_cpup((__le16 *)&data[8]);
  269. ctrl->wPFrameRate = le16_to_cpup((__le16 *)&data[10]);
  270. ctrl->wCompQuality = le16_to_cpup((__le16 *)&data[12]);
  271. ctrl->wCompWindowSize = le16_to_cpup((__le16 *)&data[14]);
  272. ctrl->wDelay = le16_to_cpup((__le16 *)&data[16]);
  273. ctrl->dwMaxVideoFrameSize = get_unaligned_le32(&data[18]);
  274. ctrl->dwMaxPayloadTransferSize = get_unaligned_le32(&data[22]);
  275. if (size >= 34) {
  276. ctrl->dwClockFrequency = get_unaligned_le32(&data[26]);
  277. ctrl->bmFramingInfo = data[30];
  278. ctrl->bPreferedVersion = data[31];
  279. ctrl->bMinVersion = data[32];
  280. ctrl->bMaxVersion = data[33];
  281. } else {
  282. ctrl->dwClockFrequency = stream->dev->clock_frequency;
  283. ctrl->bmFramingInfo = 0;
  284. ctrl->bPreferedVersion = 0;
  285. ctrl->bMinVersion = 0;
  286. ctrl->bMaxVersion = 0;
  287. }
  288. /*
  289. * Some broken devices return null or wrong dwMaxVideoFrameSize and
  290. * dwMaxPayloadTransferSize fields. Try to get the value from the
  291. * format and frame descriptors.
  292. */
  293. uvc_fixup_video_ctrl(stream, ctrl);
  294. ret = 0;
  295. out:
  296. kfree(data);
  297. return ret;
  298. }
  299. static int uvc_set_video_ctrl(struct uvc_streaming *stream,
  300. struct uvc_streaming_control *ctrl, int probe)
  301. {
  302. u16 size = uvc_video_ctrl_size(stream);
  303. u8 *data;
  304. int ret;
  305. data = kzalloc(size, GFP_KERNEL);
  306. if (data == NULL)
  307. return -ENOMEM;
  308. *(__le16 *)&data[0] = cpu_to_le16(ctrl->bmHint);
  309. data[2] = ctrl->bFormatIndex;
  310. data[3] = ctrl->bFrameIndex;
  311. *(__le32 *)&data[4] = cpu_to_le32(ctrl->dwFrameInterval);
  312. *(__le16 *)&data[8] = cpu_to_le16(ctrl->wKeyFrameRate);
  313. *(__le16 *)&data[10] = cpu_to_le16(ctrl->wPFrameRate);
  314. *(__le16 *)&data[12] = cpu_to_le16(ctrl->wCompQuality);
  315. *(__le16 *)&data[14] = cpu_to_le16(ctrl->wCompWindowSize);
  316. *(__le16 *)&data[16] = cpu_to_le16(ctrl->wDelay);
  317. put_unaligned_le32(ctrl->dwMaxVideoFrameSize, &data[18]);
  318. put_unaligned_le32(ctrl->dwMaxPayloadTransferSize, &data[22]);
  319. if (size >= 34) {
  320. put_unaligned_le32(ctrl->dwClockFrequency, &data[26]);
  321. data[30] = ctrl->bmFramingInfo;
  322. data[31] = ctrl->bPreferedVersion;
  323. data[32] = ctrl->bMinVersion;
  324. data[33] = ctrl->bMaxVersion;
  325. }
  326. ret = __uvc_query_ctrl(stream->dev, UVC_SET_CUR, 0, stream->intfnum,
  327. probe ? UVC_VS_PROBE_CONTROL : UVC_VS_COMMIT_CONTROL, data,
  328. size, uvc_timeout_param);
  329. if (ret != size) {
  330. dev_err(&stream->intf->dev,
  331. "Failed to set UVC %s control : %d (exp. %u).\n",
  332. probe ? "probe" : "commit", ret, size);
  333. ret = -EIO;
  334. }
  335. kfree(data);
  336. return ret;
  337. }
  338. int uvc_probe_video(struct uvc_streaming *stream,
  339. struct uvc_streaming_control *probe)
  340. {
  341. struct uvc_streaming_control probe_min, probe_max;
  342. unsigned int i;
  343. int ret;
  344. /*
  345. * Perform probing. The device should adjust the requested values
  346. * according to its capabilities. However, some devices, namely the
  347. * first generation UVC Logitech webcams, don't implement the Video
  348. * Probe control properly, and just return the needed bandwidth. For
  349. * that reason, if the needed bandwidth exceeds the maximum available
  350. * bandwidth, try to lower the quality.
  351. */
  352. ret = uvc_set_video_ctrl(stream, probe, 1);
  353. if (ret < 0)
  354. goto done;
  355. /* Get the minimum and maximum values for compression settings. */
  356. if (!(stream->dev->quirks & UVC_QUIRK_PROBE_MINMAX)) {
  357. ret = uvc_get_video_ctrl(stream, &probe_min, 1, UVC_GET_MIN);
  358. if (ret < 0)
  359. goto done;
  360. ret = uvc_get_video_ctrl(stream, &probe_max, 1, UVC_GET_MAX);
  361. if (ret < 0)
  362. goto done;
  363. probe->wCompQuality = probe_max.wCompQuality;
  364. }
  365. for (i = 0; i < 2; ++i) {
  366. ret = uvc_set_video_ctrl(stream, probe, 1);
  367. if (ret < 0)
  368. goto done;
  369. ret = uvc_get_video_ctrl(stream, probe, 1, UVC_GET_CUR);
  370. if (ret < 0)
  371. goto done;
  372. if (stream->intf->num_altsetting == 1)
  373. break;
  374. if (probe->dwMaxPayloadTransferSize <= stream->maxpsize)
  375. break;
  376. if (stream->dev->quirks & UVC_QUIRK_PROBE_MINMAX) {
  377. ret = -ENOSPC;
  378. goto done;
  379. }
  380. /* TODO: negotiate compression parameters */
  381. probe->wKeyFrameRate = probe_min.wKeyFrameRate;
  382. probe->wPFrameRate = probe_min.wPFrameRate;
  383. probe->wCompQuality = probe_max.wCompQuality;
  384. probe->wCompWindowSize = probe_min.wCompWindowSize;
  385. }
  386. done:
  387. return ret;
  388. }
  389. static int uvc_commit_video(struct uvc_streaming *stream,
  390. struct uvc_streaming_control *probe)
  391. {
  392. return uvc_set_video_ctrl(stream, probe, 0);
  393. }
  394. /* -----------------------------------------------------------------------------
  395. * Clocks and timestamps
  396. */
  397. static inline ktime_t uvc_video_get_time(void)
  398. {
  399. if (uvc_clock_param == CLOCK_MONOTONIC)
  400. return ktime_get();
  401. else
  402. return ktime_get_real();
  403. }
  404. static void
  405. uvc_video_clock_decode(struct uvc_streaming *stream, struct uvc_buffer *buf,
  406. const u8 *data, int len)
  407. {
  408. struct uvc_clock_sample *sample;
  409. unsigned int header_size;
  410. bool has_pts = false;
  411. bool has_scr = false;
  412. unsigned long flags;
  413. ktime_t time;
  414. u16 host_sof;
  415. u16 dev_sof;
  416. switch (data[1] & (UVC_STREAM_PTS | UVC_STREAM_SCR)) {
  417. case UVC_STREAM_PTS | UVC_STREAM_SCR:
  418. header_size = 12;
  419. has_pts = true;
  420. has_scr = true;
  421. break;
  422. case UVC_STREAM_PTS:
  423. header_size = 6;
  424. has_pts = true;
  425. break;
  426. case UVC_STREAM_SCR:
  427. header_size = 8;
  428. has_scr = true;
  429. break;
  430. default:
  431. header_size = 2;
  432. break;
  433. }
  434. /* Check for invalid headers. */
  435. if (len < header_size)
  436. return;
  437. /*
  438. * Extract the timestamps:
  439. *
  440. * - store the frame PTS in the buffer structure
  441. * - if the SCR field is present, retrieve the host SOF counter and
  442. * kernel timestamps and store them with the SCR STC and SOF fields
  443. * in the ring buffer
  444. */
  445. if (has_pts && buf != NULL)
  446. buf->pts = get_unaligned_le32(&data[2]);
  447. if (!has_scr)
  448. return;
  449. /*
  450. * To limit the amount of data, drop SCRs with an SOF identical to the
  451. * previous one.
  452. */
  453. dev_sof = get_unaligned_le16(&data[header_size - 2]);
  454. if (dev_sof == stream->clock.last_sof)
  455. return;
  456. stream->clock.last_sof = dev_sof;
  457. host_sof = usb_get_current_frame_number(stream->dev->udev);
  458. time = uvc_video_get_time();
  459. /*
  460. * The UVC specification allows device implementations that can't obtain
  461. * the USB frame number to keep their own frame counters as long as they
  462. * match the size and frequency of the frame number associated with USB
  463. * SOF tokens. The SOF values sent by such devices differ from the USB
  464. * SOF tokens by a fixed offset that needs to be estimated and accounted
  465. * for to make timestamp recovery as accurate as possible.
  466. *
  467. * The offset is estimated the first time a device SOF value is received
  468. * as the difference between the host and device SOF values. As the two
  469. * SOF values can differ slightly due to transmission delays, consider
  470. * that the offset is null if the difference is not higher than 10 ms
  471. * (negative differences can not happen and are thus considered as an
  472. * offset). The video commit control wDelay field should be used to
  473. * compute a dynamic threshold instead of using a fixed 10 ms value, but
  474. * devices don't report reliable wDelay values.
  475. *
  476. * See uvc_video_clock_host_sof() for an explanation regarding why only
  477. * the 8 LSBs of the delta are kept.
  478. */
  479. if (stream->clock.sof_offset == (u16)-1) {
  480. u16 delta_sof = (host_sof - dev_sof) & 255;
  481. if (delta_sof >= 10)
  482. stream->clock.sof_offset = delta_sof;
  483. else
  484. stream->clock.sof_offset = 0;
  485. }
  486. dev_sof = (dev_sof + stream->clock.sof_offset) & 2047;
  487. spin_lock_irqsave(&stream->clock.lock, flags);
  488. sample = &stream->clock.samples[stream->clock.head];
  489. sample->dev_stc = get_unaligned_le32(&data[header_size - 6]);
  490. sample->dev_sof = dev_sof;
  491. sample->host_sof = host_sof;
  492. sample->host_time = time;
  493. /* Update the sliding window head and count. */
  494. stream->clock.head = (stream->clock.head + 1) % stream->clock.size;
  495. if (stream->clock.count < stream->clock.size)
  496. stream->clock.count++;
  497. spin_unlock_irqrestore(&stream->clock.lock, flags);
  498. }
  499. static void uvc_video_clock_reset(struct uvc_streaming *stream)
  500. {
  501. struct uvc_clock *clock = &stream->clock;
  502. clock->head = 0;
  503. clock->count = 0;
  504. clock->last_sof = -1;
  505. clock->sof_offset = -1;
  506. }
  507. static int uvc_video_clock_init(struct uvc_streaming *stream)
  508. {
  509. struct uvc_clock *clock = &stream->clock;
  510. spin_lock_init(&clock->lock);
  511. clock->size = 32;
  512. clock->samples = kmalloc_array(clock->size, sizeof(*clock->samples),
  513. GFP_KERNEL);
  514. if (clock->samples == NULL)
  515. return -ENOMEM;
  516. uvc_video_clock_reset(stream);
  517. return 0;
  518. }
  519. static void uvc_video_clock_cleanup(struct uvc_streaming *stream)
  520. {
  521. kfree(stream->clock.samples);
  522. stream->clock.samples = NULL;
  523. }
  524. /*
  525. * uvc_video_clock_host_sof - Return the host SOF value for a clock sample
  526. *
  527. * Host SOF counters reported by usb_get_current_frame_number() usually don't
  528. * cover the whole 11-bits SOF range (0-2047) but are limited to the HCI frame
  529. * schedule window. They can be limited to 8, 9 or 10 bits depending on the host
  530. * controller and its configuration.
  531. *
  532. * We thus need to recover the SOF value corresponding to the host frame number.
  533. * As the device and host frame numbers are sampled in a short interval, the
  534. * difference between their values should be equal to a small delta plus an
  535. * integer multiple of 256 caused by the host frame number limited precision.
  536. *
  537. * To obtain the recovered host SOF value, compute the small delta by masking
  538. * the high bits of the host frame counter and device SOF difference and add it
  539. * to the device SOF value.
  540. */
  541. static u16 uvc_video_clock_host_sof(const struct uvc_clock_sample *sample)
  542. {
  543. /* The delta value can be negative. */
  544. s8 delta_sof;
  545. delta_sof = (sample->host_sof - sample->dev_sof) & 255;
  546. return (sample->dev_sof + delta_sof) & 2047;
  547. }
  548. /*
  549. * uvc_video_clock_update - Update the buffer timestamp
  550. *
  551. * This function converts the buffer PTS timestamp to the host clock domain by
  552. * going through the USB SOF clock domain and stores the result in the V4L2
  553. * buffer timestamp field.
  554. *
  555. * The relationship between the device clock and the host clock isn't known.
  556. * However, the device and the host share the common USB SOF clock which can be
  557. * used to recover that relationship.
  558. *
  559. * The relationship between the device clock and the USB SOF clock is considered
  560. * to be linear over the clock samples sliding window and is given by
  561. *
  562. * SOF = m * PTS + p
  563. *
  564. * Several methods to compute the slope (m) and intercept (p) can be used. As
  565. * the clock drift should be small compared to the sliding window size, we
  566. * assume that the line that goes through the points at both ends of the window
  567. * is a good approximation. Naming those points P1 and P2, we get
  568. *
  569. * SOF = (SOF2 - SOF1) / (STC2 - STC1) * PTS
  570. * + (SOF1 * STC2 - SOF2 * STC1) / (STC2 - STC1)
  571. *
  572. * or
  573. *
  574. * SOF = ((SOF2 - SOF1) * PTS + SOF1 * STC2 - SOF2 * STC1) / (STC2 - STC1) (1)
  575. *
  576. * to avoid losing precision in the division. Similarly, the host timestamp is
  577. * computed with
  578. *
  579. * TS = ((TS2 - TS1) * SOF + TS1 * SOF2 - TS2 * SOF1) / (SOF2 - SOF1) (2)
  580. *
  581. * SOF values are coded on 11 bits by USB. We extend their precision with 16
  582. * decimal bits, leading to a 11.16 coding.
  583. *
  584. * TODO: To avoid surprises with device clock values, PTS/STC timestamps should
  585. * be normalized using the nominal device clock frequency reported through the
  586. * UVC descriptors.
  587. *
  588. * Both the PTS/STC and SOF counters roll over, after a fixed but device
  589. * specific amount of time for PTS/STC and after 2048ms for SOF. As long as the
  590. * sliding window size is smaller than the rollover period, differences computed
  591. * on unsigned integers will produce the correct result. However, the p term in
  592. * the linear relations will be miscomputed.
  593. *
  594. * To fix the issue, we subtract a constant from the PTS and STC values to bring
  595. * PTS to half the 32 bit STC range. The sliding window STC values then fit into
  596. * the 32 bit range without any rollover.
  597. *
  598. * Similarly, we add 2048 to the device SOF values to make sure that the SOF
  599. * computed by (1) will never be smaller than 0. This offset is then compensated
  600. * by adding 2048 to the SOF values used in (2). However, this doesn't prevent
  601. * rollovers between (1) and (2): the SOF value computed by (1) can be slightly
  602. * lower than 4096, and the host SOF counters can have rolled over to 2048. This
  603. * case is handled by subtracting 2048 from the SOF value if it exceeds the host
  604. * SOF value at the end of the sliding window.
  605. *
  606. * Finally we subtract a constant from the host timestamps to bring the first
  607. * timestamp of the sliding window to 1s.
  608. */
  609. void uvc_video_clock_update(struct uvc_streaming *stream,
  610. struct vb2_v4l2_buffer *vbuf,
  611. struct uvc_buffer *buf)
  612. {
  613. struct uvc_clock *clock = &stream->clock;
  614. struct uvc_clock_sample *first;
  615. struct uvc_clock_sample *last;
  616. unsigned long flags;
  617. u64 timestamp;
  618. u32 delta_stc;
  619. u32 y1, y2;
  620. u32 x1, x2;
  621. u32 mean;
  622. u32 sof;
  623. u64 y;
  624. if (!uvc_hw_timestamps_param)
  625. return;
  626. /*
  627. * We will get called from __vb2_queue_cancel() if there are buffers
  628. * done but not dequeued by the user, but the sample array has already
  629. * been released at that time. Just bail out in that case.
  630. */
  631. if (!clock->samples)
  632. return;
  633. spin_lock_irqsave(&clock->lock, flags);
  634. if (clock->count < clock->size)
  635. goto done;
  636. first = &clock->samples[clock->head];
  637. last = &clock->samples[(clock->head - 1) % clock->size];
  638. /* First step, PTS to SOF conversion. */
  639. delta_stc = buf->pts - (1UL << 31);
  640. x1 = first->dev_stc - delta_stc;
  641. x2 = last->dev_stc - delta_stc;
  642. if (x1 == x2)
  643. goto done;
  644. y1 = (first->dev_sof + 2048) << 16;
  645. y2 = (last->dev_sof + 2048) << 16;
  646. if (y2 < y1)
  647. y2 += 2048 << 16;
  648. y = (u64)(y2 - y1) * (1ULL << 31) + (u64)y1 * (u64)x2
  649. - (u64)y2 * (u64)x1;
  650. y = div_u64(y, x2 - x1);
  651. sof = y;
  652. uvc_dbg(stream->dev, CLOCK,
  653. "%s: PTS %u y %llu.%06llu SOF %u.%06llu (x1 %u x2 %u y1 %u y2 %u SOF offset %u)\n",
  654. stream->dev->name, buf->pts,
  655. y >> 16, div_u64((y & 0xffff) * 1000000, 65536),
  656. sof >> 16, div_u64(((u64)sof & 0xffff) * 1000000LLU, 65536),
  657. x1, x2, y1, y2, clock->sof_offset);
  658. /* Second step, SOF to host clock conversion. */
  659. x1 = (uvc_video_clock_host_sof(first) + 2048) << 16;
  660. x2 = (uvc_video_clock_host_sof(last) + 2048) << 16;
  661. if (x2 < x1)
  662. x2 += 2048 << 16;
  663. if (x1 == x2)
  664. goto done;
  665. y1 = NSEC_PER_SEC;
  666. y2 = (u32)ktime_to_ns(ktime_sub(last->host_time, first->host_time)) + y1;
  667. /*
  668. * Interpolated and host SOF timestamps can wrap around at slightly
  669. * different times. Handle this by adding or removing 2048 to or from
  670. * the computed SOF value to keep it close to the SOF samples mean
  671. * value.
  672. */
  673. mean = (x1 + x2) / 2;
  674. if (mean - (1024 << 16) > sof)
  675. sof += 2048 << 16;
  676. else if (sof > mean + (1024 << 16))
  677. sof -= 2048 << 16;
  678. y = (u64)(y2 - y1) * (u64)sof + (u64)y1 * (u64)x2
  679. - (u64)y2 * (u64)x1;
  680. y = div_u64(y, x2 - x1);
  681. timestamp = ktime_to_ns(first->host_time) + y - y1;
  682. uvc_dbg(stream->dev, CLOCK,
  683. "%s: SOF %u.%06llu y %llu ts %llu buf ts %llu (x1 %u/%u/%u x2 %u/%u/%u y1 %u y2 %u)\n",
  684. stream->dev->name,
  685. sof >> 16, div_u64(((u64)sof & 0xffff) * 1000000LLU, 65536),
  686. y, timestamp, vbuf->vb2_buf.timestamp,
  687. x1, first->host_sof, first->dev_sof,
  688. x2, last->host_sof, last->dev_sof, y1, y2);
  689. /* Update the V4L2 buffer. */
  690. vbuf->vb2_buf.timestamp = timestamp;
  691. done:
  692. spin_unlock_irqrestore(&clock->lock, flags);
  693. }
  694. /* ------------------------------------------------------------------------
  695. * Stream statistics
  696. */
  697. static void uvc_video_stats_decode(struct uvc_streaming *stream,
  698. const u8 *data, int len)
  699. {
  700. unsigned int header_size;
  701. bool has_pts = false;
  702. bool has_scr = false;
  703. u16 scr_sof;
  704. u32 scr_stc;
  705. u32 pts;
  706. if (stream->stats.stream.nb_frames == 0 &&
  707. stream->stats.frame.nb_packets == 0)
  708. stream->stats.stream.start_ts = ktime_get();
  709. switch (data[1] & (UVC_STREAM_PTS | UVC_STREAM_SCR)) {
  710. case UVC_STREAM_PTS | UVC_STREAM_SCR:
  711. header_size = 12;
  712. has_pts = true;
  713. has_scr = true;
  714. break;
  715. case UVC_STREAM_PTS:
  716. header_size = 6;
  717. has_pts = true;
  718. break;
  719. case UVC_STREAM_SCR:
  720. header_size = 8;
  721. has_scr = true;
  722. break;
  723. default:
  724. header_size = 2;
  725. break;
  726. }
  727. /* Check for invalid headers. */
  728. if (len < header_size || data[0] < header_size) {
  729. stream->stats.frame.nb_invalid++;
  730. return;
  731. }
  732. /* Extract the timestamps. */
  733. if (has_pts)
  734. pts = get_unaligned_le32(&data[2]);
  735. if (has_scr) {
  736. scr_stc = get_unaligned_le32(&data[header_size - 6]);
  737. scr_sof = get_unaligned_le16(&data[header_size - 2]);
  738. }
  739. /* Is PTS constant through the whole frame ? */
  740. if (has_pts && stream->stats.frame.nb_pts) {
  741. if (stream->stats.frame.pts != pts) {
  742. stream->stats.frame.nb_pts_diffs++;
  743. stream->stats.frame.last_pts_diff =
  744. stream->stats.frame.nb_packets;
  745. }
  746. }
  747. if (has_pts) {
  748. stream->stats.frame.nb_pts++;
  749. stream->stats.frame.pts = pts;
  750. }
  751. /*
  752. * Do all frames have a PTS in their first non-empty packet, or before
  753. * their first empty packet ?
  754. */
  755. if (stream->stats.frame.size == 0) {
  756. if (len > header_size)
  757. stream->stats.frame.has_initial_pts = has_pts;
  758. if (len == header_size && has_pts)
  759. stream->stats.frame.has_early_pts = true;
  760. }
  761. /* Do the SCR.STC and SCR.SOF fields vary through the frame ? */
  762. if (has_scr && stream->stats.frame.nb_scr) {
  763. if (stream->stats.frame.scr_stc != scr_stc)
  764. stream->stats.frame.nb_scr_diffs++;
  765. }
  766. if (has_scr) {
  767. /* Expand the SOF counter to 32 bits and store its value. */
  768. if (stream->stats.stream.nb_frames > 0 ||
  769. stream->stats.frame.nb_scr > 0)
  770. stream->stats.stream.scr_sof_count +=
  771. (scr_sof - stream->stats.stream.scr_sof) % 2048;
  772. stream->stats.stream.scr_sof = scr_sof;
  773. stream->stats.frame.nb_scr++;
  774. stream->stats.frame.scr_stc = scr_stc;
  775. stream->stats.frame.scr_sof = scr_sof;
  776. if (scr_sof < stream->stats.stream.min_sof)
  777. stream->stats.stream.min_sof = scr_sof;
  778. if (scr_sof > stream->stats.stream.max_sof)
  779. stream->stats.stream.max_sof = scr_sof;
  780. }
  781. /* Record the first non-empty packet number. */
  782. if (stream->stats.frame.size == 0 && len > header_size)
  783. stream->stats.frame.first_data = stream->stats.frame.nb_packets;
  784. /* Update the frame size. */
  785. stream->stats.frame.size += len - header_size;
  786. /* Update the packets counters. */
  787. stream->stats.frame.nb_packets++;
  788. if (len <= header_size)
  789. stream->stats.frame.nb_empty++;
  790. if (data[1] & UVC_STREAM_ERR)
  791. stream->stats.frame.nb_errors++;
  792. }
  793. static void uvc_video_stats_update(struct uvc_streaming *stream)
  794. {
  795. struct uvc_stats_frame *frame = &stream->stats.frame;
  796. uvc_dbg(stream->dev, STATS,
  797. "frame %u stats: %u/%u/%u packets, %u/%u/%u pts (%searly %sinitial), %u/%u scr, last pts/stc/sof %u/%u/%u\n",
  798. stream->sequence, frame->first_data,
  799. frame->nb_packets - frame->nb_empty, frame->nb_packets,
  800. frame->nb_pts_diffs, frame->last_pts_diff, frame->nb_pts,
  801. frame->has_early_pts ? "" : "!",
  802. frame->has_initial_pts ? "" : "!",
  803. frame->nb_scr_diffs, frame->nb_scr,
  804. frame->pts, frame->scr_stc, frame->scr_sof);
  805. stream->stats.stream.nb_frames++;
  806. stream->stats.stream.nb_packets += stream->stats.frame.nb_packets;
  807. stream->stats.stream.nb_empty += stream->stats.frame.nb_empty;
  808. stream->stats.stream.nb_errors += stream->stats.frame.nb_errors;
  809. stream->stats.stream.nb_invalid += stream->stats.frame.nb_invalid;
  810. if (frame->has_early_pts)
  811. stream->stats.stream.nb_pts_early++;
  812. if (frame->has_initial_pts)
  813. stream->stats.stream.nb_pts_initial++;
  814. if (frame->last_pts_diff <= frame->first_data)
  815. stream->stats.stream.nb_pts_constant++;
  816. if (frame->nb_scr >= frame->nb_packets - frame->nb_empty)
  817. stream->stats.stream.nb_scr_count_ok++;
  818. if (frame->nb_scr_diffs + 1 == frame->nb_scr)
  819. stream->stats.stream.nb_scr_diffs_ok++;
  820. memset(&stream->stats.frame, 0, sizeof(stream->stats.frame));
  821. }
  822. size_t uvc_video_stats_dump(struct uvc_streaming *stream, char *buf,
  823. size_t size)
  824. {
  825. unsigned int scr_sof_freq;
  826. unsigned int duration;
  827. size_t count = 0;
  828. /*
  829. * Compute the SCR.SOF frequency estimate. At the nominal 1kHz SOF
  830. * frequency this will not overflow before more than 1h.
  831. */
  832. duration = ktime_ms_delta(stream->stats.stream.stop_ts,
  833. stream->stats.stream.start_ts);
  834. if (duration != 0)
  835. scr_sof_freq = stream->stats.stream.scr_sof_count * 1000
  836. / duration;
  837. else
  838. scr_sof_freq = 0;
  839. count += scnprintf(buf + count, size - count,
  840. "frames: %u\npackets: %u\nempty: %u\n"
  841. "errors: %u\ninvalid: %u\n",
  842. stream->stats.stream.nb_frames,
  843. stream->stats.stream.nb_packets,
  844. stream->stats.stream.nb_empty,
  845. stream->stats.stream.nb_errors,
  846. stream->stats.stream.nb_invalid);
  847. count += scnprintf(buf + count, size - count,
  848. "pts: %u early, %u initial, %u ok\n",
  849. stream->stats.stream.nb_pts_early,
  850. stream->stats.stream.nb_pts_initial,
  851. stream->stats.stream.nb_pts_constant);
  852. count += scnprintf(buf + count, size - count,
  853. "scr: %u count ok, %u diff ok\n",
  854. stream->stats.stream.nb_scr_count_ok,
  855. stream->stats.stream.nb_scr_diffs_ok);
  856. count += scnprintf(buf + count, size - count,
  857. "sof: %u <= sof <= %u, freq %u.%03u kHz\n",
  858. stream->stats.stream.min_sof,
  859. stream->stats.stream.max_sof,
  860. scr_sof_freq / 1000, scr_sof_freq % 1000);
  861. return count;
  862. }
  863. static void uvc_video_stats_start(struct uvc_streaming *stream)
  864. {
  865. memset(&stream->stats, 0, sizeof(stream->stats));
  866. stream->stats.stream.min_sof = 2048;
  867. }
  868. static void uvc_video_stats_stop(struct uvc_streaming *stream)
  869. {
  870. stream->stats.stream.stop_ts = ktime_get();
  871. }
  872. /* ------------------------------------------------------------------------
  873. * Video codecs
  874. */
  875. /*
  876. * Video payload decoding is handled by uvc_video_decode_start(),
  877. * uvc_video_decode_data() and uvc_video_decode_end().
  878. *
  879. * uvc_video_decode_start is called with URB data at the start of a bulk or
  880. * isochronous payload. It processes header data and returns the header size
  881. * in bytes if successful. If an error occurs, it returns a negative error
  882. * code. The following error codes have special meanings.
  883. *
  884. * - EAGAIN informs the caller that the current video buffer should be marked
  885. * as done, and that the function should be called again with the same data
  886. * and a new video buffer. This is used when end of frame conditions can be
  887. * reliably detected at the beginning of the next frame only.
  888. *
  889. * If an error other than -EAGAIN is returned, the caller will drop the current
  890. * payload. No call to uvc_video_decode_data and uvc_video_decode_end will be
  891. * made until the next payload. -ENODATA can be used to drop the current
  892. * payload if no other error code is appropriate.
  893. *
  894. * uvc_video_decode_data is called for every URB with URB data. It copies the
  895. * data to the video buffer.
  896. *
  897. * uvc_video_decode_end is called with header data at the end of a bulk or
  898. * isochronous payload. It performs any additional header data processing and
  899. * returns 0 or a negative error code if an error occurred. As header data have
  900. * already been processed by uvc_video_decode_start, this functions isn't
  901. * required to perform sanity checks a second time.
  902. *
  903. * For isochronous transfers where a payload is always transferred in a single
  904. * URB, the three functions will be called in a row.
  905. *
  906. * To let the decoder process header data and update its internal state even
  907. * when no video buffer is available, uvc_video_decode_start must be prepared
  908. * to be called with a NULL buf parameter. uvc_video_decode_data and
  909. * uvc_video_decode_end will never be called with a NULL buffer.
  910. */
  911. static int uvc_video_decode_start(struct uvc_streaming *stream,
  912. struct uvc_buffer *buf, const u8 *data, int len)
  913. {
  914. u8 fid;
  915. /*
  916. * Sanity checks:
  917. * - packet must be at least 2 bytes long
  918. * - bHeaderLength value must be at least 2 bytes (see above)
  919. * - bHeaderLength value can't be larger than the packet size.
  920. */
  921. if (len < 2 || data[0] < 2 || data[0] > len) {
  922. stream->stats.frame.nb_invalid++;
  923. return -EINVAL;
  924. }
  925. fid = data[1] & UVC_STREAM_FID;
  926. /*
  927. * Increase the sequence number regardless of any buffer states, so
  928. * that discontinuous sequence numbers always indicate lost frames.
  929. */
  930. if (stream->last_fid != fid) {
  931. stream->sequence++;
  932. if (stream->sequence)
  933. uvc_video_stats_update(stream);
  934. }
  935. uvc_video_clock_decode(stream, buf, data, len);
  936. uvc_video_stats_decode(stream, data, len);
  937. /*
  938. * Store the payload FID bit and return immediately when the buffer is
  939. * NULL.
  940. */
  941. if (buf == NULL) {
  942. stream->last_fid = fid;
  943. return -ENODATA;
  944. }
  945. /* Mark the buffer as bad if the error bit is set. */
  946. if (data[1] & UVC_STREAM_ERR) {
  947. uvc_dbg(stream->dev, FRAME,
  948. "Marking buffer as bad (error bit set)\n");
  949. buf->error = 1;
  950. }
  951. /*
  952. * Synchronize to the input stream by waiting for the FID bit to be
  953. * toggled when the buffer state is not UVC_BUF_STATE_ACTIVE.
  954. * stream->last_fid is initialized to -1, so the first isochronous
  955. * frame will always be in sync.
  956. *
  957. * If the device doesn't toggle the FID bit, invert stream->last_fid
  958. * when the EOF bit is set to force synchronisation on the next packet.
  959. */
  960. if (buf->state != UVC_BUF_STATE_ACTIVE) {
  961. if (fid == stream->last_fid) {
  962. uvc_dbg(stream->dev, FRAME,
  963. "Dropping payload (out of sync)\n");
  964. if ((stream->dev->quirks & UVC_QUIRK_STREAM_NO_FID) &&
  965. (data[1] & UVC_STREAM_EOF))
  966. stream->last_fid ^= UVC_STREAM_FID;
  967. return -ENODATA;
  968. }
  969. buf->buf.field = V4L2_FIELD_NONE;
  970. buf->buf.sequence = stream->sequence;
  971. buf->buf.vb2_buf.timestamp = ktime_to_ns(uvc_video_get_time());
  972. /* TODO: Handle PTS and SCR. */
  973. buf->state = UVC_BUF_STATE_ACTIVE;
  974. }
  975. /*
  976. * Mark the buffer as done if we're at the beginning of a new frame.
  977. * End of frame detection is better implemented by checking the EOF
  978. * bit (FID bit toggling is delayed by one frame compared to the EOF
  979. * bit), but some devices don't set the bit at end of frame (and the
  980. * last payload can be lost anyway). We thus must check if the FID has
  981. * been toggled.
  982. *
  983. * stream->last_fid is initialized to -1, so the first isochronous
  984. * frame will never trigger an end of frame detection.
  985. *
  986. * Empty buffers (bytesused == 0) don't trigger end of frame detection
  987. * as it doesn't make sense to return an empty buffer. This also
  988. * avoids detecting end of frame conditions at FID toggling if the
  989. * previous payload had the EOF bit set.
  990. */
  991. if (fid != stream->last_fid && buf->bytesused != 0) {
  992. uvc_dbg(stream->dev, FRAME,
  993. "Frame complete (FID bit toggled)\n");
  994. buf->state = UVC_BUF_STATE_READY;
  995. return -EAGAIN;
  996. }
  997. stream->last_fid = fid;
  998. return data[0];
  999. }
  1000. static inline enum dma_data_direction uvc_stream_dir(
  1001. struct uvc_streaming *stream)
  1002. {
  1003. if (stream->type == V4L2_BUF_TYPE_VIDEO_CAPTURE)
  1004. return DMA_FROM_DEVICE;
  1005. else
  1006. return DMA_TO_DEVICE;
  1007. }
  1008. static inline struct device *uvc_stream_to_dmadev(struct uvc_streaming *stream)
  1009. {
  1010. return bus_to_hcd(stream->dev->udev->bus)->self.sysdev;
  1011. }
  1012. static int uvc_submit_urb(struct uvc_urb *uvc_urb, gfp_t mem_flags)
  1013. {
  1014. /* Sync DMA. */
  1015. dma_sync_sgtable_for_device(uvc_stream_to_dmadev(uvc_urb->stream),
  1016. uvc_urb->sgt,
  1017. uvc_stream_dir(uvc_urb->stream));
  1018. return usb_submit_urb(uvc_urb->urb, mem_flags);
  1019. }
  1020. /*
  1021. * uvc_video_decode_data_work: Asynchronous memcpy processing
  1022. *
  1023. * Copy URB data to video buffers in process context, releasing buffer
  1024. * references and requeuing the URB when done.
  1025. */
  1026. static void uvc_video_copy_data_work(struct work_struct *work)
  1027. {
  1028. struct uvc_urb *uvc_urb = container_of(work, struct uvc_urb, work);
  1029. unsigned int i;
  1030. int ret;
  1031. for (i = 0; i < uvc_urb->async_operations; i++) {
  1032. struct uvc_copy_op *op = &uvc_urb->copy_operations[i];
  1033. memcpy(op->dst, op->src, op->len);
  1034. /* Release reference taken on this buffer. */
  1035. uvc_queue_buffer_release(op->buf);
  1036. }
  1037. ret = uvc_submit_urb(uvc_urb, GFP_KERNEL);
  1038. if (ret < 0)
  1039. dev_err(&uvc_urb->stream->intf->dev,
  1040. "Failed to resubmit video URB (%d).\n", ret);
  1041. }
  1042. static void uvc_video_decode_data(struct uvc_urb *uvc_urb,
  1043. struct uvc_buffer *buf, const u8 *data, int len)
  1044. {
  1045. unsigned int active_op = uvc_urb->async_operations;
  1046. struct uvc_copy_op *op = &uvc_urb->copy_operations[active_op];
  1047. unsigned int maxlen;
  1048. if (len <= 0)
  1049. return;
  1050. maxlen = buf->length - buf->bytesused;
  1051. /* Take a buffer reference for async work. */
  1052. kref_get(&buf->ref);
  1053. op->buf = buf;
  1054. op->src = data;
  1055. op->dst = buf->mem + buf->bytesused;
  1056. op->len = min_t(unsigned int, len, maxlen);
  1057. buf->bytesused += op->len;
  1058. /* Complete the current frame if the buffer size was exceeded. */
  1059. if (len > maxlen) {
  1060. uvc_dbg(uvc_urb->stream->dev, FRAME,
  1061. "Frame complete (overflow)\n");
  1062. buf->error = 1;
  1063. buf->state = UVC_BUF_STATE_READY;
  1064. }
  1065. uvc_urb->async_operations++;
  1066. }
  1067. static void uvc_video_decode_end(struct uvc_streaming *stream,
  1068. struct uvc_buffer *buf, const u8 *data, int len)
  1069. {
  1070. /* Mark the buffer as done if the EOF marker is set. */
  1071. if (data[1] & UVC_STREAM_EOF && buf->bytesused != 0) {
  1072. uvc_dbg(stream->dev, FRAME, "Frame complete (EOF found)\n");
  1073. if (data[0] == len)
  1074. uvc_dbg(stream->dev, FRAME, "EOF in empty payload\n");
  1075. buf->state = UVC_BUF_STATE_READY;
  1076. if (stream->dev->quirks & UVC_QUIRK_STREAM_NO_FID)
  1077. stream->last_fid ^= UVC_STREAM_FID;
  1078. }
  1079. }
  1080. /*
  1081. * Video payload encoding is handled by uvc_video_encode_header() and
  1082. * uvc_video_encode_data(). Only bulk transfers are currently supported.
  1083. *
  1084. * uvc_video_encode_header is called at the start of a payload. It adds header
  1085. * data to the transfer buffer and returns the header size. As the only known
  1086. * UVC output device transfers a whole frame in a single payload, the EOF bit
  1087. * is always set in the header.
  1088. *
  1089. * uvc_video_encode_data is called for every URB and copies the data from the
  1090. * video buffer to the transfer buffer.
  1091. */
  1092. static int uvc_video_encode_header(struct uvc_streaming *stream,
  1093. struct uvc_buffer *buf, u8 *data, int len)
  1094. {
  1095. data[0] = 2; /* Header length */
  1096. data[1] = UVC_STREAM_EOH | UVC_STREAM_EOF
  1097. | (stream->last_fid & UVC_STREAM_FID);
  1098. return 2;
  1099. }
  1100. static int uvc_video_encode_data(struct uvc_streaming *stream,
  1101. struct uvc_buffer *buf, u8 *data, int len)
  1102. {
  1103. struct uvc_video_queue *queue = &stream->queue;
  1104. unsigned int nbytes;
  1105. void *mem;
  1106. /* Copy video data to the URB buffer. */
  1107. mem = buf->mem + queue->buf_used;
  1108. nbytes = min((unsigned int)len, buf->bytesused - queue->buf_used);
  1109. nbytes = min(stream->bulk.max_payload_size - stream->bulk.payload_size,
  1110. nbytes);
  1111. memcpy(data, mem, nbytes);
  1112. queue->buf_used += nbytes;
  1113. return nbytes;
  1114. }
  1115. /* ------------------------------------------------------------------------
  1116. * Metadata
  1117. */
  1118. /*
  1119. * Additionally to the payload headers we also want to provide the user with USB
  1120. * Frame Numbers and system time values. The resulting buffer is thus composed
  1121. * of blocks, containing a 64-bit timestamp in nanoseconds, a 16-bit USB Frame
  1122. * Number, and a copy of the payload header.
  1123. *
  1124. * Ideally we want to capture all payload headers for each frame. However, their
  1125. * number is unknown and unbound. We thus drop headers that contain no vendor
  1126. * data and that either contain no SCR value or an SCR value identical to the
  1127. * previous header.
  1128. */
  1129. static void uvc_video_decode_meta(struct uvc_streaming *stream,
  1130. struct uvc_buffer *meta_buf,
  1131. const u8 *mem, unsigned int length)
  1132. {
  1133. struct uvc_meta_buf *meta;
  1134. size_t len_std = 2;
  1135. bool has_pts, has_scr;
  1136. unsigned long flags;
  1137. unsigned int sof;
  1138. ktime_t time;
  1139. const u8 *scr;
  1140. if (!meta_buf || length == 2)
  1141. return;
  1142. if (meta_buf->length - meta_buf->bytesused <
  1143. length + sizeof(meta->ns) + sizeof(meta->sof)) {
  1144. meta_buf->error = 1;
  1145. return;
  1146. }
  1147. has_pts = mem[1] & UVC_STREAM_PTS;
  1148. has_scr = mem[1] & UVC_STREAM_SCR;
  1149. if (has_pts) {
  1150. len_std += 4;
  1151. scr = mem + 6;
  1152. } else {
  1153. scr = mem + 2;
  1154. }
  1155. if (has_scr)
  1156. len_std += 6;
  1157. if (stream->meta.format == V4L2_META_FMT_UVC)
  1158. length = len_std;
  1159. if (length == len_std && (!has_scr ||
  1160. !memcmp(scr, stream->clock.last_scr, 6)))
  1161. return;
  1162. meta = (struct uvc_meta_buf *)((u8 *)meta_buf->mem + meta_buf->bytesused);
  1163. local_irq_save(flags);
  1164. time = uvc_video_get_time();
  1165. sof = usb_get_current_frame_number(stream->dev->udev);
  1166. local_irq_restore(flags);
  1167. put_unaligned(ktime_to_ns(time), &meta->ns);
  1168. put_unaligned(sof, &meta->sof);
  1169. if (has_scr)
  1170. memcpy(stream->clock.last_scr, scr, 6);
  1171. meta->length = mem[0];
  1172. meta->flags = mem[1];
  1173. memcpy(meta->buf, &mem[2], length - 2);
  1174. meta_buf->bytesused += length + sizeof(meta->ns) + sizeof(meta->sof);
  1175. uvc_dbg(stream->dev, FRAME,
  1176. "%s(): t-sys %lluns, SOF %u, len %u, flags 0x%x, PTS %u, STC %u frame SOF %u\n",
  1177. __func__, ktime_to_ns(time), meta->sof, meta->length,
  1178. meta->flags,
  1179. has_pts ? *(u32 *)meta->buf : 0,
  1180. has_scr ? *(u32 *)scr : 0,
  1181. has_scr ? *(u32 *)(scr + 4) & 0x7ff : 0);
  1182. }
  1183. /* ------------------------------------------------------------------------
  1184. * URB handling
  1185. */
  1186. /*
  1187. * Set error flag for incomplete buffer.
  1188. */
  1189. static void uvc_video_validate_buffer(const struct uvc_streaming *stream,
  1190. struct uvc_buffer *buf)
  1191. {
  1192. if (stream->ctrl.dwMaxVideoFrameSize != buf->bytesused &&
  1193. !(stream->cur_format->flags & UVC_FMT_FLAG_COMPRESSED))
  1194. buf->error = 1;
  1195. }
  1196. /*
  1197. * Completion handler for video URBs.
  1198. */
  1199. static void uvc_video_next_buffers(struct uvc_streaming *stream,
  1200. struct uvc_buffer **video_buf, struct uvc_buffer **meta_buf)
  1201. {
  1202. uvc_video_validate_buffer(stream, *video_buf);
  1203. if (*meta_buf) {
  1204. struct vb2_v4l2_buffer *vb2_meta = &(*meta_buf)->buf;
  1205. const struct vb2_v4l2_buffer *vb2_video = &(*video_buf)->buf;
  1206. vb2_meta->sequence = vb2_video->sequence;
  1207. vb2_meta->field = vb2_video->field;
  1208. vb2_meta->vb2_buf.timestamp = vb2_video->vb2_buf.timestamp;
  1209. (*meta_buf)->state = UVC_BUF_STATE_READY;
  1210. if (!(*meta_buf)->error)
  1211. (*meta_buf)->error = (*video_buf)->error;
  1212. *meta_buf = uvc_queue_next_buffer(&stream->meta.queue,
  1213. *meta_buf);
  1214. }
  1215. *video_buf = uvc_queue_next_buffer(&stream->queue, *video_buf);
  1216. }
  1217. static void uvc_video_decode_isoc(struct uvc_urb *uvc_urb,
  1218. struct uvc_buffer *buf, struct uvc_buffer *meta_buf)
  1219. {
  1220. struct urb *urb = uvc_urb->urb;
  1221. struct uvc_streaming *stream = uvc_urb->stream;
  1222. u8 *mem;
  1223. int ret, i;
  1224. for (i = 0; i < urb->number_of_packets; ++i) {
  1225. if (urb->iso_frame_desc[i].status < 0) {
  1226. uvc_dbg(stream->dev, FRAME,
  1227. "USB isochronous frame lost (%d)\n",
  1228. urb->iso_frame_desc[i].status);
  1229. /* Mark the buffer as faulty. */
  1230. if (buf != NULL)
  1231. buf->error = 1;
  1232. continue;
  1233. }
  1234. /* Decode the payload header. */
  1235. mem = urb->transfer_buffer + urb->iso_frame_desc[i].offset;
  1236. do {
  1237. ret = uvc_video_decode_start(stream, buf, mem,
  1238. urb->iso_frame_desc[i].actual_length);
  1239. if (ret == -EAGAIN)
  1240. uvc_video_next_buffers(stream, &buf, &meta_buf);
  1241. } while (ret == -EAGAIN);
  1242. if (ret < 0)
  1243. continue;
  1244. uvc_video_decode_meta(stream, meta_buf, mem, ret);
  1245. /* Decode the payload data. */
  1246. uvc_video_decode_data(uvc_urb, buf, mem + ret,
  1247. urb->iso_frame_desc[i].actual_length - ret);
  1248. /* Process the header again. */
  1249. uvc_video_decode_end(stream, buf, mem,
  1250. urb->iso_frame_desc[i].actual_length);
  1251. if (buf->state == UVC_BUF_STATE_READY)
  1252. uvc_video_next_buffers(stream, &buf, &meta_buf);
  1253. }
  1254. }
  1255. static void uvc_video_decode_bulk(struct uvc_urb *uvc_urb,
  1256. struct uvc_buffer *buf, struct uvc_buffer *meta_buf)
  1257. {
  1258. struct urb *urb = uvc_urb->urb;
  1259. struct uvc_streaming *stream = uvc_urb->stream;
  1260. u8 *mem;
  1261. int len, ret;
  1262. /*
  1263. * Ignore ZLPs if they're not part of a frame, otherwise process them
  1264. * to trigger the end of payload detection.
  1265. */
  1266. if (urb->actual_length == 0 && stream->bulk.header_size == 0)
  1267. return;
  1268. mem = urb->transfer_buffer;
  1269. len = urb->actual_length;
  1270. stream->bulk.payload_size += len;
  1271. /*
  1272. * If the URB is the first of its payload, decode and save the
  1273. * header.
  1274. */
  1275. if (stream->bulk.header_size == 0 && !stream->bulk.skip_payload) {
  1276. do {
  1277. ret = uvc_video_decode_start(stream, buf, mem, len);
  1278. if (ret == -EAGAIN)
  1279. uvc_video_next_buffers(stream, &buf, &meta_buf);
  1280. } while (ret == -EAGAIN);
  1281. /* If an error occurred skip the rest of the payload. */
  1282. if (ret < 0 || buf == NULL) {
  1283. stream->bulk.skip_payload = 1;
  1284. } else {
  1285. memcpy(stream->bulk.header, mem, ret);
  1286. stream->bulk.header_size = ret;
  1287. uvc_video_decode_meta(stream, meta_buf, mem, ret);
  1288. mem += ret;
  1289. len -= ret;
  1290. }
  1291. }
  1292. /*
  1293. * The buffer queue might have been cancelled while a bulk transfer
  1294. * was in progress, so we can reach here with buf equal to NULL. Make
  1295. * sure buf is never dereferenced if NULL.
  1296. */
  1297. /* Prepare video data for processing. */
  1298. if (!stream->bulk.skip_payload && buf != NULL)
  1299. uvc_video_decode_data(uvc_urb, buf, mem, len);
  1300. /*
  1301. * Detect the payload end by a URB smaller than the maximum size (or
  1302. * a payload size equal to the maximum) and process the header again.
  1303. */
  1304. if (urb->actual_length < urb->transfer_buffer_length ||
  1305. stream->bulk.payload_size >= stream->bulk.max_payload_size) {
  1306. if (!stream->bulk.skip_payload && buf != NULL) {
  1307. uvc_video_decode_end(stream, buf, stream->bulk.header,
  1308. stream->bulk.payload_size);
  1309. if (buf->state == UVC_BUF_STATE_READY)
  1310. uvc_video_next_buffers(stream, &buf, &meta_buf);
  1311. }
  1312. stream->bulk.header_size = 0;
  1313. stream->bulk.skip_payload = 0;
  1314. stream->bulk.payload_size = 0;
  1315. }
  1316. }
  1317. static void uvc_video_encode_bulk(struct uvc_urb *uvc_urb,
  1318. struct uvc_buffer *buf, struct uvc_buffer *meta_buf)
  1319. {
  1320. struct urb *urb = uvc_urb->urb;
  1321. struct uvc_streaming *stream = uvc_urb->stream;
  1322. u8 *mem = urb->transfer_buffer;
  1323. int len = stream->urb_size, ret;
  1324. if (buf == NULL) {
  1325. urb->transfer_buffer_length = 0;
  1326. return;
  1327. }
  1328. /* If the URB is the first of its payload, add the header. */
  1329. if (stream->bulk.header_size == 0) {
  1330. ret = uvc_video_encode_header(stream, buf, mem, len);
  1331. stream->bulk.header_size = ret;
  1332. stream->bulk.payload_size += ret;
  1333. mem += ret;
  1334. len -= ret;
  1335. }
  1336. /* Process video data. */
  1337. ret = uvc_video_encode_data(stream, buf, mem, len);
  1338. stream->bulk.payload_size += ret;
  1339. len -= ret;
  1340. if (buf->bytesused == stream->queue.buf_used ||
  1341. stream->bulk.payload_size == stream->bulk.max_payload_size) {
  1342. if (buf->bytesused == stream->queue.buf_used) {
  1343. stream->queue.buf_used = 0;
  1344. buf->state = UVC_BUF_STATE_READY;
  1345. buf->buf.sequence = ++stream->sequence;
  1346. uvc_queue_next_buffer(&stream->queue, buf);
  1347. stream->last_fid ^= UVC_STREAM_FID;
  1348. }
  1349. stream->bulk.header_size = 0;
  1350. stream->bulk.payload_size = 0;
  1351. }
  1352. urb->transfer_buffer_length = stream->urb_size - len;
  1353. }
  1354. static void uvc_video_complete(struct urb *urb)
  1355. {
  1356. struct uvc_urb *uvc_urb = urb->context;
  1357. struct uvc_streaming *stream = uvc_urb->stream;
  1358. struct uvc_video_queue *queue = &stream->queue;
  1359. struct uvc_video_queue *qmeta = &stream->meta.queue;
  1360. struct vb2_queue *vb2_qmeta = stream->meta.vdev.queue;
  1361. struct uvc_buffer *buf = NULL;
  1362. struct uvc_buffer *buf_meta = NULL;
  1363. unsigned long flags;
  1364. int ret;
  1365. switch (urb->status) {
  1366. case 0:
  1367. break;
  1368. default:
  1369. dev_warn(&stream->intf->dev,
  1370. "Non-zero status (%d) in video completion handler.\n",
  1371. urb->status);
  1372. fallthrough;
  1373. case -ENOENT: /* usb_poison_urb() called. */
  1374. if (stream->frozen)
  1375. return;
  1376. fallthrough;
  1377. case -ECONNRESET: /* usb_unlink_urb() called. */
  1378. case -ESHUTDOWN: /* The endpoint is being disabled. */
  1379. uvc_queue_cancel(queue, urb->status == -ESHUTDOWN);
  1380. if (vb2_qmeta)
  1381. uvc_queue_cancel(qmeta, urb->status == -ESHUTDOWN);
  1382. return;
  1383. }
  1384. buf = uvc_queue_get_current_buffer(queue);
  1385. if (vb2_qmeta) {
  1386. spin_lock_irqsave(&qmeta->irqlock, flags);
  1387. if (!list_empty(&qmeta->irqqueue))
  1388. buf_meta = list_first_entry(&qmeta->irqqueue,
  1389. struct uvc_buffer, queue);
  1390. spin_unlock_irqrestore(&qmeta->irqlock, flags);
  1391. }
  1392. /* Re-initialise the URB async work. */
  1393. uvc_urb->async_operations = 0;
  1394. /* Sync DMA and invalidate vmap range. */
  1395. dma_sync_sgtable_for_cpu(uvc_stream_to_dmadev(uvc_urb->stream),
  1396. uvc_urb->sgt, uvc_stream_dir(stream));
  1397. invalidate_kernel_vmap_range(uvc_urb->buffer,
  1398. uvc_urb->stream->urb_size);
  1399. /*
  1400. * Process the URB headers, and optionally queue expensive memcpy tasks
  1401. * to be deferred to a work queue.
  1402. */
  1403. stream->decode(uvc_urb, buf, buf_meta);
  1404. /* If no async work is needed, resubmit the URB immediately. */
  1405. if (!uvc_urb->async_operations) {
  1406. ret = uvc_submit_urb(uvc_urb, GFP_ATOMIC);
  1407. if (ret < 0)
  1408. dev_err(&stream->intf->dev,
  1409. "Failed to resubmit video URB (%d).\n", ret);
  1410. return;
  1411. }
  1412. queue_work(stream->async_wq, &uvc_urb->work);
  1413. }
  1414. /*
  1415. * Free transfer buffers.
  1416. */
  1417. static void uvc_free_urb_buffers(struct uvc_streaming *stream)
  1418. {
  1419. struct device *dma_dev = uvc_stream_to_dmadev(stream);
  1420. struct uvc_urb *uvc_urb;
  1421. for_each_uvc_urb(uvc_urb, stream) {
  1422. if (!uvc_urb->buffer)
  1423. continue;
  1424. dma_vunmap_noncontiguous(dma_dev, uvc_urb->buffer);
  1425. dma_free_noncontiguous(dma_dev, stream->urb_size, uvc_urb->sgt,
  1426. uvc_stream_dir(stream));
  1427. uvc_urb->buffer = NULL;
  1428. uvc_urb->sgt = NULL;
  1429. }
  1430. stream->urb_size = 0;
  1431. }
  1432. static bool uvc_alloc_urb_buffer(struct uvc_streaming *stream,
  1433. struct uvc_urb *uvc_urb, gfp_t gfp_flags)
  1434. {
  1435. struct device *dma_dev = uvc_stream_to_dmadev(stream);
  1436. uvc_urb->sgt = dma_alloc_noncontiguous(dma_dev, stream->urb_size,
  1437. uvc_stream_dir(stream),
  1438. gfp_flags, 0);
  1439. if (!uvc_urb->sgt)
  1440. return false;
  1441. uvc_urb->dma = uvc_urb->sgt->sgl->dma_address;
  1442. uvc_urb->buffer = dma_vmap_noncontiguous(dma_dev, stream->urb_size,
  1443. uvc_urb->sgt);
  1444. if (!uvc_urb->buffer) {
  1445. dma_free_noncontiguous(dma_dev, stream->urb_size,
  1446. uvc_urb->sgt,
  1447. uvc_stream_dir(stream));
  1448. uvc_urb->sgt = NULL;
  1449. return false;
  1450. }
  1451. return true;
  1452. }
  1453. /*
  1454. * Allocate transfer buffers. This function can be called with buffers
  1455. * already allocated when resuming from suspend, in which case it will
  1456. * return without touching the buffers.
  1457. *
  1458. * Limit the buffer size to UVC_MAX_PACKETS bulk/isochronous packets. If the
  1459. * system is too low on memory try successively smaller numbers of packets
  1460. * until allocation succeeds.
  1461. *
  1462. * Return the number of allocated packets on success or 0 when out of memory.
  1463. */
  1464. static int uvc_alloc_urb_buffers(struct uvc_streaming *stream,
  1465. unsigned int size, unsigned int psize, gfp_t gfp_flags)
  1466. {
  1467. unsigned int npackets;
  1468. unsigned int i;
  1469. /* Buffers are already allocated, bail out. */
  1470. if (stream->urb_size)
  1471. return stream->urb_size / psize;
  1472. /*
  1473. * Compute the number of packets. Bulk endpoints might transfer UVC
  1474. * payloads across multiple URBs.
  1475. */
  1476. npackets = DIV_ROUND_UP(size, psize);
  1477. if (npackets > UVC_MAX_PACKETS)
  1478. npackets = UVC_MAX_PACKETS;
  1479. /* Retry allocations until one succeed. */
  1480. for (; npackets > 1; npackets /= 2) {
  1481. stream->urb_size = psize * npackets;
  1482. for (i = 0; i < UVC_URBS; ++i) {
  1483. struct uvc_urb *uvc_urb = &stream->uvc_urb[i];
  1484. if (!uvc_alloc_urb_buffer(stream, uvc_urb, gfp_flags)) {
  1485. uvc_free_urb_buffers(stream);
  1486. break;
  1487. }
  1488. uvc_urb->stream = stream;
  1489. }
  1490. if (i == UVC_URBS) {
  1491. uvc_dbg(stream->dev, VIDEO,
  1492. "Allocated %u URB buffers of %ux%u bytes each\n",
  1493. UVC_URBS, npackets, psize);
  1494. return npackets;
  1495. }
  1496. }
  1497. uvc_dbg(stream->dev, VIDEO,
  1498. "Failed to allocate URB buffers (%u bytes per packet)\n",
  1499. psize);
  1500. return 0;
  1501. }
  1502. /*
  1503. * Uninitialize isochronous/bulk URBs and free transfer buffers.
  1504. */
  1505. static void uvc_video_stop_transfer(struct uvc_streaming *stream,
  1506. int free_buffers)
  1507. {
  1508. struct uvc_urb *uvc_urb;
  1509. uvc_video_stats_stop(stream);
  1510. /*
  1511. * We must poison the URBs rather than kill them to ensure that even
  1512. * after the completion handler returns, any asynchronous workqueues
  1513. * will be prevented from resubmitting the URBs.
  1514. */
  1515. for_each_uvc_urb(uvc_urb, stream)
  1516. usb_poison_urb(uvc_urb->urb);
  1517. flush_workqueue(stream->async_wq);
  1518. for_each_uvc_urb(uvc_urb, stream) {
  1519. usb_free_urb(uvc_urb->urb);
  1520. uvc_urb->urb = NULL;
  1521. }
  1522. if (free_buffers)
  1523. uvc_free_urb_buffers(stream);
  1524. }
  1525. /*
  1526. * Compute the maximum number of bytes per interval for an endpoint.
  1527. */
  1528. u16 uvc_endpoint_max_bpi(struct usb_device *dev, struct usb_host_endpoint *ep)
  1529. {
  1530. u16 psize;
  1531. switch (dev->speed) {
  1532. case USB_SPEED_SUPER:
  1533. case USB_SPEED_SUPER_PLUS:
  1534. return le16_to_cpu(ep->ss_ep_comp.wBytesPerInterval);
  1535. default:
  1536. psize = usb_endpoint_maxp(&ep->desc);
  1537. psize *= usb_endpoint_maxp_mult(&ep->desc);
  1538. return psize;
  1539. }
  1540. }
  1541. /*
  1542. * Initialize isochronous URBs and allocate transfer buffers. The packet size
  1543. * is given by the endpoint.
  1544. */
  1545. static int uvc_init_video_isoc(struct uvc_streaming *stream,
  1546. struct usb_host_endpoint *ep, gfp_t gfp_flags)
  1547. {
  1548. struct urb *urb;
  1549. struct uvc_urb *uvc_urb;
  1550. unsigned int npackets, i;
  1551. u16 psize;
  1552. u32 size;
  1553. psize = uvc_endpoint_max_bpi(stream->dev->udev, ep);
  1554. size = stream->ctrl.dwMaxVideoFrameSize;
  1555. npackets = uvc_alloc_urb_buffers(stream, size, psize, gfp_flags);
  1556. if (npackets == 0)
  1557. return -ENOMEM;
  1558. size = npackets * psize;
  1559. for_each_uvc_urb(uvc_urb, stream) {
  1560. urb = usb_alloc_urb(npackets, gfp_flags);
  1561. if (urb == NULL) {
  1562. uvc_video_stop_transfer(stream, 1);
  1563. return -ENOMEM;
  1564. }
  1565. urb->dev = stream->dev->udev;
  1566. urb->context = uvc_urb;
  1567. urb->pipe = usb_rcvisocpipe(stream->dev->udev,
  1568. ep->desc.bEndpointAddress);
  1569. urb->transfer_flags = URB_ISO_ASAP | URB_NO_TRANSFER_DMA_MAP;
  1570. urb->transfer_dma = uvc_urb->dma;
  1571. urb->interval = ep->desc.bInterval;
  1572. urb->transfer_buffer = uvc_urb->buffer;
  1573. urb->complete = uvc_video_complete;
  1574. urb->number_of_packets = npackets;
  1575. urb->transfer_buffer_length = size;
  1576. for (i = 0; i < npackets; ++i) {
  1577. urb->iso_frame_desc[i].offset = i * psize;
  1578. urb->iso_frame_desc[i].length = psize;
  1579. }
  1580. uvc_urb->urb = urb;
  1581. }
  1582. return 0;
  1583. }
  1584. /*
  1585. * Initialize bulk URBs and allocate transfer buffers. The packet size is
  1586. * given by the endpoint.
  1587. */
  1588. static int uvc_init_video_bulk(struct uvc_streaming *stream,
  1589. struct usb_host_endpoint *ep, gfp_t gfp_flags)
  1590. {
  1591. struct urb *urb;
  1592. struct uvc_urb *uvc_urb;
  1593. unsigned int npackets, pipe;
  1594. u16 psize;
  1595. u32 size;
  1596. psize = usb_endpoint_maxp(&ep->desc);
  1597. size = stream->ctrl.dwMaxPayloadTransferSize;
  1598. stream->bulk.max_payload_size = size;
  1599. npackets = uvc_alloc_urb_buffers(stream, size, psize, gfp_flags);
  1600. if (npackets == 0)
  1601. return -ENOMEM;
  1602. size = npackets * psize;
  1603. if (usb_endpoint_dir_in(&ep->desc))
  1604. pipe = usb_rcvbulkpipe(stream->dev->udev,
  1605. ep->desc.bEndpointAddress);
  1606. else
  1607. pipe = usb_sndbulkpipe(stream->dev->udev,
  1608. ep->desc.bEndpointAddress);
  1609. if (stream->type == V4L2_BUF_TYPE_VIDEO_OUTPUT)
  1610. size = 0;
  1611. for_each_uvc_urb(uvc_urb, stream) {
  1612. urb = usb_alloc_urb(0, gfp_flags);
  1613. if (urb == NULL) {
  1614. uvc_video_stop_transfer(stream, 1);
  1615. return -ENOMEM;
  1616. }
  1617. usb_fill_bulk_urb(urb, stream->dev->udev, pipe, uvc_urb->buffer,
  1618. size, uvc_video_complete, uvc_urb);
  1619. urb->transfer_flags = URB_NO_TRANSFER_DMA_MAP;
  1620. urb->transfer_dma = uvc_urb->dma;
  1621. uvc_urb->urb = urb;
  1622. }
  1623. return 0;
  1624. }
  1625. /*
  1626. * Initialize isochronous/bulk URBs and allocate transfer buffers.
  1627. */
  1628. static int uvc_video_start_transfer(struct uvc_streaming *stream,
  1629. gfp_t gfp_flags)
  1630. {
  1631. struct usb_interface *intf = stream->intf;
  1632. struct usb_host_endpoint *ep;
  1633. struct uvc_urb *uvc_urb;
  1634. unsigned int i;
  1635. int ret;
  1636. stream->sequence = -1;
  1637. stream->last_fid = -1;
  1638. stream->bulk.header_size = 0;
  1639. stream->bulk.skip_payload = 0;
  1640. stream->bulk.payload_size = 0;
  1641. uvc_video_stats_start(stream);
  1642. if (intf->num_altsetting > 1) {
  1643. struct usb_host_endpoint *best_ep = NULL;
  1644. unsigned int best_psize = UINT_MAX;
  1645. unsigned int bandwidth;
  1646. unsigned int altsetting;
  1647. int intfnum = stream->intfnum;
  1648. /* Isochronous endpoint, select the alternate setting. */
  1649. bandwidth = stream->ctrl.dwMaxPayloadTransferSize;
  1650. if (bandwidth == 0) {
  1651. uvc_dbg(stream->dev, VIDEO,
  1652. "Device requested null bandwidth, defaulting to lowest\n");
  1653. bandwidth = 1;
  1654. } else {
  1655. uvc_dbg(stream->dev, VIDEO,
  1656. "Device requested %u B/frame bandwidth\n",
  1657. bandwidth);
  1658. }
  1659. for (i = 0; i < intf->num_altsetting; ++i) {
  1660. struct usb_host_interface *alts;
  1661. unsigned int psize;
  1662. alts = &intf->altsetting[i];
  1663. ep = uvc_find_endpoint(alts,
  1664. stream->header.bEndpointAddress);
  1665. if (ep == NULL)
  1666. continue;
  1667. /* Check if the bandwidth is high enough. */
  1668. psize = uvc_endpoint_max_bpi(stream->dev->udev, ep);
  1669. if (psize >= bandwidth && psize <= best_psize) {
  1670. altsetting = alts->desc.bAlternateSetting;
  1671. best_psize = psize;
  1672. best_ep = ep;
  1673. }
  1674. }
  1675. if (best_ep == NULL) {
  1676. uvc_dbg(stream->dev, VIDEO,
  1677. "No fast enough alt setting for requested bandwidth\n");
  1678. return -EIO;
  1679. }
  1680. uvc_dbg(stream->dev, VIDEO,
  1681. "Selecting alternate setting %u (%u B/frame bandwidth)\n",
  1682. altsetting, best_psize);
  1683. /*
  1684. * Some devices, namely the Logitech C910 and B910, are unable
  1685. * to recover from a USB autosuspend, unless the alternate
  1686. * setting of the streaming interface is toggled.
  1687. */
  1688. if (stream->dev->quirks & UVC_QUIRK_WAKE_AUTOSUSPEND) {
  1689. usb_set_interface(stream->dev->udev, intfnum,
  1690. altsetting);
  1691. usb_set_interface(stream->dev->udev, intfnum, 0);
  1692. }
  1693. ret = usb_set_interface(stream->dev->udev, intfnum, altsetting);
  1694. if (ret < 0)
  1695. return ret;
  1696. ret = uvc_init_video_isoc(stream, best_ep, gfp_flags);
  1697. } else {
  1698. /* Bulk endpoint, proceed to URB initialization. */
  1699. ep = uvc_find_endpoint(&intf->altsetting[0],
  1700. stream->header.bEndpointAddress);
  1701. if (ep == NULL)
  1702. return -EIO;
  1703. /* Reject broken descriptors. */
  1704. if (usb_endpoint_maxp(&ep->desc) == 0)
  1705. return -EIO;
  1706. ret = uvc_init_video_bulk(stream, ep, gfp_flags);
  1707. }
  1708. if (ret < 0)
  1709. return ret;
  1710. /* Submit the URBs. */
  1711. for_each_uvc_urb(uvc_urb, stream) {
  1712. ret = uvc_submit_urb(uvc_urb, gfp_flags);
  1713. if (ret < 0) {
  1714. dev_err(&stream->intf->dev,
  1715. "Failed to submit URB %u (%d).\n",
  1716. uvc_urb_index(uvc_urb), ret);
  1717. uvc_video_stop_transfer(stream, 1);
  1718. return ret;
  1719. }
  1720. }
  1721. /*
  1722. * The Logitech C920 temporarily forgets that it should not be adjusting
  1723. * Exposure Absolute during init so restore controls to stored values.
  1724. */
  1725. if (stream->dev->quirks & UVC_QUIRK_RESTORE_CTRLS_ON_INIT)
  1726. uvc_ctrl_restore_values(stream->dev);
  1727. return 0;
  1728. }
  1729. /* --------------------------------------------------------------------------
  1730. * Suspend/resume
  1731. */
  1732. /*
  1733. * Stop streaming without disabling the video queue.
  1734. *
  1735. * To let userspace applications resume without trouble, we must not touch the
  1736. * video buffers in any way. We mark the device as frozen to make sure the URB
  1737. * completion handler won't try to cancel the queue when we kill the URBs.
  1738. */
  1739. int uvc_video_suspend(struct uvc_streaming *stream)
  1740. {
  1741. if (!uvc_queue_streaming(&stream->queue))
  1742. return 0;
  1743. stream->frozen = 1;
  1744. uvc_video_stop_transfer(stream, 0);
  1745. usb_set_interface(stream->dev->udev, stream->intfnum, 0);
  1746. return 0;
  1747. }
  1748. /*
  1749. * Reconfigure the video interface and restart streaming if it was enabled
  1750. * before suspend.
  1751. *
  1752. * If an error occurs, disable the video queue. This will wake all pending
  1753. * buffers, making sure userspace applications are notified of the problem
  1754. * instead of waiting forever.
  1755. */
  1756. int uvc_video_resume(struct uvc_streaming *stream, int reset)
  1757. {
  1758. int ret;
  1759. /*
  1760. * If the bus has been reset on resume, set the alternate setting to 0.
  1761. * This should be the default value, but some devices crash or otherwise
  1762. * misbehave if they don't receive a SET_INTERFACE request before any
  1763. * other video control request.
  1764. */
  1765. if (reset)
  1766. usb_set_interface(stream->dev->udev, stream->intfnum, 0);
  1767. stream->frozen = 0;
  1768. uvc_video_clock_reset(stream);
  1769. if (!uvc_queue_streaming(&stream->queue))
  1770. return 0;
  1771. ret = uvc_commit_video(stream, &stream->ctrl);
  1772. if (ret < 0)
  1773. return ret;
  1774. return uvc_video_start_transfer(stream, GFP_NOIO);
  1775. }
  1776. /* ------------------------------------------------------------------------
  1777. * Video device
  1778. */
  1779. /*
  1780. * Initialize the UVC video device by switching to alternate setting 0 and
  1781. * retrieve the default format.
  1782. *
  1783. * Some cameras (namely the Fuji Finepix) set the format and frame
  1784. * indexes to zero. The UVC standard doesn't clearly make this a spec
  1785. * violation, so try to silently fix the values if possible.
  1786. *
  1787. * This function is called before registering the device with V4L.
  1788. */
  1789. int uvc_video_init(struct uvc_streaming *stream)
  1790. {
  1791. struct uvc_streaming_control *probe = &stream->ctrl;
  1792. struct uvc_format *format = NULL;
  1793. struct uvc_frame *frame = NULL;
  1794. struct uvc_urb *uvc_urb;
  1795. unsigned int i;
  1796. int ret;
  1797. if (stream->nformats == 0) {
  1798. dev_info(&stream->intf->dev,
  1799. "No supported video formats found.\n");
  1800. return -EINVAL;
  1801. }
  1802. atomic_set(&stream->active, 0);
  1803. /*
  1804. * Alternate setting 0 should be the default, yet the XBox Live Vision
  1805. * Cam (and possibly other devices) crash or otherwise misbehave if
  1806. * they don't receive a SET_INTERFACE request before any other video
  1807. * control request.
  1808. */
  1809. usb_set_interface(stream->dev->udev, stream->intfnum, 0);
  1810. /*
  1811. * Set the streaming probe control with default streaming parameters
  1812. * retrieved from the device. Webcams that don't support GET_DEF
  1813. * requests on the probe control will just keep their current streaming
  1814. * parameters.
  1815. */
  1816. if (uvc_get_video_ctrl(stream, probe, 1, UVC_GET_DEF) == 0)
  1817. uvc_set_video_ctrl(stream, probe, 1);
  1818. /*
  1819. * Initialize the streaming parameters with the probe control current
  1820. * value. This makes sure SET_CUR requests on the streaming commit
  1821. * control will always use values retrieved from a successful GET_CUR
  1822. * request on the probe control, as required by the UVC specification.
  1823. */
  1824. ret = uvc_get_video_ctrl(stream, probe, 1, UVC_GET_CUR);
  1825. if (ret < 0)
  1826. return ret;
  1827. /*
  1828. * Check if the default format descriptor exists. Use the first
  1829. * available format otherwise.
  1830. */
  1831. for (i = stream->nformats; i > 0; --i) {
  1832. format = &stream->format[i-1];
  1833. if (format->index == probe->bFormatIndex)
  1834. break;
  1835. }
  1836. if (format->nframes == 0) {
  1837. dev_info(&stream->intf->dev,
  1838. "No frame descriptor found for the default format.\n");
  1839. return -EINVAL;
  1840. }
  1841. /*
  1842. * Zero bFrameIndex might be correct. Stream-based formats (including
  1843. * MPEG-2 TS and DV) do not support frames but have a dummy frame
  1844. * descriptor with bFrameIndex set to zero. If the default frame
  1845. * descriptor is not found, use the first available frame.
  1846. */
  1847. for (i = format->nframes; i > 0; --i) {
  1848. frame = &format->frame[i-1];
  1849. if (frame->bFrameIndex == probe->bFrameIndex)
  1850. break;
  1851. }
  1852. probe->bFormatIndex = format->index;
  1853. probe->bFrameIndex = frame->bFrameIndex;
  1854. stream->def_format = format;
  1855. stream->cur_format = format;
  1856. stream->cur_frame = frame;
  1857. /* Select the video decoding function */
  1858. if (stream->type == V4L2_BUF_TYPE_VIDEO_CAPTURE) {
  1859. if (stream->dev->quirks & UVC_QUIRK_BUILTIN_ISIGHT)
  1860. stream->decode = uvc_video_decode_isight;
  1861. else if (stream->intf->num_altsetting > 1)
  1862. stream->decode = uvc_video_decode_isoc;
  1863. else
  1864. stream->decode = uvc_video_decode_bulk;
  1865. } else {
  1866. if (stream->intf->num_altsetting == 1)
  1867. stream->decode = uvc_video_encode_bulk;
  1868. else {
  1869. dev_info(&stream->intf->dev,
  1870. "Isochronous endpoints are not supported for video output devices.\n");
  1871. return -EINVAL;
  1872. }
  1873. }
  1874. /* Prepare asynchronous work items. */
  1875. for_each_uvc_urb(uvc_urb, stream)
  1876. INIT_WORK(&uvc_urb->work, uvc_video_copy_data_work);
  1877. return 0;
  1878. }
  1879. int uvc_video_start_streaming(struct uvc_streaming *stream)
  1880. {
  1881. int ret;
  1882. ret = uvc_video_clock_init(stream);
  1883. if (ret < 0)
  1884. return ret;
  1885. /* Commit the streaming parameters. */
  1886. ret = uvc_commit_video(stream, &stream->ctrl);
  1887. if (ret < 0)
  1888. goto error_commit;
  1889. ret = uvc_video_start_transfer(stream, GFP_KERNEL);
  1890. if (ret < 0)
  1891. goto error_video;
  1892. return 0;
  1893. error_video:
  1894. usb_set_interface(stream->dev->udev, stream->intfnum, 0);
  1895. error_commit:
  1896. uvc_video_clock_cleanup(stream);
  1897. return ret;
  1898. }
  1899. void uvc_video_stop_streaming(struct uvc_streaming *stream)
  1900. {
  1901. uvc_video_stop_transfer(stream, 1);
  1902. if (stream->intf->num_altsetting > 1) {
  1903. usb_set_interface(stream->dev->udev, stream->intfnum, 0);
  1904. } else {
  1905. /*
  1906. * UVC doesn't specify how to inform a bulk-based device
  1907. * when the video stream is stopped. Windows sends a
  1908. * CLEAR_FEATURE(HALT) request to the video streaming
  1909. * bulk endpoint, mimic the same behaviour.
  1910. */
  1911. unsigned int epnum = stream->header.bEndpointAddress
  1912. & USB_ENDPOINT_NUMBER_MASK;
  1913. unsigned int dir = stream->header.bEndpointAddress
  1914. & USB_ENDPOINT_DIR_MASK;
  1915. unsigned int pipe;
  1916. pipe = usb_sndbulkpipe(stream->dev->udev, epnum) | dir;
  1917. usb_clear_halt(stream->dev->udev, pipe);
  1918. }
  1919. uvc_video_clock_cleanup(stream);
  1920. }