d43cdac7c754f2fe5f1b40d2e7220326d190a45b
[linux-2.6.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 #include <linux/kernel.h>
19 #include <linux/blkdev.h>
20 #include <linux/blktrace_api.h>
21 #include <linux/percpu.h>
22 #include <linux/init.h>
23 #include <linux/mutex.h>
24 #include <linux/debugfs.h>
25 #include <linux/time.h>
26 #include <trace/block.h>
27 #include <linux/uaccess.h>
28 #include "trace_output.h"
29
30 static unsigned int blktrace_seq __read_mostly = 1;
31
32 static struct trace_array *blk_tr;
33 static bool blk_tracer_enabled __read_mostly;
34
35 /* Select an alternative, minimalistic output than the original one */
36 #define TRACE_BLK_OPT_CLASSIC   0x1
37
38 static struct tracer_opt blk_tracer_opts[] = {
39         /* Default disable the minimalistic output */
40         { TRACER_OPT(blk_classic, TRACE_BLK_OPT_CLASSIC) },
41         { }
42 };
43
44 static struct tracer_flags blk_tracer_flags = {
45         .val  = 0,
46         .opts = blk_tracer_opts,
47 };
48
49 /* Global reference count of probes */
50 static atomic_t blk_probes_ref = ATOMIC_INIT(0);
51
52 static void blk_register_tracepoints(void);
53 static void blk_unregister_tracepoints(void);
54
55 /*
56  * Send out a notify message.
57  */
58 static void trace_note(struct blk_trace *bt, pid_t pid, int action,
59                        const void *data, size_t len)
60 {
61         struct blk_io_trace *t;
62
63         if (!bt->rchan)
64                 return;
65
66         t = relay_reserve(bt->rchan, sizeof(*t) + len);
67         if (t) {
68                 const int cpu = smp_processor_id();
69
70                 t->magic = BLK_IO_TRACE_MAGIC | BLK_IO_TRACE_VERSION;
71                 t->time = ktime_to_ns(ktime_get());
72                 t->device = bt->dev;
73                 t->action = action;
74                 t->pid = pid;
75                 t->cpu = cpu;
76                 t->pdu_len = len;
77                 memcpy((void *) t + sizeof(*t), data, len);
78         }
79 }
80
81 /*
82  * Send out a notify for this process, if we haven't done so since a trace
83  * started
84  */
85 static void trace_note_tsk(struct blk_trace *bt, struct task_struct *tsk)
86 {
87         tsk->btrace_seq = blktrace_seq;
88         trace_note(bt, tsk->pid, BLK_TN_PROCESS, tsk->comm, sizeof(tsk->comm));
89 }
90
91 static void trace_note_time(struct blk_trace *bt)
92 {
93         struct timespec now;
94         unsigned long flags;
95         u32 words[2];
96
97         getnstimeofday(&now);
98         words[0] = now.tv_sec;
99         words[1] = now.tv_nsec;
100
101         local_irq_save(flags);
102         trace_note(bt, 0, BLK_TN_TIMESTAMP, words, sizeof(words));
103         local_irq_restore(flags);
104 }
105
106 void __trace_note_message(struct blk_trace *bt, const char *fmt, ...)
107 {
108         int n;
109         va_list args;
110         unsigned long flags;
111         char *buf;
112
113         if (blk_tracer_enabled) {
114                 va_start(args, fmt);
115                 ftrace_vprintk(fmt, args);
116                 va_end(args);
117                 return;
118         }
119
120         if (!bt->msg_data)
121                 return;
122
123         local_irq_save(flags);
124         buf = per_cpu_ptr(bt->msg_data, smp_processor_id());
125         va_start(args, fmt);
126         n = vscnprintf(buf, BLK_TN_MAX_MSG, fmt, args);
127         va_end(args);
128
129         trace_note(bt, 0, BLK_TN_MESSAGE, buf, n);
130         local_irq_restore(flags);
131 }
132 EXPORT_SYMBOL_GPL(__trace_note_message);
133
134 static int act_log_check(struct blk_trace *bt, u32 what, sector_t sector,
135                          pid_t pid)
136 {
137         if (((bt->act_mask << BLK_TC_SHIFT) & what) == 0)
138                 return 1;
139         if (sector < bt->start_lba || sector > bt->end_lba)
140                 return 1;
141         if (bt->pid && pid != bt->pid)
142                 return 1;
143
144         return 0;
145 }
146
147 /*
148  * Data direction bit lookup
149  */
150 static const u32 ddir_act[2] = { BLK_TC_ACT(BLK_TC_READ),
151                                  BLK_TC_ACT(BLK_TC_WRITE) };
152
153 /* The ilog2() calls fall out because they're constant */
154 #define MASK_TC_BIT(rw, __name) ((rw & (1 << BIO_RW_ ## __name)) << \
155           (ilog2(BLK_TC_ ## __name) + BLK_TC_SHIFT - BIO_RW_ ## __name))
156
157 /*
158  * The worker for the various blk_add_trace*() types. Fills out a
159  * blk_io_trace structure and places it in a per-cpu subbuffer.
160  */
161 static void __blk_add_trace(struct blk_trace *bt, sector_t sector, int bytes,
162                      int rw, u32 what, int error, int pdu_len, void *pdu_data)
163 {
164         struct task_struct *tsk = current;
165         struct ring_buffer_event *event = NULL;
166         struct blk_io_trace *t;
167         unsigned long flags = 0;
168         unsigned long *sequence;
169         pid_t pid;
170         int cpu, pc = 0;
171
172         if (unlikely(bt->trace_state != Blktrace_running &&
173                      !blk_tracer_enabled))
174                 return;
175
176         what |= ddir_act[rw & WRITE];
177         what |= MASK_TC_BIT(rw, BARRIER);
178         what |= MASK_TC_BIT(rw, SYNCIO);
179         what |= MASK_TC_BIT(rw, AHEAD);
180         what |= MASK_TC_BIT(rw, META);
181         what |= MASK_TC_BIT(rw, DISCARD);
182
183         pid = tsk->pid;
184         if (unlikely(act_log_check(bt, what, sector, pid)))
185                 return;
186         cpu = raw_smp_processor_id();
187
188         if (blk_tracer_enabled) {
189                 tracing_record_cmdline(current);
190
191                 pc = preempt_count();
192                 event = trace_buffer_lock_reserve(blk_tr, TRACE_BLK,
193                                                   sizeof(*t) + pdu_len,
194                                                   0, pc);
195                 if (!event)
196                         return;
197                 t = ring_buffer_event_data(event);
198                 goto record_it;
199         }
200
201         /*
202          * A word about the locking here - we disable interrupts to reserve
203          * some space in the relay per-cpu buffer, to prevent an irq
204          * from coming in and stepping on our toes.
205          */
206         local_irq_save(flags);
207
208         if (unlikely(tsk->btrace_seq != blktrace_seq))
209                 trace_note_tsk(bt, tsk);
210
211         t = relay_reserve(bt->rchan, sizeof(*t) + pdu_len);
212         if (t) {
213                 sequence = per_cpu_ptr(bt->sequence, cpu);
214
215                 t->magic = BLK_IO_TRACE_MAGIC | BLK_IO_TRACE_VERSION;
216                 t->sequence = ++(*sequence);
217                 t->time = ktime_to_ns(ktime_get());
218 record_it:
219                 /*
220                  * These two are not needed in ftrace as they are in the
221                  * generic trace_entry, filled by tracing_generic_entry_update,
222                  * but for the trace_event->bin() synthesizer benefit we do it
223                  * here too.
224                  */
225                 t->cpu = cpu;
226                 t->pid = pid;
227
228                 t->sector = sector;
229                 t->bytes = bytes;
230                 t->action = what;
231                 t->device = bt->dev;
232                 t->error = error;
233                 t->pdu_len = pdu_len;
234
235                 if (pdu_len)
236                         memcpy((void *) t + sizeof(*t), pdu_data, pdu_len);
237
238                 if (blk_tracer_enabled) {
239                         trace_buffer_unlock_commit(blk_tr, event, 0, pc);
240                         return;
241                 }
242         }
243
244         local_irq_restore(flags);
245 }
246
247 static struct dentry *blk_tree_root;
248 static DEFINE_MUTEX(blk_tree_mutex);
249
250 static void blk_trace_cleanup(struct blk_trace *bt)
251 {
252         debugfs_remove(bt->msg_file);
253         debugfs_remove(bt->dropped_file);
254         relay_close(bt->rchan);
255         free_percpu(bt->sequence);
256         free_percpu(bt->msg_data);
257         kfree(bt);
258         if (atomic_dec_and_test(&blk_probes_ref))
259                 blk_unregister_tracepoints();
260 }
261
262 int blk_trace_remove(struct request_queue *q)
263 {
264         struct blk_trace *bt;
265
266         bt = xchg(&q->blk_trace, NULL);
267         if (!bt)
268                 return -EINVAL;
269
270         if (bt->trace_state != Blktrace_running)
271                 blk_trace_cleanup(bt);
272
273         return 0;
274 }
275 EXPORT_SYMBOL_GPL(blk_trace_remove);
276
277 static int blk_dropped_open(struct inode *inode, struct file *filp)
278 {
279         filp->private_data = inode->i_private;
280
281         return 0;
282 }
283
284 static ssize_t blk_dropped_read(struct file *filp, char __user *buffer,
285                                 size_t count, loff_t *ppos)
286 {
287         struct blk_trace *bt = filp->private_data;
288         char buf[16];
289
290         snprintf(buf, sizeof(buf), "%u\n", atomic_read(&bt->dropped));
291
292         return simple_read_from_buffer(buffer, count, ppos, buf, strlen(buf));
293 }
294
295 static const struct file_operations blk_dropped_fops = {
296         .owner =        THIS_MODULE,
297         .open =         blk_dropped_open,
298         .read =         blk_dropped_read,
299 };
300
301 static int blk_msg_open(struct inode *inode, struct file *filp)
302 {
303         filp->private_data = inode->i_private;
304
305         return 0;
306 }
307
308 static ssize_t blk_msg_write(struct file *filp, const char __user *buffer,
309                                 size_t count, loff_t *ppos)
310 {
311         char *msg;
312         struct blk_trace *bt;
313
314         if (count > BLK_TN_MAX_MSG)
315                 return -EINVAL;
316
317         msg = kmalloc(count, GFP_KERNEL);
318         if (msg == NULL)
319                 return -ENOMEM;
320
321         if (copy_from_user(msg, buffer, count)) {
322                 kfree(msg);
323                 return -EFAULT;
324         }
325
326         bt = filp->private_data;
327         __trace_note_message(bt, "%s", msg);
328         kfree(msg);
329
330         return count;
331 }
332
333 static const struct file_operations blk_msg_fops = {
334         .owner =        THIS_MODULE,
335         .open =         blk_msg_open,
336         .write =        blk_msg_write,
337 };
338
339 /*
340  * Keep track of how many times we encountered a full subbuffer, to aid
341  * the user space app in telling how many lost events there were.
342  */
343 static int blk_subbuf_start_callback(struct rchan_buf *buf, void *subbuf,
344                                      void *prev_subbuf, size_t prev_padding)
345 {
346         struct blk_trace *bt;
347
348         if (!relay_buf_full(buf))
349                 return 1;
350
351         bt = buf->chan->private_data;
352         atomic_inc(&bt->dropped);
353         return 0;
354 }
355
356 static int blk_remove_buf_file_callback(struct dentry *dentry)
357 {
358         struct dentry *parent = dentry->d_parent;
359         debugfs_remove(dentry);
360
361         /*
362         * this will fail for all but the last file, but that is ok. what we
363         * care about is the top level buts->name directory going away, when
364         * the last trace file is gone. Then we don't have to rmdir() that
365         * manually on trace stop, so it nicely solves the issue with
366         * force killing of running traces.
367         */
368
369         debugfs_remove(parent);
370         return 0;
371 }
372
373 static struct dentry *blk_create_buf_file_callback(const char *filename,
374                                                    struct dentry *parent,
375                                                    int mode,
376                                                    struct rchan_buf *buf,
377                                                    int *is_global)
378 {
379         return debugfs_create_file(filename, mode, parent, buf,
380                                         &relay_file_operations);
381 }
382
383 static struct rchan_callbacks blk_relay_callbacks = {
384         .subbuf_start           = blk_subbuf_start_callback,
385         .create_buf_file        = blk_create_buf_file_callback,
386         .remove_buf_file        = blk_remove_buf_file_callback,
387 };
388
389 /*
390  * Setup everything required to start tracing
391  */
392 int do_blk_trace_setup(struct request_queue *q, char *name, dev_t dev,
393                         struct blk_user_trace_setup *buts)
394 {
395         struct blk_trace *old_bt, *bt = NULL;
396         struct dentry *dir = NULL;
397         int ret, i;
398
399         if (!buts->buf_size || !buts->buf_nr)
400                 return -EINVAL;
401
402         strncpy(buts->name, name, BLKTRACE_BDEV_SIZE);
403         buts->name[BLKTRACE_BDEV_SIZE - 1] = '\0';
404
405         /*
406          * some device names have larger paths - convert the slashes
407          * to underscores for this to work as expected
408          */
409         for (i = 0; i < strlen(buts->name); i++)
410                 if (buts->name[i] == '/')
411                         buts->name[i] = '_';
412
413         ret = -ENOMEM;
414         bt = kzalloc(sizeof(*bt), GFP_KERNEL);
415         if (!bt)
416                 goto err;
417
418         bt->sequence = alloc_percpu(unsigned long);
419         if (!bt->sequence)
420                 goto err;
421
422         bt->msg_data = __alloc_percpu(BLK_TN_MAX_MSG, __alignof__(char));
423         if (!bt->msg_data)
424                 goto err;
425
426         ret = -ENOENT;
427
428         mutex_lock(&blk_tree_mutex);
429         if (!blk_tree_root) {
430                 blk_tree_root = debugfs_create_dir("block", NULL);
431                 if (!blk_tree_root) {
432                         mutex_unlock(&blk_tree_mutex);
433                         goto err;
434                 }
435         }
436         mutex_unlock(&blk_tree_mutex);
437
438         dir = debugfs_create_dir(buts->name, blk_tree_root);
439
440         if (!dir)
441                 goto err;
442
443         bt->dir = dir;
444         bt->dev = dev;
445         atomic_set(&bt->dropped, 0);
446
447         ret = -EIO;
448         bt->dropped_file = debugfs_create_file("dropped", 0444, dir, bt,
449                                                &blk_dropped_fops);
450         if (!bt->dropped_file)
451                 goto err;
452
453         bt->msg_file = debugfs_create_file("msg", 0222, dir, bt, &blk_msg_fops);
454         if (!bt->msg_file)
455                 goto err;
456
457         bt->rchan = relay_open("trace", dir, buts->buf_size,
458                                 buts->buf_nr, &blk_relay_callbacks, bt);
459         if (!bt->rchan)
460                 goto err;
461
462         bt->act_mask = buts->act_mask;
463         if (!bt->act_mask)
464                 bt->act_mask = (u16) -1;
465
466         bt->start_lba = buts->start_lba;
467         bt->end_lba = buts->end_lba;
468         if (!bt->end_lba)
469                 bt->end_lba = -1ULL;
470
471         bt->pid = buts->pid;
472         bt->trace_state = Blktrace_setup;
473
474         ret = -EBUSY;
475         old_bt = xchg(&q->blk_trace, bt);
476         if (old_bt) {
477                 (void) xchg(&q->blk_trace, old_bt);
478                 goto err;
479         }
480
481         if (atomic_add_return(1, &blk_probes_ref) == 1)
482                 blk_register_tracepoints();
483
484         return 0;
485 err:
486         if (bt) {
487                 if (bt->msg_file)
488                         debugfs_remove(bt->msg_file);
489                 if (bt->dropped_file)
490                         debugfs_remove(bt->dropped_file);
491                 free_percpu(bt->sequence);
492                 free_percpu(bt->msg_data);
493                 if (bt->rchan)
494                         relay_close(bt->rchan);
495                 kfree(bt);
496         }
497         return ret;
498 }
499
500 int blk_trace_setup(struct request_queue *q, char *name, dev_t dev,
501                     char __user *arg)
502 {
503         struct blk_user_trace_setup buts;
504         int ret;
505
506         ret = copy_from_user(&buts, arg, sizeof(buts));
507         if (ret)
508                 return -EFAULT;
509
510         ret = do_blk_trace_setup(q, name, dev, &buts);
511         if (ret)
512                 return ret;
513
514         if (copy_to_user(arg, &buts, sizeof(buts)))
515                 return -EFAULT;
516
517         return 0;
518 }
519 EXPORT_SYMBOL_GPL(blk_trace_setup);
520
521 int blk_trace_startstop(struct request_queue *q, int start)
522 {
523         int ret;
524         struct blk_trace *bt = q->blk_trace;
525
526         if (bt == NULL)
527                 return -EINVAL;
528
529         /*
530          * For starting a trace, we can transition from a setup or stopped
531          * trace. For stopping a trace, the state must be running
532          */
533         ret = -EINVAL;
534         if (start) {
535                 if (bt->trace_state == Blktrace_setup ||
536                     bt->trace_state == Blktrace_stopped) {
537                         blktrace_seq++;
538                         smp_mb();
539                         bt->trace_state = Blktrace_running;
540
541                         trace_note_time(bt);
542                         ret = 0;
543                 }
544         } else {
545                 if (bt->trace_state == Blktrace_running) {
546                         bt->trace_state = Blktrace_stopped;
547                         relay_flush(bt->rchan);
548                         ret = 0;
549                 }
550         }
551
552         return ret;
553 }
554 EXPORT_SYMBOL_GPL(blk_trace_startstop);
555
556 /**
557  * blk_trace_ioctl: - handle the ioctls associated with tracing
558  * @bdev:       the block device
559  * @cmd:        the ioctl cmd
560  * @arg:        the argument data, if any
561  *
562  **/
563 int blk_trace_ioctl(struct block_device *bdev, unsigned cmd, char __user *arg)
564 {
565         struct request_queue *q;
566         int ret, start = 0;
567         char b[BDEVNAME_SIZE];
568
569         q = bdev_get_queue(bdev);
570         if (!q)
571                 return -ENXIO;
572
573         mutex_lock(&bdev->bd_mutex);
574
575         switch (cmd) {
576         case BLKTRACESETUP:
577                 bdevname(bdev, b);
578                 ret = blk_trace_setup(q, b, bdev->bd_dev, arg);
579                 break;
580         case BLKTRACESTART:
581                 start = 1;
582         case BLKTRACESTOP:
583                 ret = blk_trace_startstop(q, start);
584                 break;
585         case BLKTRACETEARDOWN:
586                 ret = blk_trace_remove(q);
587                 break;
588         default:
589                 ret = -ENOTTY;
590                 break;
591         }
592
593         mutex_unlock(&bdev->bd_mutex);
594         return ret;
595 }
596
597 /**
598  * blk_trace_shutdown: - stop and cleanup trace structures
599  * @q:    the request queue associated with the device
600  *
601  **/
602 void blk_trace_shutdown(struct request_queue *q)
603 {
604         if (q->blk_trace) {
605                 blk_trace_startstop(q, 0);
606                 blk_trace_remove(q);
607         }
608 }
609
610 /*
611  * blktrace probes
612  */
613
614 /**
615  * blk_add_trace_rq - Add a trace for a request oriented action
616  * @q:          queue the io is for
617  * @rq:         the source request
618  * @what:       the action
619  *
620  * Description:
621  *     Records an action against a request. Will log the bio offset + size.
622  *
623  **/
624 static void blk_add_trace_rq(struct request_queue *q, struct request *rq,
625                                     u32 what)
626 {
627         struct blk_trace *bt = q->blk_trace;
628         int rw = rq->cmd_flags & 0x03;
629
630         if (likely(!bt))
631                 return;
632
633         if (blk_discard_rq(rq))
634                 rw |= (1 << BIO_RW_DISCARD);
635
636         if (blk_pc_request(rq)) {
637                 what |= BLK_TC_ACT(BLK_TC_PC);
638                 __blk_add_trace(bt, 0, rq->data_len, rw, what, rq->errors,
639                                 sizeof(rq->cmd), rq->cmd);
640         } else  {
641                 what |= BLK_TC_ACT(BLK_TC_FS);
642                 __blk_add_trace(bt, rq->hard_sector, rq->hard_nr_sectors << 9,
643                                 rw, what, rq->errors, 0, NULL);
644         }
645 }
646
647 static void blk_add_trace_rq_abort(struct request_queue *q, struct request *rq)
648 {
649         blk_add_trace_rq(q, rq, BLK_TA_ABORT);
650 }
651
652 static void blk_add_trace_rq_insert(struct request_queue *q, struct request *rq)
653 {
654         blk_add_trace_rq(q, rq, BLK_TA_INSERT);
655 }
656
657 static void blk_add_trace_rq_issue(struct request_queue *q, struct request *rq)
658 {
659         blk_add_trace_rq(q, rq, BLK_TA_ISSUE);
660 }
661
662 static void blk_add_trace_rq_requeue(struct request_queue *q,
663                                      struct request *rq)
664 {
665         blk_add_trace_rq(q, rq, BLK_TA_REQUEUE);
666 }
667
668 static void blk_add_trace_rq_complete(struct request_queue *q,
669                                       struct request *rq)
670 {
671         blk_add_trace_rq(q, rq, BLK_TA_COMPLETE);
672 }
673
674 /**
675  * blk_add_trace_bio - Add a trace for a bio oriented action
676  * @q:          queue the io is for
677  * @bio:        the source bio
678  * @what:       the action
679  *
680  * Description:
681  *     Records an action against a bio. Will log the bio offset + size.
682  *
683  **/
684 static void blk_add_trace_bio(struct request_queue *q, struct bio *bio,
685                                      u32 what)
686 {
687         struct blk_trace *bt = q->blk_trace;
688
689         if (likely(!bt))
690                 return;
691
692         __blk_add_trace(bt, bio->bi_sector, bio->bi_size, bio->bi_rw, what,
693                         !bio_flagged(bio, BIO_UPTODATE), 0, NULL);
694 }
695
696 static void blk_add_trace_bio_bounce(struct request_queue *q, struct bio *bio)
697 {
698         blk_add_trace_bio(q, bio, BLK_TA_BOUNCE);
699 }
700
701 static void blk_add_trace_bio_complete(struct request_queue *q, struct bio *bio)
702 {
703         blk_add_trace_bio(q, bio, BLK_TA_COMPLETE);
704 }
705
706 static void blk_add_trace_bio_backmerge(struct request_queue *q,
707                                         struct bio *bio)
708 {
709         blk_add_trace_bio(q, bio, BLK_TA_BACKMERGE);
710 }
711
712 static void blk_add_trace_bio_frontmerge(struct request_queue *q,
713                                          struct bio *bio)
714 {
715         blk_add_trace_bio(q, bio, BLK_TA_FRONTMERGE);
716 }
717
718 static void blk_add_trace_bio_queue(struct request_queue *q, struct bio *bio)
719 {
720         blk_add_trace_bio(q, bio, BLK_TA_QUEUE);
721 }
722
723 static void blk_add_trace_getrq(struct request_queue *q,
724                                 struct bio *bio, int rw)
725 {
726         if (bio)
727                 blk_add_trace_bio(q, bio, BLK_TA_GETRQ);
728         else {
729                 struct blk_trace *bt = q->blk_trace;
730
731                 if (bt)
732                         __blk_add_trace(bt, 0, 0, rw, BLK_TA_GETRQ, 0, 0, NULL);
733         }
734 }
735
736
737 static void blk_add_trace_sleeprq(struct request_queue *q,
738                                   struct bio *bio, int rw)
739 {
740         if (bio)
741                 blk_add_trace_bio(q, bio, BLK_TA_SLEEPRQ);
742         else {
743                 struct blk_trace *bt = q->blk_trace;
744
745                 if (bt)
746                         __blk_add_trace(bt, 0, 0, rw, BLK_TA_SLEEPRQ,
747                                         0, 0, NULL);
748         }
749 }
750
751 static void blk_add_trace_plug(struct request_queue *q)
752 {
753         struct blk_trace *bt = q->blk_trace;
754
755         if (bt)
756                 __blk_add_trace(bt, 0, 0, 0, BLK_TA_PLUG, 0, 0, NULL);
757 }
758
759 static void blk_add_trace_unplug_io(struct request_queue *q)
760 {
761         struct blk_trace *bt = q->blk_trace;
762
763         if (bt) {
764                 unsigned int pdu = q->rq.count[READ] + q->rq.count[WRITE];
765                 __be64 rpdu = cpu_to_be64(pdu);
766
767                 __blk_add_trace(bt, 0, 0, 0, BLK_TA_UNPLUG_IO, 0,
768                                 sizeof(rpdu), &rpdu);
769         }
770 }
771
772 static void blk_add_trace_unplug_timer(struct request_queue *q)
773 {
774         struct blk_trace *bt = q->blk_trace;
775
776         if (bt) {
777                 unsigned int pdu = q->rq.count[READ] + q->rq.count[WRITE];
778                 __be64 rpdu = cpu_to_be64(pdu);
779
780                 __blk_add_trace(bt, 0, 0, 0, BLK_TA_UNPLUG_TIMER, 0,
781                                 sizeof(rpdu), &rpdu);
782         }
783 }
784
785 static void blk_add_trace_split(struct request_queue *q, struct bio *bio,
786                                 unsigned int pdu)
787 {
788         struct blk_trace *bt = q->blk_trace;
789
790         if (bt) {
791                 __be64 rpdu = cpu_to_be64(pdu);
792
793                 __blk_add_trace(bt, bio->bi_sector, bio->bi_size, bio->bi_rw,
794                                 BLK_TA_SPLIT, !bio_flagged(bio, BIO_UPTODATE),
795                                 sizeof(rpdu), &rpdu);
796         }
797 }
798
799 /**
800  * blk_add_trace_remap - Add a trace for a remap operation
801  * @q:          queue the io is for
802  * @bio:        the source bio
803  * @dev:        target device
804  * @from:       source sector
805  * @to:         target sector
806  *
807  * Description:
808  *     Device mapper or raid target sometimes need to split a bio because
809  *     it spans a stripe (or similar). Add a trace for that action.
810  *
811  **/
812 static void blk_add_trace_remap(struct request_queue *q, struct bio *bio,
813                                        dev_t dev, sector_t from, sector_t to)
814 {
815         struct blk_trace *bt = q->blk_trace;
816         struct blk_io_trace_remap r;
817
818         if (likely(!bt))
819                 return;
820
821         r.device = cpu_to_be32(dev);
822         r.device_from = cpu_to_be32(bio->bi_bdev->bd_dev);
823         r.sector = cpu_to_be64(to);
824
825         __blk_add_trace(bt, from, bio->bi_size, bio->bi_rw, BLK_TA_REMAP,
826                         !bio_flagged(bio, BIO_UPTODATE), sizeof(r), &r);
827 }
828
829 /**
830  * blk_add_driver_data - Add binary message with driver-specific data
831  * @q:          queue the io is for
832  * @rq:         io request
833  * @data:       driver-specific data
834  * @len:        length of driver-specific data
835  *
836  * Description:
837  *     Some drivers might want to write driver-specific data per request.
838  *
839  **/
840 void blk_add_driver_data(struct request_queue *q,
841                          struct request *rq,
842                          void *data, size_t len)
843 {
844         struct blk_trace *bt = q->blk_trace;
845
846         if (likely(!bt))
847                 return;
848
849         if (blk_pc_request(rq))
850                 __blk_add_trace(bt, 0, rq->data_len, 0, BLK_TA_DRV_DATA,
851                                 rq->errors, len, data);
852         else
853                 __blk_add_trace(bt, rq->hard_sector, rq->hard_nr_sectors << 9,
854                                 0, BLK_TA_DRV_DATA, rq->errors, len, data);
855 }
856 EXPORT_SYMBOL_GPL(blk_add_driver_data);
857
858 static void blk_register_tracepoints(void)
859 {
860         int ret;
861
862         ret = register_trace_block_rq_abort(blk_add_trace_rq_abort);
863         WARN_ON(ret);
864         ret = register_trace_block_rq_insert(blk_add_trace_rq_insert);
865         WARN_ON(ret);
866         ret = register_trace_block_rq_issue(blk_add_trace_rq_issue);
867         WARN_ON(ret);
868         ret = register_trace_block_rq_requeue(blk_add_trace_rq_requeue);
869         WARN_ON(ret);
870         ret = register_trace_block_rq_complete(blk_add_trace_rq_complete);
871         WARN_ON(ret);
872         ret = register_trace_block_bio_bounce(blk_add_trace_bio_bounce);
873         WARN_ON(ret);
874         ret = register_trace_block_bio_complete(blk_add_trace_bio_complete);
875         WARN_ON(ret);
876         ret = register_trace_block_bio_backmerge(blk_add_trace_bio_backmerge);
877         WARN_ON(ret);
878         ret = register_trace_block_bio_frontmerge(blk_add_trace_bio_frontmerge);
879         WARN_ON(ret);
880         ret = register_trace_block_bio_queue(blk_add_trace_bio_queue);
881         WARN_ON(ret);
882         ret = register_trace_block_getrq(blk_add_trace_getrq);
883         WARN_ON(ret);
884         ret = register_trace_block_sleeprq(blk_add_trace_sleeprq);
885         WARN_ON(ret);
886         ret = register_trace_block_plug(blk_add_trace_plug);
887         WARN_ON(ret);
888         ret = register_trace_block_unplug_timer(blk_add_trace_unplug_timer);
889         WARN_ON(ret);
890         ret = register_trace_block_unplug_io(blk_add_trace_unplug_io);
891         WARN_ON(ret);
892         ret = register_trace_block_split(blk_add_trace_split);
893         WARN_ON(ret);
894         ret = register_trace_block_remap(blk_add_trace_remap);
895         WARN_ON(ret);
896 }
897
898 static void blk_unregister_tracepoints(void)
899 {
900         unregister_trace_block_remap(blk_add_trace_remap);
901         unregister_trace_block_split(blk_add_trace_split);
902         unregister_trace_block_unplug_io(blk_add_trace_unplug_io);
903         unregister_trace_block_unplug_timer(blk_add_trace_unplug_timer);
904         unregister_trace_block_plug(blk_add_trace_plug);
905         unregister_trace_block_sleeprq(blk_add_trace_sleeprq);
906         unregister_trace_block_getrq(blk_add_trace_getrq);
907         unregister_trace_block_bio_queue(blk_add_trace_bio_queue);
908         unregister_trace_block_bio_frontmerge(blk_add_trace_bio_frontmerge);
909         unregister_trace_block_bio_backmerge(blk_add_trace_bio_backmerge);
910         unregister_trace_block_bio_complete(blk_add_trace_bio_complete);
911         unregister_trace_block_bio_bounce(blk_add_trace_bio_bounce);
912         unregister_trace_block_rq_complete(blk_add_trace_rq_complete);
913         unregister_trace_block_rq_requeue(blk_add_trace_rq_requeue);
914         unregister_trace_block_rq_issue(blk_add_trace_rq_issue);
915         unregister_trace_block_rq_insert(blk_add_trace_rq_insert);
916         unregister_trace_block_rq_abort(blk_add_trace_rq_abort);
917
918         tracepoint_synchronize_unregister();
919 }
920
921 /*
922  * struct blk_io_tracer formatting routines
923  */
924
925 static void fill_rwbs(char *rwbs, const struct blk_io_trace *t)
926 {
927         int i = 0;
928         int tc = t->action >> BLK_TC_SHIFT;
929
930         if (tc & BLK_TC_DISCARD)
931                 rwbs[i++] = 'D';
932         else if (tc & BLK_TC_WRITE)
933                 rwbs[i++] = 'W';
934         else if (t->bytes)
935                 rwbs[i++] = 'R';
936         else
937                 rwbs[i++] = 'N';
938
939         if (tc & BLK_TC_AHEAD)
940                 rwbs[i++] = 'A';
941         if (tc & BLK_TC_BARRIER)
942                 rwbs[i++] = 'B';
943         if (tc & BLK_TC_SYNC)
944                 rwbs[i++] = 'S';
945         if (tc & BLK_TC_META)
946                 rwbs[i++] = 'M';
947
948         rwbs[i] = '\0';
949 }
950
951 static inline
952 const struct blk_io_trace *te_blk_io_trace(const struct trace_entry *ent)
953 {
954         return (const struct blk_io_trace *)ent;
955 }
956
957 static inline const void *pdu_start(const struct trace_entry *ent)
958 {
959         return te_blk_io_trace(ent) + 1;
960 }
961
962 static inline u32 t_sec(const struct trace_entry *ent)
963 {
964         return te_blk_io_trace(ent)->bytes >> 9;
965 }
966
967 static inline unsigned long long t_sector(const struct trace_entry *ent)
968 {
969         return te_blk_io_trace(ent)->sector;
970 }
971
972 static inline __u16 t_error(const struct trace_entry *ent)
973 {
974         return te_blk_io_trace(ent)->error;
975 }
976
977 static __u64 get_pdu_int(const struct trace_entry *ent)
978 {
979         const __u64 *val = pdu_start(ent);
980         return be64_to_cpu(*val);
981 }
982
983 static void get_pdu_remap(const struct trace_entry *ent,
984                           struct blk_io_trace_remap *r)
985 {
986         const struct blk_io_trace_remap *__r = pdu_start(ent);
987         __u64 sector = __r->sector;
988
989         r->device = be32_to_cpu(__r->device);
990         r->device_from = be32_to_cpu(__r->device_from);
991         r->sector = be64_to_cpu(sector);
992 }
993
994 static int blk_log_action_iter(struct trace_iterator *iter, const char *act)
995 {
996         char rwbs[6];
997         unsigned long long ts  = ns2usecs(iter->ts);
998         unsigned long usec_rem = do_div(ts, USEC_PER_SEC);
999         unsigned secs          = (unsigned long)ts;
1000         const struct trace_entry *ent = iter->ent;
1001         const struct blk_io_trace *t = (const struct blk_io_trace *)ent;
1002
1003         fill_rwbs(rwbs, t);
1004
1005         return trace_seq_printf(&iter->seq,
1006                                 "%3d,%-3d %2d %5d.%06lu %5u %2s %3s ",
1007                                 MAJOR(t->device), MINOR(t->device), iter->cpu,
1008                                 secs, usec_rem, ent->pid, act, rwbs);
1009 }
1010
1011 static int blk_log_action_seq(struct trace_seq *s, const struct blk_io_trace *t,
1012                               const char *act)
1013 {
1014         char rwbs[6];
1015         fill_rwbs(rwbs, t);
1016         return trace_seq_printf(s, "%3d,%-3d %2s %3s ",
1017                                 MAJOR(t->device), MINOR(t->device), act, rwbs);
1018 }
1019
1020 static int blk_log_generic(struct trace_seq *s, const struct trace_entry *ent)
1021 {
1022         char cmd[TASK_COMM_LEN];
1023
1024         trace_find_cmdline(ent->pid, cmd);
1025
1026         if (t_sec(ent))
1027                 return trace_seq_printf(s, "%llu + %u [%s]\n",
1028                                         t_sector(ent), t_sec(ent), cmd);
1029         return trace_seq_printf(s, "[%s]\n", cmd);
1030 }
1031
1032 static int blk_log_with_error(struct trace_seq *s,
1033                               const struct trace_entry *ent)
1034 {
1035         if (t_sec(ent))
1036                 return trace_seq_printf(s, "%llu + %u [%d]\n", t_sector(ent),
1037                                         t_sec(ent), t_error(ent));
1038         return trace_seq_printf(s, "%llu [%d]\n", t_sector(ent), t_error(ent));
1039 }
1040
1041 static int blk_log_remap(struct trace_seq *s, const struct trace_entry *ent)
1042 {
1043         struct blk_io_trace_remap r = { .device = 0, };
1044
1045         get_pdu_remap(ent, &r);
1046         return trace_seq_printf(s, "%llu + %u <- (%d,%d) %llu\n",
1047                                t_sector(ent),
1048                                t_sec(ent), MAJOR(r.device), MINOR(r.device),
1049                                (unsigned long long)r.sector);
1050 }
1051
1052 static int blk_log_plug(struct trace_seq *s, const struct trace_entry *ent)
1053 {
1054         char cmd[TASK_COMM_LEN];
1055
1056         trace_find_cmdline(ent->pid, cmd);
1057
1058         return trace_seq_printf(s, "[%s]\n", cmd);
1059 }
1060
1061 static int blk_log_unplug(struct trace_seq *s, const struct trace_entry *ent)
1062 {
1063         char cmd[TASK_COMM_LEN];
1064
1065         trace_find_cmdline(ent->pid, cmd);
1066
1067         return trace_seq_printf(s, "[%s] %llu\n", cmd, get_pdu_int(ent));
1068 }
1069
1070 static int blk_log_split(struct trace_seq *s, const struct trace_entry *ent)
1071 {
1072         char cmd[TASK_COMM_LEN];
1073
1074         trace_find_cmdline(ent->pid, cmd);
1075
1076         return trace_seq_printf(s, "%llu / %llu [%s]\n", t_sector(ent),
1077                                 get_pdu_int(ent), cmd);
1078 }
1079
1080 /*
1081  * struct tracer operations
1082  */
1083
1084 static void blk_tracer_print_header(struct seq_file *m)
1085 {
1086         if (!(blk_tracer_flags.val & TRACE_BLK_OPT_CLASSIC))
1087                 return;
1088         seq_puts(m, "# DEV   CPU TIMESTAMP     PID ACT FLG\n"
1089                     "#  |     |     |           |   |   |\n");
1090 }
1091
1092 static void blk_tracer_start(struct trace_array *tr)
1093 {
1094         if (atomic_add_return(1, &blk_probes_ref) == 1)
1095                 blk_register_tracepoints();
1096         trace_flags &= ~TRACE_ITER_CONTEXT_INFO;
1097 }
1098
1099 static int blk_tracer_init(struct trace_array *tr)
1100 {
1101         blk_tr = tr;
1102         blk_tracer_start(tr);
1103         blk_tracer_enabled = true;
1104         return 0;
1105 }
1106
1107 static void blk_tracer_stop(struct trace_array *tr)
1108 {
1109         trace_flags |= TRACE_ITER_CONTEXT_INFO;
1110         if (atomic_dec_and_test(&blk_probes_ref))
1111                 blk_unregister_tracepoints();
1112 }
1113
1114 static void blk_tracer_reset(struct trace_array *tr)
1115 {
1116         if (!atomic_read(&blk_probes_ref))
1117                 return;
1118
1119         blk_tracer_enabled = false;
1120         blk_tracer_stop(tr);
1121 }
1122
1123 static const struct {
1124         const char *act[2];
1125         int        (*print)(struct trace_seq *s, const struct trace_entry *ent);
1126 } what2act[] = {
1127         [__BLK_TA_QUEUE]        = {{  "Q", "queue" },      blk_log_generic },
1128         [__BLK_TA_BACKMERGE]    = {{  "M", "backmerge" },  blk_log_generic },
1129         [__BLK_TA_FRONTMERGE]   = {{  "F", "frontmerge" }, blk_log_generic },
1130         [__BLK_TA_GETRQ]        = {{  "G", "getrq" },      blk_log_generic },
1131         [__BLK_TA_SLEEPRQ]      = {{  "S", "sleeprq" },    blk_log_generic },
1132         [__BLK_TA_REQUEUE]      = {{  "R", "requeue" },    blk_log_with_error },
1133         [__BLK_TA_ISSUE]        = {{  "D", "issue" },      blk_log_generic },
1134         [__BLK_TA_COMPLETE]     = {{  "C", "complete" },   blk_log_with_error },
1135         [__BLK_TA_PLUG]         = {{  "P", "plug" },       blk_log_plug },
1136         [__BLK_TA_UNPLUG_IO]    = {{  "U", "unplug_io" },  blk_log_unplug },
1137         [__BLK_TA_UNPLUG_TIMER] = {{ "UT", "unplug_timer" }, blk_log_unplug },
1138         [__BLK_TA_INSERT]       = {{  "I", "insert" },     blk_log_generic },
1139         [__BLK_TA_SPLIT]        = {{  "X", "split" },      blk_log_split },
1140         [__BLK_TA_BOUNCE]       = {{  "B", "bounce" },     blk_log_generic },
1141         [__BLK_TA_REMAP]        = {{  "A", "remap" },      blk_log_remap },
1142 };
1143
1144 static enum print_line_t blk_trace_event_print(struct trace_iterator *iter,
1145                                                int flags)
1146 {
1147         struct trace_seq *s = &iter->seq;
1148         const struct blk_io_trace *t = (struct blk_io_trace *)iter->ent;
1149         const u16 what = t->action & ((1 << BLK_TC_SHIFT) - 1);
1150         int ret;
1151
1152         if (!trace_print_context(iter))
1153                 return TRACE_TYPE_PARTIAL_LINE;
1154
1155         if (unlikely(what == 0 || what >= ARRAY_SIZE(what2act)))
1156                 ret = trace_seq_printf(s, "Bad pc action %x\n", what);
1157         else {
1158                 const bool long_act = !!(trace_flags & TRACE_ITER_VERBOSE);
1159                 ret = blk_log_action_seq(s, t, what2act[what].act[long_act]);
1160                 if (ret)
1161                         ret = what2act[what].print(s, iter->ent);
1162         }
1163
1164         return ret ? TRACE_TYPE_HANDLED : TRACE_TYPE_PARTIAL_LINE;
1165 }
1166
1167 static int blk_trace_synthesize_old_trace(struct trace_iterator *iter)
1168 {
1169         struct trace_seq *s = &iter->seq;
1170         struct blk_io_trace *t = (struct blk_io_trace *)iter->ent;
1171         const int offset = offsetof(struct blk_io_trace, sector);
1172         struct blk_io_trace old = {
1173                 .magic    = BLK_IO_TRACE_MAGIC | BLK_IO_TRACE_VERSION,
1174                 .time     = iter->ts,
1175         };
1176
1177         if (!trace_seq_putmem(s, &old, offset))
1178                 return 0;
1179         return trace_seq_putmem(s, &t->sector,
1180                                 sizeof(old) - offset + t->pdu_len);
1181 }
1182
1183 static enum print_line_t
1184 blk_trace_event_print_binary(struct trace_iterator *iter, int flags)
1185 {
1186         return blk_trace_synthesize_old_trace(iter) ?
1187                         TRACE_TYPE_HANDLED : TRACE_TYPE_PARTIAL_LINE;
1188 }
1189
1190 static enum print_line_t blk_tracer_print_line(struct trace_iterator *iter)
1191 {
1192         const struct blk_io_trace *t;
1193         u16 what;
1194         int ret;
1195
1196         if (!(blk_tracer_flags.val & TRACE_BLK_OPT_CLASSIC))
1197                 return TRACE_TYPE_UNHANDLED;
1198
1199         t = (const struct blk_io_trace *)iter->ent;
1200         what = t->action & ((1 << BLK_TC_SHIFT) - 1);
1201
1202         if (unlikely(what == 0 || what >= ARRAY_SIZE(what2act)))
1203                 ret = trace_seq_printf(&iter->seq, "Bad pc action %x\n", what);
1204         else {
1205                 const bool long_act = !!(trace_flags & TRACE_ITER_VERBOSE);
1206                 ret = blk_log_action_iter(iter, what2act[what].act[long_act]);
1207                 if (ret)
1208                         ret = what2act[what].print(&iter->seq, iter->ent);
1209         }
1210
1211         return ret ? TRACE_TYPE_HANDLED : TRACE_TYPE_PARTIAL_LINE;
1212 }
1213
1214 static struct tracer blk_tracer __read_mostly = {
1215         .name           = "blk",
1216         .init           = blk_tracer_init,
1217         .reset          = blk_tracer_reset,
1218         .start          = blk_tracer_start,
1219         .stop           = blk_tracer_stop,
1220         .print_header   = blk_tracer_print_header,
1221         .print_line     = blk_tracer_print_line,
1222         .flags          = &blk_tracer_flags,
1223 };
1224
1225 static struct trace_event trace_blk_event = {
1226         .type           = TRACE_BLK,
1227         .trace          = blk_trace_event_print,
1228         .binary         = blk_trace_event_print_binary,
1229 };
1230
1231 static int __init init_blk_tracer(void)
1232 {
1233         if (!register_ftrace_event(&trace_blk_event)) {
1234                 pr_warning("Warning: could not register block events\n");
1235                 return 1;
1236         }
1237
1238         if (register_tracer(&blk_tracer) != 0) {
1239                 pr_warning("Warning: could not register the block tracer\n");
1240                 unregister_ftrace_event(&trace_blk_event);
1241                 return 1;
1242         }
1243
1244         return 0;
1245 }
1246
1247 device_initcall(init_blk_tracer);
1248
1249 static int blk_trace_remove_queue(struct request_queue *q)
1250 {
1251         struct blk_trace *bt;
1252
1253         bt = xchg(&q->blk_trace, NULL);
1254         if (bt == NULL)
1255                 return -EINVAL;
1256
1257         kfree(bt);
1258         return 0;
1259 }
1260
1261 /*
1262  * Setup everything required to start tracing
1263  */
1264 static int blk_trace_setup_queue(struct request_queue *q, dev_t dev)
1265 {
1266         struct blk_trace *old_bt, *bt = NULL;
1267
1268         bt = kzalloc(sizeof(*bt), GFP_KERNEL);
1269         if (!bt)
1270                 return -ENOMEM;
1271
1272         bt->dev = dev;
1273         bt->act_mask = (u16)-1;
1274         bt->end_lba = -1ULL;
1275
1276         old_bt = xchg(&q->blk_trace, bt);
1277         if (old_bt != NULL) {
1278                 (void)xchg(&q->blk_trace, old_bt);
1279                 kfree(bt);
1280                 return -EBUSY;
1281         }
1282
1283         return 0;
1284 }
1285
1286 /*
1287  * sysfs interface to enable and configure tracing
1288  */
1289
1290 static ssize_t sysfs_blk_trace_attr_show(struct device *dev,
1291                                          struct device_attribute *attr,
1292                                          char *buf);
1293 static ssize_t sysfs_blk_trace_attr_store(struct device *dev,
1294                                           struct device_attribute *attr,
1295                                           const char *buf, size_t count);
1296 #define BLK_TRACE_DEVICE_ATTR(_name) \
1297         DEVICE_ATTR(_name, S_IRUGO | S_IWUSR, \
1298                     sysfs_blk_trace_attr_show, \
1299                     sysfs_blk_trace_attr_store)
1300
1301 static BLK_TRACE_DEVICE_ATTR(enable);
1302 static BLK_TRACE_DEVICE_ATTR(act_mask);
1303 static BLK_TRACE_DEVICE_ATTR(pid);
1304 static BLK_TRACE_DEVICE_ATTR(start_lba);
1305 static BLK_TRACE_DEVICE_ATTR(end_lba);
1306
1307 static struct attribute *blk_trace_attrs[] = {
1308         &dev_attr_enable.attr,
1309         &dev_attr_act_mask.attr,
1310         &dev_attr_pid.attr,
1311         &dev_attr_start_lba.attr,
1312         &dev_attr_end_lba.attr,
1313         NULL
1314 };
1315
1316 struct attribute_group blk_trace_attr_group = {
1317         .name  = "trace",
1318         .attrs = blk_trace_attrs,
1319 };
1320
1321 static const struct {
1322         int mask;
1323         const char *str;
1324 } mask_maps[] = {
1325         { BLK_TC_READ,          "read"          },
1326         { BLK_TC_WRITE,         "write"         },
1327         { BLK_TC_BARRIER,       "barrier"       },
1328         { BLK_TC_SYNC,          "sync"          },
1329         { BLK_TC_QUEUE,         "queue"         },
1330         { BLK_TC_REQUEUE,       "requeue"       },
1331         { BLK_TC_ISSUE,         "issue"         },
1332         { BLK_TC_COMPLETE,      "complete"      },
1333         { BLK_TC_FS,            "fs"            },
1334         { BLK_TC_PC,            "pc"            },
1335         { BLK_TC_AHEAD,         "ahead"         },
1336         { BLK_TC_META,          "meta"          },
1337         { BLK_TC_DISCARD,       "discard"       },
1338         { BLK_TC_DRV_DATA,      "drv_data"      },
1339 };
1340
1341 static int blk_trace_str2mask(const char *str)
1342 {
1343         int i;
1344         int mask = 0;
1345         char *s, *token;
1346
1347         s = kstrdup(str, GFP_KERNEL);
1348         if (s == NULL)
1349                 return -ENOMEM;
1350         s = strstrip(s);
1351
1352         while (1) {
1353                 token = strsep(&s, ",");
1354                 if (token == NULL)
1355                         break;
1356
1357                 if (*token == '\0')
1358                         continue;
1359
1360                 for (i = 0; i < ARRAY_SIZE(mask_maps); i++) {
1361                         if (strcasecmp(token, mask_maps[i].str) == 0) {
1362                                 mask |= mask_maps[i].mask;
1363                                 break;
1364                         }
1365                 }
1366                 if (i == ARRAY_SIZE(mask_maps)) {
1367                         mask = -EINVAL;
1368                         break;
1369                 }
1370         }
1371         kfree(s);
1372
1373         return mask;
1374 }
1375
1376 static ssize_t blk_trace_mask2str(char *buf, int mask)
1377 {
1378         int i;
1379         char *p = buf;
1380
1381         for (i = 0; i < ARRAY_SIZE(mask_maps); i++) {
1382                 if (mask & mask_maps[i].mask) {
1383                         p += sprintf(p, "%s%s",
1384                                     (p == buf) ? "" : ",", mask_maps[i].str);
1385                 }
1386         }
1387         *p++ = '\n';
1388
1389         return p - buf;
1390 }
1391
1392 static struct request_queue *blk_trace_get_queue(struct block_device *bdev)
1393 {
1394         if (bdev->bd_disk == NULL)
1395                 return NULL;
1396
1397         return bdev_get_queue(bdev);
1398 }
1399
1400 static ssize_t sysfs_blk_trace_attr_show(struct device *dev,
1401                                          struct device_attribute *attr,
1402                                          char *buf)
1403 {
1404         struct hd_struct *p = dev_to_part(dev);
1405         struct request_queue *q;
1406         struct block_device *bdev;
1407         ssize_t ret = -ENXIO;
1408
1409         lock_kernel();
1410         bdev = bdget(part_devt(p));
1411         if (bdev == NULL)
1412                 goto out_unlock_kernel;
1413
1414         q = blk_trace_get_queue(bdev);
1415         if (q == NULL)
1416                 goto out_bdput;
1417
1418         mutex_lock(&bdev->bd_mutex);
1419
1420         if (attr == &dev_attr_enable) {
1421                 ret = sprintf(buf, "%u\n", !!q->blk_trace);
1422                 goto out_unlock_bdev;
1423         }
1424
1425         if (q->blk_trace == NULL)
1426                 ret = sprintf(buf, "disabled\n");
1427         else if (attr == &dev_attr_act_mask)
1428                 ret = blk_trace_mask2str(buf, q->blk_trace->act_mask);
1429         else if (attr == &dev_attr_pid)
1430                 ret = sprintf(buf, "%u\n", q->blk_trace->pid);
1431         else if (attr == &dev_attr_start_lba)
1432                 ret = sprintf(buf, "%llu\n", q->blk_trace->start_lba);
1433         else if (attr == &dev_attr_end_lba)
1434                 ret = sprintf(buf, "%llu\n", q->blk_trace->end_lba);
1435
1436 out_unlock_bdev:
1437         mutex_unlock(&bdev->bd_mutex);
1438 out_bdput:
1439         bdput(bdev);
1440 out_unlock_kernel:
1441         unlock_kernel();
1442         return ret;
1443 }
1444
1445 static ssize_t sysfs_blk_trace_attr_store(struct device *dev,
1446                                           struct device_attribute *attr,
1447                                           const char *buf, size_t count)
1448 {
1449         struct block_device *bdev;
1450         struct request_queue *q;
1451         struct hd_struct *p;
1452         u64 value;
1453         ssize_t ret = -EINVAL;
1454
1455         if (count == 0)
1456                 goto out;
1457
1458         if (attr == &dev_attr_act_mask) {
1459                 if (sscanf(buf, "%llx", &value) != 1) {
1460                         /* Assume it is a list of trace category names */
1461                         ret = blk_trace_str2mask(buf);
1462                         if (ret < 0)
1463                                 goto out;
1464                         value = ret;
1465                 }
1466         } else if (sscanf(buf, "%llu", &value) != 1)
1467                 goto out;
1468
1469         ret = -ENXIO;
1470
1471         lock_kernel();
1472         p = dev_to_part(dev);
1473         bdev = bdget(part_devt(p));
1474         if (bdev == NULL)
1475                 goto out_unlock_kernel;
1476
1477         q = blk_trace_get_queue(bdev);
1478         if (q == NULL)
1479                 goto out_bdput;
1480
1481         mutex_lock(&bdev->bd_mutex);
1482
1483         if (attr == &dev_attr_enable) {
1484                 if (value)
1485                         ret = blk_trace_setup_queue(q, bdev->bd_dev);
1486                 else
1487                         ret = blk_trace_remove_queue(q);
1488                 goto out_unlock_bdev;
1489         }
1490
1491         ret = 0;
1492         if (q->blk_trace == NULL)
1493                 ret = blk_trace_setup_queue(q, bdev->bd_dev);
1494
1495         if (ret == 0) {
1496                 if (attr == &dev_attr_act_mask)
1497                         q->blk_trace->act_mask = value;
1498                 else if (attr == &dev_attr_pid)
1499                         q->blk_trace->pid = value;
1500                 else if (attr == &dev_attr_start_lba)
1501                         q->blk_trace->start_lba = value;
1502                 else if (attr == &dev_attr_end_lba)
1503                         q->blk_trace->end_lba = value;
1504         }
1505
1506 out_unlock_bdev:
1507         mutex_unlock(&bdev->bd_mutex);
1508 out_bdput:
1509         bdput(bdev);
1510 out_unlock_kernel:
1511         unlock_kernel();
1512 out:
1513         return ret ? ret : count;
1514 }
1515