endpoint.c 31 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172
  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. goto exit_clear;
  317. /* device disconnected */
  318. if (unlikely(atomic_read(&ep->chip->shutdown)))
  319. goto exit_clear;
  320. if (usb_pipeout(ep->pipe)) {
  321. retire_outbound_urb(ep, ctx);
  322. /* can be stopped during retire callback */
  323. if (unlikely(!test_bit(EP_FLAG_RUNNING, &ep->flags)))
  324. goto exit_clear;
  325. if (snd_usb_endpoint_implicit_feedback_sink(ep)) {
  326. spin_lock_irqsave(&ep->lock, flags);
  327. list_add_tail(&ctx->ready_list, &ep->ready_playback_urbs);
  328. spin_unlock_irqrestore(&ep->lock, flags);
  329. queue_pending_output_urbs(ep);
  330. goto exit_clear;
  331. }
  332. prepare_outbound_urb(ep, ctx);
  333. } else {
  334. retire_inbound_urb(ep, ctx);
  335. /* can be stopped during retire callback */
  336. if (unlikely(!test_bit(EP_FLAG_RUNNING, &ep->flags)))
  337. goto exit_clear;
  338. prepare_inbound_urb(ep, ctx);
  339. }
  340. err = usb_submit_urb(urb, GFP_ATOMIC);
  341. if (err == 0)
  342. return;
  343. usb_audio_err(ep->chip, "cannot submit urb (err = %d)\n", err);
  344. if (ep->data_subs && ep->data_subs->pcm_substream) {
  345. substream = ep->data_subs->pcm_substream;
  346. snd_pcm_stop_xrun(substream);
  347. }
  348. exit_clear:
  349. clear_bit(ctx->index, &ep->active_mask);
  350. }
  351. /**
  352. * snd_usb_add_endpoint: Add an endpoint to an USB audio chip
  353. *
  354. * @chip: The chip
  355. * @alts: The USB host interface
  356. * @ep_num: The number of the endpoint to use
  357. * @direction: SNDRV_PCM_STREAM_PLAYBACK or SNDRV_PCM_STREAM_CAPTURE
  358. * @type: SND_USB_ENDPOINT_TYPE_DATA or SND_USB_ENDPOINT_TYPE_SYNC
  359. *
  360. * If the requested endpoint has not been added to the given chip before,
  361. * a new instance is created. Otherwise, a pointer to the previoulsy
  362. * created instance is returned. In case of any error, NULL is returned.
  363. *
  364. * New endpoints will be added to chip->ep_list and must be freed by
  365. * calling snd_usb_endpoint_free().
  366. */
  367. struct snd_usb_endpoint *snd_usb_add_endpoint(struct snd_usb_audio *chip,
  368. struct usb_host_interface *alts,
  369. int ep_num, int direction, int type)
  370. {
  371. struct snd_usb_endpoint *ep;
  372. int is_playback = direction == SNDRV_PCM_STREAM_PLAYBACK;
  373. if (WARN_ON(!alts))
  374. return NULL;
  375. mutex_lock(&chip->mutex);
  376. list_for_each_entry(ep, &chip->ep_list, list) {
  377. if (ep->ep_num == ep_num &&
  378. ep->iface == alts->desc.bInterfaceNumber &&
  379. ep->altsetting == alts->desc.bAlternateSetting) {
  380. usb_audio_dbg(ep->chip,
  381. "Re-using EP %x in iface %d,%d @%p\n",
  382. ep_num, ep->iface, ep->altsetting, ep);
  383. goto __exit_unlock;
  384. }
  385. }
  386. usb_audio_dbg(chip, "Creating new %s %s endpoint #%x\n",
  387. is_playback ? "playback" : "capture",
  388. type == SND_USB_ENDPOINT_TYPE_DATA ? "data" : "sync",
  389. ep_num);
  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->altsetting = 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. if (chip->usb_id == USB_ID(0x0644, 0x8038) /* TEAC UD-H01 */ &&
  419. ep->syncmaxsize == 4)
  420. ep->udh01_fb_quirk = 1;
  421. }
  422. list_add_tail(&ep->list, &chip->ep_list);
  423. __exit_unlock:
  424. mutex_unlock(&chip->mutex);
  425. return ep;
  426. }
  427. /*
  428. * wait until all urbs are processed.
  429. */
  430. static int wait_clear_urbs(struct snd_usb_endpoint *ep)
  431. {
  432. unsigned long end_time = jiffies + msecs_to_jiffies(1000);
  433. int alive;
  434. do {
  435. alive = bitmap_weight(&ep->active_mask, ep->nurbs);
  436. if (!alive)
  437. break;
  438. schedule_timeout_uninterruptible(1);
  439. } while (time_before(jiffies, end_time));
  440. if (alive)
  441. usb_audio_err(ep->chip,
  442. "timeout: still %d active urbs on EP #%x\n",
  443. alive, ep->ep_num);
  444. clear_bit(EP_FLAG_STOPPING, &ep->flags);
  445. return 0;
  446. }
  447. /* sync the pending stop operation;
  448. * this function itself doesn't trigger the stop operation
  449. */
  450. void snd_usb_endpoint_sync_pending_stop(struct snd_usb_endpoint *ep)
  451. {
  452. if (ep && test_bit(EP_FLAG_STOPPING, &ep->flags))
  453. wait_clear_urbs(ep);
  454. }
  455. /*
  456. * unlink active urbs.
  457. */
  458. static int deactivate_urbs(struct snd_usb_endpoint *ep, bool force)
  459. {
  460. unsigned int i;
  461. if (!force && atomic_read(&ep->chip->shutdown)) /* to be sure... */
  462. return -EBADFD;
  463. clear_bit(EP_FLAG_RUNNING, &ep->flags);
  464. INIT_LIST_HEAD(&ep->ready_playback_urbs);
  465. ep->next_packet_read_pos = 0;
  466. ep->next_packet_write_pos = 0;
  467. for (i = 0; i < ep->nurbs; i++) {
  468. if (test_bit(i, &ep->active_mask)) {
  469. if (!test_and_set_bit(i, &ep->unlink_mask)) {
  470. struct urb *u = ep->urb[i].urb;
  471. usb_unlink_urb(u);
  472. }
  473. }
  474. }
  475. return 0;
  476. }
  477. /*
  478. * release an endpoint's urbs
  479. */
  480. static void release_urbs(struct snd_usb_endpoint *ep, int force)
  481. {
  482. int i;
  483. /* route incoming urbs to nirvana */
  484. ep->retire_data_urb = NULL;
  485. ep->prepare_data_urb = NULL;
  486. /* stop urbs */
  487. deactivate_urbs(ep, force);
  488. wait_clear_urbs(ep);
  489. for (i = 0; i < ep->nurbs; i++)
  490. release_urb_ctx(&ep->urb[i]);
  491. if (ep->syncbuf)
  492. usb_free_coherent(ep->chip->dev, SYNC_URBS * 4,
  493. ep->syncbuf, ep->sync_dma);
  494. ep->syncbuf = NULL;
  495. ep->nurbs = 0;
  496. }
  497. /*
  498. * configure a data endpoint
  499. */
  500. static int data_ep_set_params(struct snd_usb_endpoint *ep,
  501. snd_pcm_format_t pcm_format,
  502. unsigned int channels,
  503. unsigned int period_bytes,
  504. unsigned int frames_per_period,
  505. unsigned int periods_per_buffer,
  506. struct audioformat *fmt,
  507. struct snd_usb_endpoint *sync_ep)
  508. {
  509. unsigned int maxsize, minsize, packs_per_ms, max_packs_per_urb;
  510. unsigned int max_packs_per_period, urbs_per_period, urb_packs;
  511. unsigned int max_urbs, i;
  512. int frame_bits = snd_pcm_format_physical_width(pcm_format) * channels;
  513. if (pcm_format == SNDRV_PCM_FORMAT_DSD_U16_LE && fmt->dsd_dop) {
  514. /*
  515. * When operating in DSD DOP mode, the size of a sample frame
  516. * in hardware differs from the actual physical format width
  517. * because we need to make room for the DOP markers.
  518. */
  519. frame_bits += channels << 3;
  520. }
  521. ep->datainterval = fmt->datainterval;
  522. ep->stride = frame_bits >> 3;
  523. ep->silence_value = pcm_format == SNDRV_PCM_FORMAT_U8 ? 0x80 : 0;
  524. /* assume max. frequency is 25% higher than nominal */
  525. ep->freqmax = ep->freqn + (ep->freqn >> 2);
  526. maxsize = ((ep->freqmax + 0xffff) * (frame_bits >> 3))
  527. >> (16 - ep->datainterval);
  528. /* but wMaxPacketSize might reduce this */
  529. if (ep->maxpacksize && ep->maxpacksize < maxsize) {
  530. /* whatever fits into a max. size packet */
  531. maxsize = ep->maxpacksize;
  532. ep->freqmax = (maxsize / (frame_bits >> 3))
  533. << (16 - ep->datainterval);
  534. }
  535. if (ep->fill_max)
  536. ep->curpacksize = ep->maxpacksize;
  537. else
  538. ep->curpacksize = maxsize;
  539. if (snd_usb_get_speed(ep->chip->dev) != USB_SPEED_FULL) {
  540. packs_per_ms = 8 >> ep->datainterval;
  541. max_packs_per_urb = MAX_PACKS_HS;
  542. } else {
  543. packs_per_ms = 1;
  544. max_packs_per_urb = MAX_PACKS;
  545. }
  546. if (sync_ep && !snd_usb_endpoint_implicit_feedback_sink(ep))
  547. max_packs_per_urb = min(max_packs_per_urb,
  548. 1U << sync_ep->syncinterval);
  549. max_packs_per_urb = max(1u, max_packs_per_urb >> ep->datainterval);
  550. /*
  551. * Capture endpoints need to use small URBs because there's no way
  552. * to tell in advance where the next period will end, and we don't
  553. * want the next URB to complete much after the period ends.
  554. *
  555. * Playback endpoints with implicit sync much use the same parameters
  556. * as their corresponding capture endpoint.
  557. */
  558. if (usb_pipein(ep->pipe) ||
  559. snd_usb_endpoint_implicit_feedback_sink(ep)) {
  560. urb_packs = packs_per_ms;
  561. /*
  562. * Wireless devices can poll at a max rate of once per 4ms.
  563. * For dataintervals less than 5, increase the packet count to
  564. * allow the host controller to use bursting to fill in the
  565. * gaps.
  566. */
  567. if (snd_usb_get_speed(ep->chip->dev) == USB_SPEED_WIRELESS) {
  568. int interval = ep->datainterval;
  569. while (interval < 5) {
  570. urb_packs <<= 1;
  571. ++interval;
  572. }
  573. }
  574. /* make capture URBs <= 1 ms and smaller than a period */
  575. urb_packs = min(max_packs_per_urb, urb_packs);
  576. while (urb_packs > 1 && urb_packs * maxsize >= period_bytes)
  577. urb_packs >>= 1;
  578. ep->nurbs = MAX_URBS;
  579. /*
  580. * Playback endpoints without implicit sync are adjusted so that
  581. * a period fits as evenly as possible in the smallest number of
  582. * URBs. The total number of URBs is adjusted to the size of the
  583. * ALSA buffer, subject to the MAX_URBS and MAX_QUEUE limits.
  584. */
  585. } else {
  586. /* determine how small a packet can be */
  587. minsize = (ep->freqn >> (16 - ep->datainterval)) *
  588. (frame_bits >> 3);
  589. /* with sync from device, assume it can be 12% lower */
  590. if (sync_ep)
  591. minsize -= minsize >> 3;
  592. minsize = max(minsize, 1u);
  593. /* how many packets will contain an entire ALSA period? */
  594. max_packs_per_period = DIV_ROUND_UP(period_bytes, minsize);
  595. /* how many URBs will contain a period? */
  596. urbs_per_period = DIV_ROUND_UP(max_packs_per_period,
  597. max_packs_per_urb);
  598. /* how many packets are needed in each URB? */
  599. urb_packs = DIV_ROUND_UP(max_packs_per_period, urbs_per_period);
  600. /* limit the number of frames in a single URB */
  601. ep->max_urb_frames = DIV_ROUND_UP(frames_per_period,
  602. urbs_per_period);
  603. /* try to use enough URBs to contain an entire ALSA buffer */
  604. max_urbs = min((unsigned) MAX_URBS,
  605. MAX_QUEUE * packs_per_ms / urb_packs);
  606. ep->nurbs = min(max_urbs, urbs_per_period * periods_per_buffer);
  607. }
  608. /* allocate and initialize data urbs */
  609. for (i = 0; i < ep->nurbs; i++) {
  610. struct snd_urb_ctx *u = &ep->urb[i];
  611. u->index = i;
  612. u->ep = ep;
  613. u->packets = urb_packs;
  614. u->buffer_size = maxsize * u->packets;
  615. if (fmt->fmt_type == UAC_FORMAT_TYPE_II)
  616. u->packets++; /* for transfer delimiter */
  617. u->urb = usb_alloc_urb(u->packets, GFP_KERNEL);
  618. if (!u->urb)
  619. goto out_of_memory;
  620. u->urb->transfer_buffer =
  621. usb_alloc_coherent(ep->chip->dev, u->buffer_size,
  622. GFP_KERNEL, &u->urb->transfer_dma);
  623. if (!u->urb->transfer_buffer)
  624. goto out_of_memory;
  625. u->urb->pipe = ep->pipe;
  626. u->urb->transfer_flags = URB_NO_TRANSFER_DMA_MAP;
  627. u->urb->interval = 1 << ep->datainterval;
  628. u->urb->context = u;
  629. u->urb->complete = snd_complete_urb;
  630. INIT_LIST_HEAD(&u->ready_list);
  631. }
  632. return 0;
  633. out_of_memory:
  634. release_urbs(ep, 0);
  635. return -ENOMEM;
  636. }
  637. /*
  638. * configure a sync endpoint
  639. */
  640. static int sync_ep_set_params(struct snd_usb_endpoint *ep)
  641. {
  642. int i;
  643. ep->syncbuf = usb_alloc_coherent(ep->chip->dev, SYNC_URBS * 4,
  644. GFP_KERNEL, &ep->sync_dma);
  645. if (!ep->syncbuf)
  646. return -ENOMEM;
  647. for (i = 0; i < SYNC_URBS; i++) {
  648. struct snd_urb_ctx *u = &ep->urb[i];
  649. u->index = i;
  650. u->ep = ep;
  651. u->packets = 1;
  652. u->urb = usb_alloc_urb(1, GFP_KERNEL);
  653. if (!u->urb)
  654. goto out_of_memory;
  655. u->urb->transfer_buffer = ep->syncbuf + i * 4;
  656. u->urb->transfer_dma = ep->sync_dma + i * 4;
  657. u->urb->transfer_buffer_length = 4;
  658. u->urb->pipe = ep->pipe;
  659. u->urb->transfer_flags = URB_NO_TRANSFER_DMA_MAP;
  660. u->urb->number_of_packets = 1;
  661. u->urb->interval = 1 << ep->syncinterval;
  662. u->urb->context = u;
  663. u->urb->complete = snd_complete_urb;
  664. }
  665. ep->nurbs = SYNC_URBS;
  666. return 0;
  667. out_of_memory:
  668. release_urbs(ep, 0);
  669. return -ENOMEM;
  670. }
  671. /**
  672. * snd_usb_endpoint_set_params: configure an snd_usb_endpoint
  673. *
  674. * @ep: the snd_usb_endpoint to configure
  675. * @pcm_format: the audio fomat.
  676. * @channels: the number of audio channels.
  677. * @period_bytes: the number of bytes in one alsa period.
  678. * @period_frames: the number of frames in one alsa period.
  679. * @buffer_periods: the number of periods in one alsa buffer.
  680. * @rate: the frame rate.
  681. * @fmt: the USB audio format information
  682. * @sync_ep: the sync endpoint to use, if any
  683. *
  684. * Determine the number of URBs to be used on this endpoint.
  685. * An endpoint must be configured before it can be started.
  686. * An endpoint that is already running can not be reconfigured.
  687. */
  688. int snd_usb_endpoint_set_params(struct snd_usb_endpoint *ep,
  689. snd_pcm_format_t pcm_format,
  690. unsigned int channels,
  691. unsigned int period_bytes,
  692. unsigned int period_frames,
  693. unsigned int buffer_periods,
  694. unsigned int rate,
  695. struct audioformat *fmt,
  696. struct snd_usb_endpoint *sync_ep)
  697. {
  698. int err;
  699. if (ep->use_count != 0) {
  700. usb_audio_warn(ep->chip,
  701. "Unable to change format on ep #%x: already in use\n",
  702. ep->ep_num);
  703. return -EBUSY;
  704. }
  705. /* release old buffers, if any */
  706. release_urbs(ep, 0);
  707. ep->datainterval = fmt->datainterval;
  708. ep->maxpacksize = fmt->maxpacksize;
  709. ep->fill_max = !!(fmt->attributes & UAC_EP_CS_ATTR_FILL_MAX);
  710. if (snd_usb_get_speed(ep->chip->dev) == USB_SPEED_FULL)
  711. ep->freqn = get_usb_full_speed_rate(rate);
  712. else
  713. ep->freqn = get_usb_high_speed_rate(rate);
  714. /* calculate the frequency in 16.16 format */
  715. ep->freqm = ep->freqn;
  716. ep->freqshift = INT_MIN;
  717. ep->phase = 0;
  718. switch (ep->type) {
  719. case SND_USB_ENDPOINT_TYPE_DATA:
  720. err = data_ep_set_params(ep, pcm_format, channels,
  721. period_bytes, period_frames,
  722. buffer_periods, fmt, sync_ep);
  723. break;
  724. case SND_USB_ENDPOINT_TYPE_SYNC:
  725. err = sync_ep_set_params(ep);
  726. break;
  727. default:
  728. err = -EINVAL;
  729. }
  730. usb_audio_dbg(ep->chip,
  731. "Setting params for ep #%x (type %d, %d urbs), ret=%d\n",
  732. ep->ep_num, ep->type, ep->nurbs, err);
  733. return err;
  734. }
  735. /**
  736. * snd_usb_endpoint_start: start an snd_usb_endpoint
  737. *
  738. * @ep: the endpoint to start
  739. * @can_sleep: flag indicating whether the operation is executed in
  740. * non-atomic context
  741. *
  742. * A call to this function will increment the use count of the endpoint.
  743. * In case it is not already running, the URBs for this endpoint will be
  744. * submitted. Otherwise, this function does nothing.
  745. *
  746. * Must be balanced to calls of snd_usb_endpoint_stop().
  747. *
  748. * Returns an error if the URB submission failed, 0 in all other cases.
  749. */
  750. int snd_usb_endpoint_start(struct snd_usb_endpoint *ep, bool can_sleep)
  751. {
  752. int err;
  753. unsigned int i;
  754. if (atomic_read(&ep->chip->shutdown))
  755. return -EBADFD;
  756. /* already running? */
  757. if (++ep->use_count != 1)
  758. return 0;
  759. /* just to be sure */
  760. deactivate_urbs(ep, false);
  761. if (can_sleep)
  762. wait_clear_urbs(ep);
  763. ep->active_mask = 0;
  764. ep->unlink_mask = 0;
  765. ep->phase = 0;
  766. snd_usb_endpoint_start_quirk(ep);
  767. /*
  768. * If this endpoint has a data endpoint as implicit feedback source,
  769. * don't start the urbs here. Instead, mark them all as available,
  770. * wait for the record urbs to return and queue the playback urbs
  771. * from that context.
  772. */
  773. set_bit(EP_FLAG_RUNNING, &ep->flags);
  774. if (snd_usb_endpoint_implicit_feedback_sink(ep)) {
  775. for (i = 0; i < ep->nurbs; i++) {
  776. struct snd_urb_ctx *ctx = ep->urb + i;
  777. list_add_tail(&ctx->ready_list, &ep->ready_playback_urbs);
  778. }
  779. return 0;
  780. }
  781. for (i = 0; i < ep->nurbs; i++) {
  782. struct urb *urb = ep->urb[i].urb;
  783. if (snd_BUG_ON(!urb))
  784. goto __error;
  785. if (usb_pipeout(ep->pipe)) {
  786. prepare_outbound_urb(ep, urb->context);
  787. } else {
  788. prepare_inbound_urb(ep, urb->context);
  789. }
  790. err = usb_submit_urb(urb, GFP_ATOMIC);
  791. if (err < 0) {
  792. usb_audio_err(ep->chip,
  793. "cannot submit urb %d, error %d: %s\n",
  794. i, err, usb_error_string(err));
  795. goto __error;
  796. }
  797. set_bit(i, &ep->active_mask);
  798. }
  799. return 0;
  800. __error:
  801. clear_bit(EP_FLAG_RUNNING, &ep->flags);
  802. ep->use_count--;
  803. deactivate_urbs(ep, false);
  804. return -EPIPE;
  805. }
  806. /**
  807. * snd_usb_endpoint_stop: stop an snd_usb_endpoint
  808. *
  809. * @ep: the endpoint to stop (may be NULL)
  810. *
  811. * A call to this function will decrement the use count of the endpoint.
  812. * In case the last user has requested the endpoint stop, the URBs will
  813. * actually be deactivated.
  814. *
  815. * Must be balanced to calls of snd_usb_endpoint_start().
  816. *
  817. * The caller needs to synchronize the pending stop operation via
  818. * snd_usb_endpoint_sync_pending_stop().
  819. */
  820. void snd_usb_endpoint_stop(struct snd_usb_endpoint *ep)
  821. {
  822. if (!ep)
  823. return;
  824. if (snd_BUG_ON(ep->use_count == 0))
  825. return;
  826. if (--ep->use_count == 0) {
  827. deactivate_urbs(ep, false);
  828. ep->data_subs = NULL;
  829. ep->sync_slave = NULL;
  830. ep->retire_data_urb = NULL;
  831. ep->prepare_data_urb = NULL;
  832. set_bit(EP_FLAG_STOPPING, &ep->flags);
  833. }
  834. }
  835. /**
  836. * snd_usb_endpoint_deactivate: deactivate an snd_usb_endpoint
  837. *
  838. * @ep: the endpoint to deactivate
  839. *
  840. * If the endpoint is not currently in use, this functions will
  841. * deactivate its associated URBs.
  842. *
  843. * In case of any active users, this functions does nothing.
  844. */
  845. void snd_usb_endpoint_deactivate(struct snd_usb_endpoint *ep)
  846. {
  847. if (!ep)
  848. return;
  849. if (ep->use_count != 0)
  850. return;
  851. deactivate_urbs(ep, true);
  852. wait_clear_urbs(ep);
  853. }
  854. /**
  855. * snd_usb_endpoint_release: Tear down an snd_usb_endpoint
  856. *
  857. * @ep: the endpoint to release
  858. *
  859. * This function does not care for the endpoint's use count but will tear
  860. * down all the streaming URBs immediately.
  861. */
  862. void snd_usb_endpoint_release(struct snd_usb_endpoint *ep)
  863. {
  864. release_urbs(ep, 1);
  865. }
  866. /**
  867. * snd_usb_endpoint_free: Free the resources of an snd_usb_endpoint
  868. *
  869. * @ep: the endpoint to free
  870. *
  871. * This free all resources of the given ep.
  872. */
  873. void snd_usb_endpoint_free(struct snd_usb_endpoint *ep)
  874. {
  875. kfree(ep);
  876. }
  877. /**
  878. * snd_usb_handle_sync_urb: parse an USB sync packet
  879. *
  880. * @ep: the endpoint to handle the packet
  881. * @sender: the sending endpoint
  882. * @urb: the received packet
  883. *
  884. * This function is called from the context of an endpoint that received
  885. * the packet and is used to let another endpoint object handle the payload.
  886. */
  887. void snd_usb_handle_sync_urb(struct snd_usb_endpoint *ep,
  888. struct snd_usb_endpoint *sender,
  889. const struct urb *urb)
  890. {
  891. int shift;
  892. unsigned int f;
  893. unsigned long flags;
  894. snd_BUG_ON(ep == sender);
  895. /*
  896. * In case the endpoint is operating in implicit feedback mode, prepare
  897. * a new outbound URB that has the same layout as the received packet
  898. * and add it to the list of pending urbs. queue_pending_output_urbs()
  899. * will take care of them later.
  900. */
  901. if (snd_usb_endpoint_implicit_feedback_sink(ep) &&
  902. ep->use_count != 0) {
  903. /* implicit feedback case */
  904. int i, bytes = 0;
  905. struct snd_urb_ctx *in_ctx;
  906. struct snd_usb_packet_info *out_packet;
  907. in_ctx = urb->context;
  908. /* Count overall packet size */
  909. for (i = 0; i < in_ctx->packets; i++)
  910. if (urb->iso_frame_desc[i].status == 0)
  911. bytes += urb->iso_frame_desc[i].actual_length;
  912. /*
  913. * skip empty packets. At least M-Audio's Fast Track Ultra stops
  914. * streaming once it received a 0-byte OUT URB
  915. */
  916. if (bytes == 0)
  917. return;
  918. spin_lock_irqsave(&ep->lock, flags);
  919. out_packet = ep->next_packet + ep->next_packet_write_pos;
  920. /*
  921. * Iterate through the inbound packet and prepare the lengths
  922. * for the output packet. The OUT packet we are about to send
  923. * will have the same amount of payload bytes per stride as the
  924. * IN packet we just received. Since the actual size is scaled
  925. * by the stride, use the sender stride to calculate the length
  926. * in case the number of channels differ between the implicitly
  927. * fed-back endpoint and the synchronizing endpoint.
  928. */
  929. out_packet->packets = in_ctx->packets;
  930. for (i = 0; i < in_ctx->packets; i++) {
  931. if (urb->iso_frame_desc[i].status == 0)
  932. out_packet->packet_size[i] =
  933. urb->iso_frame_desc[i].actual_length / sender->stride;
  934. else
  935. out_packet->packet_size[i] = 0;
  936. }
  937. ep->next_packet_write_pos++;
  938. ep->next_packet_write_pos %= MAX_URBS;
  939. spin_unlock_irqrestore(&ep->lock, flags);
  940. queue_pending_output_urbs(ep);
  941. return;
  942. }
  943. /*
  944. * process after playback sync complete
  945. *
  946. * Full speed devices report feedback values in 10.14 format as samples
  947. * per frame, high speed devices in 16.16 format as samples per
  948. * microframe.
  949. *
  950. * Because the Audio Class 1 spec was written before USB 2.0, many high
  951. * speed devices use a wrong interpretation, some others use an
  952. * entirely different format.
  953. *
  954. * Therefore, we cannot predict what format any particular device uses
  955. * and must detect it automatically.
  956. */
  957. if (urb->iso_frame_desc[0].status != 0 ||
  958. urb->iso_frame_desc[0].actual_length < 3)
  959. return;
  960. f = le32_to_cpup(urb->transfer_buffer);
  961. if (urb->iso_frame_desc[0].actual_length == 3)
  962. f &= 0x00ffffff;
  963. else
  964. f &= 0x0fffffff;
  965. if (f == 0)
  966. return;
  967. if (unlikely(sender->udh01_fb_quirk)) {
  968. /*
  969. * The TEAC UD-H01 firmware sometimes changes the feedback value
  970. * by +/- 0x1.0000.
  971. */
  972. if (f < ep->freqn - 0x8000)
  973. f += 0x10000;
  974. else if (f > ep->freqn + 0x8000)
  975. f -= 0x10000;
  976. } else if (unlikely(ep->freqshift == INT_MIN)) {
  977. /*
  978. * The first time we see a feedback value, determine its format
  979. * by shifting it left or right until it matches the nominal
  980. * frequency value. This assumes that the feedback does not
  981. * differ from the nominal value more than +50% or -25%.
  982. */
  983. shift = 0;
  984. while (f < ep->freqn - ep->freqn / 4) {
  985. f <<= 1;
  986. shift++;
  987. }
  988. while (f > ep->freqn + ep->freqn / 2) {
  989. f >>= 1;
  990. shift--;
  991. }
  992. ep->freqshift = shift;
  993. } else if (ep->freqshift >= 0)
  994. f <<= ep->freqshift;
  995. else
  996. f >>= -ep->freqshift;
  997. if (likely(f >= ep->freqn - ep->freqn / 8 && f <= ep->freqmax)) {
  998. /*
  999. * If the frequency looks valid, set it.
  1000. * This value is referred to in prepare_playback_urb().
  1001. */
  1002. spin_lock_irqsave(&ep->lock, flags);
  1003. ep->freqm = f;
  1004. spin_unlock_irqrestore(&ep->lock, flags);
  1005. } else {
  1006. /*
  1007. * Out of range; maybe the shift value is wrong.
  1008. * Reset it so that we autodetect again the next time.
  1009. */
  1010. ep->freqshift = INT_MIN;
  1011. }
  1012. }