message.c 67.3 KB
Newer Older
1
// SPDX-License-Identifier: GPL-2.0
Linus Torvalds's avatar
Linus Torvalds committed
2
3
/*
 * message.c - synchronous message handling
4
5
 *
 * Released under the GPLv2 only.
Linus Torvalds's avatar
Linus Torvalds committed
6
7
8
9
10
11
12
13
14
 */

#include <linux/pci.h>	/* for scatterlist macros */
#include <linux/usb.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/mm.h>
#include <linux/timer.h>
#include <linux/ctype.h>
15
#include <linux/nls.h>
Linus Torvalds's avatar
Linus Torvalds committed
16
#include <linux/device.h>
17
#include <linux/scatterlist.h>
18
#include <linux/usb/cdc.h>
19
#include <linux/usb/quirks.h>
20
#include <linux/usb/hcd.h>	/* for usbcore internals */
21
#include <linux/usb/of.h>
Linus Torvalds's avatar
Linus Torvalds committed
22
23
24
25
#include <asm/byteorder.h>

#include "usb.h"

26
27
static void cancel_async_set_config(struct usb_device *udev);

28
29
30
31
32
struct api_context {
	struct completion	done;
	int			status;
};

33
static void usb_api_blocking_completion(struct urb *urb)
Linus Torvalds's avatar
Linus Torvalds committed
34
{
35
36
37
38
	struct api_context *ctx = urb->context;

	ctx->status = urb->status;
	complete(&ctx->done);
Linus Torvalds's avatar
Linus Torvalds committed
39
40
41
}


42
43
44
45
46
47
48
/*
 * Starts urb and waits for completion or timeout. Note that this call
 * is NOT interruptible. Many device driver i/o requests should be
 * interruptible and therefore these drivers should implement their
 * own interruptible routines.
 */
static int usb_start_wait_urb(struct urb *urb, int timeout, int *actual_length)
49
{
50
	struct api_context ctx;
51
	unsigned long expire;
52
	int retval;
Linus Torvalds's avatar
Linus Torvalds committed
53

54
55
	init_completion(&ctx.done);
	urb->context = &ctx;
Linus Torvalds's avatar
Linus Torvalds committed
56
	urb->actual_length = 0;
57
58
	retval = usb_submit_urb(urb, GFP_NOIO);
	if (unlikely(retval))
59
		goto out;
Linus Torvalds's avatar
Linus Torvalds committed
60

61
	expire = timeout ? msecs_to_jiffies(timeout) : MAX_SCHEDULE_TIMEOUT;
62
63
64
	if (!wait_for_completion_timeout(&ctx.done, expire)) {
		usb_kill_urb(urb);
		retval = (ctx.status == -ENOENT ? -ETIMEDOUT : ctx.status);
65
66

		dev_dbg(&urb->dev->dev,
67
			"%s timed out on ep%d%s len=%u/%u\n",
68
			current->comm,
69
70
			usb_endpoint_num(&urb->ep->desc),
			usb_urb_dir_in(urb) ? "in" : "out",
71
72
73
			urb->actual_length,
			urb->transfer_buffer_length);
	} else
74
		retval = ctx.status;
75
out:
Linus Torvalds's avatar
Linus Torvalds committed
76
77
	if (actual_length)
		*actual_length = urb->actual_length;
78

Linus Torvalds's avatar
Linus Torvalds committed
79
	usb_free_urb(urb);
80
	return retval;
Linus Torvalds's avatar
Linus Torvalds committed
81
82
83
}

/*-------------------------------------------------------------------*/
84
/* returns status (negative) or length (positive) */
Linus Torvalds's avatar
Linus Torvalds committed
85
static int usb_internal_control_msg(struct usb_device *usb_dev,
86
				    unsigned int pipe,
Linus Torvalds's avatar
Linus Torvalds committed
87
88
89
90
91
92
93
94
95
96
				    struct usb_ctrlrequest *cmd,
				    void *data, int len, int timeout)
{
	struct urb *urb;
	int retv;
	int length;

	urb = usb_alloc_urb(0, GFP_NOIO);
	if (!urb)
		return -ENOMEM;
97

Linus Torvalds's avatar
Linus Torvalds committed
98
99
100
101
102
103
104
105
106
107
108
	usb_fill_control_urb(urb, usb_dev, pipe, (unsigned char *)cmd, data,
			     len, usb_api_blocking_completion, NULL);

	retv = usb_start_wait_urb(urb, timeout, &length);
	if (retv < 0)
		return retv;
	else
		return length;
}

/**
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
 * usb_control_msg - Builds a control urb, sends it off and waits for completion
 * @dev: pointer to the usb device to send the message to
 * @pipe: endpoint "pipe" to send the message to
 * @request: USB message request value
 * @requesttype: USB message request type value
 * @value: USB message value
 * @index: USB message index value
 * @data: pointer to the data to send
 * @size: length in bytes of the data to send
 * @timeout: time in msecs to wait for the message to complete before timing
 *	out (if 0 the wait is forever)
 *
 * Context: !in_interrupt ()
 *
 * This function sends a simple control message to a specified endpoint and
 * waits for the message to complete, or timeout.
 *
126
127
128
129
130
 * Don't use this function from within an interrupt context. If you need
 * an asynchronous message, or need to send a message from within interrupt
 * context, use usb_submit_urb(). If a thread in your driver uses this call,
 * make sure your disconnect() method can wait for it to complete. Since you
 * don't have a handle on the URB used, you can't cancel the request.
131
132
133
 *
 * Return: If successful, the number of bytes transferred. Otherwise, a negative
 * error number.
Linus Torvalds's avatar
Linus Torvalds committed
134
 */
135
136
137
int usb_control_msg(struct usb_device *dev, unsigned int pipe, __u8 request,
		    __u8 requesttype, __u16 value, __u16 index, void *data,
		    __u16 size, int timeout)
Linus Torvalds's avatar
Linus Torvalds committed
138
{
139
	struct usb_ctrlrequest *dr;
Linus Torvalds's avatar
Linus Torvalds committed
140
	int ret;
141
142

	dr = kmalloc(sizeof(struct usb_ctrlrequest), GFP_NOIO);
Linus Torvalds's avatar
Linus Torvalds committed
143
144
145
	if (!dr)
		return -ENOMEM;

146
	dr->bRequestType = requesttype;
Linus Torvalds's avatar
Linus Torvalds committed
147
	dr->bRequest = request;
148
149
150
	dr->wValue = cpu_to_le16(value);
	dr->wIndex = cpu_to_le16(index);
	dr->wLength = cpu_to_le16(size);
Linus Torvalds's avatar
Linus Torvalds committed
151
152
153

	ret = usb_internal_control_msg(dev, pipe, dr, data, size, timeout);

154
155
156
157
	/* Linger a bit, prior to the next control message. */
	if (dev->quirks & USB_QUIRK_DELAY_CTRL_MSG)
		msleep(200);

Linus Torvalds's avatar
Linus Torvalds committed
158
159
160
161
	kfree(dr);

	return ret;
}
162
EXPORT_SYMBOL_GPL(usb_control_msg);
Linus Torvalds's avatar
Linus Torvalds committed
163

