xref: /linux/drivers/usb/mon/mon_text.c (revision c537b994505099b7197e7d3125b942ecbcc51eb6)
1 /*
2  * The USB Monitor, inspired by Dave Harding's USBMon.
3  *
4  * This is a text format reader.
5  */
6 
7 #include <linux/kernel.h>
8 #include <linux/list.h>
9 #include <linux/usb.h>
10 #include <linux/time.h>
11 #include <linux/mutex.h>
12 #include <linux/debugfs.h>
13 #include <asm/uaccess.h>
14 
15 #include "usb_mon.h"
16 
17 /*
18  * No, we do not want arbitrarily long data strings.
19  * Use the binary interface if you want to capture bulk data!
20  */
21 #define DATA_MAX  32
22 
23 /*
24  * Defined by USB 2.0 clause 9.3, table 9.2.
25  */
26 #define SETUP_MAX  8
27 
28 /*
29  * This limit exists to prevent OOMs when the user process stops reading.
30  * If usbmon were available to unprivileged processes, it might be open
31  * to a local DoS. But we have to keep to root in order to prevent
32  * password sniffing from HID devices.
33  */
34 #define EVENT_MAX  (2*PAGE_SIZE / sizeof(struct mon_event_text))
35 
36 #define PRINTF_DFL  160
37 
38 struct mon_event_text {
39 	struct list_head e_link;
40 	int type;		/* submit, complete, etc. */
41 	unsigned int pipe;	/* Pipe */
42 	unsigned long id;	/* From pointer, most of the time */
43 	unsigned int tstamp;
44 	int length;		/* Depends on type: xfer length or act length */
45 	int status;
46 	char setup_flag;
47 	char data_flag;
48 	unsigned char setup[SETUP_MAX];
49 	unsigned char data[DATA_MAX];
50 };
51 
52 #define SLAB_NAME_SZ  30
53 struct mon_reader_text {
54 	struct kmem_cache *e_slab;
55 	int nevents;
56 	struct list_head e_list;
57 	struct mon_reader r;	/* In C, parent class can be placed anywhere */
58 
59 	wait_queue_head_t wait;
60 	int printf_size;
61 	char *printf_buf;
62 	struct mutex printf_lock;
63 
64 	char slab_name[SLAB_NAME_SZ];
65 };
66 
67 static struct dentry *mon_dir;		/* Usually /sys/kernel/debug/usbmon */
68 
69 static void mon_text_ctor(void *, struct kmem_cache *, unsigned long);
70 
71 /*
72  * mon_text_submit
73  * mon_text_complete
74  *
75  * May be called from an interrupt.
76  *
77  * This is called with the whole mon_bus locked, so no additional lock.
78  */
79 
80 static inline char mon_text_get_setup(struct mon_event_text *ep,
81     struct urb *urb, char ev_type, struct mon_bus *mbus)
82 {
83 
84 	if (!usb_pipecontrol(urb->pipe) || ev_type != 'S')
85 		return '-';
86 
87 	if (mbus->uses_dma && (urb->transfer_flags & URB_NO_SETUP_DMA_MAP))
88 		return mon_dmapeek(ep->setup, urb->setup_dma, SETUP_MAX);
89 	if (urb->setup_packet == NULL)
90 		return 'Z';	/* '0' would be not as pretty. */
91 
92 	memcpy(ep->setup, urb->setup_packet, SETUP_MAX);
93 	return 0;
94 }
95 
96 static inline char mon_text_get_data(struct mon_event_text *ep, struct urb *urb,
97     int len, char ev_type, struct mon_bus *mbus)
98 {
99 	int pipe = urb->pipe;
100 
101 	if (len <= 0)
102 		return 'L';
103 	if (len >= DATA_MAX)
104 		len = DATA_MAX;
105 
106 	if (usb_pipein(pipe)) {
107 		if (ev_type == 'S')
108 			return '<';
109 	} else {
110 		if (ev_type == 'C')
111 			return '>';
112 	}
113 
114 	/*
115 	 * The check to see if it's safe to poke at data has an enormous
116 	 * number of corner cases, but it seems that the following is
117 	 * more or less safe.
118 	 *
119 	 * We do not even try to look at transfer_buffer, because it can
120 	 * contain non-NULL garbage in case the upper level promised to
121 	 * set DMA for the HCD.
122 	 */
123 	if (mbus->uses_dma && (urb->transfer_flags & URB_NO_TRANSFER_DMA_MAP))
124 		return mon_dmapeek(ep->data, urb->transfer_dma, len);
125 
126 	if (urb->transfer_buffer == NULL)
127 		return 'Z';	/* '0' would be not as pretty. */
128 
129 	memcpy(ep->data, urb->transfer_buffer, len);
130 	return 0;
131 }
132 
133 static inline unsigned int mon_get_timestamp(void)
134 {
135 	struct timeval tval;
136 	unsigned int stamp;
137 
138 	do_gettimeofday(&tval);
139 	stamp = tval.tv_sec & 0xFFFF;	/* 2^32 = 4294967296. Limit to 4096s. */
140 	stamp = stamp * 1000000 + tval.tv_usec;
141 	return stamp;
142 }
143 
144 static void mon_text_event(struct mon_reader_text *rp, struct urb *urb,
145     char ev_type)
146 {
147 	struct mon_event_text *ep;
148 	unsigned int stamp;
149 
150 	stamp = mon_get_timestamp();
151 
152 	if (rp->nevents >= EVENT_MAX ||
153 	    (ep = kmem_cache_alloc(rp->e_slab, GFP_ATOMIC)) == NULL) {
154 		rp->r.m_bus->cnt_text_lost++;
155 		return;
156 	}
157 
158 	ep->type = ev_type;
159 	ep->pipe = urb->pipe;
160 	ep->id = (unsigned long) urb;
161 	ep->tstamp = stamp;
162 	ep->length = (ev_type == 'S') ?
163 	    urb->transfer_buffer_length : urb->actual_length;
164 	/* Collecting status makes debugging sense for submits, too */
165 	ep->status = urb->status;
166 
167 	ep->setup_flag = mon_text_get_setup(ep, urb, ev_type, rp->r.m_bus);
168 	ep->data_flag = mon_text_get_data(ep, urb, ep->length, ev_type,
169 			rp->r.m_bus);
170 
171 	rp->nevents++;
172 	list_add_tail(&ep->e_link, &rp->e_list);
173 	wake_up(&rp->wait);
174 }
175 
176 static void mon_text_submit(void *data, struct urb *urb)
177 {
178 	struct mon_reader_text *rp = data;
179 	mon_text_event(rp, urb, 'S');
180 }
181 
182 static void mon_text_complete(void *data, struct urb *urb)
183 {
184 	struct mon_reader_text *rp = data;
185 	mon_text_event(rp, urb, 'C');
186 }
187 
188 static void mon_text_error(void *data, struct urb *urb, int error)
189 {
190 	struct mon_reader_text *rp = data;
191 	struct mon_event_text *ep;
192 
193 	if (rp->nevents >= EVENT_MAX ||
194 	    (ep = kmem_cache_alloc(rp->e_slab, GFP_ATOMIC)) == NULL) {
195 		rp->r.m_bus->cnt_text_lost++;
196 		return;
197 	}
198 
199 	ep->type = 'E';
200 	ep->pipe = urb->pipe;
201 	ep->id = (unsigned long) urb;
202 	ep->tstamp = 0;
203 	ep->length = 0;
204 	ep->status = error;
205 
206 	ep->setup_flag = '-';
207 	ep->data_flag = 'E';
208 
209 	rp->nevents++;
210 	list_add_tail(&ep->e_link, &rp->e_list);
211 	wake_up(&rp->wait);
212 }
213 
214 /*
215  * Fetch next event from the circular buffer.
216  */
217 static struct mon_event_text *mon_text_fetch(struct mon_reader_text *rp,
218     struct mon_bus *mbus)
219 {
220 	struct list_head *p;
221 	unsigned long flags;
222 
223 	spin_lock_irqsave(&mbus->lock, flags);
224 	if (list_empty(&rp->e_list)) {
225 		spin_unlock_irqrestore(&mbus->lock, flags);
226 		return NULL;
227 	}
228 	p = rp->e_list.next;
229 	list_del(p);
230 	--rp->nevents;
231 	spin_unlock_irqrestore(&mbus->lock, flags);
232 	return list_entry(p, struct mon_event_text, e_link);
233 }
234 
235 /*
236  */
237 static int mon_text_open(struct inode *inode, struct file *file)
238 {
239 	struct mon_bus *mbus;
240 	struct usb_bus *ubus;
241 	struct mon_reader_text *rp;
242 	int rc;
243 
244 	mutex_lock(&mon_lock);
245 	mbus = inode->i_private;
246 	ubus = mbus->u_bus;
247 
248 	rp = kzalloc(sizeof(struct mon_reader_text), GFP_KERNEL);
249 	if (rp == NULL) {
250 		rc = -ENOMEM;
251 		goto err_alloc;
252 	}
253 	INIT_LIST_HEAD(&rp->e_list);
254 	init_waitqueue_head(&rp->wait);
255 	mutex_init(&rp->printf_lock);
256 
257 	rp->printf_size = PRINTF_DFL;
258 	rp->printf_buf = kmalloc(rp->printf_size, GFP_KERNEL);
259 	if (rp->printf_buf == NULL) {
260 		rc = -ENOMEM;
261 		goto err_alloc_pr;
262 	}
263 
264 	rp->r.m_bus = mbus;
265 	rp->r.r_data = rp;
266 	rp->r.rnf_submit = mon_text_submit;
267 	rp->r.rnf_error = mon_text_error;
268 	rp->r.rnf_complete = mon_text_complete;
269 
270 	snprintf(rp->slab_name, SLAB_NAME_SZ, "mon%dt_%lx", ubus->busnum,
271 	    (long)rp);
272 	rp->e_slab = kmem_cache_create(rp->slab_name,
273 	    sizeof(struct mon_event_text), sizeof(long), 0,
274 	    mon_text_ctor, NULL);
275 	if (rp->e_slab == NULL) {
276 		rc = -ENOMEM;
277 		goto err_slab;
278 	}
279 
280 	mon_reader_add(mbus, &rp->r);
281 
282 	file->private_data = rp;
283 	mutex_unlock(&mon_lock);
284 	return 0;
285 
286 // err_busy:
287 //	kmem_cache_destroy(rp->e_slab);
288 err_slab:
289 	kfree(rp->printf_buf);
290 err_alloc_pr:
291 	kfree(rp);
292 err_alloc:
293 	mutex_unlock(&mon_lock);
294 	return rc;
295 }
296 
297 /*
298  * For simplicity, we read one record in one system call and throw out
299  * what does not fit. This means that the following does not work:
300  *   dd if=/dbg/usbmon/0t bs=10
301  * Also, we do not allow seeks and do not bother advancing the offset.
302  */
303 static ssize_t mon_text_read(struct file *file, char __user *buf,
304 				size_t nbytes, loff_t *ppos)
305 {
306 	struct mon_reader_text *rp = file->private_data;
307 	struct mon_bus *mbus = rp->r.m_bus;
308 	DECLARE_WAITQUEUE(waita, current);
309 	struct mon_event_text *ep;
310 	int cnt, limit;
311 	char *pbuf;
312 	char udir, utype;
313 	int data_len, i;
314 
315 	add_wait_queue(&rp->wait, &waita);
316 	set_current_state(TASK_INTERRUPTIBLE);
317 	while ((ep = mon_text_fetch(rp, mbus)) == NULL) {
318 		if (file->f_flags & O_NONBLOCK) {
319 			set_current_state(TASK_RUNNING);
320 			remove_wait_queue(&rp->wait, &waita);
321 			return -EWOULDBLOCK;	/* Same as EAGAIN in Linux */
322 		}
323 		/*
324 		 * We do not count nwaiters, because ->release is supposed
325 		 * to be called when all openers are gone only.
326 		 */
327 		schedule();
328 		if (signal_pending(current)) {
329 			remove_wait_queue(&rp->wait, &waita);
330 			return -EINTR;
331 		}
332 		set_current_state(TASK_INTERRUPTIBLE);
333 	}
334 	set_current_state(TASK_RUNNING);
335 	remove_wait_queue(&rp->wait, &waita);
336 
337 	mutex_lock(&rp->printf_lock);
338 	cnt = 0;
339 	pbuf = rp->printf_buf;
340 	limit = rp->printf_size;
341 
342 	udir = usb_pipein(ep->pipe) ? 'i' : 'o';
343 	switch (usb_pipetype(ep->pipe)) {
344 	case PIPE_ISOCHRONOUS:	utype = 'Z'; break;
345 	case PIPE_INTERRUPT:	utype = 'I'; break;
346 	case PIPE_CONTROL:	utype = 'C'; break;
347 	default: /* PIPE_BULK */  utype = 'B';
348 	}
349 	cnt += snprintf(pbuf + cnt, limit - cnt,
350 	    "%lx %u %c %c%c:%03u:%02u",
351 	    ep->id, ep->tstamp, ep->type,
352 	    utype, udir, usb_pipedevice(ep->pipe), usb_pipeendpoint(ep->pipe));
353 
354 	if (ep->setup_flag == 0) {   /* Setup packet is present and captured */
355 		cnt += snprintf(pbuf + cnt, limit - cnt,
356 		    " s %02x %02x %04x %04x %04x",
357 		    ep->setup[0],
358 		    ep->setup[1],
359 		    (ep->setup[3] << 8) | ep->setup[2],
360 		    (ep->setup[5] << 8) | ep->setup[4],
361 		    (ep->setup[7] << 8) | ep->setup[6]);
362 	} else if (ep->setup_flag != '-') { /* Unable to capture setup packet */
363 		cnt += snprintf(pbuf + cnt, limit - cnt,
364 		    " %c __ __ ____ ____ ____", ep->setup_flag);
365 	} else {                     /* No setup for this kind of URB */
366 		cnt += snprintf(pbuf + cnt, limit - cnt, " %d", ep->status);
367 	}
368 	cnt += snprintf(pbuf + cnt, limit - cnt, " %d", ep->length);
369 
370 	if ((data_len = ep->length) > 0) {
371 		if (ep->data_flag == 0) {
372 			cnt += snprintf(pbuf + cnt, limit - cnt, " =");
373 			if (data_len >= DATA_MAX)
374 				data_len = DATA_MAX;
375 			for (i = 0; i < data_len; i++) {
376 				if (i % 4 == 0) {
377 					cnt += snprintf(pbuf + cnt, limit - cnt,
378 					    " ");
379 				}
380 				cnt += snprintf(pbuf + cnt, limit - cnt,
381 				    "%02x", ep->data[i]);
382 			}
383 			cnt += snprintf(pbuf + cnt, limit - cnt, "\n");
384 		} else {
385 			cnt += snprintf(pbuf + cnt, limit - cnt,
386 			    " %c\n", ep->data_flag);
387 		}
388 	} else {
389 		cnt += snprintf(pbuf + cnt, limit - cnt, "\n");
390 	}
391 
392 	if (copy_to_user(buf, rp->printf_buf, cnt))
393 		cnt = -EFAULT;
394 	mutex_unlock(&rp->printf_lock);
395 	kmem_cache_free(rp->e_slab, ep);
396 	return cnt;
397 }
398 
399 static int mon_text_release(struct inode *inode, struct file *file)
400 {
401 	struct mon_reader_text *rp = file->private_data;
402 	struct mon_bus *mbus;
403 	/* unsigned long flags; */
404 	struct list_head *p;
405 	struct mon_event_text *ep;
406 
407 	mutex_lock(&mon_lock);
408 	mbus = inode->i_private;
409 
410 	if (mbus->nreaders <= 0) {
411 		printk(KERN_ERR TAG ": consistency error on close\n");
412 		mutex_unlock(&mon_lock);
413 		return 0;
414 	}
415 	mon_reader_del(mbus, &rp->r);
416 
417 	/*
418 	 * In theory, e_list is protected by mbus->lock. However,
419 	 * after mon_reader_del has finished, the following is the case:
420 	 *  - we are not on reader list anymore, so new events won't be added;
421 	 *  - whole mbus may be dropped if it was orphaned.
422 	 * So, we better not touch mbus.
423 	 */
424 	/* spin_lock_irqsave(&mbus->lock, flags); */
425 	while (!list_empty(&rp->e_list)) {
426 		p = rp->e_list.next;
427 		ep = list_entry(p, struct mon_event_text, e_link);
428 		list_del(p);
429 		--rp->nevents;
430 		kmem_cache_free(rp->e_slab, ep);
431 	}
432 	/* spin_unlock_irqrestore(&mbus->lock, flags); */
433 
434 	kmem_cache_destroy(rp->e_slab);
435 	kfree(rp->printf_buf);
436 	kfree(rp);
437 
438 	mutex_unlock(&mon_lock);
439 	return 0;
440 }
441 
442 static const struct file_operations mon_fops_text = {
443 	.owner =	THIS_MODULE,
444 	.open =		mon_text_open,
445 	.llseek =	no_llseek,
446 	.read =		mon_text_read,
447 	/* .write =	mon_text_write, */
448 	/* .poll =		mon_text_poll, */
449 	/* .ioctl =	mon_text_ioctl, */
450 	.release =	mon_text_release,
451 };
452 
453 int mon_text_add(struct mon_bus *mbus, const struct usb_bus *ubus)
454 {
455 	struct dentry *d;
456 	enum { NAMESZ = 10 };
457 	char name[NAMESZ];
458 	int rc;
459 
460 	rc = snprintf(name, NAMESZ, "%dt", ubus->busnum);
461 	if (rc <= 0 || rc >= NAMESZ)
462 		goto err_print_t;
463 	d = debugfs_create_file(name, 0600, mon_dir, mbus, &mon_fops_text);
464 	if (d == NULL)
465 		goto err_create_t;
466 	mbus->dent_t = d;
467 
468 	/* XXX The stats do not belong to here (text API), but oh well... */
469 	rc = snprintf(name, NAMESZ, "%ds", ubus->busnum);
470 	if (rc <= 0 || rc >= NAMESZ)
471 		goto err_print_s;
472 	d = debugfs_create_file(name, 0600, mon_dir, mbus, &mon_fops_stat);
473 	if (d == NULL)
474 		goto err_create_s;
475 	mbus->dent_s = d;
476 
477 	return 1;
478 
479 err_create_s:
480 err_print_s:
481 	debugfs_remove(mbus->dent_t);
482 	mbus->dent_t = NULL;
483 err_create_t:
484 err_print_t:
485 	return 0;
486 }
487 
488 void mon_text_del(struct mon_bus *mbus)
489 {
490 	debugfs_remove(mbus->dent_t);
491 	debugfs_remove(mbus->dent_s);
492 }
493 
494 /*
495  * Slab interface: constructor.
496  */
497 static void mon_text_ctor(void *mem, struct kmem_cache *slab, unsigned long sflags)
498 {
499 	/*
500 	 * Nothing to initialize. No, really!
501 	 * So, we fill it with garbage to emulate a reused object.
502 	 */
503 	memset(mem, 0xe5, sizeof(struct mon_event_text));
504 }
505 
506 int __init mon_text_init(void)
507 {
508 	struct dentry *mondir;
509 
510 	mondir = debugfs_create_dir("usbmon", NULL);
511 	if (IS_ERR(mondir)) {
512 		printk(KERN_NOTICE TAG ": debugfs is not available\n");
513 		return -ENODEV;
514 	}
515 	if (mondir == NULL) {
516 		printk(KERN_NOTICE TAG ": unable to create usbmon directory\n");
517 		return -ENODEV;
518 	}
519 	mon_dir = mondir;
520 	return 0;
521 }
522 
523 void mon_text_exit(void)
524 {
525 	debugfs_remove(mon_dir);
526 }
527