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