164
165
166
167
168
169
/**
 * usb_interrupt_msg - Builds an interrupt urb, sends it off and waits for completion
 * @usb_dev: pointer to the usb device to send the message to
 * @pipe: endpoint "pipe" to send the message to
 * @data: pointer to the data to send
 * @len: length in bytes of the data to send
170
171
 * @actual_length: pointer to a location to put the actual length transferred
 *	in bytes
172
173
 * @timeout: time in msecs to wait for the message to complete before
 *	timing out (if 0 the wait is forever)
174
 *
175
176
177
178
179
 * Context: !in_interrupt ()
 *
 * This function sends a simple interrupt message to a specified endpoint and
 * waits for the message to complete, or timeout.
 *
180
181
182
183
184
 * Don't use this function from within an interrupt context. If you need
 * an asynchronous message, or need to send a message from within interrupt
 * context, use usb_submit_urb() If a thread in your driver uses this call,
 * make sure your disconnect() method can wait for it to complete. Since you
 * don't have a handle on the URB used, you can't cancel the request.
185
186
187
 *
 * Return:
 * If successful, 0. Otherwise a negative error number. The number of actual
188
 * bytes transferred will be stored in the @actual_length parameter.
189
190
191
192
193
194
195
196
 */
int usb_interrupt_msg(struct usb_device *usb_dev, unsigned int pipe,
		      void *data, int len, int *actual_length, int timeout)
{
	return usb_bulk_msg(usb_dev, pipe, data, len, actual_length, timeout);
}
EXPORT_SYMBOL_GPL(usb_interrupt_msg);

Linus Torvalds's avatar
Linus Torvalds committed
197
/**
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
 * usb_bulk_msg - Builds a bulk urb, sends it off and waits for completion
 * @usb_dev: pointer to the usb device to send the message to
 * @pipe: endpoint "pipe" to send the message to
 * @data: pointer to the data to send
 * @len: length in bytes of the data to send
 * @actual_length: pointer to a location to put the actual length transferred
 *	in bytes
 * @timeout: time in msecs to wait for the message to complete before
 *	timing out (if 0 the wait is forever)
 *
 * Context: !in_interrupt ()
 *
 * This function sends a simple bulk message to a specified endpoint
 * and waits for the message to complete, or timeout.
 *
213
214
215
216
217
 * Don't use this function from within an interrupt context. If you need
 * an asynchronous message, or need to send a message from within interrupt
 * context, use usb_submit_urb() If a thread in your driver uses this call,
 * make sure your disconnect() method can wait for it to complete. Since you
 * don't have a handle on the URB used, you can't cancel the request.
218
219
220
221
222
 *
 * Because there is no usb_interrupt_msg() and no USBDEVFS_INTERRUPT ioctl,
 * users are forced to abuse this routine by using it to submit URBs for
 * interrupt endpoints.  We will take the liberty of creating an interrupt URB
 * (with the default interval) if the target is an interrupt endpoint.
223
224
225
 *
 * Return:
 * If successful, 0. Otherwise a negative error number. The number of actual
226
 * bytes transferred will be stored in the @actual_length parameter.
227
 *
Linus Torvalds's avatar
Linus Torvalds committed
228
 */
229
230
int usb_bulk_msg(struct usb_device *usb_dev, unsigned int pipe,
		 void *data, int len, int *actual_length, int timeout)
Linus Torvalds's avatar
Linus Torvalds committed
231
232
{
	struct urb *urb;
233
	struct usb_host_endpoint *ep;
Linus Torvalds's avatar
Linus Torvalds committed
234

235
	ep = usb_pipe_endpoint(usb_dev, pipe);
236
	if (!ep || len < 0)
Linus Torvalds's avatar
Linus Torvalds committed
237
238
		return -EINVAL;

239
	urb = usb_alloc_urb(0, GFP_KERNEL);
Linus Torvalds's avatar
Linus Torvalds committed
240
241
242
	if (!urb)
		return -ENOMEM;

243
244
245
246
	if ((ep->desc.bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) ==
			USB_ENDPOINT_XFER_INT) {
		pipe = (pipe & ~(3 << 30)) | (PIPE_INTERRUPT << 30);
		usb_fill_int_urb(urb, usb_dev, pipe, data, len,
247
248
				usb_api_blocking_completion, NULL,
				ep->desc.bInterval);
249
250
251
	} else
		usb_fill_bulk_urb(urb, usb_dev, pipe, data, len,
				usb_api_blocking_completion, NULL);
Linus Torvalds's avatar
Linus Torvalds committed
252
253
254

	return usb_start_wait_urb(urb, timeout, actual_length);
}
255
EXPORT_SYMBOL_GPL(usb_bulk_msg);
Linus Torvalds's avatar
Linus Torvalds committed
256
257
258

/*-------------------------------------------------------------------*/

259
static void sg_clean(struct usb_sg_request *io)
Linus Torvalds's avatar
Linus Torvalds committed
260
261
262
{
	if (io->urbs) {
		while (io->entries--)
263
			usb_free_urb(io->urbs[io->entries]);
264
		kfree(io->urbs);
Linus Torvalds's avatar
Linus Torvalds committed
265
266
267
268
269
		io->urbs = NULL;
	}
	io->dev = NULL;
}

270
static void sg_complete(struct urb *urb)
Linus Torvalds's avatar
Linus Torvalds committed
271
{
272
	unsigned long flags;
273
	struct usb_sg_request *io = urb->context;
274
	int status = urb->status;
Linus Torvalds's avatar
Linus Torvalds committed
275

276
	spin_lock_irqsave(&io->lock, flags);
Linus Torvalds's avatar
Linus Torvalds committed
277
278
279
280
281
282
283
284
285
286
287
288
289

	/* In 2.5 we require hcds' endpoint queues not to progress after fault
	 * reports, until the completion callback (this!) returns.  That lets
	 * device driver code (like this routine) unlink queued urbs first,
	 * if it needs to, since the HC won't work on them at all.  So it's
	 * not possible for page N+1 to overwrite page N, and so on.
	 *
	 * That's only for "hard" faults; "soft" faults (unlinks) sometimes
	 * complete before the HCD can get requests away from hardware,
	 * though never during cleanup after a hard fault.
	 */
	if (io->status
			&& (io->status != -ECONNRESET
290
				|| status != -ECONNRESET)
Linus Torvalds's avatar
Linus Torvalds committed
291
			&& urb->actual_length) {
292
		dev_err(io->dev->bus->controller,
Linus Torvalds's avatar
Linus Torvalds committed
293
294
			"dev %s ep%d%s scatterlist error %d/%d\n",
			io->dev->devpath,
295
296
			usb_endpoint_num(&urb->ep->desc),
			usb_urb_dir_in(urb) ? "in" : "out",
297
			status, io->status);
298
		/* BUG (); */
Linus Torvalds's avatar
Linus Torvalds committed
299
300
	}

301
302
	if (io->status == 0 && status && status != -ECONNRESET) {
		int i, found, retval;
Linus Torvalds's avatar
Linus Torvalds committed
303

304
		io->status = status;
Linus Torvalds's avatar
Linus Torvalds committed
305
306
307
308
309

		/* the previous urbs, and this one, completed already.
		 * unlink pending urbs so they won't rx/tx bad data.
		 * careful: unlink can sometimes be synchronous...
		 */
310
		spin_unlock_irqrestore(&io->lock, flags);
Linus Torvalds's avatar
Linus Torvalds committed
311
		for (i = 0, found = 0; i < io->entries; i++) {
312
			if (!io->urbs[i])
Linus Torvalds's avatar
Linus Torvalds committed
313
314
				continue;
			if (found) {
315
				usb_block_urb(io->urbs[i]);
316
				retval = usb_unlink_urb(io->urbs[i]);
317
318
				if (retval != -EINPROGRESS &&
				    retval != -ENODEV &&
319
320
				    retval != -EBUSY &&
				    retval != -EIDRM)
321
					dev_err(&io->dev->dev,
Linus Torvalds's avatar
Linus Torvalds committed
322
						"%s, unlink --> %d\n",
323
						__func__, retval);
324
			} else if (urb == io->urbs[i])
Linus Torvalds's avatar
Linus Torvalds committed
325
326
				found = 1;
		}
327
		spin_lock_irqsave(&io->lock, flags);
Linus Torvalds's avatar
Linus Torvalds committed
328
329
330
331
332
333
	}

	/* on the last completion, signal usb_sg_wait() */
	io->bytes += urb->actual_length;
	io->count--;
	if (!io->count)
334
		complete(&io->complete);
Linus Torvalds's avatar
Linus Torvalds committed
335

336
	spin_unlock_irqrestore(&io->lock, flags);
Linus Torvalds's avatar
Linus Torvalds committed
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
}


