message.c 51.9 KB
Newer Older
Linus Torvalds's avatar
Linus Torvalds committed
1
2
3
4
5
6
7
8
9
10
11
12
13
/*
 * message.c - synchronous message handling
 */

#include <linux/pci.h>	/* for scatterlist macros */
#include <linux/usb.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/init.h>
#include <linux/mm.h>
#include <linux/timer.h>
#include <linux/ctype.h>
#include <linux/device.h>
14
#include <linux/scatterlist.h>
15
#include <linux/usb/quirks.h>
Linus Torvalds's avatar
Linus Torvalds committed
16
17
18
19
20
#include <asm/byteorder.h>

#include "hcd.h"	/* for usbcore internals */
#include "usb.h"

21
22
23
24
25
struct api_context {
	struct completion	done;
	int			status;
};

26
static void usb_api_blocking_completion(struct urb *urb)
Linus Torvalds's avatar
Linus Torvalds committed
27
{
28
29
30
31
	struct api_context *ctx = urb->context;

	ctx->status = urb->status;
	complete(&ctx->done);
Linus Torvalds's avatar
Linus Torvalds committed
32
33
34
}


35
36
37
38
39
40
41
/*
 * 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)
42
{
43
	struct api_context ctx;
44
	unsigned long expire;
45
	int retval;
Linus Torvalds's avatar
Linus Torvalds committed
46

47
48
	init_completion(&ctx.done);
	urb->context = &ctx;
Linus Torvalds's avatar
Linus Torvalds committed
49
	urb->actual_length = 0;
50
51
	retval = usb_submit_urb(urb, GFP_NOIO);
	if (unlikely(retval))
52
		goto out;
Linus Torvalds's avatar
Linus Torvalds committed
53

54
	expire = timeout ? msecs_to_jiffies(timeout) : MAX_SCHEDULE_TIMEOUT;
55
56
57
	if (!wait_for_completion_timeout(&ctx.done, expire)) {
		usb_kill_urb(urb);
		retval = (ctx.status == -ENOENT ? -ETIMEDOUT : ctx.status);
58
59
60
61

		dev_dbg(&urb->dev->dev,
			"%s timed out on ep%d%s len=%d/%d\n",
			current->comm,
62
63
			usb_endpoint_num(&urb->ep->desc),
			usb_urb_dir_in(urb) ? "in" : "out",
64
65
66
			urb->actual_length,
			urb->transfer_buffer_length);
	} else
67
		retval = ctx.status;
68
out:
Linus Torvalds's avatar
Linus Torvalds committed
69
70
	if (actual_length)
		*actual_length = urb->actual_length;
71

Linus Torvalds's avatar
Linus Torvalds committed
72
	usb_free_urb(urb);
73
	return retval;
Linus Torvalds's avatar
Linus Torvalds committed
74
75
76
}

/*-------------------------------------------------------------------*/
77
/* returns status (negative) or length (positive) */
Linus Torvalds's avatar
Linus Torvalds committed
78
static int usb_internal_control_msg(struct usb_device *usb_dev,
79
				    unsigned int pipe,
Linus Torvalds's avatar
Linus Torvalds committed
80
81
82
83
84
85
86
87
88
89
				    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;
90

Linus Torvalds's avatar
Linus Torvalds committed
91
92
93
94
95
96
97
98
99
100
101
	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;
}

/**
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
 * 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.
 *
 * If successful, it returns the number of bytes transferred, otherwise a
 * negative error number.
 *
 * Don't use this function from within an interrupt context, like a bottom half
 * handler.  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.
Linus Torvalds's avatar
Linus Torvalds committed
128
 */
129
130
131
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
132
{
133
	struct usb_ctrlrequest *dr;
Linus Torvalds's avatar
Linus Torvalds committed
134
	int ret;
135
136

	dr = kmalloc(sizeof(struct usb_ctrlrequest), GFP_NOIO);
Linus Torvalds's avatar
Linus Torvalds committed
137
138
139
	if (!dr)
		return -ENOMEM;

140
	dr->bRequestType = requesttype;
Linus Torvalds's avatar
Linus Torvalds committed
141
142
143
144
145
	dr->bRequest = request;
	dr->wValue = cpu_to_le16p(&value);
	dr->wIndex = cpu_to_le16p(&index);
	dr->wLength = cpu_to_le16p(&size);

146
	/* dbg("usb_control_msg"); */
Linus Torvalds's avatar
Linus Torvalds committed
147
148
149
150
151
152
153

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

	kfree(dr);

	return ret;
}
154
EXPORT_SYMBOL_GPL(usb_control_msg);
Linus Torvalds's avatar
Linus Torvalds committed
155

156
157
158
159
160
161
/**
 * 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
162
163
 * @actual_length: pointer to a location to put the actual length transferred
 *	in bytes
164
165
 * @timeout: time in msecs to wait for the message to complete before
 *	timing out (if 0 the wait is forever)
166
 *
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
 * Context: !in_interrupt ()
 *
 * This function sends a simple interrupt message to a specified endpoint and
 * waits for the message to complete, or timeout.
 *
 * If successful, it returns 0, otherwise a negative error number.  The number
 * of actual bytes transferred will be stored in the actual_length paramater.
 *
 * Don't use this function from within an interrupt context, like a bottom half
 * handler.  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.
 */
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
189
/**
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
 * 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.
 *
 * If successful, it returns 0, otherwise a negative error number.  The number
 * of actual bytes transferred will be stored in the actual_length paramater.
 *
 * Don't use this function from within an interrupt context, like a bottom half
 * handler.  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.
 *
 * 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.
Linus Torvalds's avatar
Linus Torvalds committed
219
 */
