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