/**
 * usb_sg_init - initializes scatterlist-based bulk/interrupt I/O request
 * @io: request block being initialized.  until usb_sg_wait() returns,
 *	treat this as a pointer to an opaque block of memory,
 * @dev: the usb device that will send or receive the data
 * @pipe: endpoint "pipe" used to transfer the data
 * @period: polling rate for interrupt endpoints, in frames or
 * 	(for high speed endpoints) microframes; ignored for bulk
 * @sg: scatterlist entries
 * @nents: how many entries in the scatterlist
 * @length: how many bytes to send from the scatterlist, or zero to
 * 	send every byte identified in the list.
 * @mem_flags: SLAB_* flags affecting memory allocations in this call
 *
354
355
356
 * This initializes a scatter/gather request, allocating resources such as
 * I/O mappings and urb memory (except maybe memory used by USB controller
 * drivers).
Linus Torvalds's avatar
Linus Torvalds committed
357
358
359
360
361
362
363
 *
 * The request must be issued using usb_sg_wait(), which waits for the I/O to
 * complete (or to be canceled) and then cleans up all resources allocated by
 * usb_sg_init().
 *
 * The request may be canceled with usb_sg_cancel(), either before or after
 * usb_sg_wait() is called.
364
365
 *
 * Return: Zero for success, else a negative errno value.
Linus Torvalds's avatar
Linus Torvalds committed
366
 */
367
368
369
int usb_sg_init(struct usb_sg_request *io, struct usb_device *dev,
		unsigned pipe, unsigned	period, struct scatterlist *sg,
		int nents, size_t length, gfp_t mem_flags)
Linus Torvalds's avatar
Linus Torvalds committed
370
{
371
372
	int i;
	int urb_flags;
373
	int use_sg;
Linus Torvalds's avatar
Linus Torvalds committed
374
375

	if (!io || !dev || !sg
376
377
			|| usb_pipecontrol(pipe)
			|| usb_pipeisoc(pipe)
Linus Torvalds's avatar
Linus Torvalds committed
378
379
380
			|| nents <= 0)
		return -EINVAL;

381
	spin_lock_init(&io->lock);
Linus Torvalds's avatar
Linus Torvalds committed
382
383
384
	io->dev = dev;
	io->pipe = pipe;

385
	if (dev->bus->sg_tablesize > 0) {
386
		use_sg = true;
Alan Stern's avatar
Alan Stern committed
387
		io->entries = 1;
388
389
	} else {
		use_sg = false;
Alan Stern's avatar
Alan Stern committed
390
		io->entries = nents;
391
	}
Alan Stern's avatar
Alan Stern committed
392
393

	/* initialize all the urbs we'll use */
394
	io->urbs = kmalloc_array(io->entries, sizeof(*io->urbs), mem_flags);
Linus Torvalds's avatar
Linus Torvalds committed
395
396
397
	if (!io->urbs)
		goto nomem;

Alan Stern's avatar
Alan Stern committed
398
	urb_flags = URB_NO_INTERRUPT;
399
	if (usb_pipein(pipe))
Linus Torvalds's avatar
Linus Torvalds committed
400
401
		urb_flags |= URB_SHORT_NOT_OK;

Alan Stern's avatar
Alan Stern committed
402
403
404
	for_each_sg(sg, sg, io->entries, i) {
		struct urb *urb;
		unsigned len;
405

Alan Stern's avatar
Alan Stern committed
406
407
408
409
		urb = usb_alloc_urb(0, mem_flags);
		if (!urb) {
			io->entries = i;
			goto nomem;
410
		}
Alan Stern's avatar
Alan Stern committed
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
		io->urbs[i] = urb;

		urb->dev = NULL;
		urb->pipe = pipe;
		urb->interval = period;
		urb->transfer_flags = urb_flags;
		urb->complete = sg_complete;
		urb->context = io;
		urb->sg = sg;

		if (use_sg) {
			/* There is no single transfer buffer */
			urb->transfer_buffer = NULL;
			urb->num_sgs = nents;

			/* A length of zero means transfer the whole sg list */
			len = length;
			if (len == 0) {
Alan Stern's avatar
Alan Stern committed
429
430
431
432
433
				struct scatterlist	*sg2;
				int			j;

				for_each_sg(sg, sg2, nents, j)
					len += sg2->length;
434
			}
Alan Stern's avatar
Alan Stern committed
435
		} else {
436
			/*
437
438
439
			 * Some systems can't use DMA; they use PIO instead.
			 * For their sakes, transfer_buffer is set whenever
			 * possible.
440
			 */
441
			if (!PageHighMem(sg_page(sg)))
Alan Stern's avatar
Alan Stern committed
442
				urb->transfer_buffer = sg_virt(sg);
443
			else
Alan Stern's avatar
Alan Stern committed
444
				urb->transfer_buffer = NULL;
445

446
			len = sg->length;
447
			if (length) {
448
				len = min_t(size_t, len, length);
449
450
451
452
				length -= len;
				if (length == 0)
					io->entries = i + 1;
			}
Linus Torvalds's avatar
Linus Torvalds committed
453
		}
Alan Stern's avatar
Alan Stern committed
454
		urb->transfer_buffer_length = len;
Linus Torvalds's avatar
Linus Torvalds committed
455
	}
Alan Stern's avatar
Alan Stern committed
456
	io->urbs[--i]->transfer_flags &= ~URB_NO_INTERRUPT;
Linus Torvalds's avatar
Linus Torvalds committed
457
458

	/* transaction state */
459
	io->count = io->entries;
Linus Torvalds's avatar
Linus Torvalds committed
460
461
	io->status = 0;
	io->bytes = 0;
462
	init_completion(&io->complete);
Linus Torvalds's avatar
Linus Torvalds committed
463
464
465
	return 0;

nomem:
466
	sg_clean(io);
Linus Torvalds's avatar
Linus Torvalds committed
467
468
	return -ENOMEM;
}
469
EXPORT_SYMBOL_GPL(usb_sg_init);
Linus Torvalds's avatar
Linus Torvalds committed
470
471
472
473
474
475
476
477
478
479
480
481
482