220
221
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
222
223
{
	struct urb *urb;
224
	struct usb_host_endpoint *ep;
Linus Torvalds's avatar
Linus Torvalds committed
225

226
227
228
	ep = (usb_pipein(pipe) ? usb_dev->ep_in : usb_dev->ep_out)
			[usb_pipeendpoint(pipe)];
	if (!ep || len < 0)
Linus Torvalds's avatar
Linus Torvalds committed
229
230
		return -EINVAL;

231
	urb = usb_alloc_urb(0, GFP_KERNEL);
Linus Torvalds's avatar
Linus Torvalds committed
232
233
234
	if (!urb)
		return -ENOMEM;

235
236
237
238
	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,
239
240
				usb_api_blocking_completion, NULL,
				ep->desc.bInterval);
241
242
243
	} else
		usb_fill_bulk_urb(urb, usb_dev, pipe, data, len,
				usb_api_blocking_completion, NULL);
Linus Torvalds's avatar
Linus Torvalds committed
244
245
246

	return usb_start_wait_urb(urb, timeout, actual_length);
}
247
EXPORT_SYMBOL_GPL(usb_bulk_msg);
Linus Torvalds's avatar
Linus Torvalds committed
248
249
250

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

251
static void sg_clean(struct usb_sg_request *io)
Linus Torvalds's avatar
Linus Torvalds committed
252
253
254
{
	if (io->urbs) {
		while (io->entries--)
255
256
			usb_free_urb(io->urbs [io->entries]);
		kfree(io->urbs);
Linus Torvalds's avatar
Linus Torvalds committed
257
258
259
		io->urbs = NULL;
	}
	if (io->dev->dev.dma_mask != NULL)
260
261
		usb_buffer_unmap_sg(io->dev, usb_pipein(io->pipe),
				    io->sg, io->nents);
Linus Torvalds's avatar
Linus Torvalds committed
262
263
264
	io->dev = NULL;
}

265
static void sg_complete(struct urb *urb)
Linus Torvalds's avatar
Linus Torvalds committed
266
{
267
	struct usb_sg_request *io = urb->context;
268
	int status = urb->status;
Linus Torvalds's avatar
Linus Torvalds committed
269

270
	spin_lock(&io->lock);
Linus Torvalds's avatar
Linus Torvalds committed
271
272
273
274
275
276
277
278
279
280
281
282
283

	/* 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
284
				|| status != -ECONNRESET)
Linus Torvalds's avatar
Linus Torvalds committed
285
			&& urb->actual_length) {
286
		dev_err(io->dev->bus->controller,
Linus Torvalds's avatar
Linus Torvalds committed
287
288
			"dev %s ep%d%s scatterlist error %d/%d\n",
			io->dev->devpath,
289
290
			usb_endpoint_num(&urb->ep->desc),
			usb_urb_dir_in(urb) ? "in" : "out",
291
			status, io->status);
292
		/* BUG (); */
Linus Torvalds's avatar
Linus Torvalds committed
293
294
	}

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

298
		io->status = status;
Linus Torvalds's avatar
Linus Torvalds committed
299
300
301
302
303

		/* 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...
		 */
304
		spin_unlock(&io->lock);
Linus Torvalds's avatar
Linus Torvalds committed
305
306
307
308
		for (i = 0, found = 0; i < io->entries; i++) {
			if (!io->urbs [i] || !io->urbs [i]->dev)
				continue;
			if (found) {
309
				retval = usb_unlink_urb(io->urbs [i]);
310
311
312
				if (retval != -EINPROGRESS &&
				    retval != -ENODEV &&
				    retval != -EBUSY)
313
					dev_err(&io->dev->dev,
Linus Torvalds's avatar
Linus Torvalds committed
314
						"%s, unlink --> %d\n",
315
						__func__, retval);
Linus Torvalds's avatar
Linus Torvalds committed
316
317
318
			} else if (urb == io->urbs [i])
				found = 1;
		}
319
		spin_lock(&io->lock);
Linus Torvalds's avatar
Linus Torvalds committed
320
321
322
323
324
325
326
	}
	urb->dev = NULL;

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

329
	spin_unlock(&io->lock);
Linus Torvalds's avatar
Linus Torvalds committed
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
}


/**
 * 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
 *
 * Returns zero for success, else a negative errno value.  This initializes a
 * scatter/gather request, allocating resources such as I/O mappings and urb
 * memory (except maybe memory used by USB controller drivers).
 *
 * 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.
 */
