1 // SPDX-License-Identifier: GPL-2.0
3 * The USB Monitor, inspired by Dave Harding's USBMon.
5 * This is a binary format reader.
11 #include <linux/kernel.h>
12 #include <linux/sched/signal.h>
13 #include <linux/types.h>
15 #include <linux/cdev.h>
16 #include <linux/export.h>
17 #include <linux/usb.h>
18 #include <linux/poll.h>
19 #include <linux/compat.h>
21 #include <linux/scatterlist.h>
22 #include <linux/slab.h>
23 #include <linux/time64.h>
25 #include <linux/uaccess.h>
30 * Defined by USB 2.0 clause 9.3, table 9.2.
35 #define MON_IOC_MAGIC 0x92
37 #define MON_IOCQ_URB_LEN _IO(MON_IOC_MAGIC, 1)
38 /* #2 used to be MON_IOCX_URB, removed before it got into Linus tree */
39 #define MON_IOCG_STATS _IOR(MON_IOC_MAGIC, 3, struct mon_bin_stats)
40 #define MON_IOCT_RING_SIZE _IO(MON_IOC_MAGIC, 4)
41 #define MON_IOCQ_RING_SIZE _IO(MON_IOC_MAGIC, 5)
42 #define MON_IOCX_GET _IOW(MON_IOC_MAGIC, 6, struct mon_bin_get)
43 #define MON_IOCX_MFETCH _IOWR(MON_IOC_MAGIC, 7, struct mon_bin_mfetch)
44 #define MON_IOCH_MFLUSH _IO(MON_IOC_MAGIC, 8)
45 /* #9 was MON_IOCT_SETAPI */
46 #define MON_IOCX_GETX _IOW(MON_IOC_MAGIC, 10, struct mon_bin_get)
49 #define MON_IOCX_GET32 _IOW(MON_IOC_MAGIC, 6, struct mon_bin_get32)
50 #define MON_IOCX_MFETCH32 _IOWR(MON_IOC_MAGIC, 7, struct mon_bin_mfetch32)
51 #define MON_IOCX_GETX32 _IOW(MON_IOC_MAGIC, 10, struct mon_bin_get32)
55 * Some architectures have enormous basic pages (16KB for ia64, 64KB for ppc).
56 * But it's all right. Just use a simple way to make sure the chunk is never
57 * smaller than a page.
59 * N.B. An application does not know our chunk size.
61 * Woops, get_zeroed_page() returns a single page. I guess we're stuck with
62 * page-sized chunks for the time being.
64 #define CHUNK_SIZE PAGE_SIZE
65 #define CHUNK_ALIGN(x) (((x)+CHUNK_SIZE-1) & ~(CHUNK_SIZE-1))
68 * The magic limit was calculated so that it allows the monitoring
69 * application to pick data once in two ticks. This way, another application,
70 * which presumably drives the bus, gets to hog CPU, yet we collect our data.
71 * If HZ is 100, a 480 mbit/s bus drives 614 KB every jiffy. USB has an
72 * enormous overhead built into the bus protocol, so we need about 1000 KB.
74 * This is still too much for most cases, where we just snoop a few
75 * descriptor fetches for enumeration. So, the default is a "reasonable"
76 * amount for systems with HZ=250 and incomplete bus saturation.
78 * XXX What about multi-megabyte URBs which take minutes to transfer?
80 #define BUFF_MAX CHUNK_ALIGN(1200*1024)
81 #define BUFF_DFL CHUNK_ALIGN(300*1024)
82 #define BUFF_MIN CHUNK_ALIGN(8*1024)
85 * The per-event API header (2 per URB).
87 * This structure is seen in userland as defined by the documentation.
90 u64 id; /* URB ID - from submission to callback */
91 unsigned char type; /* Same as in text API; extensible. */
92 unsigned char xfer_type; /* ISO, Intr, Control, Bulk */
93 unsigned char epnum; /* Endpoint number and transfer direction */
94 unsigned char devnum; /* Device address */
95 unsigned short busnum; /* Bus number */
98 s64 ts_sec; /* ktime_get_real_ts64 */
99 s32 ts_usec; /* ktime_get_real_ts64 */
101 unsigned int len_urb; /* Length of data (submitted or actual) */
102 unsigned int len_cap; /* Delivered length */
104 unsigned char setup[SETUP_LEN]; /* Only for Control S-type */
112 unsigned int xfer_flags;
113 unsigned int ndesc; /* Actual number of ISO descriptors */
117 * ISO vector, packed into the head of data stream.
118 * This has to take 16 bytes to make sure that the end of buffer
119 * wrap is not happening in the middle of a descriptor.
121 struct mon_bin_isodesc {
123 unsigned int iso_off;
124 unsigned int iso_len;
128 /* per file statistic */
129 struct mon_bin_stats {
135 struct mon_bin_hdr __user *hdr; /* Can be 48 bytes or 64. */
137 size_t alloc; /* Length of data (can be zero) */
140 struct mon_bin_mfetch {
141 u32 __user *offvec; /* Vector of events fetched */
142 u32 nfetch; /* Number of events to fetch (out: fetched) */
143 u32 nflush; /* Number of events to flush */
147 struct mon_bin_get32 {
153 struct mon_bin_mfetch32 {
160 /* Having these two values same prevents wrapping of the mon_bin_hdr */
164 #define PKT_SZ_API0 48 /* API 0 (2.6.20) size */
165 #define PKT_SZ_API1 64 /* API 1 size: extra fields */
167 #define ISODESC_MAX 128 /* Same number as usbfs allows, 2048 bytes. */
169 /* max number of USB bus supported */
170 #define MON_BIN_MAX_MINOR 128
173 * The buffer: map of used pages.
177 unsigned char *ptr; /* XXX just use page_to_virt everywhere? */
181 * This gets associated with an open file struct.
183 struct mon_reader_bin {
184 /* The buffer: one per open. */
185 spinlock_t b_lock; /* Protect b_cnt, b_in */
186 unsigned int b_size; /* Current size of the buffer - bytes */
187 unsigned int b_cnt; /* Bytes used */
188 unsigned int b_in, b_out; /* Offsets into buffer - bytes */
189 unsigned int b_read; /* Amount of read data in curr. pkt. */
190 struct mon_pgmap *b_vec; /* The map array */
191 wait_queue_head_t b_wait; /* Wait for data here */
193 struct mutex fetch_lock; /* Protect b_read, b_out */
196 /* A list of these is needed for "bus 0". Some time later. */
200 unsigned int cnt_lost;
203 static inline struct mon_bin_hdr *MON_OFF2HDR(const struct mon_reader_bin *rp,
206 return (struct mon_bin_hdr *)
207 (rp->b_vec[offset / CHUNK_SIZE].ptr + offset % CHUNK_SIZE);
210 #define MON_RING_EMPTY(rp) ((rp)->b_cnt == 0)
212 static unsigned char xfer_to_pipe[4] = {
213 PIPE_CONTROL, PIPE_ISOCHRONOUS, PIPE_BULK, PIPE_INTERRUPT
216 static const struct class mon_bin_class = {
220 static dev_t mon_bin_dev0;
221 static struct cdev mon_bin_cdev;
223 static void mon_buff_area_fill(const struct mon_reader_bin *rp,
224 unsigned int offset, unsigned int size);
225 static int mon_bin_wait_event(struct file *file, struct mon_reader_bin *rp);
226 static int mon_alloc_buff(struct mon_pgmap *map, int npages);
227 static void mon_free_buff(struct mon_pgmap *map, int npages);
230 * This is a "chunked memcpy". It does not manipulate any counters.
232 static unsigned int mon_copy_to_buff(const struct mon_reader_bin *this,
233 unsigned int off, const unsigned char *from, unsigned int length)
235 unsigned int step_len;
237 unsigned int in_page;
241 * Determine step_len.
244 in_page = CHUNK_SIZE - (off & (CHUNK_SIZE-1));
245 if (in_page < step_len)
249 * Copy data and advance pointers.
251 buf = this->b_vec[off / CHUNK_SIZE].ptr + off % CHUNK_SIZE;
252 memcpy(buf, from, step_len);
253 if ((off += step_len) >= this->b_size) off = 0;
261 * This is a little worse than the above because it's "chunked copy_to_user".
262 * The return value is an error code, not an offset.
264 static int copy_from_buf(const struct mon_reader_bin *this, unsigned int off,
265 char __user *to, int length)
267 unsigned int step_len;
269 unsigned int in_page;
273 * Determine step_len.
276 in_page = CHUNK_SIZE - (off & (CHUNK_SIZE-1));
277 if (in_page < step_len)
281 * Copy data and advance pointers.
283 buf = this->b_vec[off / CHUNK_SIZE].ptr + off % CHUNK_SIZE;
284 if (copy_to_user(to, buf, step_len))
286 if ((off += step_len) >= this->b_size) off = 0;
294 * Allocate an (aligned) area in the buffer.
295 * This is called under b_lock.
296 * Returns ~0 on failure.
298 static unsigned int mon_buff_area_alloc(struct mon_reader_bin *rp,
303 size = (size + PKT_ALIGN-1) & ~(PKT_ALIGN-1);
304 if (rp->b_cnt + size > rp->b_size)
308 if ((rp->b_in += size) >= rp->b_size)
309 rp->b_in -= rp->b_size;
314 * This is the same thing as mon_buff_area_alloc, only it does not allow
315 * buffers to wrap. This is needed by applications which pass references
316 * into mmap-ed buffers up their stacks (libpcap can do that).
318 * Currently, we always have the header stuck with the data, although
319 * it is not strictly speaking necessary.
321 * When a buffer would wrap, we place a filler packet to mark the space.
323 static unsigned int mon_buff_area_alloc_contiguous(struct mon_reader_bin *rp,
327 unsigned int fill_size;
329 size = (size + PKT_ALIGN-1) & ~(PKT_ALIGN-1);
330 if (rp->b_cnt + size > rp->b_size)
332 if (rp->b_in + size > rp->b_size) {
334 * This would wrap. Find if we still have space after
335 * skipping to the end of the buffer. If we do, place
336 * a filler packet and allocate a new packet.
338 fill_size = rp->b_size - rp->b_in;
339 if (rp->b_cnt + size + fill_size > rp->b_size)
341 mon_buff_area_fill(rp, rp->b_in, fill_size);
345 rp->b_cnt += size + fill_size;
346 } else if (rp->b_in + size == rp->b_size) {
359 * Return a few (kilo-)bytes to the head of the buffer.
360 * This is used if a data fetch fails.
362 static void mon_buff_area_shrink(struct mon_reader_bin *rp, unsigned int size)
365 /* size &= ~(PKT_ALIGN-1); -- we're called with aligned size */
368 rp->b_in += rp->b_size;
373 * This has to be called under both b_lock and fetch_lock, because
374 * it accesses both b_cnt and b_out.
376 static void mon_buff_area_free(struct mon_reader_bin *rp, unsigned int size)
379 size = (size + PKT_ALIGN-1) & ~(PKT_ALIGN-1);
381 if ((rp->b_out += size) >= rp->b_size)
382 rp->b_out -= rp->b_size;
385 static void mon_buff_area_fill(const struct mon_reader_bin *rp,
386 unsigned int offset, unsigned int size)
388 struct mon_bin_hdr *ep;
390 ep = MON_OFF2HDR(rp, offset);
391 memset(ep, 0, PKT_SIZE);
393 ep->len_cap = size - PKT_SIZE;
396 static inline char mon_bin_get_setup(unsigned char *setupb,
397 const struct urb *urb, char ev_type)
400 if (urb->setup_packet == NULL)
402 memcpy(setupb, urb->setup_packet, SETUP_LEN);
406 static unsigned int mon_bin_get_data(const struct mon_reader_bin *rp,
407 unsigned int offset, struct urb *urb, unsigned int length,
411 struct scatterlist *sg;
412 unsigned int this_len;
415 if (urb->num_sgs == 0) {
416 if (urb->transfer_buffer == NULL) {
420 mon_copy_to_buff(rp, offset, urb->transfer_buffer, length);
424 /* If IOMMU coalescing occurred, we cannot trust sg_page */
425 if (urb->transfer_flags & URB_DMA_SG_COMBINED) {
430 /* Copy up to the first non-addressable segment */
431 for_each_sg(urb->sg, sg, urb->num_sgs, i) {
432 if (length == 0 || PageHighMem(sg_page(sg)))
434 this_len = min_t(unsigned int, sg->length, length);
435 offset = mon_copy_to_buff(rp, offset, sg_virt(sg),
447 * This is the look-ahead pass in case of 'C Zi', when actual_length cannot
448 * be used to determine the length of the whole contiguous buffer.
450 static unsigned int mon_bin_collate_isodesc(const struct mon_reader_bin *rp,
451 struct urb *urb, unsigned int ndesc)
453 struct usb_iso_packet_descriptor *fp;
457 fp = urb->iso_frame_desc;
458 while (ndesc-- != 0) {
459 if (fp->actual_length != 0) {
460 if (fp->offset + fp->actual_length > length)
461 length = fp->offset + fp->actual_length;
468 static void mon_bin_get_isodesc(const struct mon_reader_bin *rp,
469 unsigned int offset, struct urb *urb, char ev_type, unsigned int ndesc)
471 struct mon_bin_isodesc *dp;
472 struct usb_iso_packet_descriptor *fp;
474 fp = urb->iso_frame_desc;
475 while (ndesc-- != 0) {
476 dp = (struct mon_bin_isodesc *)
477 (rp->b_vec[offset / CHUNK_SIZE].ptr + offset % CHUNK_SIZE);
478 dp->iso_status = fp->status;
479 dp->iso_off = fp->offset;
480 dp->iso_len = (ev_type == 'S') ? fp->length : fp->actual_length;
482 if ((offset += sizeof(struct mon_bin_isodesc)) >= rp->b_size)
488 static void mon_bin_event(struct mon_reader_bin *rp, struct urb *urb,
489 char ev_type, int status)
491 const struct usb_endpoint_descriptor *epd = &urb->ep->desc;
492 struct timespec64 ts;
494 unsigned int urb_length;
498 unsigned int ndesc, lendesc;
500 struct mon_bin_hdr *ep;
503 ktime_get_real_ts64(&ts);
505 spin_lock_irqsave(&rp->b_lock, flags);
508 * Find the maximum allowable length, then allocate space.
510 urb_length = (ev_type == 'S') ?
511 urb->transfer_buffer_length : urb->actual_length;
514 if (usb_endpoint_xfer_isoc(epd)) {
515 if (urb->number_of_packets < 0) {
517 } else if (urb->number_of_packets >= ISODESC_MAX) {
520 ndesc = urb->number_of_packets;
522 if (ev_type == 'C' && usb_urb_dir_in(urb))
523 length = mon_bin_collate_isodesc(rp, urb, ndesc);
527 lendesc = ndesc*sizeof(struct mon_bin_isodesc);
529 /* not an issue unless there's a subtle bug in a HCD somewhere */
530 if (length >= urb->transfer_buffer_length)
531 length = urb->transfer_buffer_length;
533 if (length >= rp->b_size/5)
534 length = rp->b_size/5;
536 if (usb_urb_dir_in(urb)) {
537 if (ev_type == 'S') {
541 /* Cannot rely on endpoint number in case of control ep.0 */
544 if (ev_type == 'C') {
551 if (rp->mmap_active) {
552 offset = mon_buff_area_alloc_contiguous(rp,
553 length + PKT_SIZE + lendesc);
555 offset = mon_buff_area_alloc(rp, length + PKT_SIZE + lendesc);
559 spin_unlock_irqrestore(&rp->b_lock, flags);
563 ep = MON_OFF2HDR(rp, offset);
564 if ((offset += PKT_SIZE) >= rp->b_size) offset = 0;
567 * Fill the allocated area.
569 memset(ep, 0, PKT_SIZE);
571 ep->xfer_type = xfer_to_pipe[usb_endpoint_type(epd)];
572 ep->epnum = dir | usb_endpoint_num(epd);
573 ep->devnum = urb->dev->devnum;
574 ep->busnum = urb->dev->bus->busnum;
575 ep->id = (unsigned long) urb;
576 ep->ts_sec = ts.tv_sec;
577 ep->ts_usec = ts.tv_nsec / NSEC_PER_USEC;
579 ep->len_urb = urb_length;
580 ep->len_cap = length + lendesc;
581 ep->xfer_flags = urb->transfer_flags;
583 if (usb_endpoint_xfer_int(epd)) {
584 ep->interval = urb->interval;
585 } else if (usb_endpoint_xfer_isoc(epd)) {
586 ep->interval = urb->interval;
587 ep->start_frame = urb->start_frame;
588 ep->s.iso.error_count = urb->error_count;
589 ep->s.iso.numdesc = urb->number_of_packets;
592 if (usb_endpoint_xfer_control(epd) && ev_type == 'S') {
593 ep->flag_setup = mon_bin_get_setup(ep->s.setup, urb, ev_type);
595 ep->flag_setup = '-';
600 mon_bin_get_isodesc(rp, offset, urb, ev_type, ndesc);
601 if ((offset += lendesc) >= rp->b_size)
602 offset -= rp->b_size;
606 length = mon_bin_get_data(rp, offset, urb, length,
609 delta = (ep->len_cap + PKT_ALIGN-1) & ~(PKT_ALIGN-1);
610 ep->len_cap -= length;
611 delta -= (ep->len_cap + PKT_ALIGN-1) & ~(PKT_ALIGN-1);
612 mon_buff_area_shrink(rp, delta);
615 ep->flag_data = data_tag;
618 spin_unlock_irqrestore(&rp->b_lock, flags);
620 wake_up(&rp->b_wait);
623 static void mon_bin_submit(void *data, struct urb *urb)
625 struct mon_reader_bin *rp = data;
626 mon_bin_event(rp, urb, 'S', -EINPROGRESS);
629 static void mon_bin_complete(void *data, struct urb *urb, int status)
631 struct mon_reader_bin *rp = data;
632 mon_bin_event(rp, urb, 'C', status);
635 static void mon_bin_error(void *data, struct urb *urb, int error)
637 struct mon_reader_bin *rp = data;
638 struct timespec64 ts;
641 struct mon_bin_hdr *ep;
643 ktime_get_real_ts64(&ts);
645 spin_lock_irqsave(&rp->b_lock, flags);
647 offset = mon_buff_area_alloc(rp, PKT_SIZE);
649 /* Not incrementing cnt_lost. Just because. */
650 spin_unlock_irqrestore(&rp->b_lock, flags);
654 ep = MON_OFF2HDR(rp, offset);
656 memset(ep, 0, PKT_SIZE);
658 ep->xfer_type = xfer_to_pipe[usb_endpoint_type(&urb->ep->desc)];
659 ep->epnum = usb_urb_dir_in(urb) ? USB_DIR_IN : 0;
660 ep->epnum |= usb_endpoint_num(&urb->ep->desc);
661 ep->devnum = urb->dev->devnum;
662 ep->busnum = urb->dev->bus->busnum;
663 ep->id = (unsigned long) urb;
664 ep->ts_sec = ts.tv_sec;
665 ep->ts_usec = ts.tv_nsec / NSEC_PER_USEC;
668 ep->flag_setup = '-';
671 spin_unlock_irqrestore(&rp->b_lock, flags);
673 wake_up(&rp->b_wait);
676 static int mon_bin_open(struct inode *inode, struct file *file)
678 struct mon_bus *mbus;
679 struct mon_reader_bin *rp;
683 mutex_lock(&mon_lock);
684 mbus = mon_bus_lookup(iminor(inode));
686 mutex_unlock(&mon_lock);
689 if (mbus != &mon_bus0 && mbus->u_bus == NULL) {
690 printk(KERN_ERR TAG ": consistency error on open\n");
691 mutex_unlock(&mon_lock);
695 rp = kzalloc(sizeof(struct mon_reader_bin), GFP_KERNEL);
700 spin_lock_init(&rp->b_lock);
701 init_waitqueue_head(&rp->b_wait);
702 mutex_init(&rp->fetch_lock);
703 rp->b_size = BUFF_DFL;
705 size = sizeof(struct mon_pgmap) * (rp->b_size/CHUNK_SIZE);
706 if ((rp->b_vec = kzalloc(size, GFP_KERNEL)) == NULL) {
711 if ((rc = mon_alloc_buff(rp->b_vec, rp->b_size/CHUNK_SIZE)) < 0)
716 rp->r.rnf_submit = mon_bin_submit;
717 rp->r.rnf_error = mon_bin_error;
718 rp->r.rnf_complete = mon_bin_complete;
720 mon_reader_add(mbus, &rp->r);
722 file->private_data = rp;
723 mutex_unlock(&mon_lock);
731 mutex_unlock(&mon_lock);
736 * Extract an event from buffer and copy it to user space.
737 * Wait if there is no event ready.
738 * Returns zero or error.
740 static int mon_bin_get_event(struct file *file, struct mon_reader_bin *rp,
741 struct mon_bin_hdr __user *hdr, unsigned int hdrbytes,
742 void __user *data, unsigned int nbytes)
745 struct mon_bin_hdr *ep;
750 mutex_lock(&rp->fetch_lock);
752 if ((rc = mon_bin_wait_event(file, rp)) < 0) {
753 mutex_unlock(&rp->fetch_lock);
757 ep = MON_OFF2HDR(rp, rp->b_out);
759 if (copy_to_user(hdr, ep, hdrbytes)) {
760 mutex_unlock(&rp->fetch_lock);
764 step_len = min(ep->len_cap, nbytes);
765 if ((offset = rp->b_out + PKT_SIZE) >= rp->b_size) offset = 0;
767 if (copy_from_buf(rp, offset, data, step_len)) {
768 mutex_unlock(&rp->fetch_lock);
772 spin_lock_irqsave(&rp->b_lock, flags);
773 mon_buff_area_free(rp, PKT_SIZE + ep->len_cap);
774 spin_unlock_irqrestore(&rp->b_lock, flags);
777 mutex_unlock(&rp->fetch_lock);
781 static int mon_bin_release(struct inode *inode, struct file *file)
783 struct mon_reader_bin *rp = file->private_data;
784 struct mon_bus* mbus = rp->r.m_bus;
786 mutex_lock(&mon_lock);
788 if (mbus->nreaders <= 0) {
789 printk(KERN_ERR TAG ": consistency error on close\n");
790 mutex_unlock(&mon_lock);
793 mon_reader_del(mbus, &rp->r);
795 mon_free_buff(rp->b_vec, rp->b_size/CHUNK_SIZE);
799 mutex_unlock(&mon_lock);
803 static ssize_t mon_bin_read(struct file *file, char __user *buf,
804 size_t nbytes, loff_t *ppos)
806 struct mon_reader_bin *rp = file->private_data;
807 unsigned int hdrbytes = PKT_SZ_API0;
809 struct mon_bin_hdr *ep;
816 mutex_lock(&rp->fetch_lock);
818 if ((rc = mon_bin_wait_event(file, rp)) < 0) {
819 mutex_unlock(&rp->fetch_lock);
823 ep = MON_OFF2HDR(rp, rp->b_out);
825 if (rp->b_read < hdrbytes) {
826 step_len = min(nbytes, (size_t)(hdrbytes - rp->b_read));
827 ptr = ((char *)ep) + rp->b_read;
828 if (step_len && copy_to_user(buf, ptr, step_len)) {
829 mutex_unlock(&rp->fetch_lock);
834 rp->b_read += step_len;
838 if (rp->b_read >= hdrbytes) {
839 step_len = ep->len_cap;
840 step_len -= rp->b_read - hdrbytes;
841 if (step_len > nbytes)
843 offset = rp->b_out + PKT_SIZE;
844 offset += rp->b_read - hdrbytes;
845 if (offset >= rp->b_size)
846 offset -= rp->b_size;
847 if (copy_from_buf(rp, offset, buf, step_len)) {
848 mutex_unlock(&rp->fetch_lock);
853 rp->b_read += step_len;
858 * Check if whole packet was read, and if so, jump to the next one.
860 if (rp->b_read >= hdrbytes + ep->len_cap) {
861 spin_lock_irqsave(&rp->b_lock, flags);
862 mon_buff_area_free(rp, PKT_SIZE + ep->len_cap);
863 spin_unlock_irqrestore(&rp->b_lock, flags);
867 mutex_unlock(&rp->fetch_lock);
872 * Remove at most nevents from chunked buffer.
873 * Returns the number of removed events.
875 static int mon_bin_flush(struct mon_reader_bin *rp, unsigned nevents)
878 struct mon_bin_hdr *ep;
881 mutex_lock(&rp->fetch_lock);
882 spin_lock_irqsave(&rp->b_lock, flags);
883 for (i = 0; i < nevents; ++i) {
884 if (MON_RING_EMPTY(rp))
887 ep = MON_OFF2HDR(rp, rp->b_out);
888 mon_buff_area_free(rp, PKT_SIZE + ep->len_cap);
890 spin_unlock_irqrestore(&rp->b_lock, flags);
892 mutex_unlock(&rp->fetch_lock);
897 * Fetch at most max event offsets into the buffer and put them into vec.
898 * The events are usually freed later with mon_bin_flush.
899 * Return the effective number of events fetched.
901 static int mon_bin_fetch(struct file *file, struct mon_reader_bin *rp,
902 u32 __user *vec, unsigned int max)
904 unsigned int cur_out;
905 unsigned int bytes, avail;
907 unsigned int nevents;
908 struct mon_bin_hdr *ep;
912 mutex_lock(&rp->fetch_lock);
914 if ((rc = mon_bin_wait_event(file, rp)) < 0) {
915 mutex_unlock(&rp->fetch_lock);
919 spin_lock_irqsave(&rp->b_lock, flags);
921 spin_unlock_irqrestore(&rp->b_lock, flags);
926 while (bytes < avail) {
930 ep = MON_OFF2HDR(rp, cur_out);
931 if (put_user(cur_out, &vec[nevents])) {
932 mutex_unlock(&rp->fetch_lock);
937 size = ep->len_cap + PKT_SIZE;
938 size = (size + PKT_ALIGN-1) & ~(PKT_ALIGN-1);
939 if ((cur_out += size) >= rp->b_size)
940 cur_out -= rp->b_size;
944 mutex_unlock(&rp->fetch_lock);
949 * Count events. This is almost the same as the above mon_bin_fetch,
950 * only we do not store offsets into user vector, and we have no limit.
952 static int mon_bin_queued(struct mon_reader_bin *rp)
954 unsigned int cur_out;
955 unsigned int bytes, avail;
957 unsigned int nevents;
958 struct mon_bin_hdr *ep;
961 mutex_lock(&rp->fetch_lock);
963 spin_lock_irqsave(&rp->b_lock, flags);
965 spin_unlock_irqrestore(&rp->b_lock, flags);
970 while (bytes < avail) {
971 ep = MON_OFF2HDR(rp, cur_out);
974 size = ep->len_cap + PKT_SIZE;
975 size = (size + PKT_ALIGN-1) & ~(PKT_ALIGN-1);
976 if ((cur_out += size) >= rp->b_size)
977 cur_out -= rp->b_size;
981 mutex_unlock(&rp->fetch_lock);
987 static long mon_bin_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
989 struct mon_reader_bin *rp = file->private_data;
990 // struct mon_bus* mbus = rp->r.m_bus;
992 struct mon_bin_hdr *ep;
997 case MON_IOCQ_URB_LEN:
999 * N.B. This only returns the size of data, without the header.
1001 spin_lock_irqsave(&rp->b_lock, flags);
1002 if (!MON_RING_EMPTY(rp)) {
1003 ep = MON_OFF2HDR(rp, rp->b_out);
1006 spin_unlock_irqrestore(&rp->b_lock, flags);
1009 case MON_IOCQ_RING_SIZE:
1010 mutex_lock(&rp->fetch_lock);
1012 mutex_unlock(&rp->fetch_lock);
1015 case MON_IOCT_RING_SIZE:
1017 * Changing the buffer size will flush it's contents; the new
1018 * buffer is allocated before releasing the old one to be sure
1019 * the device will stay functional also in case of memory
1024 struct mon_pgmap *vec;
1026 if (arg < BUFF_MIN || arg > BUFF_MAX)
1029 size = CHUNK_ALIGN(arg);
1030 vec = kcalloc(size / CHUNK_SIZE, sizeof(struct mon_pgmap),
1037 ret = mon_alloc_buff(vec, size/CHUNK_SIZE);
1043 mutex_lock(&rp->fetch_lock);
1044 spin_lock_irqsave(&rp->b_lock, flags);
1045 if (rp->mmap_active) {
1046 mon_free_buff(vec, size/CHUNK_SIZE);
1050 mon_free_buff(rp->b_vec, rp->b_size/CHUNK_SIZE);
1054 rp->b_read = rp->b_in = rp->b_out = rp->b_cnt = 0;
1057 spin_unlock_irqrestore(&rp->b_lock, flags);
1058 mutex_unlock(&rp->fetch_lock);
1062 case MON_IOCH_MFLUSH:
1063 ret = mon_bin_flush(rp, arg);
1069 struct mon_bin_get getb;
1071 if (copy_from_user(&getb, (void __user *)arg,
1072 sizeof(struct mon_bin_get)))
1075 if (getb.alloc > 0x10000000) /* Want to cast to u32 */
1077 ret = mon_bin_get_event(file, rp, getb.hdr,
1078 (cmd == MON_IOCX_GET)? PKT_SZ_API0: PKT_SZ_API1,
1079 getb.data, (unsigned int)getb.alloc);
1083 case MON_IOCX_MFETCH:
1085 struct mon_bin_mfetch mfetch;
1086 struct mon_bin_mfetch __user *uptr;
1088 uptr = (struct mon_bin_mfetch __user *)arg;
1090 if (copy_from_user(&mfetch, uptr, sizeof(mfetch)))
1093 if (mfetch.nflush) {
1094 ret = mon_bin_flush(rp, mfetch.nflush);
1097 if (put_user(ret, &uptr->nflush))
1100 ret = mon_bin_fetch(file, rp, mfetch.offvec, mfetch.nfetch);
1103 if (put_user(ret, &uptr->nfetch))
1109 case MON_IOCG_STATS: {
1110 struct mon_bin_stats __user *sp;
1111 unsigned int nevents;
1112 unsigned int ndropped;
1114 spin_lock_irqsave(&rp->b_lock, flags);
1115 ndropped = rp->cnt_lost;
1117 spin_unlock_irqrestore(&rp->b_lock, flags);
1118 nevents = mon_bin_queued(rp);
1120 sp = (struct mon_bin_stats __user *)arg;
1121 if (put_user(ndropped, &sp->dropped))
1123 if (put_user(nevents, &sp->queued))
1136 #ifdef CONFIG_COMPAT
1137 static long mon_bin_compat_ioctl(struct file *file,
1138 unsigned int cmd, unsigned long arg)
1140 struct mon_reader_bin *rp = file->private_data;
1145 case MON_IOCX_GET32:
1146 case MON_IOCX_GETX32:
1148 struct mon_bin_get32 getb;
1150 if (copy_from_user(&getb, (void __user *)arg,
1151 sizeof(struct mon_bin_get32)))
1154 ret = mon_bin_get_event(file, rp, compat_ptr(getb.hdr32),
1155 (cmd == MON_IOCX_GET32)? PKT_SZ_API0: PKT_SZ_API1,
1156 compat_ptr(getb.data32), getb.alloc32);
1162 case MON_IOCX_MFETCH32:
1164 struct mon_bin_mfetch32 mfetch;
1165 struct mon_bin_mfetch32 __user *uptr;
1167 uptr = (struct mon_bin_mfetch32 __user *) compat_ptr(arg);
1169 if (copy_from_user(&mfetch, uptr, sizeof(mfetch)))
1172 if (mfetch.nflush32) {
1173 ret = mon_bin_flush(rp, mfetch.nflush32);
1176 if (put_user(ret, &uptr->nflush32))
1179 ret = mon_bin_fetch(file, rp, compat_ptr(mfetch.offvec32),
1183 if (put_user(ret, &uptr->nfetch32))
1188 case MON_IOCG_STATS:
1189 return mon_bin_ioctl(file, cmd, (unsigned long) compat_ptr(arg));
1191 case MON_IOCQ_URB_LEN:
1192 case MON_IOCQ_RING_SIZE:
1193 case MON_IOCT_RING_SIZE:
1194 case MON_IOCH_MFLUSH:
1195 return mon_bin_ioctl(file, cmd, arg);
1202 #endif /* CONFIG_COMPAT */
1205 mon_bin_poll(struct file *file, struct poll_table_struct *wait)
1207 struct mon_reader_bin *rp = file->private_data;
1209 unsigned long flags;
1211 if (file->f_mode & FMODE_READ)
1212 poll_wait(file, &rp->b_wait, wait);
1214 spin_lock_irqsave(&rp->b_lock, flags);
1215 if (!MON_RING_EMPTY(rp))
1216 mask |= EPOLLIN | EPOLLRDNORM; /* readable */
1217 spin_unlock_irqrestore(&rp->b_lock, flags);
1222 * open and close: just keep track of how many times the device is
1223 * mapped, to use the proper memory allocation function.
1225 static void mon_bin_vma_open(struct vm_area_struct *vma)
1227 struct mon_reader_bin *rp = vma->vm_private_data;
1228 unsigned long flags;
1230 spin_lock_irqsave(&rp->b_lock, flags);
1232 spin_unlock_irqrestore(&rp->b_lock, flags);
1235 static void mon_bin_vma_close(struct vm_area_struct *vma)
1237 unsigned long flags;
1239 struct mon_reader_bin *rp = vma->vm_private_data;
1240 spin_lock_irqsave(&rp->b_lock, flags);
1242 spin_unlock_irqrestore(&rp->b_lock, flags);
1246 * Map ring pages to user space.
1248 static vm_fault_t mon_bin_vma_fault(struct vm_fault *vmf)
1250 struct mon_reader_bin *rp = vmf->vma->vm_private_data;
1251 unsigned long offset, chunk_idx;
1252 struct page *pageptr;
1254 offset = vmf->pgoff << PAGE_SHIFT;
1255 if (offset >= rp->b_size)
1256 return VM_FAULT_SIGBUS;
1257 chunk_idx = offset / CHUNK_SIZE;
1258 pageptr = rp->b_vec[chunk_idx].pg;
1260 vmf->page = pageptr;
1264 static const struct vm_operations_struct mon_bin_vm_ops = {
1265 .open = mon_bin_vma_open,
1266 .close = mon_bin_vma_close,
1267 .fault = mon_bin_vma_fault,
1270 static int mon_bin_mmap(struct file *filp, struct vm_area_struct *vma)
1272 /* don't do anything here: "fault" will set up page table entries */
1273 vma->vm_ops = &mon_bin_vm_ops;
1275 if (vma->vm_flags & VM_WRITE)
1278 vm_flags_mod(vma, VM_DONTEXPAND | VM_DONTDUMP, VM_MAYWRITE);
1279 vma->vm_private_data = filp->private_data;
1280 mon_bin_vma_open(vma);
1284 static const struct file_operations mon_fops_binary = {
1285 .owner = THIS_MODULE,
1286 .open = mon_bin_open,
1287 .llseek = no_llseek,
1288 .read = mon_bin_read,
1289 /* .write = mon_text_write, */
1290 .poll = mon_bin_poll,
1291 .unlocked_ioctl = mon_bin_ioctl,
1292 #ifdef CONFIG_COMPAT
1293 .compat_ioctl = mon_bin_compat_ioctl,
1295 .release = mon_bin_release,
1296 .mmap = mon_bin_mmap,
1299 static int mon_bin_wait_event(struct file *file, struct mon_reader_bin *rp)
1301 DECLARE_WAITQUEUE(waita, current);
1302 unsigned long flags;
1304 add_wait_queue(&rp->b_wait, &waita);
1305 set_current_state(TASK_INTERRUPTIBLE);
1307 spin_lock_irqsave(&rp->b_lock, flags);
1308 while (MON_RING_EMPTY(rp)) {
1309 spin_unlock_irqrestore(&rp->b_lock, flags);
1311 if (file->f_flags & O_NONBLOCK) {
1312 set_current_state(TASK_RUNNING);
1313 remove_wait_queue(&rp->b_wait, &waita);
1314 return -EWOULDBLOCK; /* Same as EAGAIN in Linux */
1317 if (signal_pending(current)) {
1318 remove_wait_queue(&rp->b_wait, &waita);
1321 set_current_state(TASK_INTERRUPTIBLE);
1323 spin_lock_irqsave(&rp->b_lock, flags);
1325 spin_unlock_irqrestore(&rp->b_lock, flags);
1327 set_current_state(TASK_RUNNING);
1328 remove_wait_queue(&rp->b_wait, &waita);
1332 static int mon_alloc_buff(struct mon_pgmap *map, int npages)
1335 unsigned long vaddr;
1337 for (n = 0; n < npages; n++) {
1338 vaddr = get_zeroed_page(GFP_KERNEL);
1341 free_page((unsigned long) map[n].ptr);
1344 map[n].ptr = (unsigned char *) vaddr;
1345 map[n].pg = virt_to_page((void *) vaddr);
1350 static void mon_free_buff(struct mon_pgmap *map, int npages)
1354 for (n = 0; n < npages; n++)
1355 free_page((unsigned long) map[n].ptr);
1358 int mon_bin_add(struct mon_bus *mbus, const struct usb_bus *ubus)
1361 unsigned minor = ubus? ubus->busnum: 0;
1363 if (minor >= MON_BIN_MAX_MINOR)
1366 dev = device_create(&mon_bin_class, ubus ? ubus->controller : NULL,
1367 MKDEV(MAJOR(mon_bin_dev0), minor), NULL,
1372 mbus->classdev = dev;
1376 void mon_bin_del(struct mon_bus *mbus)
1378 device_destroy(&mon_bin_class, mbus->classdev->devt);
1381 int __init mon_bin_init(void)
1385 rc = class_register(&mon_bin_class);
1389 rc = alloc_chrdev_region(&mon_bin_dev0, 0, MON_BIN_MAX_MINOR, "usbmon");
1393 cdev_init(&mon_bin_cdev, &mon_fops_binary);
1394 mon_bin_cdev.owner = THIS_MODULE;
1396 rc = cdev_add(&mon_bin_cdev, mon_bin_dev0, MON_BIN_MAX_MINOR);
1403 unregister_chrdev_region(mon_bin_dev0, MON_BIN_MAX_MINOR);
1405 class_unregister(&mon_bin_class);
1410 void mon_bin_exit(void)
1412 cdev_del(&mon_bin_cdev);
1413 unregister_chrdev_region(mon_bin_dev0, MON_BIN_MAX_MINOR);
1414 class_unregister(&mon_bin_class);