/**
 * usb_sg_wait - synchronously execute scatter/gather request
 * @io: request block handle, as initialized with usb_sg_init().
 * 	some fields become accessible when this call returns.
 * Context: !in_interrupt ()
 *
 * This function blocks until the specified I/O operation completes.  It
 * leverages the grouping of the related I/O requests to get good transfer
 * rates, by queueing the requests.  At higher speeds, such queuing can
 * significantly improve USB throughput.
 *
 * There are three kinds of completion for this function.
483
 *
Linus Torvalds's avatar
Linus Torvalds committed
484
485
486
487
488
 * (1) success, where io->status is zero.  The number of io->bytes
 *     transferred is as requested.
 * (2) error, where io->status is a negative errno value.  The number
 *     of io->bytes transferred before the error is usually less
 *     than requested, and can be nonzero.
489
 * (3) cancellation, a type of error with status -ECONNRESET that
Linus Torvalds's avatar
Linus Torvalds committed
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
 *     is initiated by usb_sg_cancel().
 *
 * When this function returns, all memory allocated through usb_sg_init() or
 * this call will have been freed.  The request block parameter may still be
 * passed to usb_sg_cancel(), or it may be freed.  It could also be
 * reinitialized and then reused.
 *
 * Data Transfer Rates:
 *
 * Bulk transfers are valid for full or high speed endpoints.
 * The best full speed data rate is 19 packets of 64 bytes each
 * per frame, or 1216 bytes per millisecond.
 * The best high speed data rate is 13 packets of 512 bytes each
 * per microframe, or 52 KBytes per millisecond.
 *
 * The reason to use interrupt transfers through this API would most likely
 * be to reserve high speed bandwidth, where up to 24 KBytes per millisecond
 * could be transferred.  That capability is less useful for low or full
 * speed interrupt endpoints, which allow at most one packet per millisecond,
 * of at most 8 or 64 bytes (respectively).
510
511
512
513
 *
 * It is not necessary to call this function to reserve bandwidth for devices
 * under an xHCI host controller, as the bandwidth is reserved when the
 * configuration or interface alt setting is selected.
Linus Torvalds's avatar
Linus Torvalds committed
514
 */
515
void usb_sg_wait(struct usb_sg_request *io)
Linus Torvalds's avatar
Linus Torvalds committed
516
{
517
518
	int i;
	int entries = io->entries;
Linus Torvalds's avatar
Linus Torvalds committed
519
520

	/* queue the urbs.  */
521
	spin_lock_irq(&io->lock);
522
523
	i = 0;
	while (i < entries && !io->status) {
524
		int retval;
Linus Torvalds's avatar
Linus Torvalds committed
525

526
527
		io->urbs[i]->dev = io->dev;
		spin_unlock_irq(&io->lock);
528
529
530

		retval = usb_submit_urb(io->urbs[i], GFP_NOIO);

Linus Torvalds's avatar
Linus Torvalds committed
531
532
		switch (retval) {
			/* maybe we retrying will recover */
533
		case -ENXIO:	/* hc didn't queue this one */
Linus Torvalds's avatar
Linus Torvalds committed
534
535
536
		case -EAGAIN:
		case -ENOMEM:
			retval = 0;
537
			yield();
Linus Torvalds's avatar
Linus Torvalds committed
538
539
540
541
542
543
544
545
546
			break;

			/* no error? continue immediately.
			 *
			 * NOTE: to work better with UHCI (4K I/O buffer may
			 * need 3K of TDs) it may be good to limit how many
			 * URBs are queued at once; N milliseconds?
			 */
		case 0:
547
			++i;
548
			cpu_relax();
Linus Torvalds's avatar
Linus Torvalds committed
549
550
551
552
			break;

			/* fail any uncompleted urbs */
		default:
553
554
			io->urbs[i]->status = retval;
			dev_dbg(&io->dev->dev, "%s, submit --> %d\n",
555
				__func__, retval);
556
			usb_sg_cancel(io);
Linus Torvalds's avatar
Linus Torvalds committed
557
		}
558
		spin_lock_irq(&io->lock);
Linus Torvalds's avatar
Linus Torvalds committed
559
560
561
562
563
		if (retval && (io->status == 0 || io->status == -ECONNRESET))
			io->status = retval;
	}
	io->count -= entries - i;
	if (io->count == 0)
564
565
		complete(&io->complete);
	spin_unlock_irq(&io->lock);
Linus Torvalds's avatar
Linus Torvalds committed
566
567
568
569
570

	/* OK, yes, this could be packaged as non-blocking.
	 * So could the submit loop above ... but it's easier to
	 * solve neither problem than to solve both!
	 */
571
	wait_for_completion(&io->complete);
Linus Torvalds's avatar
Linus Torvalds committed
572

573
	sg_clean(io);
Linus Torvalds's avatar
Linus Torvalds committed
574
}
575
EXPORT_SYMBOL_GPL(usb_sg_wait);
Linus Torvalds's avatar
Linus Torvalds committed
576
577
578
579
580
581
582
583
584

/**
 * usb_sg_cancel - stop scatter/gather i/o issued by usb_sg_wait()
 * @io: request block, initialized with usb_sg_init()
 *
 * This stops a request after it has been started by usb_sg_wait().
 * It can also prevents one initialized by usb_sg_init() from starting,
 * so that call just frees resources allocated to the request.
 */
585
void usb_sg_cancel(struct usb_sg_request *io)
Linus Torvalds's avatar
Linus Torvalds committed
586
{
587
	unsigned long flags;
588
	int i, retval;
Linus Torvalds's avatar
Linus Torvalds committed
589

590
	spin_lock_irqsave(&io->lock, flags);
591
592
593
594
595
596
597
	if (io->status) {
		spin_unlock_irqrestore(&io->lock, flags);
		return;
	}
	/* shut everything down */
	io->status = -ECONNRESET;
	spin_unlock_irqrestore(&io->lock, flags);
Linus Torvalds's avatar
Linus Torvalds committed
598

599
600
	for (i = io->entries - 1; i >= 0; --i) {
		usb_block_urb(io->urbs[i]);
Linus Torvalds's avatar
Linus Torvalds committed
601

602
603
604
605
606
607
608
		retval = usb_unlink_urb(io->urbs[i]);
		if (retval != -EINPROGRESS
		    && retval != -ENODEV
		    && retval != -EBUSY
		    && retval != -EIDRM)
			dev_warn(&io->dev->dev, "%s, unlink --> %d\n",
				 __func__, retval);
Linus Torvalds's avatar
Linus Torvalds committed
609
610
	}
}
611
EXPORT_SYMBOL_GPL(usb_sg_cancel);
Linus Torvalds's avatar
Linus Torvalds committed
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633

/*-------------------------------------------------------------------*/

/**
 * usb_get_descriptor - issues a generic GET_DESCRIPTOR request
 * @dev: the device whose descriptor is being retrieved
 * @type: the descriptor type (USB_DT_*)
 * @index: the number of the descriptor
 * @buf: where to put the descriptor
 * @size: how big is "buf"?
 * Context: !in_interrupt ()
 *
 * Gets a USB descriptor.  Convenience functions exist to simplify
 * getting some types of descriptors.  Use
 * usb_get_string() or usb_string() for USB_DT_STRING.
 * Device (USB_DT_DEVICE) and configuration descriptors (USB_DT_CONFIG)
 * are part of the device structure.
 * In addition to a number of USB-standard descriptors, some
 * devices also use class-specific or vendor-specific descriptors.
 *
 * This call is synchronous, and may not be used in an interrupt context.
 *
634
 * Return: The number of bytes received on success, or else the status code
Linus Torvalds's avatar
Linus Torvalds committed
635
636
 * returned by the underlying usb_control_msg() call.
 */