358
359
360
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
361
{
362
363
364
	int i;
	int urb_flags;
	int dma;
Linus Torvalds's avatar
Linus Torvalds committed
365
366

	if (!io || !dev || !sg
367
368
			|| usb_pipecontrol(pipe)
			|| usb_pipeisoc(pipe)
Linus Torvalds's avatar
Linus Torvalds committed
369
370
371
			|| nents <= 0)
		return -EINVAL;

372
	spin_lock_init(&io->lock);
Linus Torvalds's avatar
Linus Torvalds committed
373
374
375
376
377
378
379
380
381
382
	io->dev = dev;
	io->pipe = pipe;
	io->sg = sg;
	io->nents = nents;

	/* not all host controllers use DMA (like the mainstream pci ones);
	 * they can use PIO (sl811) or be software over another transport.
	 */
	dma = (dev->dev.dma_mask != NULL);
	if (dma)
383
		io->entries = usb_buffer_map_sg(dev, usb_pipein(pipe),
384
						sg, nents);
Linus Torvalds's avatar
Linus Torvalds committed
385
386
387
388
389
390
391
392
	else
		io->entries = nents;

	/* initialize all the urbs we'll use */
	if (io->entries <= 0)
		return io->entries;

	io->count = io->entries;
393
	io->urbs = kmalloc(io->entries * sizeof *io->urbs, mem_flags);
Linus Torvalds's avatar
Linus Torvalds committed
394
395
396
	if (!io->urbs)
		goto nomem;

397
398
399
	urb_flags = URB_NO_INTERRUPT;
	if (dma)
		urb_flags |= URB_NO_TRANSFER_DMA_MAP;
400
	if (usb_pipein(pipe))
Linus Torvalds's avatar
Linus Torvalds committed
401
402
403
		urb_flags |= URB_SHORT_NOT_OK;

	for (i = 0; i < io->entries; i++) {
404
		unsigned len;
Linus Torvalds's avatar
Linus Torvalds committed
405

406
407
		io->urbs[i] = usb_alloc_urb(0, mem_flags);
		if (!io->urbs[i]) {
Linus Torvalds's avatar
Linus Torvalds committed
408
409
410
411
			io->entries = i;
			goto nomem;
		}

412
413
414
415
		io->urbs[i]->dev = NULL;
		io->urbs[i]->pipe = pipe;
		io->urbs[i]->interval = period;
		io->urbs[i]->transfer_flags = urb_flags;
Linus Torvalds's avatar
Linus Torvalds committed
416

417
418
		io->urbs[i]->complete = sg_complete;
		io->urbs[i]->context = io;
Linus Torvalds's avatar
Linus Torvalds committed
419

420
421
422
423
		/*
		 * Some systems need to revert to PIO when DMA is temporarily
		 * unavailable.  For their sakes, both transfer_buffer and
		 * transfer_dma are set when possible.  However this can only
424
425
426
427
428
429
430
431
432
433
		 * work on systems without:
		 *
		 *  - HIGHMEM, since DMA buffers located in high memory are
		 *    not directly addressable by the CPU for PIO;
		 *
		 *  - IOMMU, since dma_map_sg() is allowed to use an IOMMU to
		 *    make virtually discontiguous buffers be "dma-contiguous"
		 *    so that PIO and DMA need diferent numbers of URBs.
		 *
		 * So when HIGHMEM or IOMMU are in use, transfer_buffer is NULL
434
435
		 * to prevent stale pointers and to help spot bugs.
		 */
Linus Torvalds's avatar
Linus Torvalds committed
436
		if (dma) {
437
438
			io->urbs[i]->transfer_dma = sg_dma_address(sg + i);
			len = sg_dma_len(sg + i);
439
#if defined(CONFIG_HIGHMEM) || defined(CONFIG_GART_IOMMU)
440
441
			io->urbs[i]->transfer_buffer = NULL;
#else
442
			io->urbs[i]->transfer_buffer = sg_virt(&sg[i]);
443
#endif
Linus Torvalds's avatar
Linus Torvalds committed
444
445
		} else {
			/* hc may use _only_ transfer_buffer */
446
447
			io->urbs[i]->transfer_buffer = sg_virt(&sg[i]);
			len = sg[i].length;
Linus Torvalds's avatar
Linus Torvalds committed
448
449
450
		}

		if (length) {
451
			len = min_t(unsigned, len, length);
Linus Torvalds's avatar
Linus Torvalds committed
452
453
454
455
			length -= len;
			if (length == 0)
				io->entries = i + 1;
		}
456
		io->urbs[i]->transfer_buffer_length = len;
Linus Torvalds's avatar
Linus Torvalds committed
457
	}
458
	io->urbs[--i]->transfer_flags &= ~URB_NO_INTERRUPT;
Linus Torvalds's avatar
Linus Torvalds committed
459
460
461
462

	/* transaction state */
	io->status = 0;
	io->bytes = 0;
463
	init_completion(&io->complete);
Linus Torvalds's avatar
Linus Torvalds committed
464
465
466
	return 0;

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

/**
 * 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.
 * (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
510
 *     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).
 */
511
void usb_sg_wait(struct usb_sg_request *io)
Linus Torvalds's avatar
Linus Torvalds committed
512
{
513
514
	int i;
	int entries = io->entries;
Linus Torvalds's avatar
Linus Torvalds committed
515
516

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

522
523
		io->urbs[i]->dev = io->dev;
		retval = usb_submit_urb(io->urbs [i], GFP_ATOMIC);
Linus Torvalds's avatar
Linus Torvalds committed
524
525
526
527

		/* after we submit, let completions or cancelations fire;
		 * we handshake using io->status.
		 */
528
		spin_unlock_irq(&io->lock);
Linus Torvalds's avatar
Linus Torvalds committed
529
530
		switch (retval) {
			/* maybe we retrying will recover */
531
		case -ENXIO:	/* hc didn't queue this one */
Linus Torvalds's avatar
Linus Torvalds committed
532
533
534
535
		case -EAGAIN:
		case -ENOMEM:
			io->urbs[i]->dev = NULL;
			retval = 0;
536
			yield();
Linus Torvalds's avatar
Linus Torvalds committed
537
538
539
540
541
542
543
544
545
			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:
546
			++i;
547
			cpu_relax();
Linus Torvalds's avatar
Linus Torvalds committed
548
549
550
551
			break;

			/* fail any uncompleted urbs */
		default:
552
553
554
			io->urbs[i]->dev = NULL;
			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;
Linus Torvalds's avatar
Linus Torvalds committed
588

589
	spin_lock_irqsave(&io->lock, flags);
Linus Torvalds's avatar
Linus Torvalds committed
590
591
592

	/* shut everything down, if it didn't already */
	if (!io->status) {
593
		int i;
Linus Torvalds's avatar
Linus Torvalds committed
594
595

		io->status = -ECONNRESET;
596
		spin_unlock(&io->lock);
Linus Torvalds's avatar
Linus Torvalds committed
597
		for (i = 0; i < io->entries; i++) {
598
			int retval;
Linus Torvalds's avatar
Linus Torvalds committed
599
600
601

			if (!io->urbs [i]->dev)
				continue;
602
			retval = usb_unlink_urb(io->urbs [i]);
Linus Torvalds's avatar
Linus Torvalds committed
603
			if (retval != -EINPROGRESS && retval != -EBUSY)
604
				dev_warn(&io->dev->dev, "%s, unlink --> %d\n",
605
					__func__, retval);
Linus Torvalds's avatar
Linus Torvalds committed
606
		}
607
		spin_lock(&io->lock);
Linus Torvalds's avatar
Linus Torvalds committed
608
	}
609
	spin_unlock_irqrestore(&io->lock, flags);
Linus Torvalds's avatar
Linus Torvalds committed
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
634
635
636

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

/**
 * 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.
 *
 * Returns the number of bytes received on success, or else the status code
 * 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
654
655
656
657
658
659
660
			continue;
		if (result > 1 && ((u8 *)buf)[1] != type) {
			result = -EPROTO;
			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
682
683
684

/**
 * 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.
 *
 * Returns the number of bytes received on success, or else the status code
 * 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
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
{
	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);
		if (!(result == 0 || result == -EPIPE))
			break;
	}
	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,
718
			  unsigned int index, unsigned char *buf)
Linus Torvalds's avatar
Linus Torvalds committed
719
720
721
722
723
{
	int rc;

	/* Try to read the string descriptor by asking for the maximum
	 * possible number of bytes */
724
725
726
727
	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
728
729
730
731
732
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
759
760

	/* 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;
}

/**
 * usb_string - returns ISO 8859-1 version of a string descriptor
 * @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 ()
761
 *
Linus Torvalds's avatar
Linus Torvalds committed
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
 * This converts the UTF-16LE encoded strings returned by devices, from
 * usb_get_string_descriptor(), to null-terminated ISO-8859-1 encoded ones
 * that are more usable in most kernel contexts.  Note that all characters
 * in the chosen descriptor that can't be encoded using ISO-8859-1
 * are converted to the question mark ("?") character, and this function
 * chooses strings in the first language supported by the device.
 *
 * The ASCII (or, redundantly, "US-ASCII") character set is the seven-bit
 * subset of ISO 8859-1. ISO-8859-1 is the eight-bit subset of Unicode,
 * and is appropriate for use many uses of English and several other
 * Western European languages.  (But it doesn't include the "Euro" symbol.)
 *
 * This call is synchronous, and may not be used in an interrupt context.
 *
 * Returns length of the string (>= 0) or usb_control_msg status (< 0).
 */
int usb_string(struct usb_device *dev, int index, char *buf, size_t size)
{
	unsigned char *tbuf;
	int err;
	unsigned int u, idx;

	if (dev->state == USB_STATE_SUSPENDED)
		return -EHOSTUNREACH;
	if (size <= 0 || !buf || !index)
		return -EINVAL;
	buf[0] = 0;
789
	tbuf = kmalloc(256, GFP_NOIO);
Linus Torvalds's avatar
Linus Torvalds committed
790
791
792
793
794
795
796
	if (!tbuf)
		return -ENOMEM;

	/* get langid for strings if it's not yet known */
	if (!dev->have_langid) {
		err = usb_string_sub(dev, 0, 0, tbuf);
		if (err < 0) {
797
			dev_err(&dev->dev,
Linus Torvalds's avatar
Linus Torvalds committed
798
799
800
801
				"string descriptor 0 read error: %d\n",
				err);
			goto errout;
		} else if (err < 4) {
802
			dev_err(&dev->dev, "string descriptor 0 too short\n");
Linus Torvalds's avatar
Linus Torvalds committed
803
804
805
			err = -EINVAL;
			goto errout;
		} else {
806
			dev->have_langid = 1;
807
808
809
			dev->string_langid = tbuf[2] | (tbuf[3] << 8);
			/* always use the first langid listed */
			dev_dbg(&dev->dev, "default language 0x%04x\n",
Linus Torvalds's avatar
Linus Torvalds committed
810
811
812
				dev->string_langid);
		}
	}
813

Linus Torvalds's avatar
Linus Torvalds committed
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
	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 */
	for (idx = 0, u = 2; u < err; u += 2) {
		if (idx >= size)
			break;
		if (tbuf[u+1])			/* high byte */
			buf[idx++] = '?';  /* non ISO-8859-1 character */
		else
			buf[idx++] = tbuf[u];
	}
	buf[idx] = 0;
	err = idx;

	if (tbuf[1] != USB_DT_STRING)
831
832
833
		dev_dbg(&dev->dev,
			"wrong descriptor type %02x for string %d (\"%s\")\n",
			tbuf[1], index, buf);
Linus Torvalds's avatar
Linus Torvalds committed
834
835
836
837
838

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

841
842
843
844
845
846
847
848
849
850
851
852
853
854
/**
 * 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
 *
 * Returns 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.
 */
char *usb_cache_string(struct usb_device *udev, int index)
{
	char *buf;
	char *smallbuf = NULL;
	int len;

855
856
857
858
859
860
861
862
863
	if (index <= 0)
		return NULL;

	buf = kmalloc(256, GFP_KERNEL);
	if (buf) {
		len = usb_string(udev, index, buf, 256);
		if (len > 0) {
			smallbuf = kmalloc(++len, GFP_KERNEL);
			if (!smallbuf)
864
865
866
867
868
869
870
871
				return buf;
			memcpy(smallbuf, buf, len);
		}
		kfree(buf);
	}
	return smallbuf;
}

Linus Torvalds's avatar
Linus Torvalds committed
872
873
874
875
876
877
878
/*
 * 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,
879
 * which dedicates space for this purpose.
Linus Torvalds's avatar
Linus Torvalds committed
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
 *
 * 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.
 *
 * Returns the number of bytes received on success, or else the status code
 * 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);
902
	if (ret >= 0)
Linus Torvalds's avatar
Linus Torvalds committed
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
		memcpy(&dev->descriptor, desc, size);
	kfree(desc);
	return ret;
}

/**
 * usb_get_status - issues a GET_STATUS call
 * @dev: the device whose status is being checked
 * @type: USB_RECIP_*; for device, interface, or endpoint
 * @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.
 *
 * Returns the number of bytes received on success, or else the status code
 * returned by the underlying usb_control_msg() call.
 */
int usb_get_status(struct usb_device *dev, int type, int target, void *data)
{
	int ret;
	u16 *status = kmalloc(sizeof(*status), GFP_KERNEL);

	if (!status)
		return -ENOMEM;

	ret = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
		USB_REQ_GET_STATUS, USB_DIR_IN | type, 0, target, status,
		sizeof(*status), USB_CTRL_GET_TIMEOUT);

	*(u16 *)data = *status;
	kfree(status);
	return ret;
}
946
EXPORT_SYMBOL_GPL(usb_get_status);
Linus Torvalds's avatar
Linus Torvalds committed
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974

/**
 * 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.
 *
 * Returns zero on success, or else the status code returned by the
 * underlying usb_control_msg() call.
 */
int usb_clear_halt(struct usb_device *dev, int pipe)
{
	int result;
	int endp = usb_pipeendpoint(pipe);
975
976

	if (usb_pipein(pipe))
Linus Torvalds's avatar
Linus Torvalds committed
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
		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.
	 */

	/* toggle was reset by the clear */
	usb_settoggle(dev, usb_pipeendpoint(pipe), usb_pipeout(pipe), 0);

	return 0;
}
1005
EXPORT_SYMBOL_GPL(usb_clear_halt);
Linus Torvalds's avatar
Linus Torvalds committed
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033

/**
 * 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
 *
 * Deallocates hcd/hardware state for this endpoint ... and nukes all
 * pending urbs.
 *
 * If the HCD hasn't registered a disable() function, this sets the
 * endpoint's maxpacket size to 0 to prevent further submissions.
 */
void usb_disable_endpoint(struct usb_device *dev, unsigned int epaddr)
{
	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];
		dev->ep_out[epnum] = NULL;
	} else {
		ep = dev->ep_in[epnum];
		dev->ep_in[epnum] = NULL;
	}
Alan Stern's avatar
Alan Stern committed
1034
1035
	if (ep) {
		ep->enabled = 0;
1036
1037
		usb_hcd_flush_endpoint(dev, ep);
		usb_hcd_disable_endpoint(dev, ep);
Alan Stern's avatar
Alan Stern committed
1038
	}
Linus Torvalds's avatar
Linus Torvalds committed
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
}

/**
 * usb_disable_interface -- Disable all endpoints for an interface
 * @dev: the device whose interface is being disabled
 * @intf: pointer to the interface descriptor
 *
 * Disables all the endpoints for the interface's current altsetting.
 */
void usb_disable_interface(struct usb_device *dev, struct usb_interface *intf)
{
	struct usb_host_interface *alt = intf->cur_altsetting;
	int i;

	for (i = 0; i < alt->desc.bNumEndpoints; ++i) {
		usb_disable_endpoint(dev,
				alt->endpoint[i].desc.bEndpointAddress);
	}
}

1059
/**
Linus Torvalds's avatar
Linus Torvalds committed
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
 * 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;

1073
	dev_dbg(&dev->dev, "%s nuking %s URBs\n", __func__,
1074
		skip_ep0 ? "non-ep0" : "all");
Linus Torvalds's avatar
Linus Torvalds committed
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
	for (i = skip_ep0; i < 16; ++i) {
		usb_disable_endpoint(dev, i);
		usb_disable_endpoint(dev, i + USB_DIR_IN);
	}
	dev->toggle[0] = dev->toggle[1] = 0;

	/* getting rid of interfaces will disconnect
	 * any drivers bound to them (a key side effect)
	 */
	if (dev->actconfig) {
		for (i = 0; i < dev->actconfig->desc.bNumInterfaces; i++) {
			struct usb_interface	*interface;

1088
			/* remove this interface if it has been registered */
Linus Torvalds's avatar
Linus Torvalds committed
1089
			interface = dev->actconfig->interface[i];
1090
			if (!device_is_registered(&interface->dev))
1091
				continue;
1092
			dev_dbg(&dev->dev, "unregistering interface %s\n",
Linus Torvalds's avatar
Linus Torvalds committed
1093
				interface->dev.bus_id);
1094
			device_del(&interface->dev);
1095
			usb_remove_sysfs_intf_files(interface);
Linus Torvalds's avatar
Linus Torvalds committed
1096
1097
1098
1099
1100
1101
		}

		/* Now that the interfaces are unbound, nobody should
		 * try to access them.
		 */
		for (i = 0; i < dev->actconfig->desc.bNumInterfaces; i++) {
1102
			put_device(&dev->actconfig->interface[i]->dev);
Linus Torvalds's avatar
Linus Torvalds committed
1103
1104
1105
1106
1107
1108
1109
1110
			dev->actconfig->interface[i] = NULL;
		}
		dev->actconfig = NULL;
		if (dev->state == USB_STATE_CONFIGURED)
			usb_set_device_state(dev, USB_STATE_ADDRESS);
	}
}

