endpoint.c 33 KB

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