637
638
int usb_get_descriptor(struct usb_device *dev, unsigned char type,
		       unsigned char index, void *buf, int size)
Linus Torvalds's avatar
Linus Torvalds committed
639
640
641
{
	int i;
	int result;
642
643

	memset(buf, 0, size);	/* Make sure we parse really received data */
Linus Torvalds's avatar
Linus Torvalds committed
644
645

	for (i = 0; i < 3; ++i) {
646
		/* retry on length 0 or error; some devices are flakey */
Linus Torvalds's avatar
Linus Torvalds committed
647
648
649
650
		result = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
				USB_REQ_GET_DESCRIPTOR, USB_DIR_IN,
				(type << 8) + index, 0, buf, size,
				USB_CTRL_GET_TIMEOUT);
651
		if (result <= 0 && result != -ETIMEDOUT)
Linus Torvalds's avatar
Linus Torvalds committed
652
653
			continue;
		if (result > 1 && ((u8 *)buf)[1] != type) {
654
			result = -ENODATA;
Linus Torvalds's avatar
Linus Torvalds committed
655
656
657
658
659
660
			continue;
		}
		break;
	}
	return result;
}
661
EXPORT_SYMBOL_GPL(usb_get_descriptor);
Linus Torvalds's avatar
Linus Torvalds committed
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681

/**
 * usb_get_string - gets a string descriptor
 * @dev: the device whose string descriptor is being retrieved
 * @langid: code for language chosen (from string descriptor zero)
 * @index: the number of the descriptor
 * @buf: where to put the string
 * @size: how big is "buf"?
 * Context: !in_interrupt ()
 *
 * Retrieves a string, encoded using UTF-16LE (Unicode, 16 bits per character,
 * in little-endian byte order).
 * The usb_string() function will often be a convenient way to turn
 * these strings into kernel-printable form.
 *
 * Strings may be referenced in device, configuration, interface, or other
 * descriptors, and could also be used in vendor-specific ways.
 *
 * This call is synchronous, and may not be used in an interrupt context.
 *
682
 * Return: The number of bytes received on success, or else the status code
Linus Torvalds's avatar
Linus Torvalds committed
683
684
 * returned by the underlying usb_control_msg() call.
 */
685
686
static int usb_get_string(struct usb_device *dev, unsigned short langid,
			  unsigned char index, void *buf, int size)
Linus Torvalds's avatar
Linus Torvalds committed
687
688
689
690
691
692
693
694
695
696
{
	int i;
	int result;

	for (i = 0; i < 3; ++i) {
		/* retry on length 0 or stall; some devices are flakey */
		result = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
			USB_REQ_GET_DESCRIPTOR, USB_DIR_IN,
			(USB_DT_STRING << 8) + index, langid, buf, size,
			USB_CTRL_GET_TIMEOUT);
697
698
699
700
701
702
703
		if (result == 0 || result == -EPIPE)
			continue;
		if (result > 1 && ((u8 *) buf)[1] != USB_DT_STRING) {
			result = -ENODATA;
			continue;
		}
		break;
Linus Torvalds's avatar
Linus Torvalds committed
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
	}
	return result;
}

static void usb_try_string_workarounds(unsigned char *buf, int *length)
{
	int newlength, oldlength = *length;

	for (newlength = 2; newlength + 1 < oldlength; newlength += 2)
		if (!isprint(buf[newlength]) || buf[newlength + 1])
			break;

	if (newlength > 2) {
		buf[0] = newlength;
		*length = newlength;
	}
}

static int usb_string_sub(struct usb_device *dev, unsigned int langid,
723
			  unsigned int index, unsigned char *buf)
Linus Torvalds's avatar
Linus Torvalds committed
724
725
726
727
728
{
	int rc;

	/* Try to read the string descriptor by asking for the maximum
	 * possible number of bytes */
729
730
731
732
	if (dev->quirks & USB_QUIRK_STRING_FETCH_255)
		rc = -EIO;
	else
		rc = usb_get_string(dev, langid, index, buf, 255);
Linus Torvalds's avatar
Linus Torvalds committed
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758

	/* If that failed try to read the descriptor length, then
	 * ask for just that many bytes */
	if (rc < 2) {
		rc = usb_get_string(dev, langid, index, buf, 2);
		if (rc == 2)
			rc = usb_get_string(dev, langid, index, buf, buf[0]);
	}

	if (rc >= 2) {
		if (!buf[0] && !buf[1])
			usb_try_string_workarounds(buf, &rc);

		/* There might be extra junk at the end of the descriptor */
		if (buf[0] < rc)
			rc = buf[0];

		rc = rc - (rc & 1); /* force a multiple of two */
	}

	if (rc < 2)
		rc = (rc < 0 ? rc : -EINVAL);

	return rc;
}

Daniel Mack's avatar
Daniel Mack committed
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
static int usb_get_langid(struct usb_device *dev, unsigned char *tbuf)
{
	int err;

	if (dev->have_langid)
		return 0;

	if (dev->string_langid < 0)
		return -EPIPE;

	err = usb_string_sub(dev, 0, 0, tbuf);

	/* If the string was reported but is malformed, default to english
	 * (0x0409) */
	if (err == -ENODATA || (err > 0 && err < 4)) {
		dev->string_langid = 0x0409;
		dev->have_langid = 1;
		dev_err(&dev->dev,
777
			"language id specifier not provided by device, defaulting to English\n");
Daniel Mack's avatar
Daniel Mack committed
778
779
780
781
782
783
784
		return 0;
	}

	/* In case of all other errors, we assume the device is not able to
	 * deal with strings at all. Set string_langid to -1 in order to
	 * prevent any string to be retrieved from the device */
	if (err < 0) {
785
		dev_info(&dev->dev, "string descriptor 0 read error: %d\n",
Daniel Mack's avatar
Daniel Mack committed
786
787
788
789
790
791
792
793
794
795
796
797
798
					err);
		dev->string_langid = -1;
		return -EPIPE;
	}

	/* always use the first langid listed */
	dev->string_langid = tbuf[2] | (tbuf[3] << 8);
	dev->have_langid = 1;
	dev_dbg(&dev->dev, "default language 0x%04x\n",
				dev->string_langid);
	return 0;
}

Linus Torvalds's avatar
Linus Torvalds committed
799
/**
800
 * usb_string - returns UTF-8 version of a string descriptor
Linus Torvalds's avatar
Linus Torvalds committed
801
802
803
804
805
 * @dev: the device whose string descriptor is being retrieved
 * @index: the number of the descriptor
 * @buf: where to put the string
 * @size: how big is "buf"?
 * Context: !in_interrupt ()
806
 *
Linus Torvalds's avatar
Linus Torvalds committed
807
 * This converts the UTF-16LE encoded strings returned by devices, from
808
809
 * usb_get_string_descriptor(), to null-terminated UTF-8 encoded ones
 * that are more usable in most kernel contexts.  Note that this function
Linus Torvalds's avatar
Linus Torvalds committed
810
811
812
813
 * chooses strings in the first language supported by the device.
 *
 * This call is synchronous, and may not be used in an interrupt context.
 *
814
 * Return: length of the string (>= 0) or usb_control_msg status (< 0).
Linus Torvalds's avatar
Linus Torvalds committed
815
816
817
818
819
820
821
822
 */