1111
/**
Linus Torvalds's avatar
Linus Torvalds committed
1112
1113
1114
1115
1116
1117
1118
 * usb_enable_endpoint - Enable an endpoint for USB communications
 * @dev: the device whose interface is being enabled
 * @ep: the endpoint
 *
 * Resets the endpoint toggle, and sets dev->ep_{in,out} pointers.
 * For control endpoints, both the input and output sides are handled.
 */
Alan Stern's avatar
Alan Stern committed
1119
void usb_enable_endpoint(struct usb_device *dev, struct usb_host_endpoint *ep)
Linus Torvalds's avatar
Linus Torvalds committed
1120
{
Alan Stern's avatar
Alan Stern committed
1121
1122
1123
	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
1124

Alan Stern's avatar
Alan Stern committed
1125
	if (is_out || is_control) {
Linus Torvalds's avatar
Linus Torvalds committed
1126
1127
1128
		usb_settoggle(dev, epnum, 1, 0);
		dev->ep_out[epnum] = ep;
	}
Alan Stern's avatar
Alan Stern committed
1129
	if (!is_out || is_control) {
Linus Torvalds's avatar
Linus Torvalds committed
1130
1131
1132
		usb_settoggle(dev, epnum, 0, 0);
		dev->ep_in[epnum] = ep;
	}
Alan Stern's avatar
Alan Stern committed
1133
	ep->enabled = 1;
Linus Torvalds's avatar
Linus Torvalds committed
1134
1135
}

