1 // SPDX-License-Identifier: GPL-2.0
3 * The USB Monitor, inspired by Dave Harding's USBMon.
5 * This is a text format reader.
8 #include <linux/kernel.h>
9 #include <linux/list.h>
10 #include <linux/usb.h>
11 #include <linux/slab.h>
12 #include <linux/sched/signal.h>
13 #include <linux/time.h>
14 #include <linux/ktime.h>
15 #include <linux/export.h>
16 #include <linux/mutex.h>
17 #include <linux/debugfs.h>
18 #include <linux/scatterlist.h>
19 #include <linux/uaccess.h>
24 * No, we do not want arbitrarily long data strings.
25 * Use the binary interface if you want to capture bulk data!
30 * Defined by USB 2.0 clause 9.3, table 9.2.
35 * This limit exists to prevent OOMs when the user process stops reading.
36 * If usbmon were available to unprivileged processes, it might be open
37 * to a local DoS. But we have to keep to root in order to prevent
38 * password sniffing from HID devices.
40 #define EVENT_MAX (4*PAGE_SIZE / sizeof(struct mon_event_text))
43 * Potentially unlimited number; we limit it for similar allocations.
44 * The usbfs limits this to 128, but we're not quite as generous.
48 #define PRINTF_DFL 250 /* with 5 ISOs segs */
53 unsigned int length; /* Unsigned here, signed in URB. Historic. */
56 struct mon_event_text {
57 struct list_head e_link;
58 int type; /* submit, complete, etc. */
59 unsigned long id; /* From pointer, most of the time */
66 int length; /* Depends on type: xfer length or act length */
73 int numdesc; /* Full number */
74 struct mon_iso_desc isodesc[ISODESC_MAX];
75 unsigned char setup[SETUP_MAX];
76 unsigned char data[DATA_MAX];
79 #define SLAB_NAME_SZ 30
80 struct mon_reader_text {
81 struct kmem_cache *e_slab;
83 struct list_head e_list;
84 struct mon_reader r; /* In C, parent class can be placed anywhere */
86 wait_queue_head_t wait;
89 struct mutex printf_lock;
91 char slab_name[SLAB_NAME_SZ];
94 static struct dentry *mon_dir; /* Usually /sys/kernel/debug/usbmon */
96 static void mon_text_ctor(void *);
103 static struct mon_event_text *
104 mon_text_read_wait(struct mon_reader_text *rp, struct file *file);
105 static void mon_text_read_head_t(struct mon_reader_text *rp,
106 struct mon_text_ptr *p, const struct mon_event_text *ep);
107 static void mon_text_read_head_u(struct mon_reader_text *rp,
108 struct mon_text_ptr *p, const struct mon_event_text *ep);
109 static void mon_text_read_statset(struct mon_reader_text *rp,
110 struct mon_text_ptr *p, const struct mon_event_text *ep);
111 static void mon_text_read_intstat(struct mon_reader_text *rp,
112 struct mon_text_ptr *p, const struct mon_event_text *ep);
113 static void mon_text_read_isostat(struct mon_reader_text *rp,
114 struct mon_text_ptr *p, const struct mon_event_text *ep);
115 static void mon_text_read_isodesc(struct mon_reader_text *rp,
116 struct mon_text_ptr *p, const struct mon_event_text *ep);
117 static void mon_text_read_data(struct mon_reader_text *rp,
118 struct mon_text_ptr *p, const struct mon_event_text *ep);
124 * May be called from an interrupt.
126 * This is called with the whole mon_bus locked, so no additional lock.
129 static inline char mon_text_get_setup(struct mon_event_text *ep,
130 struct urb *urb, char ev_type, struct mon_bus *mbus)
133 if (ep->xfertype != USB_ENDPOINT_XFER_CONTROL || ev_type != 'S')
136 if (urb->setup_packet == NULL)
137 return 'Z'; /* '0' would be not as pretty. */
139 memcpy(ep->setup, urb->setup_packet, SETUP_MAX);
143 static inline char mon_text_get_data(struct mon_event_text *ep, struct urb *urb,
144 int len, char ev_type, struct mon_bus *mbus)
161 if (urb->num_sgs == 0) {
162 src = urb->transfer_buffer;
164 return 'Z'; /* '0' would be not as pretty. */
166 struct scatterlist *sg = urb->sg;
168 if (PageHighMem(sg_page(sg)))
171 /* For the text interface we copy only the first sg buffer */
172 len = min_t(int, sg->length, len);
176 memcpy(ep->data, src, len);
180 static inline unsigned int mon_get_timestamp(void)
182 struct timespec64 now;
185 ktime_get_ts64(&now);
186 stamp = now.tv_sec & 0xFFF; /* 2^32 = 4294967296. Limit to 4096s. */
187 stamp = stamp * USEC_PER_SEC + now.tv_nsec / NSEC_PER_USEC;
191 static void mon_text_event(struct mon_reader_text *rp, struct urb *urb,
192 char ev_type, int status)
194 struct mon_event_text *ep;
196 struct usb_iso_packet_descriptor *fp;
197 struct mon_iso_desc *dp;
200 stamp = mon_get_timestamp();
202 if (rp->nevents >= EVENT_MAX ||
203 (ep = kmem_cache_alloc(rp->e_slab, GFP_ATOMIC)) == NULL) {
204 rp->r.m_bus->cnt_text_lost++;
209 ep->id = (unsigned long) urb;
210 ep->busnum = urb->dev->bus->busnum;
211 ep->devnum = urb->dev->devnum;
212 ep->epnum = usb_endpoint_num(&urb->ep->desc);
213 ep->xfertype = usb_endpoint_type(&urb->ep->desc);
214 ep->is_in = usb_urb_dir_in(urb);
216 ep->length = (ev_type == 'S') ?
217 urb->transfer_buffer_length : urb->actual_length;
218 /* Collecting status makes debugging sense for submits, too */
221 if (ep->xfertype == USB_ENDPOINT_XFER_INT) {
222 ep->interval = urb->interval;
223 } else if (ep->xfertype == USB_ENDPOINT_XFER_ISOC) {
224 ep->interval = urb->interval;
225 ep->start_frame = urb->start_frame;
226 ep->error_count = urb->error_count;
228 ep->numdesc = urb->number_of_packets;
229 if (ep->xfertype == USB_ENDPOINT_XFER_ISOC &&
230 urb->number_of_packets > 0) {
231 if ((ndesc = urb->number_of_packets) > ISODESC_MAX)
233 fp = urb->iso_frame_desc;
235 for (i = 0; i < ndesc; i++) {
236 dp->status = fp->status;
237 dp->offset = fp->offset;
238 dp->length = (ev_type == 'S') ?
239 fp->length : fp->actual_length;
243 /* Wasteful, but simple to understand: ISO 'C' is sparse. */
245 ep->length = urb->transfer_buffer_length;
248 ep->setup_flag = mon_text_get_setup(ep, urb, ev_type, rp->r.m_bus);
249 ep->data_flag = mon_text_get_data(ep, urb, ep->length, ev_type,
253 list_add_tail(&ep->e_link, &rp->e_list);
257 static void mon_text_submit(void *data, struct urb *urb)
259 struct mon_reader_text *rp = data;
260 mon_text_event(rp, urb, 'S', -EINPROGRESS);
263 static void mon_text_complete(void *data, struct urb *urb, int status)
265 struct mon_reader_text *rp = data;
266 mon_text_event(rp, urb, 'C', status);
269 static void mon_text_error(void *data, struct urb *urb, int error)
271 struct mon_reader_text *rp = data;
272 struct mon_event_text *ep;
274 if (rp->nevents >= EVENT_MAX ||
275 (ep = kmem_cache_alloc(rp->e_slab, GFP_ATOMIC)) == NULL) {
276 rp->r.m_bus->cnt_text_lost++;
281 ep->id = (unsigned long) urb;
282 ep->busnum = urb->dev->bus->busnum;
283 ep->devnum = urb->dev->devnum;
284 ep->epnum = usb_endpoint_num(&urb->ep->desc);
285 ep->xfertype = usb_endpoint_type(&urb->ep->desc);
286 ep->is_in = usb_urb_dir_in(urb);
287 ep->tstamp = mon_get_timestamp();
291 ep->setup_flag = '-';
295 list_add_tail(&ep->e_link, &rp->e_list);
300 * Fetch next event from the circular buffer.
302 static struct mon_event_text *mon_text_fetch(struct mon_reader_text *rp,
303 struct mon_bus *mbus)
308 spin_lock_irqsave(&mbus->lock, flags);
309 if (list_empty(&rp->e_list)) {
310 spin_unlock_irqrestore(&mbus->lock, flags);
316 spin_unlock_irqrestore(&mbus->lock, flags);
317 return list_entry(p, struct mon_event_text, e_link);
322 static int mon_text_open(struct inode *inode, struct file *file)
324 struct mon_bus *mbus;
325 struct mon_reader_text *rp;
328 mutex_lock(&mon_lock);
329 mbus = inode->i_private;
331 rp = kzalloc(sizeof(struct mon_reader_text), GFP_KERNEL);
336 INIT_LIST_HEAD(&rp->e_list);
337 init_waitqueue_head(&rp->wait);
338 mutex_init(&rp->printf_lock);
340 rp->printf_size = PRINTF_DFL;
341 rp->printf_buf = kmalloc(rp->printf_size, GFP_KERNEL);
342 if (rp->printf_buf == NULL) {
349 rp->r.rnf_submit = mon_text_submit;
350 rp->r.rnf_error = mon_text_error;
351 rp->r.rnf_complete = mon_text_complete;
353 snprintf(rp->slab_name, SLAB_NAME_SZ, "mon_text_%p", rp);
354 rp->e_slab = kmem_cache_create(rp->slab_name,
355 sizeof(struct mon_event_text), sizeof(long), 0,
357 if (rp->e_slab == NULL) {
362 mon_reader_add(mbus, &rp->r);
364 file->private_data = rp;
365 mutex_unlock(&mon_lock);
369 // kmem_cache_destroy(rp->e_slab);
371 kfree(rp->printf_buf);
375 mutex_unlock(&mon_lock);
380 * For simplicity, we read one record in one system call and throw out
381 * what does not fit. This means that the following does not work:
382 * dd if=/dbg/usbmon/0t bs=10
383 * Also, we do not allow seeks and do not bother advancing the offset.
385 static ssize_t mon_text_read_t(struct file *file, char __user *buf,
386 size_t nbytes, loff_t *ppos)
388 struct mon_reader_text *rp = file->private_data;
389 struct mon_event_text *ep;
390 struct mon_text_ptr ptr;
392 ep = mon_text_read_wait(rp, file);
395 mutex_lock(&rp->printf_lock);
397 ptr.pbuf = rp->printf_buf;
398 ptr.limit = rp->printf_size;
400 mon_text_read_head_t(rp, &ptr, ep);
401 mon_text_read_statset(rp, &ptr, ep);
402 ptr.cnt += snprintf(ptr.pbuf + ptr.cnt, ptr.limit - ptr.cnt,
404 mon_text_read_data(rp, &ptr, ep);
406 if (copy_to_user(buf, rp->printf_buf, ptr.cnt))
408 mutex_unlock(&rp->printf_lock);
409 kmem_cache_free(rp->e_slab, ep);
413 static ssize_t mon_text_read_u(struct file *file, char __user *buf,
414 size_t nbytes, loff_t *ppos)
416 struct mon_reader_text *rp = file->private_data;
417 struct mon_event_text *ep;
418 struct mon_text_ptr ptr;
420 ep = mon_text_read_wait(rp, file);
423 mutex_lock(&rp->printf_lock);
425 ptr.pbuf = rp->printf_buf;
426 ptr.limit = rp->printf_size;
428 mon_text_read_head_u(rp, &ptr, ep);
429 if (ep->type == 'E') {
430 mon_text_read_statset(rp, &ptr, ep);
431 } else if (ep->xfertype == USB_ENDPOINT_XFER_ISOC) {
432 mon_text_read_isostat(rp, &ptr, ep);
433 mon_text_read_isodesc(rp, &ptr, ep);
434 } else if (ep->xfertype == USB_ENDPOINT_XFER_INT) {
435 mon_text_read_intstat(rp, &ptr, ep);
437 mon_text_read_statset(rp, &ptr, ep);
439 ptr.cnt += snprintf(ptr.pbuf + ptr.cnt, ptr.limit - ptr.cnt,
441 mon_text_read_data(rp, &ptr, ep);
443 if (copy_to_user(buf, rp->printf_buf, ptr.cnt))
445 mutex_unlock(&rp->printf_lock);
446 kmem_cache_free(rp->e_slab, ep);
450 static struct mon_event_text *mon_text_read_wait(struct mon_reader_text *rp,
453 struct mon_bus *mbus = rp->r.m_bus;
454 DECLARE_WAITQUEUE(waita, current);
455 struct mon_event_text *ep;
457 add_wait_queue(&rp->wait, &waita);
458 set_current_state(TASK_INTERRUPTIBLE);
459 while ((ep = mon_text_fetch(rp, mbus)) == NULL) {
460 if (file->f_flags & O_NONBLOCK) {
461 set_current_state(TASK_RUNNING);
462 remove_wait_queue(&rp->wait, &waita);
463 return ERR_PTR(-EWOULDBLOCK);
466 * We do not count nwaiters, because ->release is supposed
467 * to be called when all openers are gone only.
470 if (signal_pending(current)) {
471 remove_wait_queue(&rp->wait, &waita);
472 return ERR_PTR(-EINTR);
474 set_current_state(TASK_INTERRUPTIBLE);
476 set_current_state(TASK_RUNNING);
477 remove_wait_queue(&rp->wait, &waita);
481 static void mon_text_read_head_t(struct mon_reader_text *rp,
482 struct mon_text_ptr *p, const struct mon_event_text *ep)
486 udir = (ep->is_in ? 'i' : 'o');
487 switch (ep->xfertype) {
488 case USB_ENDPOINT_XFER_ISOC: utype = 'Z'; break;
489 case USB_ENDPOINT_XFER_INT: utype = 'I'; break;
490 case USB_ENDPOINT_XFER_CONTROL: utype = 'C'; break;
491 default: /* PIPE_BULK */ utype = 'B';
493 p->cnt += snprintf(p->pbuf + p->cnt, p->limit - p->cnt,
494 "%lx %u %c %c%c:%03u:%02u",
495 ep->id, ep->tstamp, ep->type,
496 utype, udir, ep->devnum, ep->epnum);
499 static void mon_text_read_head_u(struct mon_reader_text *rp,
500 struct mon_text_ptr *p, const struct mon_event_text *ep)
504 udir = (ep->is_in ? 'i' : 'o');
505 switch (ep->xfertype) {
506 case USB_ENDPOINT_XFER_ISOC: utype = 'Z'; break;
507 case USB_ENDPOINT_XFER_INT: utype = 'I'; break;
508 case USB_ENDPOINT_XFER_CONTROL: utype = 'C'; break;
509 default: /* PIPE_BULK */ utype = 'B';
511 p->cnt += snprintf(p->pbuf + p->cnt, p->limit - p->cnt,
512 "%lx %u %c %c%c:%d:%03u:%u",
513 ep->id, ep->tstamp, ep->type,
514 utype, udir, ep->busnum, ep->devnum, ep->epnum);
517 static void mon_text_read_statset(struct mon_reader_text *rp,
518 struct mon_text_ptr *p, const struct mon_event_text *ep)
521 if (ep->setup_flag == 0) { /* Setup packet is present and captured */
522 p->cnt += snprintf(p->pbuf + p->cnt, p->limit - p->cnt,
523 " s %02x %02x %04x %04x %04x",
526 (ep->setup[3] << 8) | ep->setup[2],
527 (ep->setup[5] << 8) | ep->setup[4],
528 (ep->setup[7] << 8) | ep->setup[6]);
529 } else if (ep->setup_flag != '-') { /* Unable to capture setup packet */
530 p->cnt += snprintf(p->pbuf + p->cnt, p->limit - p->cnt,
531 " %c __ __ ____ ____ ____", ep->setup_flag);
532 } else { /* No setup for this kind of URB */
533 p->cnt += snprintf(p->pbuf + p->cnt, p->limit - p->cnt,
538 static void mon_text_read_intstat(struct mon_reader_text *rp,
539 struct mon_text_ptr *p, const struct mon_event_text *ep)
541 p->cnt += snprintf(p->pbuf + p->cnt, p->limit - p->cnt,
542 " %d:%d", ep->status, ep->interval);
545 static void mon_text_read_isostat(struct mon_reader_text *rp,
546 struct mon_text_ptr *p, const struct mon_event_text *ep)
548 if (ep->type == 'S') {
549 p->cnt += snprintf(p->pbuf + p->cnt, p->limit - p->cnt,
550 " %d:%d:%d", ep->status, ep->interval, ep->start_frame);
552 p->cnt += snprintf(p->pbuf + p->cnt, p->limit - p->cnt,
554 ep->status, ep->interval, ep->start_frame, ep->error_count);
558 static void mon_text_read_isodesc(struct mon_reader_text *rp,
559 struct mon_text_ptr *p, const struct mon_event_text *ep)
561 int ndesc; /* Display this many */
563 const struct mon_iso_desc *dp;
565 p->cnt += snprintf(p->pbuf + p->cnt, p->limit - p->cnt,
568 if (ndesc > ISODESC_MAX)
573 for (i = 0; i < ndesc; i++) {
574 p->cnt += snprintf(p->pbuf + p->cnt, p->limit - p->cnt,
575 " %d:%u:%u", dp->status, dp->offset, dp->length);
580 static void mon_text_read_data(struct mon_reader_text *rp,
581 struct mon_text_ptr *p, const struct mon_event_text *ep)
585 if ((data_len = ep->length) > 0) {
586 if (ep->data_flag == 0) {
587 p->cnt += snprintf(p->pbuf + p->cnt, p->limit - p->cnt,
589 if (data_len >= DATA_MAX)
591 for (i = 0; i < data_len; i++) {
593 p->cnt += snprintf(p->pbuf + p->cnt,
597 p->cnt += snprintf(p->pbuf + p->cnt,
599 "%02x", ep->data[i]);
601 p->cnt += snprintf(p->pbuf + p->cnt, p->limit - p->cnt,
604 p->cnt += snprintf(p->pbuf + p->cnt, p->limit - p->cnt,
605 " %c\n", ep->data_flag);
608 p->cnt += snprintf(p->pbuf + p->cnt, p->limit - p->cnt, "\n");
612 static int mon_text_release(struct inode *inode, struct file *file)
614 struct mon_reader_text *rp = file->private_data;
615 struct mon_bus *mbus;
616 /* unsigned long flags; */
618 struct mon_event_text *ep;
620 mutex_lock(&mon_lock);
621 mbus = inode->i_private;
623 if (mbus->nreaders <= 0) {
624 printk(KERN_ERR TAG ": consistency error on close\n");
625 mutex_unlock(&mon_lock);
628 mon_reader_del(mbus, &rp->r);
631 * In theory, e_list is protected by mbus->lock. However,
632 * after mon_reader_del has finished, the following is the case:
633 * - we are not on reader list anymore, so new events won't be added;
634 * - whole mbus may be dropped if it was orphaned.
635 * So, we better not touch mbus.
637 /* spin_lock_irqsave(&mbus->lock, flags); */
638 while (!list_empty(&rp->e_list)) {
640 ep = list_entry(p, struct mon_event_text, e_link);
643 kmem_cache_free(rp->e_slab, ep);
645 /* spin_unlock_irqrestore(&mbus->lock, flags); */
647 kmem_cache_destroy(rp->e_slab);
648 kfree(rp->printf_buf);
651 mutex_unlock(&mon_lock);
655 static const struct file_operations mon_fops_text_t = {
656 .owner = THIS_MODULE,
657 .open = mon_text_open,
659 .read = mon_text_read_t,
660 .release = mon_text_release,
663 static const struct file_operations mon_fops_text_u = {
664 .owner = THIS_MODULE,
665 .open = mon_text_open,
667 .read = mon_text_read_u,
668 .release = mon_text_release,
671 int mon_text_add(struct mon_bus *mbus, const struct usb_bus *ubus)
674 enum { NAMESZ = 10 };
676 int busnum = ubus? ubus->busnum: 0;
683 rc = snprintf(name, NAMESZ, "%dt", busnum);
684 if (rc <= 0 || rc >= NAMESZ)
686 d = debugfs_create_file(name, 0600, mon_dir, mbus,
693 rc = snprintf(name, NAMESZ, "%du", busnum);
694 if (rc <= 0 || rc >= NAMESZ)
696 d = debugfs_create_file(name, 0600, mon_dir, mbus, &mon_fops_text_u);
701 rc = snprintf(name, NAMESZ, "%ds", busnum);
702 if (rc <= 0 || rc >= NAMESZ)
704 d = debugfs_create_file(name, 0600, mon_dir, mbus, &mon_fops_stat);
713 debugfs_remove(mbus->dent_u);
718 debugfs_remove(mbus->dent_t);
726 void mon_text_del(struct mon_bus *mbus)
728 debugfs_remove(mbus->dent_u);
729 if (mbus->dent_t != NULL)
730 debugfs_remove(mbus->dent_t);
731 debugfs_remove(mbus->dent_s);
735 * Slab interface: constructor.
737 static void mon_text_ctor(void *mem)
740 * Nothing to initialize. No, really!
741 * So, we fill it with garbage to emulate a reused object.
743 memset(mem, 0xe5, sizeof(struct mon_event_text));
746 int __init mon_text_init(void)
748 struct dentry *mondir;
750 mondir = debugfs_create_dir("usbmon", usb_debug_root);
751 if (IS_ERR(mondir)) {
752 /* debugfs not available, but we can use usbmon without it */
755 if (mondir == NULL) {
756 printk(KERN_NOTICE TAG ": unable to create usbmon directory\n");
763 void mon_text_exit(void)
765 debugfs_remove(mon_dir);