endpoint.c 31 KB

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