1136
/**
Linus Torvalds's avatar
Linus Torvalds committed
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
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
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
 * usb_enable_interface - Enable all the endpoints for an interface
 * @dev: the device whose interface is being enabled
 * @intf: pointer to the interface descriptor
 *
 * Enables all the endpoints for the interface's current altsetting.
 */
static void usb_enable_interface(struct usb_device *dev,
				 struct usb_interface *intf)
{
	struct usb_host_interface *alt = intf->cur_altsetting;
	int i;

	for (i = 0; i < alt->desc.bNumEndpoints; ++i)
		usb_enable_endpoint(dev, &alt->endpoint[i]);
}

/**
 * usb_set_interface - Makes a particular alternate setting be current
 * @dev: the device whose interface is being updated
 * @interface: the interface being updated
 * @alternate: the setting being chosen.
 * Context: !in_interrupt ()
 *
 * This is used to enable data transfers on interfaces that may not
 * be enabled by default.  Not all devices support such configurability.
 * Only the driver bound to an interface may change its setting.
 *
 * Within any given configuration, each interface may have several
 * alternative settings.  These are often used to control levels of
 * bandwidth consumption.  For example, the default setting for a high
 * speed interrupt endpoint may not send more than 64 bytes per microframe,
 * while interrupt transfers of up to 3KBytes per microframe are legal.
 * Also, isochronous endpoints may never be part of an
 * interface's default setting.  To access such bandwidth, alternate
 * interface settings must be made current.
 *
 * Note that in the Linux USB subsystem, bandwidth associated with
 * an endpoint in a given alternate setting is not reserved until an URB
 * is submitted that needs that bandwidth.  Some other operating systems
 * allocate bandwidth early, when a configuration is chosen.
 *
 * This call is synchronous, and may not be used in an interrupt context.
 * Also, drivers must not change altsettings while urbs are scheduled for
 * endpoints in that interface; all such urbs must first be completed
 * (perhaps forced by unlinking).
 *
 * Returns zero on success, or else the status code returned by the
 * underlying usb_control_msg() call.
 */
