• Home
  • History
  • Annotate
  • Line#
  • Navigate
  • Raw
  • Download
  • only in /asuswrt-rt-n18u-9.0.0.4.380.2695/release/src-rt-6.x.4708/linux/linux-2.6.36/drivers/usb/mon/
1/*
2 * The USB Monitor, inspired by Dave Harding's USBMon.
3 *
4 * This is a binary format reader.
5 *
6 * Copyright (C) 2006 Paolo Abeni (paolo.abeni@email.it)
7 * Copyright (C) 2006,2007 Pete Zaitcev (zaitcev@redhat.com)
8 */
9
10#include <linux/kernel.h>
11#include <linux/types.h>
12#include <linux/fs.h>
13#include <linux/cdev.h>
14#include <linux/usb.h>
15#include <linux/poll.h>
16#include <linux/compat.h>
17#include <linux/mm.h>
18#include <linux/smp_lock.h>
19#include <linux/scatterlist.h>
20#include <linux/slab.h>
21
22#include <asm/uaccess.h>
23
24#include "usb_mon.h"
25
26/*
27 * Defined by USB 2.0 clause 9.3, table 9.2.
28 */
29#define SETUP_LEN  8
30
31/* ioctl macros */
32#define MON_IOC_MAGIC 0x92
33
34#define MON_IOCQ_URB_LEN _IO(MON_IOC_MAGIC, 1)
35/* #2 used to be MON_IOCX_URB, removed before it got into Linus tree */
36#define MON_IOCG_STATS _IOR(MON_IOC_MAGIC, 3, struct mon_bin_stats)
37#define MON_IOCT_RING_SIZE _IO(MON_IOC_MAGIC, 4)
38#define MON_IOCQ_RING_SIZE _IO(MON_IOC_MAGIC, 5)
39#define MON_IOCX_GET   _IOW(MON_IOC_MAGIC, 6, struct mon_bin_get)
40#define MON_IOCX_MFETCH _IOWR(MON_IOC_MAGIC, 7, struct mon_bin_mfetch)
41#define MON_IOCH_MFLUSH _IO(MON_IOC_MAGIC, 8)
42/* #9 was MON_IOCT_SETAPI */
43#define MON_IOCX_GETX   _IOW(MON_IOC_MAGIC, 10, struct mon_bin_get)
44
45#ifdef CONFIG_COMPAT
46#define MON_IOCX_GET32 _IOW(MON_IOC_MAGIC, 6, struct mon_bin_get32)
47#define MON_IOCX_MFETCH32 _IOWR(MON_IOC_MAGIC, 7, struct mon_bin_mfetch32)
48#define MON_IOCX_GETX32   _IOW(MON_IOC_MAGIC, 10, struct mon_bin_get32)
49#endif
50
51/*
52 * Some architectures have enormous basic pages (16KB for ia64, 64KB for ppc).
53 * But it's all right. Just use a simple way to make sure the chunk is never
54 * smaller than a page.
55 *
56 * N.B. An application does not know our chunk size.
57 *
58 * Woops, get_zeroed_page() returns a single page. I guess we're stuck with
59 * page-sized chunks for the time being.
60 */
61#define CHUNK_SIZE   PAGE_SIZE
62#define CHUNK_ALIGN(x)   (((x)+CHUNK_SIZE-1) & ~(CHUNK_SIZE-1))
63
64#define BUFF_MAX  CHUNK_ALIGN(1200*1024)
65#define BUFF_DFL   CHUNK_ALIGN(300*1024)
66#define BUFF_MIN     CHUNK_ALIGN(8*1024)
67
68/*
69 * The per-event API header (2 per URB).
70 *
71 * This structure is seen in userland as defined by the documentation.
72 */
73struct mon_bin_hdr {
74	u64 id;			/* URB ID - from submission to callback */
75	unsigned char type;	/* Same as in text API; extensible. */
76	unsigned char xfer_type;	/* ISO, Intr, Control, Bulk */
77	unsigned char epnum;	/* Endpoint number and transfer direction */
78	unsigned char devnum;	/* Device address */
79	unsigned short busnum;	/* Bus number */
80	char flag_setup;
81	char flag_data;
82	s64 ts_sec;		/* gettimeofday */
83	s32 ts_usec;		/* gettimeofday */
84	int status;
85	unsigned int len_urb;	/* Length of data (submitted or actual) */
86	unsigned int len_cap;	/* Delivered length */
87	union {
88		unsigned char setup[SETUP_LEN];	/* Only for Control S-type */
89		struct iso_rec {
90			int error_count;
91			int numdesc;
92		} iso;
93	} s;
94	int interval;
95	int start_frame;
96	unsigned int xfer_flags;
97	unsigned int ndesc;	/* Actual number of ISO descriptors */
98};
99
100/*
101 * ISO vector, packed into the head of data stream.
102 * This has to take 16 bytes to make sure that the end of buffer
103 * wrap is not happening in the middle of a descriptor.
104 */
105struct mon_bin_isodesc {
106	int          iso_status;
107	unsigned int iso_off;
108	unsigned int iso_len;
109	u32 _pad;
110};
111
112/* per file statistic */
113struct mon_bin_stats {
114	u32 queued;
115	u32 dropped;
116};
117
118struct mon_bin_get {
119	struct mon_bin_hdr __user *hdr;	/* Can be 48 bytes or 64. */
120	void __user *data;
121	size_t alloc;		/* Length of data (can be zero) */
122};
123
124struct mon_bin_mfetch {
125	u32 __user *offvec;	/* Vector of events fetched */
126	u32 nfetch;		/* Number of events to fetch (out: fetched) */
127	u32 nflush;		/* Number of events to flush */
128};
129
130#ifdef CONFIG_COMPAT
131struct mon_bin_get32 {
132	u32 hdr32;
133	u32 data32;
134	u32 alloc32;
135};
136
137struct mon_bin_mfetch32 {
138        u32 offvec32;
139        u32 nfetch32;
140        u32 nflush32;
141};
142#endif
143
144/* Having these two values same prevents wrapping of the mon_bin_hdr */
145#define PKT_ALIGN   64
146#define PKT_SIZE    64
147
148#define PKT_SZ_API0 48	/* API 0 (2.6.20) size */
149#define PKT_SZ_API1 64	/* API 1 size: extra fields */
150
151#define ISODESC_MAX   128	/* Same number as usbfs allows, 2048 bytes. */
152
153/* max number of USB bus supported */
154#define MON_BIN_MAX_MINOR 128
155
156/*
157 * The buffer: map of used pages.
158 */
159struct mon_pgmap {
160	struct page *pg;
161	unsigned char *ptr;
162};
163
164/*
165 * This gets associated with an open file struct.
166 */
167struct mon_reader_bin {
168	/* The buffer: one per open. */
169	spinlock_t b_lock;		/* Protect b_cnt, b_in */
170	unsigned int b_size;		/* Current size of the buffer - bytes */
171	unsigned int b_cnt;		/* Bytes used */
172	unsigned int b_in, b_out;	/* Offsets into buffer - bytes */
173	unsigned int b_read;		/* Amount of read data in curr. pkt. */
174	struct mon_pgmap *b_vec;	/* The map array */
175	wait_queue_head_t b_wait;	/* Wait for data here */
176
177	struct mutex fetch_lock;	/* Protect b_read, b_out */
178	int mmap_active;
179
180	/* A list of these is needed for "bus 0". Some time later. */
181	struct mon_reader r;
182
183	/* Stats */
184	unsigned int cnt_lost;
185};
186
187static inline struct mon_bin_hdr *MON_OFF2HDR(const struct mon_reader_bin *rp,
188    unsigned int offset)
189{
190	return (struct mon_bin_hdr *)
191	    (rp->b_vec[offset / CHUNK_SIZE].ptr + offset % CHUNK_SIZE);
192}
193
194#define MON_RING_EMPTY(rp)	((rp)->b_cnt == 0)
195
196static unsigned char xfer_to_pipe[4] = {
197	PIPE_CONTROL, PIPE_ISOCHRONOUS, PIPE_BULK, PIPE_INTERRUPT
198};
199
200static struct class *mon_bin_class;
201static dev_t mon_bin_dev0;
202static struct cdev mon_bin_cdev;
203
204static void mon_buff_area_fill(const struct mon_reader_bin *rp,
205    unsigned int offset, unsigned int size);
206static int mon_bin_wait_event(struct file *file, struct mon_reader_bin *rp);
207static int mon_alloc_buff(struct mon_pgmap *map, int npages);
208static void mon_free_buff(struct mon_pgmap *map, int npages);
209
210/*
211 * This is a "chunked memcpy". It does not manipulate any counters.
212 */
213static unsigned int mon_copy_to_buff(const struct mon_reader_bin *this,
214    unsigned int off, const unsigned char *from, unsigned int length)
215{
216	unsigned int step_len;
217	unsigned char *buf;
218	unsigned int in_page;
219
220	while (length) {
221		/*
222		 * Determine step_len.
223		 */
224		step_len = length;
225		in_page = CHUNK_SIZE - (off & (CHUNK_SIZE-1));
226		if (in_page < step_len)
227			step_len = in_page;
228
229		/*
230		 * Copy data and advance pointers.
231		 */
232		buf = this->b_vec[off / CHUNK_SIZE].ptr + off % CHUNK_SIZE;
233		memcpy(buf, from, step_len);
234		if ((off += step_len) >= this->b_size) off = 0;
235		from += step_len;
236		length -= step_len;
237	}
238	return off;
239}
240
241/*
242 * This is a little worse than the above because it's "chunked copy_to_user".
243 * The return value is an error code, not an offset.
244 */
245static int copy_from_buf(const struct mon_reader_bin *this, unsigned int off,
246    char __user *to, int length)
247{
248	unsigned int step_len;
249	unsigned char *buf;
250	unsigned int in_page;
251
252	while (length) {
253		/*
254		 * Determine step_len.
255		 */
256		step_len = length;
257		in_page = CHUNK_SIZE - (off & (CHUNK_SIZE-1));
258		if (in_page < step_len)
259			step_len = in_page;
260
261		/*
262		 * Copy data and advance pointers.
263		 */
264		buf = this->b_vec[off / CHUNK_SIZE].ptr + off % CHUNK_SIZE;
265		if (copy_to_user(to, buf, step_len))
266			return -EINVAL;
267		if ((off += step_len) >= this->b_size) off = 0;
268		to += step_len;
269		length -= step_len;
270	}
271	return 0;
272}
273
274/*
275 * Allocate an (aligned) area in the buffer.
276 * This is called under b_lock.
277 * Returns ~0 on failure.
278 */
279static unsigned int mon_buff_area_alloc(struct mon_reader_bin *rp,
280    unsigned int size)
281{
282	unsigned int offset;
283
284	size = (size + PKT_ALIGN-1) & ~(PKT_ALIGN-1);
285	if (rp->b_cnt + size > rp->b_size)
286		return ~0;
287	offset = rp->b_in;
288	rp->b_cnt += size;
289	if ((rp->b_in += size) >= rp->b_size)
290		rp->b_in -= rp->b_size;
291	return offset;
292}
293
294/*
295 * This is the same thing as mon_buff_area_alloc, only it does not allow
296 * buffers to wrap. This is needed by applications which pass references
297 * into mmap-ed buffers up their stacks (libpcap can do that).
298 *
299 * Currently, we always have the header stuck with the data, although
300 * it is not strictly speaking necessary.
301 *
302 * When a buffer would wrap, we place a filler packet to mark the space.
303 */
304static unsigned int mon_buff_area_alloc_contiguous(struct mon_reader_bin *rp,
305    unsigned int size)
306{
307	unsigned int offset;
308	unsigned int fill_size;
309
310	size = (size + PKT_ALIGN-1) & ~(PKT_ALIGN-1);
311	if (rp->b_cnt + size > rp->b_size)
312		return ~0;
313	if (rp->b_in + size > rp->b_size) {
314		/*
315		 * This would wrap. Find if we still have space after
316		 * skipping to the end of the buffer. If we do, place
317		 * a filler packet and allocate a new packet.
318		 */
319		fill_size = rp->b_size - rp->b_in;
320		if (rp->b_cnt + size + fill_size > rp->b_size)
321			return ~0;
322		mon_buff_area_fill(rp, rp->b_in, fill_size);
323
324		offset = 0;
325		rp->b_in = size;
326		rp->b_cnt += size + fill_size;
327	} else if (rp->b_in + size == rp->b_size) {
328		offset = rp->b_in;
329		rp->b_in = 0;
330		rp->b_cnt += size;
331	} else {
332		offset = rp->b_in;
333		rp->b_in += size;
334		rp->b_cnt += size;
335	}
336	return offset;
337}
338
339/*
340 * Return a few (kilo-)bytes to the head of the buffer.
341 * This is used if a data fetch fails.
342 */
343static void mon_buff_area_shrink(struct mon_reader_bin *rp, unsigned int size)
344{
345
346	/* size &= ~(PKT_ALIGN-1);  -- we're called with aligned size */
347	rp->b_cnt -= size;
348	if (rp->b_in < size)
349		rp->b_in += rp->b_size;
350	rp->b_in -= size;
351}
352
353/*
354 * This has to be called under both b_lock and fetch_lock, because
355 * it accesses both b_cnt and b_out.
356 */
357static void mon_buff_area_free(struct mon_reader_bin *rp, unsigned int size)
358{
359
360	size = (size + PKT_ALIGN-1) & ~(PKT_ALIGN-1);
361	rp->b_cnt -= size;
362	if ((rp->b_out += size) >= rp->b_size)
363		rp->b_out -= rp->b_size;
364}
365
366static void mon_buff_area_fill(const struct mon_reader_bin *rp,
367    unsigned int offset, unsigned int size)
368{
369	struct mon_bin_hdr *ep;
370
371	ep = MON_OFF2HDR(rp, offset);
372	memset(ep, 0, PKT_SIZE);
373	ep->type = '@';
374	ep->len_cap = size - PKT_SIZE;
375}
376
377static inline char mon_bin_get_setup(unsigned char *setupb,
378    const struct urb *urb, char ev_type)
379{
380
381	if (urb->setup_packet == NULL)
382		return 'Z';
383	memcpy(setupb, urb->setup_packet, SETUP_LEN);
384	return 0;
385}
386
387static unsigned int mon_bin_get_data(const struct mon_reader_bin *rp,
388    unsigned int offset, struct urb *urb, unsigned int length,
389    char *flag)
390{
391	int i;
392	struct scatterlist *sg;
393	unsigned int this_len;
394
395	*flag = 0;
396	if (urb->num_sgs == 0) {
397		if (urb->transfer_buffer == NULL) {
398			*flag = 'Z';
399			return length;
400		}
401		mon_copy_to_buff(rp, offset, urb->transfer_buffer, length);
402		length = 0;
403
404	} else {
405		/* If IOMMU coalescing occurred, we cannot trust sg_page */
406		if (urb->transfer_flags & URB_DMA_SG_COMBINED) {
407			*flag = 'D';
408			return length;
409		}
410
411		/* Copy up to the first non-addressable segment */
412		for_each_sg(urb->sg, sg, urb->num_sgs, i) {
413			if (length == 0 || PageHighMem(sg_page(sg)))
414				break;
415			this_len = min_t(unsigned int, sg->length, length);
416			offset = mon_copy_to_buff(rp, offset, sg_virt(sg),
417					this_len);
418			length -= this_len;
419		}
420		if (i == 0)
421			*flag = 'D';
422	}
423
424	return length;
425}
426
427static void mon_bin_get_isodesc(const struct mon_reader_bin *rp,
428    unsigned int offset, struct urb *urb, char ev_type, unsigned int ndesc)
429{
430	struct mon_bin_isodesc *dp;
431	struct usb_iso_packet_descriptor *fp;
432
433	fp = urb->iso_frame_desc;
434	while (ndesc-- != 0) {
435		dp = (struct mon_bin_isodesc *)
436		    (rp->b_vec[offset / CHUNK_SIZE].ptr + offset % CHUNK_SIZE);
437		dp->iso_status = fp->status;
438		dp->iso_off = fp->offset;
439		dp->iso_len = (ev_type == 'S') ? fp->length : fp->actual_length;
440		dp->_pad = 0;
441		if ((offset += sizeof(struct mon_bin_isodesc)) >= rp->b_size)
442			offset = 0;
443		fp++;
444	}
445}
446
447static void mon_bin_event(struct mon_reader_bin *rp, struct urb *urb,
448    char ev_type, int status)
449{
450	const struct usb_endpoint_descriptor *epd = &urb->ep->desc;
451	struct timeval ts;
452	unsigned long flags;
453	unsigned int urb_length;
454	unsigned int offset;
455	unsigned int length;
456	unsigned int delta;
457	unsigned int ndesc, lendesc;
458	unsigned char dir;
459	struct mon_bin_hdr *ep;
460	char data_tag = 0;
461
462	do_gettimeofday(&ts);
463
464	spin_lock_irqsave(&rp->b_lock, flags);
465
466	/*
467	 * Find the maximum allowable length, then allocate space.
468	 */
469	if (usb_endpoint_xfer_isoc(epd)) {
470		if (urb->number_of_packets < 0) {
471			ndesc = 0;
472		} else if (urb->number_of_packets >= ISODESC_MAX) {
473			ndesc = ISODESC_MAX;
474		} else {
475			ndesc = urb->number_of_packets;
476		}
477	} else {
478		ndesc = 0;
479	}
480	lendesc = ndesc*sizeof(struct mon_bin_isodesc);
481
482	urb_length = (ev_type == 'S') ?
483	    urb->transfer_buffer_length : urb->actual_length;
484	length = urb_length;
485
486	if (length >= rp->b_size/5)
487		length = rp->b_size/5;
488
489	if (usb_urb_dir_in(urb)) {
490		if (ev_type == 'S') {
491			length = 0;
492			data_tag = '<';
493		}
494		/* Cannot rely on endpoint number in case of control ep.0 */
495		dir = USB_DIR_IN;
496	} else {
497		if (ev_type == 'C') {
498			length = 0;
499			data_tag = '>';
500		}
501		dir = 0;
502	}
503
504	if (rp->mmap_active) {
505		offset = mon_buff_area_alloc_contiguous(rp,
506						 length + PKT_SIZE + lendesc);
507	} else {
508		offset = mon_buff_area_alloc(rp, length + PKT_SIZE + lendesc);
509	}
510	if (offset == ~0) {
511		rp->cnt_lost++;
512		spin_unlock_irqrestore(&rp->b_lock, flags);
513		return;
514	}
515
516	ep = MON_OFF2HDR(rp, offset);
517	if ((offset += PKT_SIZE) >= rp->b_size) offset = 0;
518
519	/*
520	 * Fill the allocated area.
521	 */
522	memset(ep, 0, PKT_SIZE);
523	ep->type = ev_type;
524	ep->xfer_type = xfer_to_pipe[usb_endpoint_type(epd)];
525	ep->epnum = dir | usb_endpoint_num(epd);
526	ep->devnum = urb->dev->devnum;
527	ep->busnum = urb->dev->bus->busnum;
528	ep->id = (unsigned long) urb;
529	ep->ts_sec = ts.tv_sec;
530	ep->ts_usec = ts.tv_usec;
531	ep->status = status;
532	ep->len_urb = urb_length;
533	ep->len_cap = length + lendesc;
534	ep->xfer_flags = urb->transfer_flags;
535
536	if (usb_endpoint_xfer_int(epd)) {
537		ep->interval = urb->interval;
538	} else if (usb_endpoint_xfer_isoc(epd)) {
539		ep->interval = urb->interval;
540		ep->start_frame = urb->start_frame;
541		ep->s.iso.error_count = urb->error_count;
542		ep->s.iso.numdesc = urb->number_of_packets;
543	}
544
545	if (usb_endpoint_xfer_control(epd) && ev_type == 'S') {
546		ep->flag_setup = mon_bin_get_setup(ep->s.setup, urb, ev_type);
547	} else {
548		ep->flag_setup = '-';
549	}
550
551	if (ndesc != 0) {
552		ep->ndesc = ndesc;
553		mon_bin_get_isodesc(rp, offset, urb, ev_type, ndesc);
554		if ((offset += lendesc) >= rp->b_size)
555			offset -= rp->b_size;
556	}
557
558	if (length != 0) {
559		length = mon_bin_get_data(rp, offset, urb, length,
560				&ep->flag_data);
561		if (length > 0) {
562			delta = (ep->len_cap + PKT_ALIGN-1) & ~(PKT_ALIGN-1);
563			ep->len_cap -= length;
564			delta -= (ep->len_cap + PKT_ALIGN-1) & ~(PKT_ALIGN-1);
565			mon_buff_area_shrink(rp, delta);
566		}
567	} else {
568		ep->flag_data = data_tag;
569	}
570
571	spin_unlock_irqrestore(&rp->b_lock, flags);
572
573	wake_up(&rp->b_wait);
574}
575
576static void mon_bin_submit(void *data, struct urb *urb)
577{
578	struct mon_reader_bin *rp = data;
579	mon_bin_event(rp, urb, 'S', -EINPROGRESS);
580}
581
582static void mon_bin_complete(void *data, struct urb *urb, int status)
583{
584	struct mon_reader_bin *rp = data;
585	mon_bin_event(rp, urb, 'C', status);
586}
587
588static void mon_bin_error(void *data, struct urb *urb, int error)
589{
590	struct mon_reader_bin *rp = data;
591	struct timeval ts;
592	unsigned long flags;
593	unsigned int offset;
594	struct mon_bin_hdr *ep;
595
596	do_gettimeofday(&ts);
597
598	spin_lock_irqsave(&rp->b_lock, flags);
599
600	offset = mon_buff_area_alloc(rp, PKT_SIZE);
601	if (offset == ~0) {
602		/* Not incrementing cnt_lost. Just because. */
603		spin_unlock_irqrestore(&rp->b_lock, flags);
604		return;
605	}
606
607	ep = MON_OFF2HDR(rp, offset);
608
609	memset(ep, 0, PKT_SIZE);
610	ep->type = 'E';
611	ep->xfer_type = xfer_to_pipe[usb_endpoint_type(&urb->ep->desc)];
612	ep->epnum = usb_urb_dir_in(urb) ? USB_DIR_IN : 0;
613	ep->epnum |= usb_endpoint_num(&urb->ep->desc);
614	ep->devnum = urb->dev->devnum;
615	ep->busnum = urb->dev->bus->busnum;
616	ep->id = (unsigned long) urb;
617	ep->ts_sec = ts.tv_sec;
618	ep->ts_usec = ts.tv_usec;
619	ep->status = error;
620
621	ep->flag_setup = '-';
622	ep->flag_data = 'E';
623
624	spin_unlock_irqrestore(&rp->b_lock, flags);
625
626	wake_up(&rp->b_wait);
627}
628
629static int mon_bin_open(struct inode *inode, struct file *file)
630{
631	struct mon_bus *mbus;
632	struct mon_reader_bin *rp;
633	size_t size;
634	int rc;
635
636	mutex_lock(&mon_lock);
637	if ((mbus = mon_bus_lookup(iminor(inode))) == NULL) {
638		mutex_unlock(&mon_lock);
639		return -ENODEV;
640	}
641	if (mbus != &mon_bus0 && mbus->u_bus == NULL) {
642		printk(KERN_ERR TAG ": consistency error on open\n");
643		mutex_unlock(&mon_lock);
644		return -ENODEV;
645	}
646
647	rp = kzalloc(sizeof(struct mon_reader_bin), GFP_KERNEL);
648	if (rp == NULL) {
649		rc = -ENOMEM;
650		goto err_alloc;
651	}
652	spin_lock_init(&rp->b_lock);
653	init_waitqueue_head(&rp->b_wait);
654	mutex_init(&rp->fetch_lock);
655	rp->b_size = BUFF_DFL;
656
657	size = sizeof(struct mon_pgmap) * (rp->b_size/CHUNK_SIZE);
658	if ((rp->b_vec = kzalloc(size, GFP_KERNEL)) == NULL) {
659		rc = -ENOMEM;
660		goto err_allocvec;
661	}
662
663	if ((rc = mon_alloc_buff(rp->b_vec, rp->b_size/CHUNK_SIZE)) < 0)
664		goto err_allocbuff;
665
666	rp->r.m_bus = mbus;
667	rp->r.r_data = rp;
668	rp->r.rnf_submit = mon_bin_submit;
669	rp->r.rnf_error = mon_bin_error;
670	rp->r.rnf_complete = mon_bin_complete;
671
672	mon_reader_add(mbus, &rp->r);
673
674	file->private_data = rp;
675	mutex_unlock(&mon_lock);
676	return 0;
677
678err_allocbuff:
679	kfree(rp->b_vec);
680err_allocvec:
681	kfree(rp);
682err_alloc:
683	mutex_unlock(&mon_lock);
684	return rc;
685}
686
687/*
688 * Extract an event from buffer and copy it to user space.
689 * Wait if there is no event ready.
690 * Returns zero or error.
691 */
692static int mon_bin_get_event(struct file *file, struct mon_reader_bin *rp,
693    struct mon_bin_hdr __user *hdr, unsigned int hdrbytes,
694    void __user *data, unsigned int nbytes)
695{
696	unsigned long flags;
697	struct mon_bin_hdr *ep;
698	size_t step_len;
699	unsigned int offset;
700	int rc;
701
702	mutex_lock(&rp->fetch_lock);
703
704	if ((rc = mon_bin_wait_event(file, rp)) < 0) {
705		mutex_unlock(&rp->fetch_lock);
706		return rc;
707	}
708
709	ep = MON_OFF2HDR(rp, rp->b_out);
710
711	if (copy_to_user(hdr, ep, hdrbytes)) {
712		mutex_unlock(&rp->fetch_lock);
713		return -EFAULT;
714	}
715
716	step_len = min(ep->len_cap, nbytes);
717	if ((offset = rp->b_out + PKT_SIZE) >= rp->b_size) offset = 0;
718
719	if (copy_from_buf(rp, offset, data, step_len)) {
720		mutex_unlock(&rp->fetch_lock);
721		return -EFAULT;
722	}
723
724	spin_lock_irqsave(&rp->b_lock, flags);
725	mon_buff_area_free(rp, PKT_SIZE + ep->len_cap);
726	spin_unlock_irqrestore(&rp->b_lock, flags);
727	rp->b_read = 0;
728
729	mutex_unlock(&rp->fetch_lock);
730	return 0;
731}
732
733static int mon_bin_release(struct inode *inode, struct file *file)
734{
735	struct mon_reader_bin *rp = file->private_data;
736	struct mon_bus* mbus = rp->r.m_bus;
737
738	mutex_lock(&mon_lock);
739
740	if (mbus->nreaders <= 0) {
741		printk(KERN_ERR TAG ": consistency error on close\n");
742		mutex_unlock(&mon_lock);
743		return 0;
744	}
745	mon_reader_del(mbus, &rp->r);
746
747	mon_free_buff(rp->b_vec, rp->b_size/CHUNK_SIZE);
748	kfree(rp->b_vec);
749	kfree(rp);
750
751	mutex_unlock(&mon_lock);
752	return 0;
753}
754
755static ssize_t mon_bin_read(struct file *file, char __user *buf,
756    size_t nbytes, loff_t *ppos)
757{
758	struct mon_reader_bin *rp = file->private_data;
759	unsigned int hdrbytes = PKT_SZ_API0;
760	unsigned long flags;
761	struct mon_bin_hdr *ep;
762	unsigned int offset;
763	size_t step_len;
764	char *ptr;
765	ssize_t done = 0;
766	int rc;
767
768	mutex_lock(&rp->fetch_lock);
769
770	if ((rc = mon_bin_wait_event(file, rp)) < 0) {
771		mutex_unlock(&rp->fetch_lock);
772		return rc;
773	}
774
775	ep = MON_OFF2HDR(rp, rp->b_out);
776
777	if (rp->b_read < hdrbytes) {
778		step_len = min(nbytes, (size_t)(hdrbytes - rp->b_read));
779		ptr = ((char *)ep) + rp->b_read;
780		if (step_len && copy_to_user(buf, ptr, step_len)) {
781			mutex_unlock(&rp->fetch_lock);
782			return -EFAULT;
783		}
784		nbytes -= step_len;
785		buf += step_len;
786		rp->b_read += step_len;
787		done += step_len;
788	}
789
790	if (rp->b_read >= hdrbytes) {
791		step_len = ep->len_cap;
792		step_len -= rp->b_read - hdrbytes;
793		if (step_len > nbytes)
794			step_len = nbytes;
795		offset = rp->b_out + PKT_SIZE;
796		offset += rp->b_read - hdrbytes;
797		if (offset >= rp->b_size)
798			offset -= rp->b_size;
799		if (copy_from_buf(rp, offset, buf, step_len)) {
800			mutex_unlock(&rp->fetch_lock);
801			return -EFAULT;
802		}
803		nbytes -= step_len;
804		buf += step_len;
805		rp->b_read += step_len;
806		done += step_len;
807	}
808
809	/*
810	 * Check if whole packet was read, and if so, jump to the next one.
811	 */
812	if (rp->b_read >= hdrbytes + ep->len_cap) {
813		spin_lock_irqsave(&rp->b_lock, flags);
814		mon_buff_area_free(rp, PKT_SIZE + ep->len_cap);
815		spin_unlock_irqrestore(&rp->b_lock, flags);
816		rp->b_read = 0;
817	}
818
819	mutex_unlock(&rp->fetch_lock);
820	return done;
821}
822
823/*
824 * Remove at most nevents from chunked buffer.
825 * Returns the number of removed events.
826 */
827static int mon_bin_flush(struct mon_reader_bin *rp, unsigned nevents)
828{
829	unsigned long flags;
830	struct mon_bin_hdr *ep;
831	int i;
832
833	mutex_lock(&rp->fetch_lock);
834	spin_lock_irqsave(&rp->b_lock, flags);
835	for (i = 0; i < nevents; ++i) {
836		if (MON_RING_EMPTY(rp))
837			break;
838
839		ep = MON_OFF2HDR(rp, rp->b_out);
840		mon_buff_area_free(rp, PKT_SIZE + ep->len_cap);
841	}
842	spin_unlock_irqrestore(&rp->b_lock, flags);
843	rp->b_read = 0;
844	mutex_unlock(&rp->fetch_lock);
845	return i;
846}
847
848/*
849 * Fetch at most max event offsets into the buffer and put them into vec.
850 * The events are usually freed later with mon_bin_flush.
851 * Return the effective number of events fetched.
852 */
853static int mon_bin_fetch(struct file *file, struct mon_reader_bin *rp,
854    u32 __user *vec, unsigned int max)
855{
856	unsigned int cur_out;
857	unsigned int bytes, avail;
858	unsigned int size;
859	unsigned int nevents;
860	struct mon_bin_hdr *ep;
861	unsigned long flags;
862	int rc;
863
864	mutex_lock(&rp->fetch_lock);
865
866	if ((rc = mon_bin_wait_event(file, rp)) < 0) {
867		mutex_unlock(&rp->fetch_lock);
868		return rc;
869	}
870
871	spin_lock_irqsave(&rp->b_lock, flags);
872	avail = rp->b_cnt;
873	spin_unlock_irqrestore(&rp->b_lock, flags);
874
875	cur_out = rp->b_out;
876	nevents = 0;
877	bytes = 0;
878	while (bytes < avail) {
879		if (nevents >= max)
880			break;
881
882		ep = MON_OFF2HDR(rp, cur_out);
883		if (put_user(cur_out, &vec[nevents])) {
884			mutex_unlock(&rp->fetch_lock);
885			return -EFAULT;
886		}
887
888		nevents++;
889		size = ep->len_cap + PKT_SIZE;
890		size = (size + PKT_ALIGN-1) & ~(PKT_ALIGN-1);
891		if ((cur_out += size) >= rp->b_size)
892			cur_out -= rp->b_size;
893		bytes += size;
894	}
895
896	mutex_unlock(&rp->fetch_lock);
897	return nevents;
898}
899
900/*
901 * Count events. This is almost the same as the above mon_bin_fetch,
902 * only we do not store offsets into user vector, and we have no limit.
903 */
904static int mon_bin_queued(struct mon_reader_bin *rp)
905{
906	unsigned int cur_out;
907	unsigned int bytes, avail;
908	unsigned int size;
909	unsigned int nevents;
910	struct mon_bin_hdr *ep;
911	unsigned long flags;
912
913	mutex_lock(&rp->fetch_lock);
914
915	spin_lock_irqsave(&rp->b_lock, flags);
916	avail = rp->b_cnt;
917	spin_unlock_irqrestore(&rp->b_lock, flags);
918
919	cur_out = rp->b_out;
920	nevents = 0;
921	bytes = 0;
922	while (bytes < avail) {
923		ep = MON_OFF2HDR(rp, cur_out);
924
925		nevents++;
926		size = ep->len_cap + PKT_SIZE;
927		size = (size + PKT_ALIGN-1) & ~(PKT_ALIGN-1);
928		if ((cur_out += size) >= rp->b_size)
929			cur_out -= rp->b_size;
930		bytes += size;
931	}
932
933	mutex_unlock(&rp->fetch_lock);
934	return nevents;
935}
936
937/*
938 */
939static long mon_bin_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
940{
941	struct mon_reader_bin *rp = file->private_data;
942	// struct mon_bus* mbus = rp->r.m_bus;
943	int ret = 0;
944	struct mon_bin_hdr *ep;
945	unsigned long flags;
946
947	switch (cmd) {
948
949	case MON_IOCQ_URB_LEN:
950		/*
951		 * N.B. This only returns the size of data, without the header.
952		 */
953		spin_lock_irqsave(&rp->b_lock, flags);
954		if (!MON_RING_EMPTY(rp)) {
955			ep = MON_OFF2HDR(rp, rp->b_out);
956			ret = ep->len_cap;
957		}
958		spin_unlock_irqrestore(&rp->b_lock, flags);
959		break;
960
961	case MON_IOCQ_RING_SIZE:
962		ret = rp->b_size;
963		break;
964
965	case MON_IOCT_RING_SIZE:
966		/*
967		 * Changing the buffer size will flush it's contents; the new
968		 * buffer is allocated before releasing the old one to be sure
969		 * the device will stay functional also in case of memory
970		 * pressure.
971		 */
972		{
973		int size;
974		struct mon_pgmap *vec;
975
976		if (arg < BUFF_MIN || arg > BUFF_MAX)
977			return -EINVAL;
978
979		size = CHUNK_ALIGN(arg);
980		if ((vec = kzalloc(sizeof(struct mon_pgmap) * (size/CHUNK_SIZE),
981		    GFP_KERNEL)) == NULL) {
982			ret = -ENOMEM;
983			break;
984		}
985
986		ret = mon_alloc_buff(vec, size/CHUNK_SIZE);
987		if (ret < 0) {
988			kfree(vec);
989			break;
990		}
991
992		mutex_lock(&rp->fetch_lock);
993		spin_lock_irqsave(&rp->b_lock, flags);
994		mon_free_buff(rp->b_vec, rp->b_size/CHUNK_SIZE);
995		kfree(rp->b_vec);
996		rp->b_vec  = vec;
997		rp->b_size = size;
998		rp->b_read = rp->b_in = rp->b_out = rp->b_cnt = 0;
999		rp->cnt_lost = 0;
1000		spin_unlock_irqrestore(&rp->b_lock, flags);
1001		mutex_unlock(&rp->fetch_lock);
1002		}
1003		break;
1004
1005	case MON_IOCH_MFLUSH:
1006		ret = mon_bin_flush(rp, arg);
1007		break;
1008
1009	case MON_IOCX_GET:
1010	case MON_IOCX_GETX:
1011		{
1012		struct mon_bin_get getb;
1013
1014		if (copy_from_user(&getb, (void __user *)arg,
1015					    sizeof(struct mon_bin_get)))
1016			return -EFAULT;
1017
1018		if (getb.alloc > 0x10000000)	/* Want to cast to u32 */
1019			return -EINVAL;
1020		ret = mon_bin_get_event(file, rp, getb.hdr,
1021		    (cmd == MON_IOCX_GET)? PKT_SZ_API0: PKT_SZ_API1,
1022		    getb.data, (unsigned int)getb.alloc);
1023		}
1024		break;
1025
1026	case MON_IOCX_MFETCH:
1027		{
1028		struct mon_bin_mfetch mfetch;
1029		struct mon_bin_mfetch __user *uptr;
1030
1031		uptr = (struct mon_bin_mfetch __user *)arg;
1032
1033		if (copy_from_user(&mfetch, uptr, sizeof(mfetch)))
1034			return -EFAULT;
1035
1036		if (mfetch.nflush) {
1037			ret = mon_bin_flush(rp, mfetch.nflush);
1038			if (ret < 0)
1039				return ret;
1040			if (put_user(ret, &uptr->nflush))
1041				return -EFAULT;
1042		}
1043		ret = mon_bin_fetch(file, rp, mfetch.offvec, mfetch.nfetch);
1044		if (ret < 0)
1045			return ret;
1046		if (put_user(ret, &uptr->nfetch))
1047			return -EFAULT;
1048		ret = 0;
1049		}
1050		break;
1051
1052	case MON_IOCG_STATS: {
1053		struct mon_bin_stats __user *sp;
1054		unsigned int nevents;
1055		unsigned int ndropped;
1056
1057		spin_lock_irqsave(&rp->b_lock, flags);
1058		ndropped = rp->cnt_lost;
1059		rp->cnt_lost = 0;
1060		spin_unlock_irqrestore(&rp->b_lock, flags);
1061		nevents = mon_bin_queued(rp);
1062
1063		sp = (struct mon_bin_stats __user *)arg;
1064		if (put_user(rp->cnt_lost, &sp->dropped))
1065			return -EFAULT;
1066		if (put_user(nevents, &sp->queued))
1067			return -EFAULT;
1068
1069		}
1070		break;
1071
1072	default:
1073		return -ENOTTY;
1074	}
1075
1076	return ret;
1077}
1078
1079#ifdef CONFIG_COMPAT
1080static long mon_bin_compat_ioctl(struct file *file,
1081    unsigned int cmd, unsigned long arg)
1082{
1083	struct mon_reader_bin *rp = file->private_data;
1084	int ret;
1085
1086	switch (cmd) {
1087
1088	case MON_IOCX_GET32:
1089	case MON_IOCX_GETX32:
1090		{
1091		struct mon_bin_get32 getb;
1092
1093		if (copy_from_user(&getb, (void __user *)arg,
1094					    sizeof(struct mon_bin_get32)))
1095			return -EFAULT;
1096
1097		ret = mon_bin_get_event(file, rp, compat_ptr(getb.hdr32),
1098		    (cmd == MON_IOCX_GET32)? PKT_SZ_API0: PKT_SZ_API1,
1099		    compat_ptr(getb.data32), getb.alloc32);
1100		if (ret < 0)
1101			return ret;
1102		}
1103		return 0;
1104
1105	case MON_IOCX_MFETCH32:
1106		{
1107		struct mon_bin_mfetch32 mfetch;
1108		struct mon_bin_mfetch32 __user *uptr;
1109
1110		uptr = (struct mon_bin_mfetch32 __user *) compat_ptr(arg);
1111
1112		if (copy_from_user(&mfetch, uptr, sizeof(mfetch)))
1113			return -EFAULT;
1114
1115		if (mfetch.nflush32) {
1116			ret = mon_bin_flush(rp, mfetch.nflush32);
1117			if (ret < 0)
1118				return ret;
1119			if (put_user(ret, &uptr->nflush32))
1120				return -EFAULT;
1121		}
1122		ret = mon_bin_fetch(file, rp, compat_ptr(mfetch.offvec32),
1123		    mfetch.nfetch32);
1124		if (ret < 0)
1125			return ret;
1126		if (put_user(ret, &uptr->nfetch32))
1127			return -EFAULT;
1128		}
1129		return 0;
1130
1131	case MON_IOCG_STATS:
1132		return mon_bin_ioctl(file, cmd, (unsigned long) compat_ptr(arg));
1133
1134	case MON_IOCQ_URB_LEN:
1135	case MON_IOCQ_RING_SIZE:
1136	case MON_IOCT_RING_SIZE:
1137	case MON_IOCH_MFLUSH:
1138		return mon_bin_ioctl(file, cmd, arg);
1139
1140	default:
1141		;
1142	}
1143	return -ENOTTY;
1144}
1145#endif /* CONFIG_COMPAT */
1146
1147static unsigned int
1148mon_bin_poll(struct file *file, struct poll_table_struct *wait)
1149{
1150	struct mon_reader_bin *rp = file->private_data;
1151	unsigned int mask = 0;
1152	unsigned long flags;
1153
1154	if (file->f_mode & FMODE_READ)
1155		poll_wait(file, &rp->b_wait, wait);
1156
1157	spin_lock_irqsave(&rp->b_lock, flags);
1158	if (!MON_RING_EMPTY(rp))
1159		mask |= POLLIN | POLLRDNORM;    /* readable */
1160	spin_unlock_irqrestore(&rp->b_lock, flags);
1161	return mask;
1162}
1163
1164/*
1165 * open and close: just keep track of how many times the device is
1166 * mapped, to use the proper memory allocation function.
1167 */
1168static void mon_bin_vma_open(struct vm_area_struct *vma)
1169{
1170	struct mon_reader_bin *rp = vma->vm_private_data;
1171	rp->mmap_active++;
1172}
1173
1174static void mon_bin_vma_close(struct vm_area_struct *vma)
1175{
1176	struct mon_reader_bin *rp = vma->vm_private_data;
1177	rp->mmap_active--;
1178}
1179
1180/*
1181 * Map ring pages to user space.
1182 */
1183static int mon_bin_vma_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
1184{
1185	struct mon_reader_bin *rp = vma->vm_private_data;
1186	unsigned long offset, chunk_idx;
1187	struct page *pageptr;
1188
1189	offset = vmf->pgoff << PAGE_SHIFT;
1190	if (offset >= rp->b_size)
1191		return VM_FAULT_SIGBUS;
1192	chunk_idx = offset / CHUNK_SIZE;
1193	pageptr = rp->b_vec[chunk_idx].pg;
1194	get_page(pageptr);
1195	vmf->page = pageptr;
1196	return 0;
1197}
1198
1199static const struct vm_operations_struct mon_bin_vm_ops = {
1200	.open =     mon_bin_vma_open,
1201	.close =    mon_bin_vma_close,
1202	.fault =    mon_bin_vma_fault,
1203};
1204
1205static int mon_bin_mmap(struct file *filp, struct vm_area_struct *vma)
1206{
1207	/* don't do anything here: "fault" will set up page table entries */
1208	vma->vm_ops = &mon_bin_vm_ops;
1209	vma->vm_flags |= VM_RESERVED;
1210	vma->vm_private_data = filp->private_data;
1211	mon_bin_vma_open(vma);
1212	return 0;
1213}
1214
1215static const struct file_operations mon_fops_binary = {
1216	.owner =	THIS_MODULE,
1217	.open =		mon_bin_open,
1218	.llseek =	no_llseek,
1219	.read =		mon_bin_read,
1220	/* .write =	mon_text_write, */
1221	.poll =		mon_bin_poll,
1222	.unlocked_ioctl = mon_bin_ioctl,
1223#ifdef CONFIG_COMPAT
1224	.compat_ioctl =	mon_bin_compat_ioctl,
1225#endif
1226	.release =	mon_bin_release,
1227	.mmap =		mon_bin_mmap,
1228};
1229
1230static int mon_bin_wait_event(struct file *file, struct mon_reader_bin *rp)
1231{
1232	DECLARE_WAITQUEUE(waita, current);
1233	unsigned long flags;
1234
1235	add_wait_queue(&rp->b_wait, &waita);
1236	set_current_state(TASK_INTERRUPTIBLE);
1237
1238	spin_lock_irqsave(&rp->b_lock, flags);
1239	while (MON_RING_EMPTY(rp)) {
1240		spin_unlock_irqrestore(&rp->b_lock, flags);
1241
1242		if (file->f_flags & O_NONBLOCK) {
1243			set_current_state(TASK_RUNNING);
1244			remove_wait_queue(&rp->b_wait, &waita);
1245			return -EWOULDBLOCK; /* Same as EAGAIN in Linux */
1246		}
1247		schedule();
1248		if (signal_pending(current)) {
1249			remove_wait_queue(&rp->b_wait, &waita);
1250			return -EINTR;
1251		}
1252		set_current_state(TASK_INTERRUPTIBLE);
1253
1254		spin_lock_irqsave(&rp->b_lock, flags);
1255	}
1256	spin_unlock_irqrestore(&rp->b_lock, flags);
1257
1258	set_current_state(TASK_RUNNING);
1259	remove_wait_queue(&rp->b_wait, &waita);
1260	return 0;
1261}
1262
1263static int mon_alloc_buff(struct mon_pgmap *map, int npages)
1264{
1265	int n;
1266	unsigned long vaddr;
1267
1268	for (n = 0; n < npages; n++) {
1269		vaddr = get_zeroed_page(GFP_KERNEL);
1270		if (vaddr == 0) {
1271			while (n-- != 0)
1272				free_page((unsigned long) map[n].ptr);
1273			return -ENOMEM;
1274		}
1275		map[n].ptr = (unsigned char *) vaddr;
1276		map[n].pg = virt_to_page((void *) vaddr);
1277	}
1278	return 0;
1279}
1280
1281static void mon_free_buff(struct mon_pgmap *map, int npages)
1282{
1283	int n;
1284
1285	for (n = 0; n < npages; n++)
1286		free_page((unsigned long) map[n].ptr);
1287}
1288
1289int mon_bin_add(struct mon_bus *mbus, const struct usb_bus *ubus)
1290{
1291	struct device *dev;
1292	unsigned minor = ubus? ubus->busnum: 0;
1293
1294	if (minor >= MON_BIN_MAX_MINOR)
1295		return 0;
1296
1297	dev = device_create(mon_bin_class, ubus ? ubus->controller : NULL,
1298			    MKDEV(MAJOR(mon_bin_dev0), minor), NULL,
1299			    "usbmon%d", minor);
1300	if (IS_ERR(dev))
1301		return 0;
1302
1303	mbus->classdev = dev;
1304	return 1;
1305}
1306
1307void mon_bin_del(struct mon_bus *mbus)
1308{
1309	device_destroy(mon_bin_class, mbus->classdev->devt);
1310}
1311
1312int __init mon_bin_init(void)
1313{
1314	int rc;
1315
1316	mon_bin_class = class_create(THIS_MODULE, "usbmon");
1317	if (IS_ERR(mon_bin_class)) {
1318		rc = PTR_ERR(mon_bin_class);
1319		goto err_class;
1320	}
1321
1322	rc = alloc_chrdev_region(&mon_bin_dev0, 0, MON_BIN_MAX_MINOR, "usbmon");
1323	if (rc < 0)
1324		goto err_dev;
1325
1326	cdev_init(&mon_bin_cdev, &mon_fops_binary);
1327	mon_bin_cdev.owner = THIS_MODULE;
1328
1329	rc = cdev_add(&mon_bin_cdev, mon_bin_dev0, MON_BIN_MAX_MINOR);
1330	if (rc < 0)
1331		goto err_add;
1332
1333	return 0;
1334
1335err_add:
1336	unregister_chrdev_region(mon_bin_dev0, MON_BIN_MAX_MINOR);
1337err_dev:
1338	class_destroy(mon_bin_class);
1339err_class:
1340	return rc;
1341}
1342
1343void mon_bin_exit(void)
1344{
1345	cdev_del(&mon_bin_cdev);
1346	unregister_chrdev_region(mon_bin_dev0, MON_BIN_MAX_MINOR);
1347	class_destroy(mon_bin_class);
1348}
1349