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