int usb_set_interface(struct usb_device *dev, int interface, int alternate)
{
	struct usb_interface *iface;
	struct usb_host_interface *alt;
	int ret;
	int manual = 0;
1192
1193
	unsigned int epaddr;
	unsigned int pipe;
Linus Torvalds's avatar
Linus Torvalds committed
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210

	if (dev->state == USB_STATE_SUSPENDED)
		return -EHOSTUNREACH;

	iface = usb_ifnum_to_if(dev, interface);
	if (!iface) {
		dev_dbg(&dev->dev, "selecting invalid interface %d\n",
			interface);
		return -EINVAL;
	}

	alt = usb_altnum_to_altsetting(iface, alternate);
	if (!alt) {
		warn("selecting invalid altsetting %d", alternate);
		return -EINVAL;
	}

1211
1212
1213
1214
	if (dev->quirks & USB_QUIRK_NO_SET_INTF)
		ret = -EPIPE;
	else
		ret = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
Linus Torvalds's avatar
Linus Torvalds committed
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
				   USB_REQ_SET_INTERFACE, USB_RECIP_INTERFACE,
				   alternate, interface, NULL, 0, 5000);

	/* 9.4.10 says devices don't need this and are free to STALL the
	 * request if the interface only has one alternate setting.
	 */
	if (ret == -EPIPE && iface->num_altsetting == 1) {
		dev_dbg(&dev->dev,
			"manual set_interface for iface %d, alt %d\n",
			interface, alternate);
		manual = 1;
	} else if (ret < 0)
		return ret;

	/* FIXME drivers shouldn't need to replicate/bugfix the logic here
	 * when they implement async or easily-killable versions of this or
	 * other "should-be-internal" functions (like clear_halt).
	 * should hcd+usbcore postprocess control requests?
	 */

	/* prevent submissions using previous endpoint settings */
1236
	if (iface->cur_altsetting != alt)
1237
		usb_remove_sysfs_intf_files(iface);
Linus Torvalds's avatar
Linus Torvalds committed
1238
1239
1240
1241
1242
	usb_disable_interface(dev, iface);

	iface->cur_altsetting = alt;

	/* If the interface only has one altsetting and the device didn't
1243
	 * accept the request, we attempt to carry out the equivalent action
Linus Torvalds's avatar
Linus Torvalds committed
1244
1245
1246
1247
1248
1249
1250
	 * by manually clearing the HALT feature for each endpoint in the
	 * new altsetting.
	 */
	if (manual) {
		int i;

		for (i = 0; i < alt->desc.bNumEndpoints; i++) {
1251
1252
1253
1254
1255
			epaddr = alt->endpoint[i].desc.bEndpointAddress;
			pipe = __create_pipe(dev,
					USB_ENDPOINT_NUMBER_MASK & epaddr) |
					(usb_endpoint_out(epaddr) ?
					USB_DIR_OUT : USB_DIR_IN);
Linus Torvalds's avatar
Linus Torvalds committed
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272

			usb_clear_halt(dev, pipe);
		}
	}

	/* 9.1.1.5: reset toggles for all endpoints in the new altsetting
	 *
	 * Note:
	 * Despite EP0 is always present in all interfaces/AS, the list of
	 * endpoints from the descriptor does not contain EP0. Due to its
	 * omnipresence one might expect EP0 being considered "affected" by
	 * any SetInterface request and hence assume toggles need to be reset.
	 * However, EP0 toggles are re-synced for every individual transfer
	 * during the SETUP stage - hence EP0 toggles are "don't care" here.
	 * (Likewise, EP0 never "halts" on well designed devices.)
	 */
	usb_enable_interface(dev, iface);