int usb_string(struct usb_device *dev, int index, char *buf, size_t size)
{
	unsigned char *tbuf;
	int err;

	if (dev->state == USB_STATE_SUSPENDED)
		return -EHOSTUNREACH;
823
	if (size <= 0 || !buf)
Linus Torvalds's avatar
Linus Torvalds committed
824
825
		return -EINVAL;
	buf[0] = 0;
826
827
	if (index <= 0 || index >= 256)
		return -EINVAL;
Alan Stern's avatar
Alan Stern committed
828
	tbuf = kmalloc(256, GFP_NOIO);
Linus Torvalds's avatar
Linus Torvalds committed
829
830
831
	if (!tbuf)
		return -ENOMEM;

Daniel Mack's avatar
Daniel Mack committed
832
833
834
	err = usb_get_langid(dev, tbuf);
	if (err < 0)
		goto errout;
835

Linus Torvalds's avatar
Linus Torvalds committed
836
837
838
839
840
	err = usb_string_sub(dev, dev->string_langid, index, tbuf);
	if (err < 0)
		goto errout;

	size--;		/* leave room for trailing NULL char in output buffer */
Alan Stern's avatar
Alan Stern committed
841
842
	err = utf16s_to_utf8s((wchar_t *) &tbuf[2], (err - 2) / 2,
			UTF16_LITTLE_ENDIAN, buf, size);
843
	buf[err] = 0;
Linus Torvalds's avatar
Linus Torvalds committed
844
845

	if (tbuf[1] != USB_DT_STRING)
846
847
848
		dev_dbg(&dev->dev,
			"wrong descriptor type %02x for string %d (\"%s\")\n",
			tbuf[1], index, buf);
Linus Torvalds's avatar
Linus Torvalds committed
849
850
851
852
853

 errout:
	kfree(tbuf);
	return err;
}
854
EXPORT_SYMBOL_GPL(usb_string);
Linus Torvalds's avatar
Linus Torvalds committed
855

856
857
858
/* one UTF-8-encoded 16-bit character has at most three bytes */
#define MAX_USB_STRING_SIZE (127 * 3 + 1)

859
860
861
862
863
/**
 * usb_cache_string - read a string descriptor and cache it for later use
 * @udev: the device whose string descriptor is being read
 * @index: the descriptor index
 *
864
865
 * Return: A pointer to a kmalloc'ed buffer containing the descriptor string,
 * or %NULL if the index is 0 or the string could not be read.
866
867
868
869
870
871
872
 */
char *usb_cache_string(struct usb_device *udev, int index)
{
	char *buf;
	char *smallbuf = NULL;
	int len;

873
874
875
	if (index <= 0)
		return NULL;

876
	buf = kmalloc(MAX_USB_STRING_SIZE, GFP_NOIO);
877
	if (buf) {
878
		len = usb_string(udev, index, buf, MAX_USB_STRING_SIZE);
879
		if (len > 0) {
880
			smallbuf = kmalloc(++len, GFP_NOIO);
881
			if (!smallbuf)
882
883
884
885
886
887
888
889
				return buf;
			memcpy(smallbuf, buf, len);
		}
		kfree(buf);
	}
	return smallbuf;
}

Linus Torvalds's avatar
Linus Torvalds committed
890
891
892
893
894
895
896
/*
 * usb_get_device_descriptor - (re)reads the device descriptor (usbcore)
 * @dev: the device whose device descriptor is being updated
 * @size: how much of the descriptor to read
 * Context: !in_interrupt ()
 *
 * Updates the copy of the device descriptor stored in the device structure,
897
 * which dedicates space for this purpose.
Linus Torvalds's avatar
Linus Torvalds committed
898
899
900
901
902
903
904
 *
 * Not exported, only for use by the core.  If drivers really want to read
 * the device descriptor directly, they can call usb_get_descriptor() with
 * type = USB_DT_DEVICE and index = 0.
 *
 * This call is synchronous, and may not be used in an interrupt context.
 *
905
 * Return: The number of bytes received on success, or else the status code
Linus Torvalds's avatar
Linus Torvalds committed
906
907
908
909
910
911
912
913
914
915
916
917
918
919
 * returned by the underlying usb_control_msg() call.
 */
int usb_get_device_descriptor(struct usb_device *dev, unsigned int size)
{
	struct usb_device_descriptor *desc;
	int ret;

	if (size > sizeof(*desc))
		return -EINVAL;
	desc = kmalloc(sizeof(*desc), GFP_NOIO);
	if (!desc)
		return -ENOMEM;

	ret = usb_get_descriptor(dev, USB_DT_DEVICE, 0, desc, size);
920
	if (ret >= 0)
Linus Torvalds's avatar
Linus Torvalds committed
921
922
923
924
925
		memcpy(&dev->descriptor, desc, size);
	kfree(desc);
	return ret;
}

926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
/*
 * usb_set_isoch_delay - informs the device of the packet transmit delay
 * @dev: the device whose delay is to be informed
 * Context: !in_interrupt()
 *
 * Since this is an optional request, we don't bother if it fails.
 */
int usb_set_isoch_delay(struct usb_device *dev)
{
	/* skip hub devices */
	if (dev->descriptor.bDeviceClass == USB_CLASS_HUB)
		return 0;

	/* skip non-SS/non-SSP devices */
	if (dev->speed < USB_SPEED_SUPER)
		return 0;

	return usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
			USB_REQ_SET_ISOCH_DELAY,
			USB_DIR_OUT | USB_TYPE_STANDARD | USB_RECIP_DEVICE,
946
			dev->hub_delay, 0, NULL, 0,
947
948
949
			USB_CTRL_SET_TIMEOUT);
}

Linus Torvalds's avatar
Linus Torvalds committed
950
951
952
/**
 * usb_get_status - issues a GET_STATUS call
 * @dev: the device whose status is being checked
953
 * @recip: USB_RECIP_*; for device, interface, or endpoint
954
 * @type: USB_STATUS_TYPE_*; for standard or PTM status types
Linus Torvalds's avatar
Linus Torvalds committed
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
 * @target: zero (for device), else interface or endpoint number
 * @data: pointer to two bytes of bitmap data
 * Context: !in_interrupt ()
 *
 * Returns device, interface, or endpoint status.  Normally only of
 * interest to see if the device is self powered, or has enabled the
 * remote wakeup facility; or whether a bulk or interrupt endpoint
 * is halted ("stalled").
 *
 * Bits in these status bitmaps are set using the SET_FEATURE request,
 * and cleared using the CLEAR_FEATURE request.  The usb_clear_halt()
 * function should be used to clear halt ("stall") status.
 *
 * This call is synchronous, and may not be used in an interrupt context.
 *
970
971
 * Returns 0 and the status value in *@data (in host byte order) on success,
 * or else the status code from the underlying usb_control_msg() call.
Linus Torvalds's avatar
Linus Torvalds committed
972
 */
973
974
int usb_get_status(struct usb_device *dev, int recip, int type, int target,
		void *data)
