1/*
2 * devices.c
3 * (C) Copyright 1999 Randy Dunlap.
4 * (C) Copyright 1999,2000 Thomas Sailer <sailer@ife.ee.ethz.ch>. (proc file per device)
5 * (C) Copyright 1999 Deti Fliegl (new USB architecture)
6 *
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, write to the Free Software
19 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
20 *
21 *************************************************************
22 *
23 * <mountpoint>/devices contains USB topology, device, config, class,
24 * interface, & endpoint data.
25 *
26 * I considered using /proc/bus/usb/devices/device# for each device
27 * as it is attached or detached, but I didn't like this for some
28 * reason -- maybe it's just too deep of a directory structure.
29 * I also don't like looking in multiple places to gather and view
30 * the data.  Having only one file for ./devices also prevents race
31 * conditions that could arise if a program was reading device info
32 * for devices that are being removed (unplugged).  (That is, the
33 * program may find a directory for devnum_12 then try to open it,
34 * but it was just unplugged, so the directory is now deleted.
35 * But programs would just have to be prepared for situations like
36 * this in any plug-and-play environment.)
37 *
38 * 1999-12-16: Thomas Sailer <sailer@ife.ee.ethz.ch>
39 *   Converted the whole proc stuff to real
40 *   read methods. Now not the whole device list needs to fit
41 *   into one page, only the device list for one bus.
42 *   Added a poll method to /proc/bus/usb/devices, to wake
43 *   up an eventual usbd
44 * 2000-01-04: Thomas Sailer <sailer@ife.ee.ethz.ch>
45 *   Turned into its own filesystem
46 * 2000-07-05: Ashley Montanaro <ashley@compsoc.man.ac.uk>
47 *   Converted file reading routine to dump to buffer once
48 *   per device, not per bus
49 *
50 * $Id: devices.c,v 1.1.1.1 2007/10/11 23:34:37 Exp $
51 */
52
53#include <linux/fs.h>
54#include <linux/mm.h>
55#include <linux/slab.h>
56#include <linux/poll.h>
57#include <linux/usb.h>
58#include <linux/smp_lock.h>
59#include <linux/usbdevice_fs.h>
60#include <linux/mutex.h>
61#include <asm/uaccess.h>
62
63#include "usb.h"
64#include "hcd.h"
65
66#define MAX_TOPO_LEVEL		6
67
68/* Define ALLOW_SERIAL_NUMBER if you want to see the serial number of devices */
69#define ALLOW_SERIAL_NUMBER
70
71static const char *format_topo =
72/* T:  Bus=dd Lev=dd Prnt=dd Port=dd Cnt=dd Dev#=ddd Spd=ddd MxCh=dd */
73"\nT:  Bus=%2.2d Lev=%2.2d Prnt=%2.2d Port=%2.2d Cnt=%2.2d Dev#=%3d Spd=%3s MxCh=%2d\n";
74
75static const char *format_string_manufacturer =
76  "S:  Manufacturer=%.100s\n";
77
78static const char *format_string_product =
79  "S:  Product=%.100s\n";
80
81#ifdef ALLOW_SERIAL_NUMBER
82static const char *format_string_serialnumber =
83  "S:  SerialNumber=%.100s\n";
84#endif
85
86static const char *format_bandwidth =
87/* B:  Alloc=ddd/ddd us (xx%), #Int=ddd, #Iso=ddd */
88  "B:  Alloc=%3d/%3d us (%2d%%), #Int=%3d, #Iso=%3d\n";
89
90static const char *format_device1 =
91/* D:  Ver=xx.xx Cls=xx(sssss) Sub=xx Prot=xx MxPS=dd #Cfgs=dd */
92  "D:  Ver=%2x.%02x Cls=%02x(%-5s) Sub=%02x Prot=%02x MxPS=%2d #Cfgs=%3d\n";
93
94static const char *format_device2 =
95  "P:  Vendor=%04x ProdID=%04x Rev=%2x.%02x\n";
96
97static const char *format_config =
98/* C:  #Ifs=dd Cfg#=dd Atr=xx MPwr=dddmA */
99  "C:%c #Ifs=%2d Cfg#=%2d Atr=%02x MxPwr=%3dmA\n";
100
101static const char *format_iface =
102  "I:%c If#=%2d Alt=%2d #EPs=%2d Cls=%02x(%-5s) Sub=%02x Prot=%02x Driver=%s\n";
103
104static const char *format_endpt =
105/* E:  Ad=xx(s) Atr=xx(ssss) MxPS=dddd Ivl=D?s */
106  "E:  Ad=%02x(%c) Atr=%02x(%-4s) MxPS=%4d Ivl=%d%cs\n";
107
108
109/*
110 * Need access to the driver and USB bus lists.
111 * extern struct list_head usb_bus_list;
112 * However, these will come from functions that return ptrs to each of them.
113 */
114
115static DECLARE_WAIT_QUEUE_HEAD(deviceconndiscwq);
116static unsigned int conndiscevcnt = 0;
117
118/* this struct stores the poll state for <mountpoint>/devices pollers */
119struct usb_device_status {
120	unsigned int lastev;
121};
122
123struct class_info {
124	int class;
125	char *class_name;
126};
127
128static const struct class_info clas_info[] =
129{					/* max. 5 chars. per name string */
130	{USB_CLASS_PER_INTERFACE,	">ifc"},
131	{USB_CLASS_AUDIO,		"audio"},
132	{USB_CLASS_COMM,		"comm."},
133	{USB_CLASS_HID,			"HID"},
134	{USB_CLASS_HUB,			"hub"},
135	{USB_CLASS_PHYSICAL,		"PID"},
136	{USB_CLASS_PRINTER,		"print"},
137	{USB_CLASS_MASS_STORAGE,	"stor."},
138	{USB_CLASS_CDC_DATA,		"data"},
139	{USB_CLASS_APP_SPEC,		"app."},
140	{USB_CLASS_VENDOR_SPEC,		"vend."},
141	{USB_CLASS_STILL_IMAGE,		"still"},
142	{USB_CLASS_CSCID,		"scard"},
143	{USB_CLASS_CONTENT_SEC,		"c-sec"},
144	{-1,				"unk."}		/* leave as last */
145};
146
147/*****************************************************************/
148
149void usbfs_conn_disc_event(void)
150{
151	conndiscevcnt++;
152	wake_up(&deviceconndiscwq);
153}
154
155static const char *class_decode(const int class)
156{
157	int ix;
158
159	for (ix = 0; clas_info[ix].class != -1; ix++)
160		if (clas_info[ix].class == class)
161			break;
162	return clas_info[ix].class_name;
163}
164
165static char *usb_dump_endpoint_descriptor(
166	int speed,
167	char *start,
168	char *end,
169	const struct usb_endpoint_descriptor *desc
170)
171{
172	char dir, unit, *type;
173	unsigned interval, bandwidth = 1;
174
175	if (start > end)
176		return start;
177
178	dir = usb_endpoint_dir_in(desc) ? 'I' : 'O';
179
180	if (speed == USB_SPEED_HIGH) {
181		switch (le16_to_cpu(desc->wMaxPacketSize) & (0x03 << 11)) {
182		case 1 << 11:	bandwidth = 2; break;
183		case 2 << 11:	bandwidth = 3; break;
184		}
185	}
186
187	/* this isn't checking for illegal values */
188	switch (desc->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) {
189	case USB_ENDPOINT_XFER_CONTROL:
190		type = "Ctrl";
191		if (speed == USB_SPEED_HIGH) 	/* uframes per NAK */
192			interval = desc->bInterval;
193		else
194			interval = 0;
195		dir = 'B';			/* ctrl is bidirectional */
196		break;
197	case USB_ENDPOINT_XFER_ISOC:
198		type = "Isoc";
199		interval = 1 << (desc->bInterval - 1);
200		break;
201	case USB_ENDPOINT_XFER_BULK:
202		type = "Bulk";
203		if (speed == USB_SPEED_HIGH && dir == 'O') /* uframes per NAK */
204			interval = desc->bInterval;
205		else
206			interval = 0;
207		break;
208	case USB_ENDPOINT_XFER_INT:
209		type = "Int.";
210		if (speed == USB_SPEED_HIGH)
211			interval = 1 << (desc->bInterval - 1);
212		else
213			interval = desc->bInterval;
214		break;
215	default:	/* "can't happen" */
216		return start;
217	}
218	interval *= (speed == USB_SPEED_HIGH) ? 125 : 1000;
219	if (interval % 1000)
220		unit = 'u';
221	else {
222		unit = 'm';
223		interval /= 1000;
224	}
225
226	start += sprintf(start, format_endpt, desc->bEndpointAddress, dir,
227			 desc->bmAttributes, type,
228			 (le16_to_cpu(desc->wMaxPacketSize) & 0x07ff) * bandwidth,
229			 interval, unit);
230	return start;
231}
232
233static char *usb_dump_interface_descriptor(char *start, char *end,
234	const struct usb_interface_cache *intfc,
235	const struct usb_interface *iface,
236	int setno)
237{
238	const struct usb_interface_descriptor *desc = &intfc->altsetting[setno].desc;
239	const char *driver_name = "";
240	int active = 0;
241
242	if (start > end)
243		return start;
244	if (iface) {
245		driver_name = (iface->dev.driver
246				? iface->dev.driver->name
247				: "(none)");
248		active = (desc == &iface->cur_altsetting->desc);
249	}
250	start += sprintf(start, format_iface,
251			 active ? '*' : ' ',	/* mark active altsetting */
252			 desc->bInterfaceNumber,
253			 desc->bAlternateSetting,
254			 desc->bNumEndpoints,
255			 desc->bInterfaceClass,
256			 class_decode(desc->bInterfaceClass),
257			 desc->bInterfaceSubClass,
258			 desc->bInterfaceProtocol,
259			 driver_name);
260	return start;
261}
262
263static char *usb_dump_interface(
264	int speed,
265	char *start,
266	char *end,
267	const struct usb_interface_cache *intfc,
268	const struct usb_interface *iface,
269	int setno
270) {
271	const struct usb_host_interface *desc = &intfc->altsetting[setno];
272	int i;
273
274	start = usb_dump_interface_descriptor(start, end, intfc, iface, setno);
275	for (i = 0; i < desc->desc.bNumEndpoints; i++) {
276		if (start > end)
277			return start;
278		start = usb_dump_endpoint_descriptor(speed,
279				start, end, &desc->endpoint[i].desc);
280	}
281	return start;
282}
283
284/* TBD:
285 * 0. TBDs
286 * 1. marking active interface altsettings (code lists all, but should mark
287 *    which ones are active, if any)
288 */
289
290static char *usb_dump_config_descriptor(char *start, char *end, const struct usb_config_descriptor *desc, int active)
291{
292	if (start > end)
293		return start;
294	start += sprintf(start, format_config,
295			 active ? '*' : ' ',	/* mark active/actual/current cfg. */
296			 desc->bNumInterfaces,
297			 desc->bConfigurationValue,
298			 desc->bmAttributes,
299			 desc->bMaxPower * 2);
300	return start;
301}
302
303static char *usb_dump_config (
304	int speed,
305	char *start,
306	char *end,
307	const struct usb_host_config *config,
308	int active
309)
310{
311	int i, j;
312	struct usb_interface_cache *intfc;
313	struct usb_interface *interface;
314
315	if (start > end)
316		return start;
317	if (!config)		/* getting these some in 2.3.7; none in 2.3.6 */
318		return start + sprintf(start, "(null Cfg. desc.)\n");
319	start = usb_dump_config_descriptor(start, end, &config->desc, active);
320	for (i = 0; i < config->desc.bNumInterfaces; i++) {
321		intfc = config->intf_cache[i];
322		interface = config->interface[i];
323		for (j = 0; j < intfc->num_altsetting; j++) {
324			if (start > end)
325				return start;
326			start = usb_dump_interface(speed,
327				start, end, intfc, interface, j);
328		}
329	}
330	return start;
331}
332
333/*
334 * Dump the different USB descriptors.
335 */
336static char *usb_dump_device_descriptor(char *start, char *end, const struct usb_device_descriptor *desc)
337{
338	u16 bcdUSB = le16_to_cpu(desc->bcdUSB);
339	u16 bcdDevice = le16_to_cpu(desc->bcdDevice);
340
341	if (start > end)
342		return start;
343	start += sprintf(start, format_device1,
344			  bcdUSB >> 8, bcdUSB & 0xff,
345			  desc->bDeviceClass,
346			  class_decode (desc->bDeviceClass),
347			  desc->bDeviceSubClass,
348			  desc->bDeviceProtocol,
349			  desc->bMaxPacketSize0,
350			  desc->bNumConfigurations);
351	if (start > end)
352		return start;
353	start += sprintf(start, format_device2,
354			 le16_to_cpu(desc->idVendor),
355			 le16_to_cpu(desc->idProduct),
356			 bcdDevice >> 8, bcdDevice & 0xff);
357	return start;
358}
359
360/*
361 * Dump the different strings that this device holds.
362 */
363static char *usb_dump_device_strings(char *start, char *end, struct usb_device *dev)
364{
365	if (start > end)
366		return start;
367	if (dev->manufacturer)
368		start += sprintf(start, format_string_manufacturer, dev->manufacturer);
369	if (start > end)
370		goto out;
371	if (dev->product)
372		start += sprintf(start, format_string_product, dev->product);
373	if (start > end)
374		goto out;
375#ifdef ALLOW_SERIAL_NUMBER
376	if (dev->serial)
377		start += sprintf(start, format_string_serialnumber, dev->serial);
378#endif
379 out:
380	return start;
381}
382
383static char *usb_dump_desc(char *start, char *end, struct usb_device *dev)
384{
385	int i;
386
387	if (start > end)
388		return start;
389
390	start = usb_dump_device_descriptor(start, end, &dev->descriptor);
391
392	if (start > end)
393		return start;
394
395	start = usb_dump_device_strings(start, end, dev);
396
397	for (i = 0; i < dev->descriptor.bNumConfigurations; i++) {
398		if (start > end)
399			return start;
400		start = usb_dump_config(dev->speed,
401				start, end, dev->config + i,
402				/* active ? */
403				(dev->config + i) == dev->actconfig);
404	}
405	return start;
406}
407
408
409#ifdef PROC_EXTRA     /* TBD: may want to add this code later */
410
411static char *usb_dump_hub_descriptor(char *start, char *end, const struct usb_hub_descriptor * desc)
412{
413	int leng = USB_DT_HUB_NONVAR_SIZE;
414	unsigned char *ptr = (unsigned char *)desc;
415
416	if (start > end)
417		return start;
418	start += sprintf(start, "Interface:");
419	while (leng && start <= end) {
420		start += sprintf(start, " %02x", *ptr);
421		ptr++; leng--;
422	}
423	*start++ = '\n';
424	return start;
425}
426
427static char *usb_dump_string(char *start, char *end, const struct usb_device *dev, char *id, int index)
428{
429	if (start > end)
430		return start;
431	start += sprintf(start, "Interface:");
432	if (index <= dev->maxstring && dev->stringindex && dev->stringindex[index])
433		start += sprintf(start, "%s: %.100s ", id, dev->stringindex[index]);
434	return start;
435}
436
437#endif /* PROC_EXTRA */
438
439/*****************************************************************/
440
441/* This is a recursive function. Parameters:
442 * buffer - the user-space buffer to write data into
443 * nbytes - the maximum number of bytes to write
444 * skip_bytes - the number of bytes to skip before writing anything
445 * file_offset - the offset into the devices file on completion
446 * The caller must own the device lock.
447 */
448static ssize_t usb_device_dump(char __user **buffer, size_t *nbytes, loff_t *skip_bytes, loff_t *file_offset,
449				struct usb_device *usbdev, struct usb_bus *bus, int level, int index, int count)
450{
451	int chix;
452	int ret, cnt = 0;
453	int parent_devnum = 0;
454	char *pages_start, *data_end, *speed;
455	unsigned int length;
456	ssize_t total_written = 0;
457
458	/* don't bother with anything else if we're not writing any data */
459	if (*nbytes <= 0)
460		return 0;
461
462	if (level > MAX_TOPO_LEVEL)
463		return 0;
464	/* allocate 2^1 pages = 8K (on i386); should be more than enough for one device */
465        if (!(pages_start = (char*) __get_free_pages(GFP_KERNEL,1)))
466                return -ENOMEM;
467
468	if (usbdev->parent && usbdev->parent->devnum != -1)
469		parent_devnum = usbdev->parent->devnum;
470	/*
471	 * So the root hub's parent is 0 and any device that is
472	 * plugged into the root hub has a parent of 0.
473	 */
474	switch (usbdev->speed) {
475	case USB_SPEED_LOW:
476		speed = "1.5"; break;
477	case USB_SPEED_UNKNOWN:		/* usb 1.1 root hub code */
478	case USB_SPEED_FULL:
479		speed = "12 "; break;
480	case USB_SPEED_HIGH:
481		speed = "480"; break;
482	default:
483		speed = "?? ";
484	}
485	data_end = pages_start + sprintf(pages_start, format_topo,
486			bus->busnum, level, parent_devnum,
487			index, count, usbdev->devnum,
488			speed, usbdev->maxchild);
489	/*
490	 * level = topology-tier level;
491	 * parent_devnum = parent device number;
492	 * index = parent's connector number;
493	 * count = device count at this level
494	 */
495	/* If this is the root hub, display the bandwidth information */
496	if (level == 0) {
497		int	max;
498
499		/* high speed reserves 80%, full/low reserves 90% */
500		if (usbdev->speed == USB_SPEED_HIGH)
501			max = 800;
502		else
503			max = FRAME_TIME_MAX_USECS_ALLOC;
504
505		/* report "average" periodic allocation over a microsecond.
506		 * the schedules are actually bursty, HCDs need to deal with
507		 * that and just compute/report this average.
508		 */
509		data_end += sprintf(data_end, format_bandwidth,
510				bus->bandwidth_allocated, max,
511				(100 * bus->bandwidth_allocated + max / 2)
512					/ max,
513			         bus->bandwidth_int_reqs,
514				 bus->bandwidth_isoc_reqs);
515
516	}
517	data_end = usb_dump_desc(data_end, pages_start + (2 * PAGE_SIZE) - 256, usbdev);
518
519	if (data_end > (pages_start + (2 * PAGE_SIZE) - 256))
520		data_end += sprintf(data_end, "(truncated)\n");
521
522	length = data_end - pages_start;
523	/* if we can start copying some data to the user */
524	if (length > *skip_bytes) {
525		length -= *skip_bytes;
526		if (length > *nbytes)
527			length = *nbytes;
528		if (copy_to_user(*buffer, pages_start + *skip_bytes, length)) {
529			free_pages((unsigned long)pages_start, 1);
530			return -EFAULT;
531		}
532		*nbytes -= length;
533		*file_offset += length;
534		total_written += length;
535		*buffer += length;
536		*skip_bytes = 0;
537	} else
538		*skip_bytes -= length;
539
540	free_pages((unsigned long)pages_start, 1);
541
542	/* Now look at all of this device's children. */
543	for (chix = 0; chix < usbdev->maxchild; chix++) {
544		struct usb_device *childdev = usbdev->children[chix];
545
546		if (childdev) {
547			usb_lock_device(childdev);
548			ret = usb_device_dump(buffer, nbytes, skip_bytes, file_offset, childdev,
549					bus, level + 1, chix, ++cnt);
550			usb_unlock_device(childdev);
551			if (ret == -EFAULT)
552				return total_written;
553			total_written += ret;
554		}
555	}
556	return total_written;
557}
558
559static ssize_t usb_device_read(struct file *file, char __user *buf, size_t nbytes, loff_t *ppos)
560{
561	struct usb_bus *bus;
562	ssize_t ret, total_written = 0;
563	loff_t skip_bytes = *ppos;
564
565	if (*ppos < 0)
566		return -EINVAL;
567	if (nbytes <= 0)
568		return 0;
569	if (!access_ok(VERIFY_WRITE, buf, nbytes))
570		return -EFAULT;
571
572	mutex_lock(&usb_bus_list_lock);
573	/* print devices for all busses */
574	list_for_each_entry(bus, &usb_bus_list, bus_list) {
575		/* recurse through all children of the root hub */
576		if (!bus->root_hub)
577			continue;
578		usb_lock_device(bus->root_hub);
579		ret = usb_device_dump(&buf, &nbytes, &skip_bytes, ppos, bus->root_hub, bus, 0, 0, 0);
580		usb_unlock_device(bus->root_hub);
581		if (ret < 0) {
582			mutex_unlock(&usb_bus_list_lock);
583			return ret;
584		}
585		total_written += ret;
586	}
587	mutex_unlock(&usb_bus_list_lock);
588	return total_written;
589}
590
591/* Kernel lock for "lastev" protection */
592static unsigned int usb_device_poll(struct file *file, struct poll_table_struct *wait)
593{
594	struct usb_device_status *st = file->private_data;
595	unsigned int mask = 0;
596
597	lock_kernel();
598	if (!st) {
599		st = kmalloc(sizeof(struct usb_device_status), GFP_KERNEL);
600
601		/* we may have dropped BKL - need to check for having lost the race */
602		if (file->private_data) {
603			kfree(st);
604			st = file->private_data;
605			goto lost_race;
606		}
607		/* we haven't lost - check for allocation failure now */
608		if (!st) {
609			unlock_kernel();
610			return POLLIN;
611		}
612
613		/*
614		 * need to prevent the module from being unloaded, since
615		 * proc_unregister does not call the release method and
616		 * we would have a memory leak
617		 */
618		st->lastev = conndiscevcnt;
619		file->private_data = st;
620		mask = POLLIN;
621	}
622lost_race:
623	if (file->f_mode & FMODE_READ)
624                poll_wait(file, &deviceconndiscwq, wait);
625	if (st->lastev != conndiscevcnt)
626		mask |= POLLIN;
627	st->lastev = conndiscevcnt;
628	unlock_kernel();
629	return mask;
630}
631
632static int usb_device_open(struct inode *inode, struct file *file)
633{
634        file->private_data = NULL;
635        return 0;
636}
637
638static int usb_device_release(struct inode *inode, struct file *file)
639{
640	kfree(file->private_data);
641	file->private_data = NULL;
642        return 0;
643}
644
645static loff_t usb_device_lseek(struct file * file, loff_t offset, int orig)
646{
647	loff_t ret;
648
649	lock_kernel();
650
651	switch (orig) {
652	case 0:
653		file->f_pos = offset;
654		ret = file->f_pos;
655		break;
656	case 1:
657		file->f_pos += offset;
658		ret = file->f_pos;
659		break;
660	case 2:
661	default:
662		ret = -EINVAL;
663	}
664
665	unlock_kernel();
666	return ret;
667}
668
669const struct file_operations usbfs_devices_fops = {
670	.llseek =	usb_device_lseek,
671	.read =		usb_device_read,
672	.poll =		usb_device_poll,
673	.open =		usb_device_open,
674	.release =	usb_device_release,
675};
676