xref: /openbmc/linux/kernel/trace/blktrace.c (revision dc6a81c3)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Copyright (C) 2006 Jens Axboe <axboe@kernel.dk>
4  *
5  */
6 #include <linux/kernel.h>
7 #include <linux/blkdev.h>
8 #include <linux/blktrace_api.h>
9 #include <linux/percpu.h>
10 #include <linux/init.h>
11 #include <linux/mutex.h>
12 #include <linux/slab.h>
13 #include <linux/debugfs.h>
14 #include <linux/export.h>
15 #include <linux/time.h>
16 #include <linux/uaccess.h>
17 #include <linux/list.h>
18 #include <linux/blk-cgroup.h>
19 
20 #include "../../block/blk.h"
21 
22 #include <trace/events/block.h>
23 
24 #include "trace_output.h"
25 
26 #ifdef CONFIG_BLK_DEV_IO_TRACE
27 
28 static unsigned int blktrace_seq __read_mostly = 1;
29 
30 static struct trace_array *blk_tr;
31 static bool blk_tracer_enabled __read_mostly;
32 
33 static LIST_HEAD(running_trace_list);
34 static __cacheline_aligned_in_smp DEFINE_SPINLOCK(running_trace_lock);
35 
36 /* Select an alternative, minimalistic output than the original one */
37 #define TRACE_BLK_OPT_CLASSIC	0x1
38 #define TRACE_BLK_OPT_CGROUP	0x2
39 #define TRACE_BLK_OPT_CGNAME	0x4
40 
41 static struct tracer_opt blk_tracer_opts[] = {
42 	/* Default disable the minimalistic output */
43 	{ TRACER_OPT(blk_classic, TRACE_BLK_OPT_CLASSIC) },
44 #ifdef CONFIG_BLK_CGROUP
45 	{ TRACER_OPT(blk_cgroup, TRACE_BLK_OPT_CGROUP) },
46 	{ TRACER_OPT(blk_cgname, TRACE_BLK_OPT_CGNAME) },
47 #endif
48 	{ }
49 };
50 
51 static struct tracer_flags blk_tracer_flags = {
52 	.val  = 0,
53 	.opts = blk_tracer_opts,
54 };
55 
56 /* Global reference count of probes */
57 static DEFINE_MUTEX(blk_probe_mutex);
58 static int blk_probes_ref;
59 
60 static void blk_register_tracepoints(void);
61 static void blk_unregister_tracepoints(void);
62 
63 /*
64  * Send out a notify message.
65  */
66 static void trace_note(struct blk_trace *bt, pid_t pid, int action,
67 		       const void *data, size_t len, u64 cgid)
68 {
69 	struct blk_io_trace *t;
70 	struct ring_buffer_event *event = NULL;
71 	struct trace_buffer *buffer = NULL;
72 	int pc = 0;
73 	int cpu = smp_processor_id();
74 	bool blk_tracer = blk_tracer_enabled;
75 	ssize_t cgid_len = cgid ? sizeof(cgid) : 0;
76 
77 	if (blk_tracer) {
78 		buffer = blk_tr->array_buffer.buffer;
79 		pc = preempt_count();
80 		event = trace_buffer_lock_reserve(buffer, TRACE_BLK,
81 						  sizeof(*t) + len + cgid_len,
82 						  0, pc);
83 		if (!event)
84 			return;
85 		t = ring_buffer_event_data(event);
86 		goto record_it;
87 	}
88 
89 	if (!bt->rchan)
90 		return;
91 
92 	t = relay_reserve(bt->rchan, sizeof(*t) + len + cgid_len);
93 	if (t) {
94 		t->magic = BLK_IO_TRACE_MAGIC | BLK_IO_TRACE_VERSION;
95 		t->time = ktime_to_ns(ktime_get());
96 record_it:
97 		t->device = bt->dev;
98 		t->action = action | (cgid ? __BLK_TN_CGROUP : 0);
99 		t->pid = pid;
100 		t->cpu = cpu;
101 		t->pdu_len = len + cgid_len;
102 		if (cgid_len)
103 			memcpy((void *)t + sizeof(*t), &cgid, cgid_len);
104 		memcpy((void *) t + sizeof(*t) + cgid_len, data, len);
105 
106 		if (blk_tracer)
107 			trace_buffer_unlock_commit(blk_tr, buffer, event, 0, pc);
108 	}
109 }
110 
111 /*
112  * Send out a notify for this process, if we haven't done so since a trace
113  * started
114  */
115 static void trace_note_tsk(struct task_struct *tsk)
116 {
117 	unsigned long flags;
118 	struct blk_trace *bt;
119 
120 	tsk->btrace_seq = blktrace_seq;
121 	spin_lock_irqsave(&running_trace_lock, flags);
122 	list_for_each_entry(bt, &running_trace_list, running_list) {
123 		trace_note(bt, tsk->pid, BLK_TN_PROCESS, tsk->comm,
124 			   sizeof(tsk->comm), 0);
125 	}
126 	spin_unlock_irqrestore(&running_trace_lock, flags);
127 }
128 
129 static void trace_note_time(struct blk_trace *bt)
130 {
131 	struct timespec64 now;
132 	unsigned long flags;
133 	u32 words[2];
134 
135 	/* need to check user space to see if this breaks in y2038 or y2106 */
136 	ktime_get_real_ts64(&now);
137 	words[0] = (u32)now.tv_sec;
138 	words[1] = now.tv_nsec;
139 
140 	local_irq_save(flags);
141 	trace_note(bt, 0, BLK_TN_TIMESTAMP, words, sizeof(words), 0);
142 	local_irq_restore(flags);
143 }
144 
145 void __trace_note_message(struct blk_trace *bt, struct blkcg *blkcg,
146 	const char *fmt, ...)
147 {
148 	int n;
149 	va_list args;
150 	unsigned long flags;
151 	char *buf;
152 
153 	if (unlikely(bt->trace_state != Blktrace_running &&
154 		     !blk_tracer_enabled))
155 		return;
156 
157 	/*
158 	 * If the BLK_TC_NOTIFY action mask isn't set, don't send any note
159 	 * message to the trace.
160 	 */
161 	if (!(bt->act_mask & BLK_TC_NOTIFY))
162 		return;
163 
164 	local_irq_save(flags);
165 	buf = this_cpu_ptr(bt->msg_data);
166 	va_start(args, fmt);
167 	n = vscnprintf(buf, BLK_TN_MAX_MSG, fmt, args);
168 	va_end(args);
169 
170 	if (!(blk_tracer_flags.val & TRACE_BLK_OPT_CGROUP))
171 		blkcg = NULL;
172 #ifdef CONFIG_BLK_CGROUP
173 	trace_note(bt, 0, BLK_TN_MESSAGE, buf, n,
174 		   blkcg ? cgroup_id(blkcg->css.cgroup) : 1);
175 #else
176 	trace_note(bt, 0, BLK_TN_MESSAGE, buf, n, 0);
177 #endif
178 	local_irq_restore(flags);
179 }
180 EXPORT_SYMBOL_GPL(__trace_note_message);
181 
182 static int act_log_check(struct blk_trace *bt, u32 what, sector_t sector,
183 			 pid_t pid)
184 {
185 	if (((bt->act_mask << BLK_TC_SHIFT) & what) == 0)
186 		return 1;
187 	if (sector && (sector < bt->start_lba || sector > bt->end_lba))
188 		return 1;
189 	if (bt->pid && pid != bt->pid)
190 		return 1;
191 
192 	return 0;
193 }
194 
195 /*
196  * Data direction bit lookup
197  */
198 static const u32 ddir_act[2] = { BLK_TC_ACT(BLK_TC_READ),
199 				 BLK_TC_ACT(BLK_TC_WRITE) };
200 
201 #define BLK_TC_RAHEAD		BLK_TC_AHEAD
202 #define BLK_TC_PREFLUSH		BLK_TC_FLUSH
203 
204 /* The ilog2() calls fall out because they're constant */
205 #define MASK_TC_BIT(rw, __name) ((rw & REQ_ ## __name) << \
206 	  (ilog2(BLK_TC_ ## __name) + BLK_TC_SHIFT - __REQ_ ## __name))
207 
208 /*
209  * The worker for the various blk_add_trace*() types. Fills out a
210  * blk_io_trace structure and places it in a per-cpu subbuffer.
211  */
212 static void __blk_add_trace(struct blk_trace *bt, sector_t sector, int bytes,
213 		     int op, int op_flags, u32 what, int error, int pdu_len,
214 		     void *pdu_data, u64 cgid)
215 {
216 	struct task_struct *tsk = current;
217 	struct ring_buffer_event *event = NULL;
218 	struct trace_buffer *buffer = NULL;
219 	struct blk_io_trace *t;
220 	unsigned long flags = 0;
221 	unsigned long *sequence;
222 	pid_t pid;
223 	int cpu, pc = 0;
224 	bool blk_tracer = blk_tracer_enabled;
225 	ssize_t cgid_len = cgid ? sizeof(cgid) : 0;
226 
227 	if (unlikely(bt->trace_state != Blktrace_running && !blk_tracer))
228 		return;
229 
230 	what |= ddir_act[op_is_write(op) ? WRITE : READ];
231 	what |= MASK_TC_BIT(op_flags, SYNC);
232 	what |= MASK_TC_BIT(op_flags, RAHEAD);
233 	what |= MASK_TC_BIT(op_flags, META);
234 	what |= MASK_TC_BIT(op_flags, PREFLUSH);
235 	what |= MASK_TC_BIT(op_flags, FUA);
236 	if (op == REQ_OP_DISCARD || op == REQ_OP_SECURE_ERASE)
237 		what |= BLK_TC_ACT(BLK_TC_DISCARD);
238 	if (op == REQ_OP_FLUSH)
239 		what |= BLK_TC_ACT(BLK_TC_FLUSH);
240 	if (cgid)
241 		what |= __BLK_TA_CGROUP;
242 
243 	pid = tsk->pid;
244 	if (act_log_check(bt, what, sector, pid))
245 		return;
246 	cpu = raw_smp_processor_id();
247 
248 	if (blk_tracer) {
249 		tracing_record_cmdline(current);
250 
251 		buffer = blk_tr->array_buffer.buffer;
252 		pc = preempt_count();
253 		event = trace_buffer_lock_reserve(buffer, TRACE_BLK,
254 						  sizeof(*t) + pdu_len + cgid_len,
255 						  0, pc);
256 		if (!event)
257 			return;
258 		t = ring_buffer_event_data(event);
259 		goto record_it;
260 	}
261 
262 	if (unlikely(tsk->btrace_seq != blktrace_seq))
263 		trace_note_tsk(tsk);
264 
265 	/*
266 	 * A word about the locking here - we disable interrupts to reserve
267 	 * some space in the relay per-cpu buffer, to prevent an irq
268 	 * from coming in and stepping on our toes.
269 	 */
270 	local_irq_save(flags);
271 	t = relay_reserve(bt->rchan, sizeof(*t) + pdu_len + cgid_len);
272 	if (t) {
273 		sequence = per_cpu_ptr(bt->sequence, cpu);
274 
275 		t->magic = BLK_IO_TRACE_MAGIC | BLK_IO_TRACE_VERSION;
276 		t->sequence = ++(*sequence);
277 		t->time = ktime_to_ns(ktime_get());
278 record_it:
279 		/*
280 		 * These two are not needed in ftrace as they are in the
281 		 * generic trace_entry, filled by tracing_generic_entry_update,
282 		 * but for the trace_event->bin() synthesizer benefit we do it
283 		 * here too.
284 		 */
285 		t->cpu = cpu;
286 		t->pid = pid;
287 
288 		t->sector = sector;
289 		t->bytes = bytes;
290 		t->action = what;
291 		t->device = bt->dev;
292 		t->error = error;
293 		t->pdu_len = pdu_len + cgid_len;
294 
295 		if (cgid_len)
296 			memcpy((void *)t + sizeof(*t), &cgid, cgid_len);
297 		if (pdu_len)
298 			memcpy((void *)t + sizeof(*t) + cgid_len, pdu_data, pdu_len);
299 
300 		if (blk_tracer) {
301 			trace_buffer_unlock_commit(blk_tr, buffer, event, 0, pc);
302 			return;
303 		}
304 	}
305 
306 	local_irq_restore(flags);
307 }
308 
309 static void blk_trace_free(struct blk_trace *bt)
310 {
311 	debugfs_remove(bt->msg_file);
312 	debugfs_remove(bt->dropped_file);
313 	relay_close(bt->rchan);
314 	debugfs_remove(bt->dir);
315 	free_percpu(bt->sequence);
316 	free_percpu(bt->msg_data);
317 	kfree(bt);
318 }
319 
320 static void get_probe_ref(void)
321 {
322 	mutex_lock(&blk_probe_mutex);
323 	if (++blk_probes_ref == 1)
324 		blk_register_tracepoints();
325 	mutex_unlock(&blk_probe_mutex);
326 }
327 
328 static void put_probe_ref(void)
329 {
330 	mutex_lock(&blk_probe_mutex);
331 	if (!--blk_probes_ref)
332 		blk_unregister_tracepoints();
333 	mutex_unlock(&blk_probe_mutex);
334 }
335 
336 static void blk_trace_cleanup(struct blk_trace *bt)
337 {
338 	blk_trace_free(bt);
339 	put_probe_ref();
340 }
341 
342 static int __blk_trace_remove(struct request_queue *q)
343 {
344 	struct blk_trace *bt;
345 
346 	bt = xchg(&q->blk_trace, NULL);
347 	if (!bt)
348 		return -EINVAL;
349 
350 	if (bt->trace_state != Blktrace_running)
351 		blk_trace_cleanup(bt);
352 
353 	return 0;
354 }
355 
356 int blk_trace_remove(struct request_queue *q)
357 {
358 	int ret;
359 
360 	mutex_lock(&q->blk_trace_mutex);
361 	ret = __blk_trace_remove(q);
362 	mutex_unlock(&q->blk_trace_mutex);
363 
364 	return ret;
365 }
366 EXPORT_SYMBOL_GPL(blk_trace_remove);
367 
368 static ssize_t blk_dropped_read(struct file *filp, char __user *buffer,
369 				size_t count, loff_t *ppos)
370 {
371 	struct blk_trace *bt = filp->private_data;
372 	char buf[16];
373 
374 	snprintf(buf, sizeof(buf), "%u\n", atomic_read(&bt->dropped));
375 
376 	return simple_read_from_buffer(buffer, count, ppos, buf, strlen(buf));
377 }
378 
379 static const struct file_operations blk_dropped_fops = {
380 	.owner =	THIS_MODULE,
381 	.open =		simple_open,
382 	.read =		blk_dropped_read,
383 	.llseek =	default_llseek,
384 };
385 
386 static ssize_t blk_msg_write(struct file *filp, const char __user *buffer,
387 				size_t count, loff_t *ppos)
388 {
389 	char *msg;
390 	struct blk_trace *bt;
391 
392 	if (count >= BLK_TN_MAX_MSG)
393 		return -EINVAL;
394 
395 	msg = memdup_user_nul(buffer, count);
396 	if (IS_ERR(msg))
397 		return PTR_ERR(msg);
398 
399 	bt = filp->private_data;
400 	__trace_note_message(bt, NULL, "%s", msg);
401 	kfree(msg);
402 
403 	return count;
404 }
405 
406 static const struct file_operations blk_msg_fops = {
407 	.owner =	THIS_MODULE,
408 	.open =		simple_open,
409 	.write =	blk_msg_write,
410 	.llseek =	noop_llseek,
411 };
412 
413 /*
414  * Keep track of how many times we encountered a full subbuffer, to aid
415  * the user space app in telling how many lost events there were.
416  */
417 static int blk_subbuf_start_callback(struct rchan_buf *buf, void *subbuf,
418 				     void *prev_subbuf, size_t prev_padding)
419 {
420 	struct blk_trace *bt;
421 
422 	if (!relay_buf_full(buf))
423 		return 1;
424 
425 	bt = buf->chan->private_data;
426 	atomic_inc(&bt->dropped);
427 	return 0;
428 }
429 
430 static int blk_remove_buf_file_callback(struct dentry *dentry)
431 {
432 	debugfs_remove(dentry);
433 
434 	return 0;
435 }
436 
437 static struct dentry *blk_create_buf_file_callback(const char *filename,
438 						   struct dentry *parent,
439 						   umode_t mode,
440 						   struct rchan_buf *buf,
441 						   int *is_global)
442 {
443 	return debugfs_create_file(filename, mode, parent, buf,
444 					&relay_file_operations);
445 }
446 
447 static struct rchan_callbacks blk_relay_callbacks = {
448 	.subbuf_start		= blk_subbuf_start_callback,
449 	.create_buf_file	= blk_create_buf_file_callback,
450 	.remove_buf_file	= blk_remove_buf_file_callback,
451 };
452 
453 static void blk_trace_setup_lba(struct blk_trace *bt,
454 				struct block_device *bdev)
455 {
456 	struct hd_struct *part = NULL;
457 
458 	if (bdev)
459 		part = bdev->bd_part;
460 
461 	if (part) {
462 		bt->start_lba = part->start_sect;
463 		bt->end_lba = part->start_sect + part->nr_sects;
464 	} else {
465 		bt->start_lba = 0;
466 		bt->end_lba = -1ULL;
467 	}
468 }
469 
470 /*
471  * Setup everything required to start tracing
472  */
473 static int do_blk_trace_setup(struct request_queue *q, char *name, dev_t dev,
474 			      struct block_device *bdev,
475 			      struct blk_user_trace_setup *buts)
476 {
477 	struct blk_trace *bt = NULL;
478 	struct dentry *dir = NULL;
479 	int ret;
480 
481 	if (!buts->buf_size || !buts->buf_nr)
482 		return -EINVAL;
483 
484 	if (!blk_debugfs_root)
485 		return -ENOENT;
486 
487 	strncpy(buts->name, name, BLKTRACE_BDEV_SIZE);
488 	buts->name[BLKTRACE_BDEV_SIZE - 1] = '\0';
489 
490 	/*
491 	 * some device names have larger paths - convert the slashes
492 	 * to underscores for this to work as expected
493 	 */
494 	strreplace(buts->name, '/', '_');
495 
496 	bt = kzalloc(sizeof(*bt), GFP_KERNEL);
497 	if (!bt)
498 		return -ENOMEM;
499 
500 	ret = -ENOMEM;
501 	bt->sequence = alloc_percpu(unsigned long);
502 	if (!bt->sequence)
503 		goto err;
504 
505 	bt->msg_data = __alloc_percpu(BLK_TN_MAX_MSG, __alignof__(char));
506 	if (!bt->msg_data)
507 		goto err;
508 
509 	ret = -ENOENT;
510 
511 	dir = debugfs_lookup(buts->name, blk_debugfs_root);
512 	if (!dir)
513 		bt->dir = dir = debugfs_create_dir(buts->name, blk_debugfs_root);
514 
515 	bt->dev = dev;
516 	atomic_set(&bt->dropped, 0);
517 	INIT_LIST_HEAD(&bt->running_list);
518 
519 	ret = -EIO;
520 	bt->dropped_file = debugfs_create_file("dropped", 0444, dir, bt,
521 					       &blk_dropped_fops);
522 
523 	bt->msg_file = debugfs_create_file("msg", 0222, dir, bt, &blk_msg_fops);
524 
525 	bt->rchan = relay_open("trace", dir, buts->buf_size,
526 				buts->buf_nr, &blk_relay_callbacks, bt);
527 	if (!bt->rchan)
528 		goto err;
529 
530 	bt->act_mask = buts->act_mask;
531 	if (!bt->act_mask)
532 		bt->act_mask = (u16) -1;
533 
534 	blk_trace_setup_lba(bt, bdev);
535 
536 	/* overwrite with user settings */
537 	if (buts->start_lba)
538 		bt->start_lba = buts->start_lba;
539 	if (buts->end_lba)
540 		bt->end_lba = buts->end_lba;
541 
542 	bt->pid = buts->pid;
543 	bt->trace_state = Blktrace_setup;
544 
545 	ret = -EBUSY;
546 	if (cmpxchg(&q->blk_trace, NULL, bt))
547 		goto err;
548 
549 	get_probe_ref();
550 
551 	ret = 0;
552 err:
553 	if (dir && !bt->dir)
554 		dput(dir);
555 	if (ret)
556 		blk_trace_free(bt);
557 	return ret;
558 }
559 
560 static int __blk_trace_setup(struct request_queue *q, char *name, dev_t dev,
561 			     struct block_device *bdev, char __user *arg)
562 {
563 	struct blk_user_trace_setup buts;
564 	int ret;
565 
566 	ret = copy_from_user(&buts, arg, sizeof(buts));
567 	if (ret)
568 		return -EFAULT;
569 
570 	ret = do_blk_trace_setup(q, name, dev, bdev, &buts);
571 	if (ret)
572 		return ret;
573 
574 	if (copy_to_user(arg, &buts, sizeof(buts))) {
575 		__blk_trace_remove(q);
576 		return -EFAULT;
577 	}
578 	return 0;
579 }
580 
581 int blk_trace_setup(struct request_queue *q, char *name, dev_t dev,
582 		    struct block_device *bdev,
583 		    char __user *arg)
584 {
585 	int ret;
586 
587 	mutex_lock(&q->blk_trace_mutex);
588 	ret = __blk_trace_setup(q, name, dev, bdev, arg);
589 	mutex_unlock(&q->blk_trace_mutex);
590 
591 	return ret;
592 }
593 EXPORT_SYMBOL_GPL(blk_trace_setup);
594 
595 #if defined(CONFIG_COMPAT) && defined(CONFIG_X86_64)
596 static int compat_blk_trace_setup(struct request_queue *q, char *name,
597 				  dev_t dev, struct block_device *bdev,
598 				  char __user *arg)
599 {
600 	struct blk_user_trace_setup buts;
601 	struct compat_blk_user_trace_setup cbuts;
602 	int ret;
603 
604 	if (copy_from_user(&cbuts, arg, sizeof(cbuts)))
605 		return -EFAULT;
606 
607 	buts = (struct blk_user_trace_setup) {
608 		.act_mask = cbuts.act_mask,
609 		.buf_size = cbuts.buf_size,
610 		.buf_nr = cbuts.buf_nr,
611 		.start_lba = cbuts.start_lba,
612 		.end_lba = cbuts.end_lba,
613 		.pid = cbuts.pid,
614 	};
615 
616 	ret = do_blk_trace_setup(q, name, dev, bdev, &buts);
617 	if (ret)
618 		return ret;
619 
620 	if (copy_to_user(arg, &buts.name, ARRAY_SIZE(buts.name))) {
621 		__blk_trace_remove(q);
622 		return -EFAULT;
623 	}
624 
625 	return 0;
626 }
627 #endif
628 
629 static int __blk_trace_startstop(struct request_queue *q, int start)
630 {
631 	int ret;
632 	struct blk_trace *bt = q->blk_trace;
633 
634 	if (bt == NULL)
635 		return -EINVAL;
636 
637 	/*
638 	 * For starting a trace, we can transition from a setup or stopped
639 	 * trace. For stopping a trace, the state must be running
640 	 */
641 	ret = -EINVAL;
642 	if (start) {
643 		if (bt->trace_state == Blktrace_setup ||
644 		    bt->trace_state == Blktrace_stopped) {
645 			blktrace_seq++;
646 			smp_mb();
647 			bt->trace_state = Blktrace_running;
648 			spin_lock_irq(&running_trace_lock);
649 			list_add(&bt->running_list, &running_trace_list);
650 			spin_unlock_irq(&running_trace_lock);
651 
652 			trace_note_time(bt);
653 			ret = 0;
654 		}
655 	} else {
656 		if (bt->trace_state == Blktrace_running) {
657 			bt->trace_state = Blktrace_stopped;
658 			spin_lock_irq(&running_trace_lock);
659 			list_del_init(&bt->running_list);
660 			spin_unlock_irq(&running_trace_lock);
661 			relay_flush(bt->rchan);
662 			ret = 0;
663 		}
664 	}
665 
666 	return ret;
667 }
668 
669 int blk_trace_startstop(struct request_queue *q, int start)
670 {
671 	int ret;
672 
673 	mutex_lock(&q->blk_trace_mutex);
674 	ret = __blk_trace_startstop(q, start);
675 	mutex_unlock(&q->blk_trace_mutex);
676 
677 	return ret;
678 }
679 EXPORT_SYMBOL_GPL(blk_trace_startstop);
680 
681 /*
682  * When reading or writing the blktrace sysfs files, the references to the
683  * opened sysfs or device files should prevent the underlying block device
684  * from being removed. So no further delete protection is really needed.
685  */
686 
687 /**
688  * blk_trace_ioctl: - handle the ioctls associated with tracing
689  * @bdev:	the block device
690  * @cmd:	the ioctl cmd
691  * @arg:	the argument data, if any
692  *
693  **/
694 int blk_trace_ioctl(struct block_device *bdev, unsigned cmd, char __user *arg)
695 {
696 	struct request_queue *q;
697 	int ret, start = 0;
698 	char b[BDEVNAME_SIZE];
699 
700 	q = bdev_get_queue(bdev);
701 	if (!q)
702 		return -ENXIO;
703 
704 	mutex_lock(&q->blk_trace_mutex);
705 
706 	switch (cmd) {
707 	case BLKTRACESETUP:
708 		bdevname(bdev, b);
709 		ret = __blk_trace_setup(q, b, bdev->bd_dev, bdev, arg);
710 		break;
711 #if defined(CONFIG_COMPAT) && defined(CONFIG_X86_64)
712 	case BLKTRACESETUP32:
713 		bdevname(bdev, b);
714 		ret = compat_blk_trace_setup(q, b, bdev->bd_dev, bdev, arg);
715 		break;
716 #endif
717 	case BLKTRACESTART:
718 		start = 1;
719 		/* fall through */
720 	case BLKTRACESTOP:
721 		ret = __blk_trace_startstop(q, start);
722 		break;
723 	case BLKTRACETEARDOWN:
724 		ret = __blk_trace_remove(q);
725 		break;
726 	default:
727 		ret = -ENOTTY;
728 		break;
729 	}
730 
731 	mutex_unlock(&q->blk_trace_mutex);
732 	return ret;
733 }
734 
735 /**
736  * blk_trace_shutdown: - stop and cleanup trace structures
737  * @q:    the request queue associated with the device
738  *
739  **/
740 void blk_trace_shutdown(struct request_queue *q)
741 {
742 	mutex_lock(&q->blk_trace_mutex);
743 
744 	if (q->blk_trace) {
745 		__blk_trace_startstop(q, 0);
746 		__blk_trace_remove(q);
747 	}
748 
749 	mutex_unlock(&q->blk_trace_mutex);
750 }
751 
752 #ifdef CONFIG_BLK_CGROUP
753 static u64 blk_trace_bio_get_cgid(struct request_queue *q, struct bio *bio)
754 {
755 	struct blk_trace *bt = q->blk_trace;
756 
757 	if (!bt || !(blk_tracer_flags.val & TRACE_BLK_OPT_CGROUP))
758 		return 0;
759 
760 	if (!bio->bi_blkg)
761 		return 0;
762 	return cgroup_id(bio_blkcg(bio)->css.cgroup);
763 }
764 #else
765 u64 blk_trace_bio_get_cgid(struct request_queue *q, struct bio *bio)
766 {
767 	return 0;
768 }
769 #endif
770 
771 static u64
772 blk_trace_request_get_cgid(struct request_queue *q, struct request *rq)
773 {
774 	if (!rq->bio)
775 		return 0;
776 	/* Use the first bio */
777 	return blk_trace_bio_get_cgid(q, rq->bio);
778 }
779 
780 /*
781  * blktrace probes
782  */
783 
784 /**
785  * blk_add_trace_rq - Add a trace for a request oriented action
786  * @rq:		the source request
787  * @error:	return status to log
788  * @nr_bytes:	number of completed bytes
789  * @what:	the action
790  * @cgid:	the cgroup info
791  *
792  * Description:
793  *     Records an action against a request. Will log the bio offset + size.
794  *
795  **/
796 static void blk_add_trace_rq(struct request *rq, int error,
797 			     unsigned int nr_bytes, u32 what, u64 cgid)
798 {
799 	struct blk_trace *bt = rq->q->blk_trace;
800 
801 	if (likely(!bt))
802 		return;
803 
804 	if (blk_rq_is_passthrough(rq))
805 		what |= BLK_TC_ACT(BLK_TC_PC);
806 	else
807 		what |= BLK_TC_ACT(BLK_TC_FS);
808 
809 	__blk_add_trace(bt, blk_rq_trace_sector(rq), nr_bytes, req_op(rq),
810 			rq->cmd_flags, what, error, 0, NULL, cgid);
811 }
812 
813 static void blk_add_trace_rq_insert(void *ignore,
814 				    struct request_queue *q, struct request *rq)
815 {
816 	blk_add_trace_rq(rq, 0, blk_rq_bytes(rq), BLK_TA_INSERT,
817 			 blk_trace_request_get_cgid(q, rq));
818 }
819 
820 static void blk_add_trace_rq_issue(void *ignore,
821 				   struct request_queue *q, struct request *rq)
822 {
823 	blk_add_trace_rq(rq, 0, blk_rq_bytes(rq), BLK_TA_ISSUE,
824 			 blk_trace_request_get_cgid(q, rq));
825 }
826 
827 static void blk_add_trace_rq_requeue(void *ignore,
828 				     struct request_queue *q,
829 				     struct request *rq)
830 {
831 	blk_add_trace_rq(rq, 0, blk_rq_bytes(rq), BLK_TA_REQUEUE,
832 			 blk_trace_request_get_cgid(q, rq));
833 }
834 
835 static void blk_add_trace_rq_complete(void *ignore, struct request *rq,
836 			int error, unsigned int nr_bytes)
837 {
838 	blk_add_trace_rq(rq, error, nr_bytes, BLK_TA_COMPLETE,
839 			 blk_trace_request_get_cgid(rq->q, rq));
840 }
841 
842 /**
843  * blk_add_trace_bio - Add a trace for a bio oriented action
844  * @q:		queue the io is for
845  * @bio:	the source bio
846  * @what:	the action
847  * @error:	error, if any
848  *
849  * Description:
850  *     Records an action against a bio. Will log the bio offset + size.
851  *
852  **/
853 static void blk_add_trace_bio(struct request_queue *q, struct bio *bio,
854 			      u32 what, int error)
855 {
856 	struct blk_trace *bt = q->blk_trace;
857 
858 	if (likely(!bt))
859 		return;
860 
861 	__blk_add_trace(bt, bio->bi_iter.bi_sector, bio->bi_iter.bi_size,
862 			bio_op(bio), bio->bi_opf, what, error, 0, NULL,
863 			blk_trace_bio_get_cgid(q, bio));
864 }
865 
866 static void blk_add_trace_bio_bounce(void *ignore,
867 				     struct request_queue *q, struct bio *bio)
868 {
869 	blk_add_trace_bio(q, bio, BLK_TA_BOUNCE, 0);
870 }
871 
872 static void blk_add_trace_bio_complete(void *ignore,
873 				       struct request_queue *q, struct bio *bio,
874 				       int error)
875 {
876 	blk_add_trace_bio(q, bio, BLK_TA_COMPLETE, error);
877 }
878 
879 static void blk_add_trace_bio_backmerge(void *ignore,
880 					struct request_queue *q,
881 					struct request *rq,
882 					struct bio *bio)
883 {
884 	blk_add_trace_bio(q, bio, BLK_TA_BACKMERGE, 0);
885 }
886 
887 static void blk_add_trace_bio_frontmerge(void *ignore,
888 					 struct request_queue *q,
889 					 struct request *rq,
890 					 struct bio *bio)
891 {
892 	blk_add_trace_bio(q, bio, BLK_TA_FRONTMERGE, 0);
893 }
894 
895 static void blk_add_trace_bio_queue(void *ignore,
896 				    struct request_queue *q, struct bio *bio)
897 {
898 	blk_add_trace_bio(q, bio, BLK_TA_QUEUE, 0);
899 }
900 
901 static void blk_add_trace_getrq(void *ignore,
902 				struct request_queue *q,
903 				struct bio *bio, int rw)
904 {
905 	if (bio)
906 		blk_add_trace_bio(q, bio, BLK_TA_GETRQ, 0);
907 	else {
908 		struct blk_trace *bt = q->blk_trace;
909 
910 		if (bt)
911 			__blk_add_trace(bt, 0, 0, rw, 0, BLK_TA_GETRQ, 0, 0,
912 					NULL, 0);
913 	}
914 }
915 
916 
917 static void blk_add_trace_sleeprq(void *ignore,
918 				  struct request_queue *q,
919 				  struct bio *bio, int rw)
920 {
921 	if (bio)
922 		blk_add_trace_bio(q, bio, BLK_TA_SLEEPRQ, 0);
923 	else {
924 		struct blk_trace *bt = q->blk_trace;
925 
926 		if (bt)
927 			__blk_add_trace(bt, 0, 0, rw, 0, BLK_TA_SLEEPRQ,
928 					0, 0, NULL, 0);
929 	}
930 }
931 
932 static void blk_add_trace_plug(void *ignore, struct request_queue *q)
933 {
934 	struct blk_trace *bt = q->blk_trace;
935 
936 	if (bt)
937 		__blk_add_trace(bt, 0, 0, 0, 0, BLK_TA_PLUG, 0, 0, NULL, 0);
938 }
939 
940 static void blk_add_trace_unplug(void *ignore, struct request_queue *q,
941 				    unsigned int depth, bool explicit)
942 {
943 	struct blk_trace *bt = q->blk_trace;
944 
945 	if (bt) {
946 		__be64 rpdu = cpu_to_be64(depth);
947 		u32 what;
948 
949 		if (explicit)
950 			what = BLK_TA_UNPLUG_IO;
951 		else
952 			what = BLK_TA_UNPLUG_TIMER;
953 
954 		__blk_add_trace(bt, 0, 0, 0, 0, what, 0, sizeof(rpdu), &rpdu, 0);
955 	}
956 }
957 
958 static void blk_add_trace_split(void *ignore,
959 				struct request_queue *q, struct bio *bio,
960 				unsigned int pdu)
961 {
962 	struct blk_trace *bt = q->blk_trace;
963 
964 	if (bt) {
965 		__be64 rpdu = cpu_to_be64(pdu);
966 
967 		__blk_add_trace(bt, bio->bi_iter.bi_sector,
968 				bio->bi_iter.bi_size, bio_op(bio), bio->bi_opf,
969 				BLK_TA_SPLIT, bio->bi_status, sizeof(rpdu),
970 				&rpdu, blk_trace_bio_get_cgid(q, bio));
971 	}
972 }
973 
974 /**
975  * blk_add_trace_bio_remap - Add a trace for a bio-remap operation
976  * @ignore:	trace callback data parameter (not used)
977  * @q:		queue the io is for
978  * @bio:	the source bio
979  * @dev:	target device
980  * @from:	source sector
981  *
982  * Description:
983  *     Device mapper or raid target sometimes need to split a bio because
984  *     it spans a stripe (or similar). Add a trace for that action.
985  *
986  **/
987 static void blk_add_trace_bio_remap(void *ignore,
988 				    struct request_queue *q, struct bio *bio,
989 				    dev_t dev, sector_t from)
990 {
991 	struct blk_trace *bt = q->blk_trace;
992 	struct blk_io_trace_remap r;
993 
994 	if (likely(!bt))
995 		return;
996 
997 	r.device_from = cpu_to_be32(dev);
998 	r.device_to   = cpu_to_be32(bio_dev(bio));
999 	r.sector_from = cpu_to_be64(from);
1000 
1001 	__blk_add_trace(bt, bio->bi_iter.bi_sector, bio->bi_iter.bi_size,
1002 			bio_op(bio), bio->bi_opf, BLK_TA_REMAP, bio->bi_status,
1003 			sizeof(r), &r, blk_trace_bio_get_cgid(q, bio));
1004 }
1005 
1006 /**
1007  * blk_add_trace_rq_remap - Add a trace for a request-remap operation
1008  * @ignore:	trace callback data parameter (not used)
1009  * @q:		queue the io is for
1010  * @rq:		the source request
1011  * @dev:	target device
1012  * @from:	source sector
1013  *
1014  * Description:
1015  *     Device mapper remaps request to other devices.
1016  *     Add a trace for that action.
1017  *
1018  **/
1019 static void blk_add_trace_rq_remap(void *ignore,
1020 				   struct request_queue *q,
1021 				   struct request *rq, dev_t dev,
1022 				   sector_t from)
1023 {
1024 	struct blk_trace *bt = q->blk_trace;
1025 	struct blk_io_trace_remap r;
1026 
1027 	if (likely(!bt))
1028 		return;
1029 
1030 	r.device_from = cpu_to_be32(dev);
1031 	r.device_to   = cpu_to_be32(disk_devt(rq->rq_disk));
1032 	r.sector_from = cpu_to_be64(from);
1033 
1034 	__blk_add_trace(bt, blk_rq_pos(rq), blk_rq_bytes(rq),
1035 			rq_data_dir(rq), 0, BLK_TA_REMAP, 0,
1036 			sizeof(r), &r, blk_trace_request_get_cgid(q, rq));
1037 }
1038 
1039 /**
1040  * blk_add_driver_data - Add binary message with driver-specific data
1041  * @q:		queue the io is for
1042  * @rq:		io request
1043  * @data:	driver-specific data
1044  * @len:	length of driver-specific data
1045  *
1046  * Description:
1047  *     Some drivers might want to write driver-specific data per request.
1048  *
1049  **/
1050 void blk_add_driver_data(struct request_queue *q,
1051 			 struct request *rq,
1052 			 void *data, size_t len)
1053 {
1054 	struct blk_trace *bt = q->blk_trace;
1055 
1056 	if (likely(!bt))
1057 		return;
1058 
1059 	__blk_add_trace(bt, blk_rq_trace_sector(rq), blk_rq_bytes(rq), 0, 0,
1060 				BLK_TA_DRV_DATA, 0, len, data,
1061 				blk_trace_request_get_cgid(q, rq));
1062 }
1063 EXPORT_SYMBOL_GPL(blk_add_driver_data);
1064 
1065 static void blk_register_tracepoints(void)
1066 {
1067 	int ret;
1068 
1069 	ret = register_trace_block_rq_insert(blk_add_trace_rq_insert, NULL);
1070 	WARN_ON(ret);
1071 	ret = register_trace_block_rq_issue(blk_add_trace_rq_issue, NULL);
1072 	WARN_ON(ret);
1073 	ret = register_trace_block_rq_requeue(blk_add_trace_rq_requeue, NULL);
1074 	WARN_ON(ret);
1075 	ret = register_trace_block_rq_complete(blk_add_trace_rq_complete, NULL);
1076 	WARN_ON(ret);
1077 	ret = register_trace_block_bio_bounce(blk_add_trace_bio_bounce, NULL);
1078 	WARN_ON(ret);
1079 	ret = register_trace_block_bio_complete(blk_add_trace_bio_complete, NULL);
1080 	WARN_ON(ret);
1081 	ret = register_trace_block_bio_backmerge(blk_add_trace_bio_backmerge, NULL);
1082 	WARN_ON(ret);
1083 	ret = register_trace_block_bio_frontmerge(blk_add_trace_bio_frontmerge, NULL);
1084 	WARN_ON(ret);
1085 	ret = register_trace_block_bio_queue(blk_add_trace_bio_queue, NULL);
1086 	WARN_ON(ret);
1087 	ret = register_trace_block_getrq(blk_add_trace_getrq, NULL);
1088 	WARN_ON(ret);
1089 	ret = register_trace_block_sleeprq(blk_add_trace_sleeprq, NULL);
1090 	WARN_ON(ret);
1091 	ret = register_trace_block_plug(blk_add_trace_plug, NULL);
1092 	WARN_ON(ret);
1093 	ret = register_trace_block_unplug(blk_add_trace_unplug, NULL);
1094 	WARN_ON(ret);
1095 	ret = register_trace_block_split(blk_add_trace_split, NULL);
1096 	WARN_ON(ret);
1097 	ret = register_trace_block_bio_remap(blk_add_trace_bio_remap, NULL);
1098 	WARN_ON(ret);
1099 	ret = register_trace_block_rq_remap(blk_add_trace_rq_remap, NULL);
1100 	WARN_ON(ret);
1101 }
1102 
1103 static void blk_unregister_tracepoints(void)
1104 {
1105 	unregister_trace_block_rq_remap(blk_add_trace_rq_remap, NULL);
1106 	unregister_trace_block_bio_remap(blk_add_trace_bio_remap, NULL);
1107 	unregister_trace_block_split(blk_add_trace_split, NULL);
1108 	unregister_trace_block_unplug(blk_add_trace_unplug, NULL);
1109 	unregister_trace_block_plug(blk_add_trace_plug, NULL);
1110 	unregister_trace_block_sleeprq(blk_add_trace_sleeprq, NULL);
1111 	unregister_trace_block_getrq(blk_add_trace_getrq, NULL);
1112 	unregister_trace_block_bio_queue(blk_add_trace_bio_queue, NULL);
1113 	unregister_trace_block_bio_frontmerge(blk_add_trace_bio_frontmerge, NULL);
1114 	unregister_trace_block_bio_backmerge(blk_add_trace_bio_backmerge, NULL);
1115 	unregister_trace_block_bio_complete(blk_add_trace_bio_complete, NULL);
1116 	unregister_trace_block_bio_bounce(blk_add_trace_bio_bounce, NULL);
1117 	unregister_trace_block_rq_complete(blk_add_trace_rq_complete, NULL);
1118 	unregister_trace_block_rq_requeue(blk_add_trace_rq_requeue, NULL);
1119 	unregister_trace_block_rq_issue(blk_add_trace_rq_issue, NULL);
1120 	unregister_trace_block_rq_insert(blk_add_trace_rq_insert, NULL);
1121 
1122 	tracepoint_synchronize_unregister();
1123 }
1124 
1125 /*
1126  * struct blk_io_tracer formatting routines
1127  */
1128 
1129 static void fill_rwbs(char *rwbs, const struct blk_io_trace *t)
1130 {
1131 	int i = 0;
1132 	int tc = t->action >> BLK_TC_SHIFT;
1133 
1134 	if ((t->action & ~__BLK_TN_CGROUP) == BLK_TN_MESSAGE) {
1135 		rwbs[i++] = 'N';
1136 		goto out;
1137 	}
1138 
1139 	if (tc & BLK_TC_FLUSH)
1140 		rwbs[i++] = 'F';
1141 
1142 	if (tc & BLK_TC_DISCARD)
1143 		rwbs[i++] = 'D';
1144 	else if (tc & BLK_TC_WRITE)
1145 		rwbs[i++] = 'W';
1146 	else if (t->bytes)
1147 		rwbs[i++] = 'R';
1148 	else
1149 		rwbs[i++] = 'N';
1150 
1151 	if (tc & BLK_TC_FUA)
1152 		rwbs[i++] = 'F';
1153 	if (tc & BLK_TC_AHEAD)
1154 		rwbs[i++] = 'A';
1155 	if (tc & BLK_TC_SYNC)
1156 		rwbs[i++] = 'S';
1157 	if (tc & BLK_TC_META)
1158 		rwbs[i++] = 'M';
1159 out:
1160 	rwbs[i] = '\0';
1161 }
1162 
1163 static inline
1164 const struct blk_io_trace *te_blk_io_trace(const struct trace_entry *ent)
1165 {
1166 	return (const struct blk_io_trace *)ent;
1167 }
1168 
1169 static inline const void *pdu_start(const struct trace_entry *ent, bool has_cg)
1170 {
1171 	return (void *)(te_blk_io_trace(ent) + 1) + (has_cg ? sizeof(u64) : 0);
1172 }
1173 
1174 static inline u64 t_cgid(const struct trace_entry *ent)
1175 {
1176 	return *(u64 *)(te_blk_io_trace(ent) + 1);
1177 }
1178 
1179 static inline int pdu_real_len(const struct trace_entry *ent, bool has_cg)
1180 {
1181 	return te_blk_io_trace(ent)->pdu_len - (has_cg ? sizeof(u64) : 0);
1182 }
1183 
1184 static inline u32 t_action(const struct trace_entry *ent)
1185 {
1186 	return te_blk_io_trace(ent)->action;
1187 }
1188 
1189 static inline u32 t_bytes(const struct trace_entry *ent)
1190 {
1191 	return te_blk_io_trace(ent)->bytes;
1192 }
1193 
1194 static inline u32 t_sec(const struct trace_entry *ent)
1195 {
1196 	return te_blk_io_trace(ent)->bytes >> 9;
1197 }
1198 
1199 static inline unsigned long long t_sector(const struct trace_entry *ent)
1200 {
1201 	return te_blk_io_trace(ent)->sector;
1202 }
1203 
1204 static inline __u16 t_error(const struct trace_entry *ent)
1205 {
1206 	return te_blk_io_trace(ent)->error;
1207 }
1208 
1209 static __u64 get_pdu_int(const struct trace_entry *ent, bool has_cg)
1210 {
1211 	const __u64 *val = pdu_start(ent, has_cg);
1212 	return be64_to_cpu(*val);
1213 }
1214 
1215 static void get_pdu_remap(const struct trace_entry *ent,
1216 			  struct blk_io_trace_remap *r, bool has_cg)
1217 {
1218 	const struct blk_io_trace_remap *__r = pdu_start(ent, has_cg);
1219 	__u64 sector_from = __r->sector_from;
1220 
1221 	r->device_from = be32_to_cpu(__r->device_from);
1222 	r->device_to   = be32_to_cpu(__r->device_to);
1223 	r->sector_from = be64_to_cpu(sector_from);
1224 }
1225 
1226 typedef void (blk_log_action_t) (struct trace_iterator *iter, const char *act,
1227 	bool has_cg);
1228 
1229 static void blk_log_action_classic(struct trace_iterator *iter, const char *act,
1230 	bool has_cg)
1231 {
1232 	char rwbs[RWBS_LEN];
1233 	unsigned long long ts  = iter->ts;
1234 	unsigned long nsec_rem = do_div(ts, NSEC_PER_SEC);
1235 	unsigned secs	       = (unsigned long)ts;
1236 	const struct blk_io_trace *t = te_blk_io_trace(iter->ent);
1237 
1238 	fill_rwbs(rwbs, t);
1239 
1240 	trace_seq_printf(&iter->seq,
1241 			 "%3d,%-3d %2d %5d.%09lu %5u %2s %3s ",
1242 			 MAJOR(t->device), MINOR(t->device), iter->cpu,
1243 			 secs, nsec_rem, iter->ent->pid, act, rwbs);
1244 }
1245 
1246 static void blk_log_action(struct trace_iterator *iter, const char *act,
1247 	bool has_cg)
1248 {
1249 	char rwbs[RWBS_LEN];
1250 	const struct blk_io_trace *t = te_blk_io_trace(iter->ent);
1251 
1252 	fill_rwbs(rwbs, t);
1253 	if (has_cg) {
1254 		u64 id = t_cgid(iter->ent);
1255 
1256 		if (blk_tracer_flags.val & TRACE_BLK_OPT_CGNAME) {
1257 			char blkcg_name_buf[NAME_MAX + 1] = "<...>";
1258 
1259 			cgroup_path_from_kernfs_id(id, blkcg_name_buf,
1260 				sizeof(blkcg_name_buf));
1261 			trace_seq_printf(&iter->seq, "%3d,%-3d %s %2s %3s ",
1262 				 MAJOR(t->device), MINOR(t->device),
1263 				 blkcg_name_buf, act, rwbs);
1264 		} else {
1265 			/*
1266 			 * The cgid portion used to be "INO,GEN".  Userland
1267 			 * builds a FILEID_INO32_GEN fid out of them and
1268 			 * opens the cgroup using open_by_handle_at(2).
1269 			 * While 32bit ino setups are still the same, 64bit
1270 			 * ones now use the 64bit ino as the whole ID and
1271 			 * no longer use generation.
1272 			 *
1273 			 * Regarldess of the content, always output
1274 			 * "LOW32,HIGH32" so that FILEID_INO32_GEN fid can
1275 			 * be mapped back to @id on both 64 and 32bit ino
1276 			 * setups.  See __kernfs_fh_to_dentry().
1277 			 */
1278 			trace_seq_printf(&iter->seq,
1279 				 "%3d,%-3d %llx,%-llx %2s %3s ",
1280 				 MAJOR(t->device), MINOR(t->device),
1281 				 id & U32_MAX, id >> 32, act, rwbs);
1282 		}
1283 	} else
1284 		trace_seq_printf(&iter->seq, "%3d,%-3d %2s %3s ",
1285 				 MAJOR(t->device), MINOR(t->device), act, rwbs);
1286 }
1287 
1288 static void blk_log_dump_pdu(struct trace_seq *s,
1289 	const struct trace_entry *ent, bool has_cg)
1290 {
1291 	const unsigned char *pdu_buf;
1292 	int pdu_len;
1293 	int i, end;
1294 
1295 	pdu_buf = pdu_start(ent, has_cg);
1296 	pdu_len = pdu_real_len(ent, has_cg);
1297 
1298 	if (!pdu_len)
1299 		return;
1300 
1301 	/* find the last zero that needs to be printed */
1302 	for (end = pdu_len - 1; end >= 0; end--)
1303 		if (pdu_buf[end])
1304 			break;
1305 	end++;
1306 
1307 	trace_seq_putc(s, '(');
1308 
1309 	for (i = 0; i < pdu_len; i++) {
1310 
1311 		trace_seq_printf(s, "%s%02x",
1312 				 i == 0 ? "" : " ", pdu_buf[i]);
1313 
1314 		/*
1315 		 * stop when the rest is just zeroes and indicate so
1316 		 * with a ".." appended
1317 		 */
1318 		if (i == end && end != pdu_len - 1) {
1319 			trace_seq_puts(s, " ..) ");
1320 			return;
1321 		}
1322 	}
1323 
1324 	trace_seq_puts(s, ") ");
1325 }
1326 
1327 static void blk_log_generic(struct trace_seq *s, const struct trace_entry *ent, bool has_cg)
1328 {
1329 	char cmd[TASK_COMM_LEN];
1330 
1331 	trace_find_cmdline(ent->pid, cmd);
1332 
1333 	if (t_action(ent) & BLK_TC_ACT(BLK_TC_PC)) {
1334 		trace_seq_printf(s, "%u ", t_bytes(ent));
1335 		blk_log_dump_pdu(s, ent, has_cg);
1336 		trace_seq_printf(s, "[%s]\n", cmd);
1337 	} else {
1338 		if (t_sec(ent))
1339 			trace_seq_printf(s, "%llu + %u [%s]\n",
1340 						t_sector(ent), t_sec(ent), cmd);
1341 		else
1342 			trace_seq_printf(s, "[%s]\n", cmd);
1343 	}
1344 }
1345 
1346 static void blk_log_with_error(struct trace_seq *s,
1347 			      const struct trace_entry *ent, bool has_cg)
1348 {
1349 	if (t_action(ent) & BLK_TC_ACT(BLK_TC_PC)) {
1350 		blk_log_dump_pdu(s, ent, has_cg);
1351 		trace_seq_printf(s, "[%d]\n", t_error(ent));
1352 	} else {
1353 		if (t_sec(ent))
1354 			trace_seq_printf(s, "%llu + %u [%d]\n",
1355 					 t_sector(ent),
1356 					 t_sec(ent), t_error(ent));
1357 		else
1358 			trace_seq_printf(s, "%llu [%d]\n",
1359 					 t_sector(ent), t_error(ent));
1360 	}
1361 }
1362 
1363 static void blk_log_remap(struct trace_seq *s, const struct trace_entry *ent, bool has_cg)
1364 {
1365 	struct blk_io_trace_remap r = { .device_from = 0, };
1366 
1367 	get_pdu_remap(ent, &r, has_cg);
1368 	trace_seq_printf(s, "%llu + %u <- (%d,%d) %llu\n",
1369 			 t_sector(ent), t_sec(ent),
1370 			 MAJOR(r.device_from), MINOR(r.device_from),
1371 			 (unsigned long long)r.sector_from);
1372 }
1373 
1374 static void blk_log_plug(struct trace_seq *s, const struct trace_entry *ent, bool has_cg)
1375 {
1376 	char cmd[TASK_COMM_LEN];
1377 
1378 	trace_find_cmdline(ent->pid, cmd);
1379 
1380 	trace_seq_printf(s, "[%s]\n", cmd);
1381 }
1382 
1383 static void blk_log_unplug(struct trace_seq *s, const struct trace_entry *ent, bool has_cg)
1384 {
1385 	char cmd[TASK_COMM_LEN];
1386 
1387 	trace_find_cmdline(ent->pid, cmd);
1388 
1389 	trace_seq_printf(s, "[%s] %llu\n", cmd, get_pdu_int(ent, has_cg));
1390 }
1391 
1392 static void blk_log_split(struct trace_seq *s, const struct trace_entry *ent, bool has_cg)
1393 {
1394 	char cmd[TASK_COMM_LEN];
1395 
1396 	trace_find_cmdline(ent->pid, cmd);
1397 
1398 	trace_seq_printf(s, "%llu / %llu [%s]\n", t_sector(ent),
1399 			 get_pdu_int(ent, has_cg), cmd);
1400 }
1401 
1402 static void blk_log_msg(struct trace_seq *s, const struct trace_entry *ent,
1403 			bool has_cg)
1404 {
1405 
1406 	trace_seq_putmem(s, pdu_start(ent, has_cg),
1407 		pdu_real_len(ent, has_cg));
1408 	trace_seq_putc(s, '\n');
1409 }
1410 
1411 /*
1412  * struct tracer operations
1413  */
1414 
1415 static void blk_tracer_print_header(struct seq_file *m)
1416 {
1417 	if (!(blk_tracer_flags.val & TRACE_BLK_OPT_CLASSIC))
1418 		return;
1419 	seq_puts(m, "# DEV   CPU TIMESTAMP     PID ACT FLG\n"
1420 		    "#  |     |     |           |   |   |\n");
1421 }
1422 
1423 static void blk_tracer_start(struct trace_array *tr)
1424 {
1425 	blk_tracer_enabled = true;
1426 }
1427 
1428 static int blk_tracer_init(struct trace_array *tr)
1429 {
1430 	blk_tr = tr;
1431 	blk_tracer_start(tr);
1432 	return 0;
1433 }
1434 
1435 static void blk_tracer_stop(struct trace_array *tr)
1436 {
1437 	blk_tracer_enabled = false;
1438 }
1439 
1440 static void blk_tracer_reset(struct trace_array *tr)
1441 {
1442 	blk_tracer_stop(tr);
1443 }
1444 
1445 static const struct {
1446 	const char *act[2];
1447 	void	   (*print)(struct trace_seq *s, const struct trace_entry *ent,
1448 			    bool has_cg);
1449 } what2act[] = {
1450 	[__BLK_TA_QUEUE]	= {{  "Q", "queue" },	   blk_log_generic },
1451 	[__BLK_TA_BACKMERGE]	= {{  "M", "backmerge" },  blk_log_generic },
1452 	[__BLK_TA_FRONTMERGE]	= {{  "F", "frontmerge" }, blk_log_generic },
1453 	[__BLK_TA_GETRQ]	= {{  "G", "getrq" },	   blk_log_generic },
1454 	[__BLK_TA_SLEEPRQ]	= {{  "S", "sleeprq" },	   blk_log_generic },
1455 	[__BLK_TA_REQUEUE]	= {{  "R", "requeue" },	   blk_log_with_error },
1456 	[__BLK_TA_ISSUE]	= {{  "D", "issue" },	   blk_log_generic },
1457 	[__BLK_TA_COMPLETE]	= {{  "C", "complete" },   blk_log_with_error },
1458 	[__BLK_TA_PLUG]		= {{  "P", "plug" },	   blk_log_plug },
1459 	[__BLK_TA_UNPLUG_IO]	= {{  "U", "unplug_io" },  blk_log_unplug },
1460 	[__BLK_TA_UNPLUG_TIMER]	= {{ "UT", "unplug_timer" }, blk_log_unplug },
1461 	[__BLK_TA_INSERT]	= {{  "I", "insert" },	   blk_log_generic },
1462 	[__BLK_TA_SPLIT]	= {{  "X", "split" },	   blk_log_split },
1463 	[__BLK_TA_BOUNCE]	= {{  "B", "bounce" },	   blk_log_generic },
1464 	[__BLK_TA_REMAP]	= {{  "A", "remap" },	   blk_log_remap },
1465 };
1466 
1467 static enum print_line_t print_one_line(struct trace_iterator *iter,
1468 					bool classic)
1469 {
1470 	struct trace_array *tr = iter->tr;
1471 	struct trace_seq *s = &iter->seq;
1472 	const struct blk_io_trace *t;
1473 	u16 what;
1474 	bool long_act;
1475 	blk_log_action_t *log_action;
1476 	bool has_cg;
1477 
1478 	t	   = te_blk_io_trace(iter->ent);
1479 	what	   = (t->action & ((1 << BLK_TC_SHIFT) - 1)) & ~__BLK_TA_CGROUP;
1480 	long_act   = !!(tr->trace_flags & TRACE_ITER_VERBOSE);
1481 	log_action = classic ? &blk_log_action_classic : &blk_log_action;
1482 	has_cg	   = t->action & __BLK_TA_CGROUP;
1483 
1484 	if ((t->action & ~__BLK_TN_CGROUP) == BLK_TN_MESSAGE) {
1485 		log_action(iter, long_act ? "message" : "m", has_cg);
1486 		blk_log_msg(s, iter->ent, has_cg);
1487 		return trace_handle_return(s);
1488 	}
1489 
1490 	if (unlikely(what == 0 || what >= ARRAY_SIZE(what2act)))
1491 		trace_seq_printf(s, "Unknown action %x\n", what);
1492 	else {
1493 		log_action(iter, what2act[what].act[long_act], has_cg);
1494 		what2act[what].print(s, iter->ent, has_cg);
1495 	}
1496 
1497 	return trace_handle_return(s);
1498 }
1499 
1500 static enum print_line_t blk_trace_event_print(struct trace_iterator *iter,
1501 					       int flags, struct trace_event *event)
1502 {
1503 	return print_one_line(iter, false);
1504 }
1505 
1506 static void blk_trace_synthesize_old_trace(struct trace_iterator *iter)
1507 {
1508 	struct trace_seq *s = &iter->seq;
1509 	struct blk_io_trace *t = (struct blk_io_trace *)iter->ent;
1510 	const int offset = offsetof(struct blk_io_trace, sector);
1511 	struct blk_io_trace old = {
1512 		.magic	  = BLK_IO_TRACE_MAGIC | BLK_IO_TRACE_VERSION,
1513 		.time     = iter->ts,
1514 	};
1515 
1516 	trace_seq_putmem(s, &old, offset);
1517 	trace_seq_putmem(s, &t->sector,
1518 			 sizeof(old) - offset + t->pdu_len);
1519 }
1520 
1521 static enum print_line_t
1522 blk_trace_event_print_binary(struct trace_iterator *iter, int flags,
1523 			     struct trace_event *event)
1524 {
1525 	blk_trace_synthesize_old_trace(iter);
1526 
1527 	return trace_handle_return(&iter->seq);
1528 }
1529 
1530 static enum print_line_t blk_tracer_print_line(struct trace_iterator *iter)
1531 {
1532 	if (!(blk_tracer_flags.val & TRACE_BLK_OPT_CLASSIC))
1533 		return TRACE_TYPE_UNHANDLED;
1534 
1535 	return print_one_line(iter, true);
1536 }
1537 
1538 static int
1539 blk_tracer_set_flag(struct trace_array *tr, u32 old_flags, u32 bit, int set)
1540 {
1541 	/* don't output context-info for blk_classic output */
1542 	if (bit == TRACE_BLK_OPT_CLASSIC) {
1543 		if (set)
1544 			tr->trace_flags &= ~TRACE_ITER_CONTEXT_INFO;
1545 		else
1546 			tr->trace_flags |= TRACE_ITER_CONTEXT_INFO;
1547 	}
1548 	return 0;
1549 }
1550 
1551 static struct tracer blk_tracer __read_mostly = {
1552 	.name		= "blk",
1553 	.init		= blk_tracer_init,
1554 	.reset		= blk_tracer_reset,
1555 	.start		= blk_tracer_start,
1556 	.stop		= blk_tracer_stop,
1557 	.print_header	= blk_tracer_print_header,
1558 	.print_line	= blk_tracer_print_line,
1559 	.flags		= &blk_tracer_flags,
1560 	.set_flag	= blk_tracer_set_flag,
1561 };
1562 
1563 static struct trace_event_functions trace_blk_event_funcs = {
1564 	.trace		= blk_trace_event_print,
1565 	.binary		= blk_trace_event_print_binary,
1566 };
1567 
1568 static struct trace_event trace_blk_event = {
1569 	.type		= TRACE_BLK,
1570 	.funcs		= &trace_blk_event_funcs,
1571 };
1572 
1573 static int __init init_blk_tracer(void)
1574 {
1575 	if (!register_trace_event(&trace_blk_event)) {
1576 		pr_warn("Warning: could not register block events\n");
1577 		return 1;
1578 	}
1579 
1580 	if (register_tracer(&blk_tracer) != 0) {
1581 		pr_warn("Warning: could not register the block tracer\n");
1582 		unregister_trace_event(&trace_blk_event);
1583 		return 1;
1584 	}
1585 
1586 	return 0;
1587 }
1588 
1589 device_initcall(init_blk_tracer);
1590 
1591 static int blk_trace_remove_queue(struct request_queue *q)
1592 {
1593 	struct blk_trace *bt;
1594 
1595 	bt = xchg(&q->blk_trace, NULL);
1596 	if (bt == NULL)
1597 		return -EINVAL;
1598 
1599 	put_probe_ref();
1600 	blk_trace_free(bt);
1601 	return 0;
1602 }
1603 
1604 /*
1605  * Setup everything required to start tracing
1606  */
1607 static int blk_trace_setup_queue(struct request_queue *q,
1608 				 struct block_device *bdev)
1609 {
1610 	struct blk_trace *bt = NULL;
1611 	int ret = -ENOMEM;
1612 
1613 	bt = kzalloc(sizeof(*bt), GFP_KERNEL);
1614 	if (!bt)
1615 		return -ENOMEM;
1616 
1617 	bt->msg_data = __alloc_percpu(BLK_TN_MAX_MSG, __alignof__(char));
1618 	if (!bt->msg_data)
1619 		goto free_bt;
1620 
1621 	bt->dev = bdev->bd_dev;
1622 	bt->act_mask = (u16)-1;
1623 
1624 	blk_trace_setup_lba(bt, bdev);
1625 
1626 	ret = -EBUSY;
1627 	if (cmpxchg(&q->blk_trace, NULL, bt))
1628 		goto free_bt;
1629 
1630 	get_probe_ref();
1631 	return 0;
1632 
1633 free_bt:
1634 	blk_trace_free(bt);
1635 	return ret;
1636 }
1637 
1638 /*
1639  * sysfs interface to enable and configure tracing
1640  */
1641 
1642 static ssize_t sysfs_blk_trace_attr_show(struct device *dev,
1643 					 struct device_attribute *attr,
1644 					 char *buf);
1645 static ssize_t sysfs_blk_trace_attr_store(struct device *dev,
1646 					  struct device_attribute *attr,
1647 					  const char *buf, size_t count);
1648 #define BLK_TRACE_DEVICE_ATTR(_name) \
1649 	DEVICE_ATTR(_name, S_IRUGO | S_IWUSR, \
1650 		    sysfs_blk_trace_attr_show, \
1651 		    sysfs_blk_trace_attr_store)
1652 
1653 static BLK_TRACE_DEVICE_ATTR(enable);
1654 static BLK_TRACE_DEVICE_ATTR(act_mask);
1655 static BLK_TRACE_DEVICE_ATTR(pid);
1656 static BLK_TRACE_DEVICE_ATTR(start_lba);
1657 static BLK_TRACE_DEVICE_ATTR(end_lba);
1658 
1659 static struct attribute *blk_trace_attrs[] = {
1660 	&dev_attr_enable.attr,
1661 	&dev_attr_act_mask.attr,
1662 	&dev_attr_pid.attr,
1663 	&dev_attr_start_lba.attr,
1664 	&dev_attr_end_lba.attr,
1665 	NULL
1666 };
1667 
1668 struct attribute_group blk_trace_attr_group = {
1669 	.name  = "trace",
1670 	.attrs = blk_trace_attrs,
1671 };
1672 
1673 static const struct {
1674 	int mask;
1675 	const char *str;
1676 } mask_maps[] = {
1677 	{ BLK_TC_READ,		"read"		},
1678 	{ BLK_TC_WRITE,		"write"		},
1679 	{ BLK_TC_FLUSH,		"flush"		},
1680 	{ BLK_TC_SYNC,		"sync"		},
1681 	{ BLK_TC_QUEUE,		"queue"		},
1682 	{ BLK_TC_REQUEUE,	"requeue"	},
1683 	{ BLK_TC_ISSUE,		"issue"		},
1684 	{ BLK_TC_COMPLETE,	"complete"	},
1685 	{ BLK_TC_FS,		"fs"		},
1686 	{ BLK_TC_PC,		"pc"		},
1687 	{ BLK_TC_NOTIFY,	"notify"	},
1688 	{ BLK_TC_AHEAD,		"ahead"		},
1689 	{ BLK_TC_META,		"meta"		},
1690 	{ BLK_TC_DISCARD,	"discard"	},
1691 	{ BLK_TC_DRV_DATA,	"drv_data"	},
1692 	{ BLK_TC_FUA,		"fua"		},
1693 };
1694 
1695 static int blk_trace_str2mask(const char *str)
1696 {
1697 	int i;
1698 	int mask = 0;
1699 	char *buf, *s, *token;
1700 
1701 	buf = kstrdup(str, GFP_KERNEL);
1702 	if (buf == NULL)
1703 		return -ENOMEM;
1704 	s = strstrip(buf);
1705 
1706 	while (1) {
1707 		token = strsep(&s, ",");
1708 		if (token == NULL)
1709 			break;
1710 
1711 		if (*token == '\0')
1712 			continue;
1713 
1714 		for (i = 0; i < ARRAY_SIZE(mask_maps); i++) {
1715 			if (strcasecmp(token, mask_maps[i].str) == 0) {
1716 				mask |= mask_maps[i].mask;
1717 				break;
1718 			}
1719 		}
1720 		if (i == ARRAY_SIZE(mask_maps)) {
1721 			mask = -EINVAL;
1722 			break;
1723 		}
1724 	}
1725 	kfree(buf);
1726 
1727 	return mask;
1728 }
1729 
1730 static ssize_t blk_trace_mask2str(char *buf, int mask)
1731 {
1732 	int i;
1733 	char *p = buf;
1734 
1735 	for (i = 0; i < ARRAY_SIZE(mask_maps); i++) {
1736 		if (mask & mask_maps[i].mask) {
1737 			p += sprintf(p, "%s%s",
1738 				    (p == buf) ? "" : ",", mask_maps[i].str);
1739 		}
1740 	}
1741 	*p++ = '\n';
1742 
1743 	return p - buf;
1744 }
1745 
1746 static struct request_queue *blk_trace_get_queue(struct block_device *bdev)
1747 {
1748 	if (bdev->bd_disk == NULL)
1749 		return NULL;
1750 
1751 	return bdev_get_queue(bdev);
1752 }
1753 
1754 static ssize_t sysfs_blk_trace_attr_show(struct device *dev,
1755 					 struct device_attribute *attr,
1756 					 char *buf)
1757 {
1758 	struct hd_struct *p = dev_to_part(dev);
1759 	struct request_queue *q;
1760 	struct block_device *bdev;
1761 	ssize_t ret = -ENXIO;
1762 
1763 	bdev = bdget(part_devt(p));
1764 	if (bdev == NULL)
1765 		goto out;
1766 
1767 	q = blk_trace_get_queue(bdev);
1768 	if (q == NULL)
1769 		goto out_bdput;
1770 
1771 	mutex_lock(&q->blk_trace_mutex);
1772 
1773 	if (attr == &dev_attr_enable) {
1774 		ret = sprintf(buf, "%u\n", !!q->blk_trace);
1775 		goto out_unlock_bdev;
1776 	}
1777 
1778 	if (q->blk_trace == NULL)
1779 		ret = sprintf(buf, "disabled\n");
1780 	else if (attr == &dev_attr_act_mask)
1781 		ret = blk_trace_mask2str(buf, q->blk_trace->act_mask);
1782 	else if (attr == &dev_attr_pid)
1783 		ret = sprintf(buf, "%u\n", q->blk_trace->pid);
1784 	else if (attr == &dev_attr_start_lba)
1785 		ret = sprintf(buf, "%llu\n", q->blk_trace->start_lba);
1786 	else if (attr == &dev_attr_end_lba)
1787 		ret = sprintf(buf, "%llu\n", q->blk_trace->end_lba);
1788 
1789 out_unlock_bdev:
1790 	mutex_unlock(&q->blk_trace_mutex);
1791 out_bdput:
1792 	bdput(bdev);
1793 out:
1794 	return ret;
1795 }
1796 
1797 static ssize_t sysfs_blk_trace_attr_store(struct device *dev,
1798 					  struct device_attribute *attr,
1799 					  const char *buf, size_t count)
1800 {
1801 	struct block_device *bdev;
1802 	struct request_queue *q;
1803 	struct hd_struct *p;
1804 	u64 value;
1805 	ssize_t ret = -EINVAL;
1806 
1807 	if (count == 0)
1808 		goto out;
1809 
1810 	if (attr == &dev_attr_act_mask) {
1811 		if (kstrtoull(buf, 0, &value)) {
1812 			/* Assume it is a list of trace category names */
1813 			ret = blk_trace_str2mask(buf);
1814 			if (ret < 0)
1815 				goto out;
1816 			value = ret;
1817 		}
1818 	} else if (kstrtoull(buf, 0, &value))
1819 		goto out;
1820 
1821 	ret = -ENXIO;
1822 
1823 	p = dev_to_part(dev);
1824 	bdev = bdget(part_devt(p));
1825 	if (bdev == NULL)
1826 		goto out;
1827 
1828 	q = blk_trace_get_queue(bdev);
1829 	if (q == NULL)
1830 		goto out_bdput;
1831 
1832 	mutex_lock(&q->blk_trace_mutex);
1833 
1834 	if (attr == &dev_attr_enable) {
1835 		if (!!value == !!q->blk_trace) {
1836 			ret = 0;
1837 			goto out_unlock_bdev;
1838 		}
1839 		if (value)
1840 			ret = blk_trace_setup_queue(q, bdev);
1841 		else
1842 			ret = blk_trace_remove_queue(q);
1843 		goto out_unlock_bdev;
1844 	}
1845 
1846 	ret = 0;
1847 	if (q->blk_trace == NULL)
1848 		ret = blk_trace_setup_queue(q, bdev);
1849 
1850 	if (ret == 0) {
1851 		if (attr == &dev_attr_act_mask)
1852 			q->blk_trace->act_mask = value;
1853 		else if (attr == &dev_attr_pid)
1854 			q->blk_trace->pid = value;
1855 		else if (attr == &dev_attr_start_lba)
1856 			q->blk_trace->start_lba = value;
1857 		else if (attr == &dev_attr_end_lba)
1858 			q->blk_trace->end_lba = value;
1859 	}
1860 
1861 out_unlock_bdev:
1862 	mutex_unlock(&q->blk_trace_mutex);
1863 out_bdput:
1864 	bdput(bdev);
1865 out:
1866 	return ret ? ret : count;
1867 }
1868 
1869 int blk_trace_init_sysfs(struct device *dev)
1870 {
1871 	return sysfs_create_group(&dev->kobj, &blk_trace_attr_group);
1872 }
1873 
1874 void blk_trace_remove_sysfs(struct device *dev)
1875 {
1876 	sysfs_remove_group(&dev->kobj, &blk_trace_attr_group);
1877 }
1878 
1879 #endif /* CONFIG_BLK_DEV_IO_TRACE */
1880 
1881 #ifdef CONFIG_EVENT_TRACING
1882 
1883 void blk_fill_rwbs(char *rwbs, unsigned int op, int bytes)
1884 {
1885 	int i = 0;
1886 
1887 	if (op & REQ_PREFLUSH)
1888 		rwbs[i++] = 'F';
1889 
1890 	switch (op & REQ_OP_MASK) {
1891 	case REQ_OP_WRITE:
1892 	case REQ_OP_WRITE_SAME:
1893 		rwbs[i++] = 'W';
1894 		break;
1895 	case REQ_OP_DISCARD:
1896 		rwbs[i++] = 'D';
1897 		break;
1898 	case REQ_OP_SECURE_ERASE:
1899 		rwbs[i++] = 'D';
1900 		rwbs[i++] = 'E';
1901 		break;
1902 	case REQ_OP_FLUSH:
1903 		rwbs[i++] = 'F';
1904 		break;
1905 	case REQ_OP_READ:
1906 		rwbs[i++] = 'R';
1907 		break;
1908 	default:
1909 		rwbs[i++] = 'N';
1910 	}
1911 
1912 	if (op & REQ_FUA)
1913 		rwbs[i++] = 'F';
1914 	if (op & REQ_RAHEAD)
1915 		rwbs[i++] = 'A';
1916 	if (op & REQ_SYNC)
1917 		rwbs[i++] = 'S';
1918 	if (op & REQ_META)
1919 		rwbs[i++] = 'M';
1920 
1921 	rwbs[i] = '\0';
1922 }
1923 EXPORT_SYMBOL_GPL(blk_fill_rwbs);
1924 
1925 #endif /* CONFIG_EVENT_TRACING */
1926 
1927