1273
	if (device_is_registered(&iface->dev))
1274
		usb_create_sysfs_intf_files(iface);
Linus Torvalds's avatar
Linus Torvalds committed
1275
1276
1277

	return 0;
}
1278
EXPORT_SYMBOL_GPL(usb_set_interface);
Linus Torvalds's avatar
Linus Torvalds committed
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292

/**
 * usb_reset_configuration - lightweight device reset
 * @dev: the device whose configuration is being reset
 *
 * This issues a standard SET_CONFIGURATION request to the device using
 * the current configuration.  The effect is to reset most USB-related
 * state in the device, including interface altsettings (reset to zero),
 * endpoint halts (cleared), and data toggle (only for bulk and interrupt
 * endpoints).  Other usbcore state is unchanged, including bindings of
 * usb device drivers to interfaces.
 *
 * Because this affects multiple interfaces, avoid using this with composite
 * (multi-interface) devices.  Instead, the driver for each interface may
1293
1294
1295
 * use usb_set_interface() on the interfaces it claims.  Be careful though;
 * some devices don't support the SET_INTERFACE request, and others won't
 * reset all the interface state (notably data toggles).  Resetting the whole
Linus Torvalds's avatar
Linus Torvalds committed
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
 * configuration would affect other drivers' interfaces.
 *
 * The caller must own the device lock.
 *
 * Returns zero on success, else a negative error code.
 */
int usb_reset_configuration(struct usb_device *dev)
{
	int			i, retval;
	struct usb_host_config	*config;

	if (dev->state == USB_STATE_SUSPENDED)
		return -EHOSTUNREACH;

	/* caller must have locked the device and must own
	 * the usb bus readlock (so driver bindings are stable);
	 * calls during probe() are fine
	 */

	for (i = 1; i < 16; ++i) {
		usb_disable_endpoint(dev, i);
		usb_disable_endpoint(dev, i + USB_DIR_IN);
	}

	config = dev->actconfig;
	retval = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
			USB_REQ_SET_CONFIGURATION, 0,
			config->desc.bConfigurationValue, 0,
			NULL, 0, USB_CTRL_SET_TIMEOUT);
1325
	if (retval < 0)
Linus Torvalds's avatar
Linus Torvalds committed
1326
1327
1328
1329
1330
1331
1332
1333
1334
		return retval;

	dev->toggle[0] = dev->toggle[1] = 0;

	/* re-init hc/hcd interface/endpoint state */
	for (i = 0; i < config->desc.bNumInterfaces; i++) {
		struct usb_interface *intf = config->interface[i];
		struct usb_host_interface *alt;

1335
		usb_remove_sysfs_intf_files(intf);
Linus Torvalds's avatar
Linus Torvalds committed
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
		alt = usb_altnum_to_altsetting(intf, 0);

		/* No altsetting 0?  We'll assume the first altsetting.
		 * We could use a GetInterface call, but if a device is
		 * so non-compliant that it doesn't have altsetting 0
		 * then I wouldn't trust its reply anyway.
		 */
		if (!alt)
			alt = &intf->altsetting[0];

		intf->cur_altsetting = alt;
		usb_enable_interface(dev, intf);
1348
1349
		if (device_is_registered(&intf->dev))
			usb_create_sysfs_intf_files(intf);
Linus Torvalds's avatar
Linus Torvalds committed
1350
1351
1352
	}
	return 0;
}
1353
EXPORT_SYMBOL_GPL(usb_reset_configuration);
Linus Torvalds's avatar
Linus Torvalds committed
1354

1355
static void usb_release_interface(struct device *dev)
Linus Torvalds's avatar
Linus Torvalds committed
1356
1357
1358
1359
1360
1361
1362
1363
1364
{
	struct usb_interface *intf = to_usb_interface(dev);
	struct usb_interface_cache *intfc =
			altsetting_to_usb_interface_cache(intf->altsetting);

	kref_put(&intfc->ref, usb_release_interface_cache);
	kfree(intf);
}

1365
#ifdef	CONFIG_HOTPLUG
1366
static int usb_if_uevent(struct device *dev, struct kobj_uevent_env *env)
1367
1368
1369
1370
1371
1372
1373
1374
1375
{
	struct usb_device *usb_dev;
	struct usb_interface *intf;
	struct usb_host_interface *alt;

	intf = to_usb_interface(dev);
	usb_dev = interface_to_usbdev(intf);
	alt = intf->cur_altsetting;

1376
	if (add_uevent_var(env, "INTERFACE=%d/%d/%d",
1377
1378
1379
1380
1381
		   alt->desc.bInterfaceClass,
		   alt->desc.bInterfaceSubClass,
		   alt->desc.bInterfaceProtocol))
		return -ENOMEM;

1382
	if (add_uevent_var(env,
1383
1384
		   "MODALIAS=usb:"
		   "v%04Xp%04Xd%04Xdc%02Xdsc%02Xdp%02Xic%02Xisc%02Xip%02X",
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
		   le16_to_cpu(usb_dev->descriptor.idVendor),
		   le16_to_cpu(usb_dev->descriptor.idProduct),
		   le16_to_cpu(usb_dev->descriptor.bcdDevice),
		   usb_dev->descriptor.bDeviceClass,
		   usb_dev->descriptor.bDeviceSubClass,
		   usb_dev->descriptor.bDeviceProtocol,
		   alt->desc.bInterfaceClass,
		   alt->desc.bInterfaceSubClass,
		   alt->desc.bInterfaceProtocol))
		return -ENOMEM;

	return 0;
}

#else

1401
static int usb_if_uevent(struct device *dev, struct kobj_uevent_env *env)
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
{
	return -ENODEV;
}
#endif	/* CONFIG_HOTPLUG */

struct device_type usb_if_device_type = {
	.name =		"usb_interface",
	.release =	usb_release_interface,
	.uevent =	usb_if_uevent,
};

