endpoint.c 33 KB

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