endpoint.c 30 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135
  1. /*
  2. * This program is free software; you can redistribute it and/or modify
  3. * it under the terms of the GNU General Public License as published by
  4. * the Free Software Foundation; either version 2 of the License, or
  5. * (at your option) any later version.
  6. *
  7. * This program is distributed in the hope that it will be useful,
  8. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. * GNU General Public License for more details.
  11. *
  12. * You should have received a copy of the GNU General Public License
  13. * along with this program; if not, write to the Free Software
  14. * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  15. *
  16. */
  17. #include <linux/gfp.h>
  18. #include <linux/init.h>
  19. #include <linux/ratelimit.h>
  20. #include <linux/usb.h>
  21. #include <linux/usb/audio.h>
  22. #include <linux/slab.h>
  23. #include <sound/core.h>
  24. #include <sound/pcm.h>
  25. #include <sound/pcm_params.h>
  26. #include "usbaudio.h"
  27. #include "helper.h"
  28. #include "card.h"
  29. #include "endpoint.h"
  30. #include "pcm.h"
  31. #include "quirks.h"
  32. #define EP_FLAG_ACTIVATED 0
  33. #define EP_FLAG_RUNNING 1
  34. #define EP_FLAG_STOPPING 2
  35. /*
  36. * snd_usb_endpoint is a model that abstracts everything related to an
  37. * USB endpoint and its streaming.
  38. *
  39. * There are functions to activate and deactivate the streaming URBs and
  40. * optional callbacks to let the pcm logic handle the actual content of the
  41. * packets for playback and record. Thus, the bus streaming and the audio
  42. * handlers are fully decoupled.
  43. *
  44. * There are two different types of endpoints in audio applications.
  45. *
  46. * SND_USB_ENDPOINT_TYPE_DATA handles full audio data payload for both
  47. * inbound and outbound traffic.
  48. *
  49. * SND_USB_ENDPOINT_TYPE_SYNC endpoints are for inbound traffic only and
  50. * expect the payload to carry Q10.14 / Q16.16 formatted sync information
  51. * (3 or 4 bytes).
  52. *
  53. * Each endpoint has to be configured prior to being used by calling
  54. * snd_usb_endpoint_set_params().
  55. *
  56. * The model incorporates a reference counting, so that multiple users
  57. * can call snd_usb_endpoint_start() and snd_usb_endpoint_stop(), and
  58. * only the first user will effectively start the URBs, and only the last
  59. * one to stop it will tear the URBs down again.
  60. */
  61. /*
  62. * convert a sampling rate into our full speed format (fs/1000 in Q16.16)
  63. * this will overflow at approx 524 kHz
  64. */
  65. static inline unsigned get_usb_full_speed_rate(unsigned int rate)
  66. {
  67. return ((rate << 13) + 62) / 125;
  68. }
  69. /*
  70. * convert a sampling rate into USB high speed format (fs/8000 in Q16.16)
  71. * this will overflow at approx 4 MHz
  72. */
  73. static inline unsigned get_usb_high_speed_rate(unsigned int rate)
  74. {
  75. return ((rate << 10) + 62) / 125;
  76. }
  77. /*
  78. * release a urb data
  79. */
  80. static void release_urb_ctx(struct snd_urb_ctx *u)
  81. {
  82. if (u->buffer_size)
  83. usb_free_coherent(u->ep->chip->dev, u->buffer_size,
  84. u->urb->transfer_buffer,
  85. u->urb->transfer_dma);
  86. usb_free_urb(u->urb);
  87. u->urb = NULL;
  88. }
  89. static const char *usb_error_string(int err)
  90. {
  91. switch (err) {
  92. case -ENODEV:
  93. return "no device";
  94. case -ENOENT:
  95. return "endpoint not enabled";
  96. case -EPIPE:
  97. return "endpoint stalled";
  98. case -ENOSPC:
  99. return "not enough bandwidth";
  100. case -ESHUTDOWN:
  101. return "device disabled";
  102. case -EHOSTUNREACH:
  103. return "device suspended";
  104. case -EINVAL:
  105. case -EAGAIN:
  106. case -EFBIG:
  107. case -EMSGSIZE:
  108. return "internal error";
  109. default:
  110. return "unknown error";
  111. }
  112. }
  113. /**
  114. * snd_usb_endpoint_implicit_feedback_sink: Report endpoint usage type
  115. *
  116. * @ep: The snd_usb_endpoint
  117. *
  118. * Determine whether an endpoint is driven by an implicit feedback
  119. * data endpoint source.
  120. */
  121. int snd_usb_endpoint_implicit_feedback_sink(struct snd_usb_endpoint *ep)
  122. {
  123. return ep->sync_master &&
  124. ep->sync_master->type == SND_USB_ENDPOINT_TYPE_DATA &&
  125. ep->type == SND_USB_ENDPOINT_TYPE_DATA &&
  126. usb_pipeout(ep->pipe);
  127. }
  128. /*
  129. * For streaming based on information derived from sync endpoints,
  130. * prepare_outbound_urb_sizes() will call next_packet_size() to
  131. * determine the number of samples to be sent in the next packet.
  132. *
  133. * For implicit feedback, next_packet_size() is unused.
  134. */
  135. int snd_usb_endpoint_next_packet_size(struct snd_usb_endpoint *ep)
  136. {
  137. unsigned long flags;
  138. int ret;
  139. if (ep->fill_max)
  140. return ep->maxframesize;
  141. spin_lock_irqsave(&ep->lock, flags);
  142. ep->phase = (ep->phase & 0xffff)
  143. + (ep->freqm << ep->datainterval);
  144. ret = min(ep->phase >> 16, ep->maxframesize);
  145. spin_unlock_irqrestore(&ep->lock, flags);
  146. return ret;
  147. }
  148. static void retire_outbound_urb(struct snd_usb_endpoint *ep,
  149. struct snd_urb_ctx *urb_ctx)
  150. {
  151. if (ep->retire_data_urb)
  152. ep->retire_data_urb(ep->data_subs, urb_ctx->urb);
  153. }
  154. static void retire_inbound_urb(struct snd_usb_endpoint *ep,
  155. struct snd_urb_ctx *urb_ctx)
  156. {
  157. struct urb *urb = urb_ctx->urb;
  158. if (unlikely(ep->skip_packets > 0)) {
  159. ep->skip_packets--;
  160. return;
  161. }
  162. if (ep->sync_slave)
  163. snd_usb_handle_sync_urb(ep->sync_slave, ep, urb);
  164. if (ep->retire_data_urb)
  165. ep->retire_data_urb(ep->data_subs, urb);
  166. }
  167. /*
  168. * Prepare a PLAYBACK urb for submission to the bus.
  169. */
  170. static void prepare_outbound_urb(struct snd_usb_endpoint *ep,
  171. struct snd_urb_ctx *ctx)
  172. {
  173. int i;
  174. struct urb *urb = ctx->urb;
  175. unsigned char *cp = urb->transfer_buffer;
  176. urb->dev = ep->chip->dev; /* we need to set this at each time */
  177. switch (ep->type) {
  178. case SND_USB_ENDPOINT_TYPE_DATA:
  179. if (ep->prepare_data_urb) {
  180. ep->prepare_data_urb(ep->data_subs, urb);
  181. } else {
  182. /* no data provider, so send silence */
  183. unsigned int offs = 0;
  184. for (i = 0; i < ctx->packets; ++i) {
  185. int counts;
  186. if (ctx->packet_size[i])
  187. counts = ctx->packet_size[i];
  188. else
  189. counts = snd_usb_endpoint_next_packet_size(ep);
  190. urb->iso_frame_desc[i].offset = offs * ep->stride;
  191. urb->iso_frame_desc[i].length = counts * ep->stride;
  192. offs += counts;
  193. }
  194. urb->number_of_packets = ctx->packets;
  195. urb->transfer_buffer_length = offs * ep->stride;
  196. memset(urb->transfer_buffer, ep->silence_value,
  197. offs * ep->stride);
  198. }
  199. break;
  200. case SND_USB_ENDPOINT_TYPE_SYNC:
  201. if (snd_usb_get_speed(ep->chip->dev) >= USB_SPEED_HIGH) {
  202. /*
  203. * fill the length and offset of each urb descriptor.
  204. * the fixed 12.13 frequency is passed as 16.16 through the pipe.
  205. */
  206. urb->iso_frame_desc[0].length = 4;
  207. urb->iso_frame_desc[0].offset = 0;
  208. cp[0] = ep->freqn;
  209. cp[1] = ep->freqn >> 8;
  210. cp[2] = ep->freqn >> 16;
  211. cp[3] = ep->freqn >> 24;
  212. } else {
  213. /*
  214. * fill the length and offset of each urb descriptor.
  215. * the fixed 10.14 frequency is passed through the pipe.
  216. */
  217. urb->iso_frame_desc[0].length = 3;
  218. urb->iso_frame_desc[0].offset = 0;
  219. cp[0] = ep->freqn >> 2;
  220. cp[1] = ep->freqn >> 10;
  221. cp[2] = ep->freqn >> 18;
  222. }
  223. break;
  224. }
  225. }
  226. /*
  227. * Prepare a CAPTURE or SYNC urb for submission to the bus.
  228. */
  229. static inline void prepare_inbound_urb(struct snd_usb_endpoint *ep,
  230. struct snd_urb_ctx *urb_ctx)
  231. {
  232. int i, offs;
  233. struct urb *urb = urb_ctx->urb;
  234. urb->dev = ep->chip->dev; /* we need to set this at each time */
  235. switch (ep->type) {
  236. case SND_USB_ENDPOINT_TYPE_DATA:
  237. offs = 0;
  238. for (i = 0; i < urb_ctx->packets; i++) {
  239. urb->iso_frame_desc[i].offset = offs;
  240. urb->iso_frame_desc[i].length = ep->curpacksize;
  241. offs += ep->curpacksize;
  242. }
  243. urb->transfer_buffer_length = offs;
  244. urb->number_of_packets = urb_ctx->packets;
  245. break;
  246. case SND_USB_ENDPOINT_TYPE_SYNC:
  247. urb->iso_frame_desc[0].length = min(4u, ep->syncmaxsize);
  248. urb->iso_frame_desc[0].offset = 0;
  249. break;
  250. }
  251. }
  252. /*
  253. * Send output urbs that have been prepared previously. URBs are dequeued
  254. * from ep->ready_playback_urbs and in case there there aren't any available
  255. * or there are no packets that have been prepared, this function does
  256. * nothing.
  257. *
  258. * The reason why the functionality of sending and preparing URBs is separated
  259. * is that host controllers don't guarantee the order in which they return
  260. * inbound and outbound packets to their submitters.
  261. *
  262. * This function is only used for implicit feedback endpoints. For endpoints
  263. * driven by dedicated sync endpoints, URBs are immediately re-submitted
  264. * from their completion handler.
  265. */
  266. static void queue_pending_output_urbs(struct snd_usb_endpoint *ep)
  267. {
  268. while (test_bit(EP_FLAG_RUNNING, &ep->flags)) {
  269. unsigned long flags;
  270. struct snd_usb_packet_info *uninitialized_var(packet);
  271. struct snd_urb_ctx *ctx = NULL;
  272. struct urb *urb;
  273. int err, i;
  274. spin_lock_irqsave(&ep->lock, flags);
  275. if (ep->next_packet_read_pos != ep->next_packet_write_pos) {
  276. packet = ep->next_packet + ep->next_packet_read_pos;
  277. ep->next_packet_read_pos++;
  278. ep->next_packet_read_pos %= MAX_URBS;
  279. /* take URB out of FIFO */
  280. if (!list_empty(&ep->ready_playback_urbs))
  281. ctx = list_first_entry(&ep->ready_playback_urbs,
  282. struct snd_urb_ctx, ready_list);
  283. }
  284. spin_unlock_irqrestore(&ep->lock, flags);
  285. if (ctx == NULL)
  286. return;
  287. list_del_init(&ctx->ready_list);
  288. urb = ctx->urb;
  289. /* copy over the length information */
  290. for (i = 0; i < packet->packets; i++)
  291. ctx->packet_size[i] = packet->packet_size[i];
  292. /* call the data handler to fill in playback data */
  293. prepare_outbound_urb(ep, ctx);
  294. err = usb_submit_urb(ctx->urb, GFP_ATOMIC);
  295. if (err < 0)
  296. snd_printk(KERN_ERR "Unable to submit urb #%d: %d (urb %p)\n",
  297. ctx->index, err, ctx->urb);
  298. else
  299. set_bit(ctx->index, &ep->active_mask);
  300. }
  301. }
  302. /*
  303. * complete callback for urbs
  304. */
  305. static void snd_complete_urb(struct urb *urb)
  306. {
  307. struct snd_urb_ctx *ctx = urb->context;
  308. struct snd_usb_endpoint *ep = ctx->ep;
  309. int err;
  310. if (unlikely(urb->status == -ENOENT || /* unlinked */
  311. urb->status == -ENODEV || /* device removed */
  312. urb->status == -ECONNRESET || /* unlinked */
  313. urb->status == -ESHUTDOWN || /* device disabled */
  314. ep->chip->shutdown)) /* device disconnected */
  315. goto exit_clear;
  316. if (usb_pipeout(ep->pipe)) {
  317. retire_outbound_urb(ep, ctx);
  318. /* can be stopped during retire callback */
  319. if (unlikely(!test_bit(EP_FLAG_RUNNING, &ep->flags)))
  320. goto exit_clear;
  321. if (snd_usb_endpoint_implicit_feedback_sink(ep)) {
  322. unsigned long flags;
  323. spin_lock_irqsave(&ep->lock, flags);
  324. list_add_tail(&ctx->ready_list, &ep->ready_playback_urbs);
  325. spin_unlock_irqrestore(&ep->lock, flags);
  326. queue_pending_output_urbs(ep);
  327. goto exit_clear;
  328. }
  329. prepare_outbound_urb(ep, ctx);
  330. } else {
  331. retire_inbound_urb(ep, ctx);
  332. /* can be stopped during retire callback */
  333. if (unlikely(!test_bit(EP_FLAG_RUNNING, &ep->flags)))
  334. goto exit_clear;
  335. prepare_inbound_urb(ep, ctx);
  336. }
  337. err = usb_submit_urb(urb, GFP_ATOMIC);
  338. if (err == 0)
  339. return;
  340. snd_printk(KERN_ERR "cannot submit urb (err = %d)\n", err);
  341. //snd_pcm_stop(substream, SNDRV_PCM_STATE_XRUN);
  342. exit_clear:
  343. clear_bit(ctx->index, &ep->active_mask);
  344. }
  345. /**
  346. * snd_usb_add_endpoint: Add an endpoint to an USB audio chip
  347. *
  348. * @chip: The chip
  349. * @alts: The USB host interface
  350. * @ep_num: The number of the endpoint to use
  351. * @direction: SNDRV_PCM_STREAM_PLAYBACK or SNDRV_PCM_STREAM_CAPTURE
  352. * @type: SND_USB_ENDPOINT_TYPE_DATA or SND_USB_ENDPOINT_TYPE_SYNC
  353. *
  354. * If the requested endpoint has not been added to the given chip before,
  355. * a new instance is created. Otherwise, a pointer to the previoulsy
  356. * created instance is returned. In case of any error, NULL is returned.
  357. *
  358. * New endpoints will be added to chip->ep_list and must be freed by
  359. * calling snd_usb_endpoint_free().
  360. */
  361. struct snd_usb_endpoint *snd_usb_add_endpoint(struct snd_usb_audio *chip,
  362. struct usb_host_interface *alts,
  363. int ep_num, int direction, int type)
  364. {
  365. struct snd_usb_endpoint *ep;
  366. int is_playback = direction == SNDRV_PCM_STREAM_PLAYBACK;
  367. if (WARN_ON(!alts))
  368. return NULL;
  369. mutex_lock(&chip->mutex);
  370. list_for_each_entry(ep, &chip->ep_list, list) {
  371. if (ep->ep_num == ep_num &&
  372. ep->iface == alts->desc.bInterfaceNumber &&
  373. ep->alt_idx == alts->desc.bAlternateSetting) {
  374. snd_printdd(KERN_DEBUG "Re-using EP %x in iface %d,%d @%p\n",
  375. ep_num, ep->iface, ep->alt_idx, ep);
  376. goto __exit_unlock;
  377. }
  378. }
  379. snd_printdd(KERN_DEBUG "Creating new %s %s endpoint #%x\n",
  380. is_playback ? "playback" : "capture",
  381. type == SND_USB_ENDPOINT_TYPE_DATA ? "data" : "sync",
  382. ep_num);
  383. ep = kzalloc(sizeof(*ep), GFP_KERNEL);
  384. if (!ep)
  385. goto __exit_unlock;
  386. ep->chip = chip;
  387. spin_lock_init(&ep->lock);
  388. ep->type = type;
  389. ep->ep_num = ep_num;
  390. ep->iface = alts->desc.bInterfaceNumber;
  391. ep->alt_idx = alts->desc.bAlternateSetting;
  392. INIT_LIST_HEAD(&ep->ready_playback_urbs);
  393. ep_num &= USB_ENDPOINT_NUMBER_MASK;
  394. if (is_playback)
  395. ep->pipe = usb_sndisocpipe(chip->dev, ep_num);
  396. else
  397. ep->pipe = usb_rcvisocpipe(chip->dev, ep_num);
  398. if (type == SND_USB_ENDPOINT_TYPE_SYNC) {
  399. if (get_endpoint(alts, 1)->bLength >= USB_DT_ENDPOINT_AUDIO_SIZE &&
  400. get_endpoint(alts, 1)->bRefresh >= 1 &&
  401. get_endpoint(alts, 1)->bRefresh <= 9)
  402. ep->syncinterval = get_endpoint(alts, 1)->bRefresh;
  403. else if (snd_usb_get_speed(chip->dev) == USB_SPEED_FULL)
  404. ep->syncinterval = 1;
  405. else if (get_endpoint(alts, 1)->bInterval >= 1 &&
  406. get_endpoint(alts, 1)->bInterval <= 16)
  407. ep->syncinterval = get_endpoint(alts, 1)->bInterval - 1;
  408. else
  409. ep->syncinterval = 3;
  410. ep->syncmaxsize = le16_to_cpu(get_endpoint(alts, 1)->wMaxPacketSize);
  411. }
  412. list_add_tail(&ep->list, &chip->ep_list);
  413. __exit_unlock:
  414. mutex_unlock(&chip->mutex);
  415. return ep;
  416. }
  417. /*
  418. * wait until all urbs are processed.
  419. */
  420. static int wait_clear_urbs(struct snd_usb_endpoint *ep)
  421. {
  422. unsigned long end_time = jiffies + msecs_to_jiffies(1000);
  423. int alive;
  424. do {
  425. alive = bitmap_weight(&ep->active_mask, ep->nurbs);
  426. if (!alive)
  427. break;
  428. schedule_timeout_uninterruptible(1);
  429. } while (time_before(jiffies, end_time));
  430. if (alive)
  431. snd_printk(KERN_ERR "timeout: still %d active urbs on EP #%x\n",
  432. alive, ep->ep_num);
  433. clear_bit(EP_FLAG_STOPPING, &ep->flags);
  434. return 0;
  435. }
  436. /* sync the pending stop operation;
  437. * this function itself doesn't trigger the stop operation
  438. */
  439. void snd_usb_endpoint_sync_pending_stop(struct snd_usb_endpoint *ep)
  440. {
  441. if (ep && test_bit(EP_FLAG_STOPPING, &ep->flags))
  442. wait_clear_urbs(ep);
  443. }
  444. /*
  445. * unlink active urbs.
  446. */
  447. static int deactivate_urbs(struct snd_usb_endpoint *ep, bool force)
  448. {
  449. unsigned int i;
  450. if (!force && ep->chip->shutdown) /* to be sure... */
  451. return -EBADFD;
  452. clear_bit(EP_FLAG_RUNNING, &ep->flags);
  453. INIT_LIST_HEAD(&ep->ready_playback_urbs);
  454. ep->next_packet_read_pos = 0;
  455. ep->next_packet_write_pos = 0;
  456. for (i = 0; i < ep->nurbs; i++) {
  457. if (test_bit(i, &ep->active_mask)) {
  458. if (!test_and_set_bit(i, &ep->unlink_mask)) {
  459. struct urb *u = ep->urb[i].urb;
  460. usb_unlink_urb(u);
  461. }
  462. }
  463. }
  464. return 0;
  465. }
  466. /*
  467. * release an endpoint's urbs
  468. */
  469. static void release_urbs(struct snd_usb_endpoint *ep, int force)
  470. {
  471. int i;
  472. /* route incoming urbs to nirvana */
  473. ep->retire_data_urb = NULL;
  474. ep->prepare_data_urb = NULL;
  475. /* stop urbs */
  476. deactivate_urbs(ep, force);
  477. wait_clear_urbs(ep);
  478. for (i = 0; i < ep->nurbs; i++)
  479. release_urb_ctx(&ep->urb[i]);
  480. if (ep->syncbuf)
  481. usb_free_coherent(ep->chip->dev, SYNC_URBS * 4,
  482. ep->syncbuf, ep->sync_dma);
  483. ep->syncbuf = NULL;
  484. ep->nurbs = 0;
  485. }
  486. /*
  487. * configure a data endpoint
  488. */
  489. static int data_ep_set_params(struct snd_usb_endpoint *ep,
  490. snd_pcm_format_t pcm_format,
  491. unsigned int channels,
  492. unsigned int period_bytes,
  493. unsigned int frames_per_period,
  494. unsigned int periods_per_buffer,
  495. struct audioformat *fmt,
  496. struct snd_usb_endpoint *sync_ep)
  497. {
  498. unsigned int maxsize, minsize, packs_per_ms, max_packs_per_urb;
  499. unsigned int max_packs_per_period, urbs_per_period, urb_packs;
  500. unsigned int max_urbs, i;
  501. int frame_bits = snd_pcm_format_physical_width(pcm_format) * channels;
  502. if (pcm_format == SNDRV_PCM_FORMAT_DSD_U16_LE && fmt->dsd_dop) {
  503. /*
  504. * When operating in DSD DOP mode, the size of a sample frame
  505. * in hardware differs from the actual physical format width
  506. * because we need to make room for the DOP markers.
  507. */
  508. frame_bits += channels << 3;
  509. }
  510. ep->datainterval = fmt->datainterval;
  511. ep->stride = frame_bits >> 3;
  512. ep->silence_value = pcm_format == SNDRV_PCM_FORMAT_U8 ? 0x80 : 0;
  513. /* assume max. frequency is 25% higher than nominal */
  514. ep->freqmax = ep->freqn + (ep->freqn >> 2);
  515. maxsize = ((ep->freqmax + 0xffff) * (frame_bits >> 3))
  516. >> (16 - ep->datainterval);
  517. /* but wMaxPacketSize might reduce this */
  518. if (ep->maxpacksize && ep->maxpacksize < maxsize) {
  519. /* whatever fits into a max. size packet */
  520. maxsize = ep->maxpacksize;
  521. ep->freqmax = (maxsize / (frame_bits >> 3))
  522. << (16 - ep->datainterval);
  523. }
  524. if (ep->fill_max)
  525. ep->curpacksize = ep->maxpacksize;
  526. else
  527. ep->curpacksize = maxsize;
  528. if (snd_usb_get_speed(ep->chip->dev) != USB_SPEED_FULL) {
  529. packs_per_ms = 8 >> ep->datainterval;
  530. max_packs_per_urb = MAX_PACKS_HS;
  531. } else {
  532. packs_per_ms = 1;
  533. max_packs_per_urb = MAX_PACKS;
  534. }
  535. if (sync_ep && !snd_usb_endpoint_implicit_feedback_sink(ep))
  536. max_packs_per_urb = min(max_packs_per_urb,
  537. 1U << sync_ep->syncinterval);
  538. max_packs_per_urb = max(1u, max_packs_per_urb >> ep->datainterval);
  539. /*
  540. * Capture endpoints need to use small URBs because there's no way
  541. * to tell in advance where the next period will end, and we don't
  542. * want the next URB to complete much after the period ends.
  543. *
  544. * Playback endpoints with implicit sync much use the same parameters
  545. * as their corresponding capture endpoint.
  546. */
  547. if (usb_pipein(ep->pipe) ||
  548. snd_usb_endpoint_implicit_feedback_sink(ep)) {
  549. /* make capture URBs <= 1 ms and smaller than a period */
  550. urb_packs = min(max_packs_per_urb, packs_per_ms);
  551. while (urb_packs > 1 && urb_packs * maxsize >= period_bytes)
  552. urb_packs >>= 1;
  553. ep->nurbs = MAX_URBS;
  554. /*
  555. * Playback endpoints without implicit sync are adjusted so that
  556. * a period fits as evenly as possible in the smallest number of
  557. * URBs. The total number of URBs is adjusted to the size of the
  558. * ALSA buffer, subject to the MAX_URBS and MAX_QUEUE limits.
  559. */
  560. } else {
  561. /* determine how small a packet can be */
  562. minsize = (ep->freqn >> (16 - ep->datainterval)) *
  563. (frame_bits >> 3);
  564. /* with sync from device, assume it can be 12% lower */
  565. if (sync_ep)
  566. minsize -= minsize >> 3;
  567. minsize = max(minsize, 1u);
  568. /* how many packets will contain an entire ALSA period? */
  569. max_packs_per_period = DIV_ROUND_UP(period_bytes, minsize);
  570. /* how many URBs will contain a period? */
  571. urbs_per_period = DIV_ROUND_UP(max_packs_per_period,
  572. max_packs_per_urb);
  573. /* how many packets are needed in each URB? */
  574. urb_packs = DIV_ROUND_UP(max_packs_per_period, urbs_per_period);
  575. /* limit the number of frames in a single URB */
  576. ep->max_urb_frames = DIV_ROUND_UP(frames_per_period,
  577. urbs_per_period);
  578. /* try to use enough URBs to contain an entire ALSA buffer */
  579. max_urbs = min((unsigned) MAX_URBS,
  580. MAX_QUEUE * packs_per_ms / urb_packs);
  581. ep->nurbs = min(max_urbs, urbs_per_period * periods_per_buffer);
  582. }
  583. /* allocate and initialize data urbs */
  584. for (i = 0; i < ep->nurbs; i++) {
  585. struct snd_urb_ctx *u = &ep->urb[i];
  586. u->index = i;
  587. u->ep = ep;
  588. u->packets = urb_packs;
  589. u->buffer_size = maxsize * u->packets;
  590. if (fmt->fmt_type == UAC_FORMAT_TYPE_II)
  591. u->packets++; /* for transfer delimiter */
  592. u->urb = usb_alloc_urb(u->packets, GFP_KERNEL);
  593. if (!u->urb)
  594. goto out_of_memory;
  595. u->urb->transfer_buffer =
  596. usb_alloc_coherent(ep->chip->dev, u->buffer_size,
  597. GFP_KERNEL, &u->urb->transfer_dma);
  598. if (!u->urb->transfer_buffer)
  599. goto out_of_memory;
  600. u->urb->pipe = ep->pipe;
  601. u->urb->transfer_flags = URB_NO_TRANSFER_DMA_MAP;
  602. u->urb->interval = 1 << ep->datainterval;
  603. u->urb->context = u;
  604. u->urb->complete = snd_complete_urb;
  605. INIT_LIST_HEAD(&u->ready_list);
  606. }
  607. return 0;
  608. out_of_memory:
  609. release_urbs(ep, 0);
  610. return -ENOMEM;
  611. }
  612. /*
  613. * configure a sync endpoint
  614. */
  615. static int sync_ep_set_params(struct snd_usb_endpoint *ep,
  616. struct audioformat *fmt)
  617. {
  618. int i;
  619. ep->syncbuf = usb_alloc_coherent(ep->chip->dev, SYNC_URBS * 4,
  620. GFP_KERNEL, &ep->sync_dma);
  621. if (!ep->syncbuf)
  622. return -ENOMEM;
  623. for (i = 0; i < SYNC_URBS; i++) {
  624. struct snd_urb_ctx *u = &ep->urb[i];
  625. u->index = i;
  626. u->ep = ep;
  627. u->packets = 1;
  628. u->urb = usb_alloc_urb(1, GFP_KERNEL);
  629. if (!u->urb)
  630. goto out_of_memory;
  631. u->urb->transfer_buffer = ep->syncbuf + i * 4;
  632. u->urb->transfer_dma = ep->sync_dma + i * 4;
  633. u->urb->transfer_buffer_length = 4;
  634. u->urb->pipe = ep->pipe;
  635. u->urb->transfer_flags = URB_NO_TRANSFER_DMA_MAP;
  636. u->urb->number_of_packets = 1;
  637. u->urb->interval = 1 << ep->syncinterval;
  638. u->urb->context = u;
  639. u->urb->complete = snd_complete_urb;
  640. }
  641. ep->nurbs = SYNC_URBS;
  642. return 0;
  643. out_of_memory:
  644. release_urbs(ep, 0);
  645. return -ENOMEM;
  646. }
  647. /**
  648. * snd_usb_endpoint_set_params: configure an snd_usb_endpoint
  649. *
  650. * @ep: the snd_usb_endpoint to configure
  651. * @pcm_format: the audio fomat.
  652. * @channels: the number of audio channels.
  653. * @period_bytes: the number of bytes in one alsa period.
  654. * @period_frames: the number of frames in one alsa period.
  655. * @buffer_periods: the number of periods in one alsa buffer.
  656. * @rate: the frame rate.
  657. * @fmt: the USB audio format information
  658. * @sync_ep: the sync endpoint to use, if any
  659. *
  660. * Determine the number of URBs to be used on this endpoint.
  661. * An endpoint must be configured before it can be started.
  662. * An endpoint that is already running can not be reconfigured.
  663. */
  664. int snd_usb_endpoint_set_params(struct snd_usb_endpoint *ep,
  665. snd_pcm_format_t pcm_format,
  666. unsigned int channels,
  667. unsigned int period_bytes,
  668. unsigned int period_frames,
  669. unsigned int buffer_periods,
  670. unsigned int rate,
  671. struct audioformat *fmt,
  672. struct snd_usb_endpoint *sync_ep)
  673. {
  674. int err;
  675. if (ep->use_count != 0) {
  676. snd_printk(KERN_WARNING "Unable to change format on ep #%x: already in use\n",
  677. ep->ep_num);
  678. return -EBUSY;
  679. }
  680. /* release old buffers, if any */
  681. release_urbs(ep, 0);
  682. ep->datainterval = fmt->datainterval;
  683. ep->maxpacksize = fmt->maxpacksize;
  684. ep->fill_max = !!(fmt->attributes & UAC_EP_CS_ATTR_FILL_MAX);
  685. if (snd_usb_get_speed(ep->chip->dev) == USB_SPEED_FULL)
  686. ep->freqn = get_usb_full_speed_rate(rate);
  687. else
  688. ep->freqn = get_usb_high_speed_rate(rate);
  689. /* calculate the frequency in 16.16 format */
  690. ep->freqm = ep->freqn;
  691. ep->freqshift = INT_MIN;
  692. ep->phase = 0;
  693. switch (ep->type) {
  694. case SND_USB_ENDPOINT_TYPE_DATA:
  695. err = data_ep_set_params(ep, pcm_format, channels,
  696. period_bytes, period_frames,
  697. buffer_periods, fmt, sync_ep);
  698. break;
  699. case SND_USB_ENDPOINT_TYPE_SYNC:
  700. err = sync_ep_set_params(ep, fmt);
  701. break;
  702. default:
  703. err = -EINVAL;
  704. }
  705. snd_printdd(KERN_DEBUG "Setting params for ep #%x (type %d, %d urbs), ret=%d\n",
  706. ep->ep_num, ep->type, ep->nurbs, err);
  707. return err;
  708. }
  709. /**
  710. * snd_usb_endpoint_start: start an snd_usb_endpoint
  711. *
  712. * @ep: the endpoint to start
  713. * @can_sleep: flag indicating whether the operation is executed in
  714. * non-atomic context
  715. *
  716. * A call to this function will increment the use count of the endpoint.
  717. * In case it is not already running, the URBs for this endpoint will be
  718. * submitted. Otherwise, this function does nothing.
  719. *
  720. * Must be balanced to calls of snd_usb_endpoint_stop().
  721. *
  722. * Returns an error if the URB submission failed, 0 in all other cases.
  723. */
  724. int snd_usb_endpoint_start(struct snd_usb_endpoint *ep, bool can_sleep)
  725. {
  726. int err;
  727. unsigned int i;
  728. if (ep->chip->shutdown)
  729. return -EBADFD;
  730. /* already running? */
  731. if (++ep->use_count != 1)
  732. return 0;
  733. /* just to be sure */
  734. deactivate_urbs(ep, false);
  735. if (can_sleep)
  736. wait_clear_urbs(ep);
  737. ep->active_mask = 0;
  738. ep->unlink_mask = 0;
  739. ep->phase = 0;
  740. snd_usb_endpoint_start_quirk(ep);
  741. /*
  742. * If this endpoint has a data endpoint as implicit feedback source,
  743. * don't start the urbs here. Instead, mark them all as available,
  744. * wait for the record urbs to return and queue the playback urbs
  745. * from that context.
  746. */
  747. set_bit(EP_FLAG_RUNNING, &ep->flags);
  748. if (snd_usb_endpoint_implicit_feedback_sink(ep)) {
  749. for (i = 0; i < ep->nurbs; i++) {
  750. struct snd_urb_ctx *ctx = ep->urb + i;
  751. list_add_tail(&ctx->ready_list, &ep->ready_playback_urbs);
  752. }
  753. return 0;
  754. }
  755. for (i = 0; i < ep->nurbs; i++) {
  756. struct urb *urb = ep->urb[i].urb;
  757. if (snd_BUG_ON(!urb))
  758. goto __error;
  759. if (usb_pipeout(ep->pipe)) {
  760. prepare_outbound_urb(ep, urb->context);
  761. } else {
  762. prepare_inbound_urb(ep, urb->context);
  763. }
  764. err = usb_submit_urb(urb, GFP_ATOMIC);
  765. if (err < 0) {
  766. snd_printk(KERN_ERR "cannot submit urb %d, error %d: %s\n",
  767. i, err, usb_error_string(err));
  768. goto __error;
  769. }
  770. set_bit(i, &ep->active_mask);
  771. }
  772. return 0;
  773. __error:
  774. clear_bit(EP_FLAG_RUNNING, &ep->flags);
  775. ep->use_count--;
  776. deactivate_urbs(ep, false);
  777. return -EPIPE;
  778. }
  779. /**
  780. * snd_usb_endpoint_stop: stop an snd_usb_endpoint
  781. *
  782. * @ep: the endpoint to stop (may be NULL)
  783. *
  784. * A call to this function will decrement the use count of the endpoint.
  785. * In case the last user has requested the endpoint stop, the URBs will
  786. * actually be deactivated.
  787. *
  788. * Must be balanced to calls of snd_usb_endpoint_start().
  789. *
  790. * The caller needs to synchronize the pending stop operation via
  791. * snd_usb_endpoint_sync_pending_stop().
  792. */
  793. void snd_usb_endpoint_stop(struct snd_usb_endpoint *ep)
  794. {
  795. if (!ep)
  796. return;
  797. if (snd_BUG_ON(ep->use_count == 0))
  798. return;
  799. if (--ep->use_count == 0) {
  800. deactivate_urbs(ep, false);
  801. ep->data_subs = NULL;
  802. ep->sync_slave = NULL;
  803. ep->retire_data_urb = NULL;
  804. ep->prepare_data_urb = NULL;
  805. set_bit(EP_FLAG_STOPPING, &ep->flags);
  806. }
  807. }
  808. /**
  809. * snd_usb_endpoint_deactivate: deactivate an snd_usb_endpoint
  810. *
  811. * @ep: the endpoint to deactivate
  812. *
  813. * If the endpoint is not currently in use, this functions will select the
  814. * alternate interface setting 0 for the interface of this endpoint.
  815. *
  816. * In case of any active users, this functions does nothing.
  817. *
  818. * Returns an error if usb_set_interface() failed, 0 in all other
  819. * cases.
  820. */
  821. int snd_usb_endpoint_deactivate(struct snd_usb_endpoint *ep)
  822. {
  823. if (!ep)
  824. return -EINVAL;
  825. deactivate_urbs(ep, true);
  826. wait_clear_urbs(ep);
  827. if (ep->use_count != 0)
  828. return 0;
  829. clear_bit(EP_FLAG_ACTIVATED, &ep->flags);
  830. return 0;
  831. }
  832. /**
  833. * snd_usb_endpoint_free: Free the resources of an snd_usb_endpoint
  834. *
  835. * @ep: the list header of the endpoint to free
  836. *
  837. * This function does not care for the endpoint's use count but will tear
  838. * down all the streaming URBs immediately and free all resources.
  839. */
  840. void snd_usb_endpoint_free(struct list_head *head)
  841. {
  842. struct snd_usb_endpoint *ep;
  843. ep = list_entry(head, struct snd_usb_endpoint, list);
  844. release_urbs(ep, 1);
  845. kfree(ep);
  846. }
  847. /**
  848. * snd_usb_handle_sync_urb: parse an USB sync packet
  849. *
  850. * @ep: the endpoint to handle the packet
  851. * @sender: the sending endpoint
  852. * @urb: the received packet
  853. *
  854. * This function is called from the context of an endpoint that received
  855. * the packet and is used to let another endpoint object handle the payload.
  856. */
  857. void snd_usb_handle_sync_urb(struct snd_usb_endpoint *ep,
  858. struct snd_usb_endpoint *sender,
  859. const struct urb *urb)
  860. {
  861. int shift;
  862. unsigned int f;
  863. unsigned long flags;
  864. snd_BUG_ON(ep == sender);
  865. /*
  866. * In case the endpoint is operating in implicit feedback mode, prepare
  867. * a new outbound URB that has the same layout as the received packet
  868. * and add it to the list of pending urbs. queue_pending_output_urbs()
  869. * will take care of them later.
  870. */
  871. if (snd_usb_endpoint_implicit_feedback_sink(ep) &&
  872. ep->use_count != 0) {
  873. /* implicit feedback case */
  874. int i, bytes = 0;
  875. struct snd_urb_ctx *in_ctx;
  876. struct snd_usb_packet_info *out_packet;
  877. in_ctx = urb->context;
  878. /* Count overall packet size */
  879. for (i = 0; i < in_ctx->packets; i++)
  880. if (urb->iso_frame_desc[i].status == 0)
  881. bytes += urb->iso_frame_desc[i].actual_length;
  882. /*
  883. * skip empty packets. At least M-Audio's Fast Track Ultra stops
  884. * streaming once it received a 0-byte OUT URB
  885. */
  886. if (bytes == 0)
  887. return;
  888. spin_lock_irqsave(&ep->lock, flags);
  889. out_packet = ep->next_packet + ep->next_packet_write_pos;
  890. /*
  891. * Iterate through the inbound packet and prepare the lengths
  892. * for the output packet. The OUT packet we are about to send
  893. * will have the same amount of payload bytes per stride as the
  894. * IN packet we just received. Since the actual size is scaled
  895. * by the stride, use the sender stride to calculate the length
  896. * in case the number of channels differ between the implicitly
  897. * fed-back endpoint and the synchronizing endpoint.
  898. */
  899. out_packet->packets = in_ctx->packets;
  900. for (i = 0; i < in_ctx->packets; i++) {
  901. if (urb->iso_frame_desc[i].status == 0)
  902. out_packet->packet_size[i] =
  903. urb->iso_frame_desc[i].actual_length / sender->stride;
  904. else
  905. out_packet->packet_size[i] = 0;
  906. }
  907. ep->next_packet_write_pos++;
  908. ep->next_packet_write_pos %= MAX_URBS;
  909. spin_unlock_irqrestore(&ep->lock, flags);
  910. queue_pending_output_urbs(ep);
  911. return;
  912. }
  913. /*
  914. * process after playback sync complete
  915. *
  916. * Full speed devices report feedback values in 10.14 format as samples
  917. * per frame, high speed devices in 16.16 format as samples per
  918. * microframe.
  919. *
  920. * Because the Audio Class 1 spec was written before USB 2.0, many high
  921. * speed devices use a wrong interpretation, some others use an
  922. * entirely different format.
  923. *
  924. * Therefore, we cannot predict what format any particular device uses
  925. * and must detect it automatically.
  926. */
  927. if (urb->iso_frame_desc[0].status != 0 ||
  928. urb->iso_frame_desc[0].actual_length < 3)
  929. return;
  930. f = le32_to_cpup(urb->transfer_buffer);
  931. if (urb->iso_frame_desc[0].actual_length == 3)
  932. f &= 0x00ffffff;
  933. else
  934. f &= 0x0fffffff;
  935. if (f == 0)
  936. return;
  937. if (unlikely(ep->freqshift == INT_MIN)) {
  938. /*
  939. * The first time we see a feedback value, determine its format
  940. * by shifting it left or right until it matches the nominal
  941. * frequency value. This assumes that the feedback does not
  942. * differ from the nominal value more than +50% or -25%.
  943. */
  944. shift = 0;
  945. while (f < ep->freqn - ep->freqn / 4) {
  946. f <<= 1;
  947. shift++;
  948. }
  949. while (f > ep->freqn + ep->freqn / 2) {
  950. f >>= 1;
  951. shift--;
  952. }
  953. ep->freqshift = shift;
  954. } else if (ep->freqshift >= 0)
  955. f <<= ep->freqshift;
  956. else
  957. f >>= -ep->freqshift;
  958. if (likely(f >= ep->freqn - ep->freqn / 8 && f <= ep->freqmax)) {
  959. /*
  960. * If the frequency looks valid, set it.
  961. * This value is referred to in prepare_playback_urb().
  962. */
  963. spin_lock_irqsave(&ep->lock, flags);
  964. ep->freqm = f;
  965. spin_unlock_irqrestore(&ep->lock, flags);
  966. } else {
  967. /*
  968. * Out of range; maybe the shift value is wrong.
  969. * Reset it so that we autodetect again the next time.
  970. */
  971. ep->freqshift = INT_MIN;
  972. }
  973. }