endpoint.c 30 KB

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