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