Linus Torvalds's avatar
Linus Torvalds committed
975
976
{
	int ret;
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
	void *status;
	int length;

	switch (type) {
	case USB_STATUS_TYPE_STANDARD:
		length = 2;
		break;
	case USB_STATUS_TYPE_PTM:
		if (recip != USB_RECIP_DEVICE)
			return -EINVAL;

		length = 4;
		break;
	default:
		return -EINVAL;
	}
Linus Torvalds's avatar
Linus Torvalds committed
993

994
	status =  kmalloc(length, GFP_KERNEL);
Linus Torvalds's avatar
Linus Torvalds committed
995
996
997
998
	if (!status)
		return -ENOMEM;

	ret = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
999
		USB_REQ_GET_STATUS, USB_DIR_IN | recip, USB_STATUS_TYPE_STANDARD,
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
		target, status, length, USB_CTRL_GET_TIMEOUT);

	switch (ret) {
	case 4:
		if (type != USB_STATUS_TYPE_PTM) {
			ret = -EIO;
			break;
		}

		*(u32 *) data = le32_to_cpu(*(__le32 *) status);
1010
		ret = 0;
1011
1012
1013
1014
1015
1016
		break;
	case 2:
		if (type != USB_STATUS_TYPE_STANDARD) {
			ret = -EIO;
			break;
		}
Linus Torvalds's avatar
Linus Torvalds committed
1017

1018
		*(u16 *) data = le16_to_cpu(*(__le16 *) status);
1019
		ret = 0;
1020
1021
		break;
	default:
1022
1023
		ret = -EIO;
	}
1024

Linus Torvalds's avatar
Linus Torvalds committed
1025
1026
1027
	kfree(status);
	return ret;
}
1028
EXPORT_SYMBOL_GPL(usb_get_status);
Linus Torvalds's avatar
Linus Torvalds committed
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049

/**
 * usb_clear_halt - tells device to clear endpoint halt/stall condition
 * @dev: device whose endpoint is halted
 * @pipe: endpoint "pipe" being cleared
 * Context: !in_interrupt ()
 *
 * This is used to clear halt conditions for bulk and interrupt endpoints,
 * as reported by URB completion status.  Endpoints that are halted are
 * sometimes referred to as being "stalled".  Such endpoints are unable
 * to transmit or receive data until the halt status is cleared.  Any URBs
 * queued for such an endpoint should normally be unlinked by the driver
 * before clearing the halt condition, as described in sections 5.7.5
 * and 5.8.5 of the USB 2.0 spec.
 *
 * Note that control and isochronous endpoints don't halt, although control
 * endpoints report "protocol stall" (for unsupported requests) using the
 * same status code used to report a true stall.
 *
 * This call is synchronous, and may not be used in an interrupt context.
 *
1050
 * Return: Zero on success, or else the status code returned by the
Linus Torvalds's avatar
Linus Torvalds committed
1051
1052
1053
1054
1055
1056
 * underlying usb_control_msg() call.
 */
int usb_clear_halt(struct usb_device *dev, int pipe)
{
	int result;
	int endp = usb_pipeendpoint(pipe);
1057
1058

	if (usb_pipein(pipe))
Linus Torvalds's avatar
Linus Torvalds committed
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
		endp |= USB_DIR_IN;

	/* we don't care if it wasn't halted first. in fact some devices
	 * (like some ibmcam model 1 units) seem to expect hosts to make
	 * this request for iso endpoints, which can't halt!
	 */
	result = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
		USB_REQ_CLEAR_FEATURE, USB_RECIP_ENDPOINT,
		USB_ENDPOINT_HALT, endp, NULL, 0,
		USB_CTRL_SET_TIMEOUT);

	/* don't un-halt or force to DATA0 except on success */
	if (result < 0)
		return result;

	/* NOTE:  seems like Microsoft and Apple don't bother verifying
	 * the clear "took", so some devices could lock up if you check...
	 * such as the Hagiwara FlashGate DUAL.  So we won't bother.
	 *
	 * NOTE:  make sure the logic here doesn't diverge much from
	 * the copy in usb-storage, for as long as we need two copies.
	 */

1082
	usb_reset_endpoint(dev, endp);
Linus Torvalds's avatar
Linus Torvalds committed
1083
1084
1085

	return 0;
}
1086
EXPORT_SYMBOL_GPL(usb_clear_halt);
Linus Torvalds's avatar
Linus Torvalds committed
1087

Alan Stern's avatar
Alan Stern committed
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
static int create_intf_ep_devs(struct usb_interface *intf)
{
	struct usb_device *udev = interface_to_usbdev(intf);
	struct usb_host_interface *alt = intf->cur_altsetting;
	int i;

	if (intf->ep_devs_created || intf->unregistering)
		return 0;

	for (i = 0; i < alt->desc.bNumEndpoints; ++i)
		(void) usb_create_ep_devs(&intf->dev, &alt->endpoint[i], udev);
	intf->ep_devs_created = 1;
	return 0;
}

static void remove_intf_ep_devs(struct usb_interface *intf)
{
	struct usb_host_interface *alt = intf->cur_altsetting;
	int i;

	if (!intf->ep_devs_created)
		return;

	for (i = 0; i < alt->desc.bNumEndpoints; ++i)
		usb_remove_ep_devs(&alt->endpoint[i]);
	intf->ep_devs_created = 0;
}

Linus Torvalds's avatar
Linus Torvalds committed
1116
1117
1118
1119
1120
/**
 * usb_disable_endpoint -- Disable an endpoint by address
 * @dev: the device whose endpoint is being disabled
 * @epaddr: the endpoint's address.  Endpoint number for output,
 *	endpoint number + USB_DIR_IN for input
1121
1122
 * @reset_hardware: flag to erase any endpoint state stored in the
 *	controller hardware
Linus Torvalds's avatar
Linus Torvalds committed
1123
 *
1124
1125
1126
 * Disables the endpoint for URB submission and nukes all pending URBs.
 * If @reset_hardware is set then also deallocates hcd/hardware state
 * for the endpoint.
Linus Torvalds's avatar
Linus Torvalds committed
1127
 */
1128
1129
void usb_disable_endpoint(struct usb_device *dev, unsigned int epaddr,
		bool reset_hardware)
Linus Torvalds's avatar
Linus Torvalds committed
1130
1131
1132
1133
1134
1135
1136
1137
1138
{
	unsigned int epnum = epaddr & USB_ENDPOINT_NUMBER_MASK;
	struct usb_host_endpoint *ep;

	if (!dev)
		return;

	if (usb_endpoint_out(epaddr)) {
		ep = dev->ep_out[epnum];
1139
1140
		if (reset_hardware)
			dev->ep_out[epnum] = NULL;
Linus Torvalds's avatar
Linus Torvalds committed
1141
1142
	} else {
		ep = dev->ep_in[epnum];
1143
1144
		if (reset_hardware)
			dev->ep_in[epnum] = NULL;
Linus Torvalds's avatar
Linus Torvalds committed
1145
	}
Alan Stern's avatar
Alan Stern committed
1146
1147
	if (ep) {
		ep->enabled = 0;
1148
		usb_hcd_flush_endpoint(dev, ep);
1149
1150
		if (reset_hardware)
			usb_hcd_disable_endpoint(dev, ep);
Alan Stern's avatar
Alan Stern committed
1151
	}
Linus Torvalds's avatar
Linus Torvalds committed
1152
1153
}

1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
/**
 * usb_reset_endpoint - Reset an endpoint's state.
 * @dev: the device whose endpoint is to be reset
 * @epaddr: the endpoint's address.  Endpoint number for output,
 *	endpoint number + USB_DIR_IN for input
 *
 * Resets any host-side endpoint state such as the toggle bit,
 * sequence number or current window.
 */