1413
static struct usb_interface_assoc_descriptor *find_iad(struct usb_device *dev,
1414
1415
						struct usb_host_config *config,
						u8 inum)
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
{
	struct usb_interface_assoc_descriptor *retval = NULL;
	struct usb_interface_assoc_descriptor *intf_assoc;
	int first_intf;
	int last_intf;
	int i;

	for (i = 0; (i < USB_MAXIADS && config->intf_assoc[i]); i++) {
		intf_assoc = config->intf_assoc[i];
		if (intf_assoc->bInterfaceCount == 0)
			continue;

		first_intf = intf_assoc->bFirstInterface;
		last_intf = first_intf + (intf_assoc->bInterfaceCount - 1);
		if (inum >= first_intf && inum <= last_intf) {
			if (!retval)
				retval = intf_assoc;
			else
				dev_err(&dev->dev, "Interface #%d referenced"
					" by multiple IADs\n", inum);
		}
	}

	return retval;
}

Linus Torvalds's avatar
Linus Torvalds committed
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
/*
 * usb_set_configuration - Makes a particular device setting be current
 * @dev: the device whose configuration is being updated
 * @configuration: the configuration being chosen.
 * Context: !in_interrupt(), caller owns the device lock
 *
 * This is used to enable non-default device modes.  Not all devices
 * use this kind of configurability; many devices only have one
 * configuration.
 *
1452
1453
1454
1455
1456
1457
1458
1459
 * @configuration is the value of the configuration to be installed.
 * According to the USB spec (e.g. section 9.1.1.5), configuration values
 * must be non-zero; a value of zero indicates that the device in
 * unconfigured.  However some devices erroneously use 0 as one of their
 * configuration values.  To help manage such devices, this routine will
 * accept @configuration = -1 as indicating the device should be put in
 * an unconfigured state.
 *
Linus Torvalds's avatar
Linus Torvalds committed
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
 * USB device configurations may affect Linux interoperability,
 * power consumption and the functionality available.  For example,
 * the default configuration is limited to using 100mA of bus power,
 * so that when certain device functionality requires more power,
 * and the device is bus powered, that functionality should be in some
 * non-default device configuration.  Other device modes may also be
 * reflected as configuration options, such as whether two ISDN
 * channels are available independently; and choosing between open
 * standard device protocols (like CDC) or proprietary ones.
 *
1470
1471
1472
 * Note that a non-authorized device (dev->authorized == 0) will only
 * be put in unconfigured mode.
 *
Linus Torvalds's avatar
Linus Torvalds committed
1473
1474
1475
1476
1477
1478
 * Note that USB has an additional level of device configurability,
 * associated with interfaces.  That configurability is accessed using
 * usb_set_interface().
 *
 * This call is synchronous. The calling context must be able to sleep,
 * must own the device lock, and must not hold the driver model's USB
1479
 * bus mutex; usb device driver probe() methods cannot use this routine.
Linus Torvalds's avatar
Linus Torvalds committed
1480
1481
 *
 * Returns zero on success, or else the status code returned by the
1482
 * underlying call that failed.  On successful completion, each interface
Linus Torvalds's avatar
Linus Torvalds committed
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
 * in the original device configuration has been destroyed, and each one
 * in the new configuration has been probed by all relevant usb device
 * drivers currently known to the kernel.
 */
int usb_set_configuration(struct usb_device *dev, int configuration)
{
	int i, ret;
	struct usb_host_config *cp = NULL;
	struct usb_interface **new_interfaces = NULL;
	int n, nintf;

1494
	if (dev->authorized == 0 || configuration == -1)
1495
1496
1497
1498
1499
1500
1501
1502
		configuration = 0;
	else {
		for (i = 0; i < dev->descriptor.bNumConfigurations; i++) {
			if (dev->config[i].desc.bConfigurationValue ==
					configuration) {
				cp = &dev->config[i];
				break;
			}
Linus Torvalds's avatar
Linus Torvalds committed
1503
1504
1505
1506
1507
1508
1509
1510
		}
	}
	if ((!cp && configuration != 0))
		return -EINVAL;

	/* The USB spec says configuration 0 means unconfigured.
	 * But if a device includes a configuration numbered 0,
	 * we will accept it as a correctly configured state.
1511
	 * Use -1 if you really want to unconfigure the device.
Linus Torvalds's avatar
Linus Torvalds committed
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
	 */
	if (cp && configuration == 0)
		dev_warn(&dev->dev, "config 0 descriptor??\n");

	/* Allocate memory for new interfaces before doing anything else,
	 * so that if we run out then nothing will have changed. */
	n = nintf = 0;
	if (cp) {
		nintf = cp->desc.bNumInterfaces;
		new_interfaces = kmalloc(nintf * sizeof(*new_interfaces),
				GFP_KERNEL);
		if (!new_interfaces) {
1524
			dev_err(&dev->dev, "Out of memory\n");
Linus Torvalds's avatar
Linus Torvalds committed
1525
1526
1527
1528
			return -ENOMEM;
		}

		for (; n < nintf; ++n) {
1529
			new_interfaces[n] = kzalloc(
Linus Torvalds's avatar
Linus Torvalds committed
1530
1531
1532
					sizeof(struct usb_interface),
					GFP_KERNEL);
			if (!new_interfaces[n]) {
1533
				dev_err(&dev->dev, "Out of memory\n");
Linus Torvalds's avatar
Linus Torvalds committed
1534
1535
1536
1537
1538
1539
1540
1541
1542
				ret = -ENOMEM;
free_interfaces:
				while (--n >= 0)
					kfree(new_interfaces[n]);
				kfree(new_interfaces);
				return ret;
			}
		}

1543
1544
1545
1546
1547
1548
		i = dev->bus_mA - cp->desc.bMaxPower * 2;
		if (i < 0)
			dev_warn(&dev->dev, "new config #%d exceeds power "
					"limit by %dmA\n",
					configuration, -i);
	}
1549

Alan Stern's avatar