void usb_reset_endpoint(struct usb_device *dev, unsigned int epaddr)
{
	unsigned int epnum = epaddr & USB_ENDPOINT_NUMBER_MASK;
	struct usb_host_endpoint *ep;

	if (usb_endpoint_out(epaddr))
		ep = dev->ep_out[epnum];
	else
		ep = dev->ep_in[epnum];
	if (ep)
		usb_hcd_reset_endpoint(dev, ep);
}
EXPORT_SYMBOL_GPL(usb_reset_endpoint);


Linus Torvalds's avatar
Linus Torvalds committed
1178
1179
1180
1181
/**
 * usb_disable_interface -- Disable all endpoints for an interface
 * @dev: the device whose interface is being disabled
 * @intf: pointer to the interface descriptor
1182
1183
 * @reset_hardware: flag to erase any endpoint state stored in the
 *	controller hardware
Linus Torvalds's avatar
Linus Torvalds committed
1184
1185
1186
 *
 * Disables all the endpoints for the interface's current altsetting.
 */
1187
1188
void usb_disable_interface(struct usb_device *dev, struct usb_interface *intf,
		bool reset_hardware)
Linus Torvalds's avatar
Linus Torvalds committed
1189
1190
1191
1192
1193
1194
{
	struct usb_host_interface *alt = intf->cur_altsetting;
	int i;

	for (i = 0; i < alt->desc.bNumEndpoints; ++i) {
		usb_disable_endpoint(dev,
1195
1196
				alt->endpoint[i].desc.bEndpointAddress,
				reset_hardware);
Linus Torvalds's avatar
Linus Torvalds committed
1197
1198
1199
	}
}

1200
/**
Linus Torvalds's avatar
Linus Torvalds committed
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
 * usb_disable_device - Disable all the endpoints for a USB device
 * @dev: the device whose endpoints are being disabled
 * @skip_ep0: 0 to disable endpoint 0, 1 to skip it.
 *
 * Disables all the device's endpoints, potentially including endpoint 0.
 * Deallocates hcd/hardware state for the endpoints (nuking all or most
 * pending urbs) and usbcore state for the interfaces, so that usbcore
 * must usb_set_configuration() before any interfaces could be used.
 */
void usb_disable_device(struct usb_device *dev, int skip_ep0)
{
	int i;
1213
	struct usb_hcd *hcd = bus_to_hcd(dev->bus);
Linus Torvalds's avatar
Linus Torvalds committed
1214
1215
1216
1217
1218

	/* getting rid of interfaces will disconnect
	 * any drivers bound to them (a key side effect)
	 */
	if (dev->actconfig) {
1219
1220
1221
1222
1223
1224
1225
1226
		/*
		 * FIXME: In order to avoid self-deadlock involving the
		 * bandwidth_mutex, we have to mark all the interfaces
		 * before unregistering any of them.
		 */
		for (i = 0; i < dev->actconfig->desc.bNumInterfaces; i++)
			dev->actconfig->interface[i]->unregistering = 1;

Linus Torvalds's avatar
Linus Torvalds committed
1227
1228
1229
		for (i = 0; i < dev->actconfig->desc.bNumInterfaces; i++) {
			struct usb_interface	*interface;

1230
			/* remove this interface if it has been registered */
Linus Torvalds's avatar
Linus Torvalds committed
1231
			interface = dev->actconfig->interface[i];
1232
			if (!device_is_registered(&interface->dev))
1233
				continue;
1234
			dev_dbg(&dev->dev, "unregistering interface %s\n",
1235
				dev_name(&interface->dev));
Alan Stern's avatar
Alan Stern committed
1236
			remove_intf_ep_devs(interface);
1237
			device_del(&interface->dev);
Linus Torvalds's avatar
Linus Torvalds committed
1238
1239
1240
1241
1242
1243
		}

		/* Now that the interfaces are unbound, nobody should
		 * try to access them.
		 */
		for (i = 0; i < dev->actconfig->desc.bNumInterfaces; i++) {
1244
			put_device(&dev->actconfig->interface[i]->dev);
Linus Torvalds's avatar
Linus Torvalds committed
1245
1246
			dev->actconfig->interface[i] = NULL;
		}
1247

1248
		usb_disable_usb2_hardware_lpm(dev);
1249
		usb_unlocked_disable_lpm(dev);
1250
		usb_disable_ltm(dev);
1251

Linus Torvalds's avatar
Linus Torvalds committed
1252
1253
1254
1255
		dev->actconfig = NULL;
		if (dev->state == USB_STATE_CONFIGURED)
			usb_set_device_state(dev, USB_STATE_ADDRESS);
	}
1256
1257
1258

	dev_dbg(&dev->dev, "%s nuking %s URBs\n", __func__,
		skip_ep0 ? "non-ep0" : "all");
1259
1260
1261
1262
1263
1264
1265
	if (hcd->driver->check_bandwidth) {
		/* First pass: Cancel URBs, leave endpoint pointers intact. */
		for (i = skip_ep0; i < 16; ++i) {
			usb_disable_endpoint(dev, i, false);
			usb_disable_endpoint(dev, i + USB_DIR_IN, false);
		}
		/* Remove endpoints from the host controller internal state */
1266
		mutex_lock(hcd->bandwidth_mutex);
1267
		usb_hcd_alloc_bandwidth(dev, NULL, NULL, NULL);
1268
		mutex_unlock(hcd->bandwidth_mutex);
1269
1270
		/* Second pass: remove endpoint pointers */
	}
1271
1272
1273
1274
	for (i = skip_ep0; i < 16; ++i) {
		usb_disable_endpoint(dev, i, true);
		usb_disable_endpoint(dev, i + USB_DIR_IN, true);
	}
Linus Torvalds's avatar
Linus Torvalds committed
1275
1276
}

1277
/**
Linus Torvalds's avatar
Linus Torvalds committed
1278
1279
1280
 * usb_enable_endpoint - Enable an endpoint for USB communications
 * @dev: the device whose interface is being enabled
 * @ep: the endpoint
1281
 * @reset_ep: flag to reset the endpoint state
Linus Torvalds's avatar
Linus Torvalds committed
1282
 *
1283
 * Resets the endpoint state if asked, and sets dev->ep_{in,out} pointers.
Linus Torvalds's avatar
Linus Torvalds committed
1284
1285
 * For control endpoints, both the input and output sides are handled.
 */
1286
void usb_enable_endpoint(struct usb_device *dev, struct usb_host_endpoint *ep,
1287
		bool reset_ep)
Linus Torvalds's avatar
Linus Torvalds committed
1288
{
Alan Stern's avatar
Alan Stern committed
1289
1290
1291
	int epnum = usb_endpoint_num(&ep->desc);
	int is_out = usb_endpoint_dir_out(&ep->desc);
	int is_control = usb_endpoint_xfer_control(&ep->desc);
Linus Torvalds's avatar
Linus Torvalds committed
1292

1293
1294
1295
	if (reset_ep)
		usb_hcd_reset_endpoint(dev, ep);
	if (is_out || is_control)
Linus Torvalds's avatar
Linus Torvalds committed
1296
		dev->ep_out[epnum] = ep;
1297
	if (!is_out || is_control)
Linus Torvalds's avatar
Linus Torvalds committed
1298
		dev->ep_in[epnum] = ep;
Alan Stern's avatar
Alan Stern committed
1299
	ep->enabled = 1;