Whamcloud - gitweb
LU-812 compat: clean up mutex lock to use kernel mutex primitive
[fs/lustre-release.git] / lustre / llite / lloop.c
1 /* -*- mode: c; c-basic-offset: 8; indent-tabs-mode: nil; -*-
2  * vim:expandtab:shiftwidth=8:tabstop=8:
3  *
4  * GPL HEADER START
5  *
6  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License version 2 only,
10  * as published by the Free Software Foundation.
11  *
12  * This program is distributed in the hope that it will be useful, but
13  * WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * General Public License version 2 for more details (a copy is included
16  * in the LICENSE file that accompanied this code).
17  *
18  * You should have received a copy of the GNU General Public License
19  * version 2 along with this program; If not, see
20  * http://www.sun.com/software/products/lustre/docs/GPLv2.pdf
21  *
22  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
23  * CA 95054 USA or visit www.sun.com if you need additional information or
24  * have any questions.
25  *
26  * GPL HEADER END
27  */
28 /*
29  * Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
30  * Use is subject to license terms.
31  *
32  * Copyright (c) 2011, Whamcloud, Inc.
33  */
34 /*
35  * This file is part of Lustre, http://www.lustre.org/
36  * Lustre is a trademark of Sun Microsystems, Inc.
37  */
38
39 /*
40  *  linux/drivers/block/loop.c
41  *
42  *  Written by Theodore Ts'o, 3/29/93
43  *
44  * Copyright 1993 by Theodore Ts'o.  Redistribution of this file is
45  * permitted under the GNU General Public License.
46  *
47  * Modularized and updated for 1.1.16 kernel - Mitch Dsouza 28th May 1994
48  * Adapted for 1.3.59 kernel - Andries Brouwer, 1 Feb 1996
49  *
50  * Fixed do_loop_request() re-entrancy - Vincent.Renardias@waw.com Mar 20, 1997
51  *
52  * Added devfs support - Richard Gooch <rgooch@atnf.csiro.au> 16-Jan-1998
53  *
54  * Handle sparse backing files correctly - Kenn Humborg, Jun 28, 1998
55  *
56  * Loadable modules and other fixes by AK, 1998
57  *
58  * Maximum number of loop devices now dynamic via max_loop module parameter.
59  * Russell Kroll <rkroll@exploits.org> 19990701
60  *
61  * Maximum number of loop devices when compiled-in now selectable by passing
62  * max_loop=<1-255> to the kernel on boot.
63  * Erik I. Bols?, <eriki@himolde.no>, Oct 31, 1999
64  *
65  * Completely rewrite request handling to be make_request_fn style and
66  * non blocking, pushing work to a helper thread. Lots of fixes from
67  * Al Viro too.
68  * Jens Axboe <axboe@suse.de>, Nov 2000
69  *
70  * Support up to 256 loop devices
71  * Heinz Mauelshagen <mge@sistina.com>, Feb 2002
72  *
73  * Support for falling back on the write file operation when the address space
74  * operations prepare_write and/or commit_write are not available on the
75  * backing filesystem.
76  * Anton Altaparmakov, 16 Feb 2005
77  *
78  * Still To Fix:
79  * - Advisory locking is ignored here.
80  * - Should use an own CAP_* category instead of CAP_SYS_ADMIN
81  *
82  */
83
84 #ifndef AUTOCONF_INCLUDED
85 #include <linux/config.h>
86 #endif
87 #include <linux/module.h>
88
89 #include <linux/sched.h>
90 #include <linux/fs.h>
91 #include <linux/file.h>
92 #include <linux/stat.h>
93 #include <linux/errno.h>
94 #include <linux/major.h>
95 #include <linux/wait.h>
96 #include <linux/blkdev.h>
97 #include <linux/blkpg.h>
98 #include <linux/init.h>
99 #include <linux/smp_lock.h>
100 #include <linux/swap.h>
101 #include <linux/slab.h>
102 #include <linux/suspend.h>
103 #include <linux/writeback.h>
104 #include <linux/buffer_head.h>                /* for invalidate_bdev() */
105 #include <linux/completion.h>
106 #include <linux/highmem.h>
107 #include <linux/gfp.h>
108 #include <linux/swap.h>
109 #include <linux/pagevec.h>
110
111 #include <asm/uaccess.h>
112
113 #include <lustre_lib.h>
114 #include <lustre_lite.h>
115 #include "llite_internal.h"
116
117 #define LLOOP_MAX_SEGMENTS        PTLRPC_MAX_BRW_PAGES
118
119 /* Possible states of device */
120 enum {
121         LLOOP_UNBOUND,
122         LLOOP_BOUND,
123         LLOOP_RUNDOWN,
124 };
125
126 struct lloop_device {
127         int                  lo_number;
128         int                  lo_refcnt;
129         loff_t               lo_offset;
130         loff_t               lo_sizelimit;
131         int                  lo_flags;
132         int                (*ioctl)(struct lloop_device *, int cmd,
133                                     unsigned long arg);
134
135         struct file         *lo_backing_file;
136         struct block_device *lo_device;
137         unsigned             lo_blocksize;
138
139         int                  old_gfp_mask;
140
141         cfs_spinlock_t       lo_lock;
142         struct bio          *lo_bio;
143         struct bio          *lo_biotail;
144         int                  lo_state;
145         cfs_semaphore_t      lo_sem;
146         cfs_mutex_t          lo_ctl_mutex;
147         cfs_atomic_t         lo_pending;
148         cfs_waitq_t          lo_bh_wait;
149
150         struct request_queue *lo_queue;
151
152         const struct lu_env *lo_env;
153         struct cl_io         lo_io;
154         struct ll_dio_pages  lo_pvec;
155
156         /* data to handle bio for lustre. */
157         struct lo_request_data {
158                 struct page *lrd_pages[LLOOP_MAX_SEGMENTS];
159                 loff_t       lrd_offsets[LLOOP_MAX_SEGMENTS];
160         } lo_requests[1];
161 };
162
163 /*
164  * Loop flags
165  */
166 enum {
167         LO_FLAGS_READ_ONLY       = 1,
168 };
169
170 static int lloop_major;
171 #define MAX_LOOP_DEFAULT  16
172 static int max_loop = MAX_LOOP_DEFAULT;
173 static struct lloop_device *loop_dev;
174 static struct gendisk **disks;
175 static cfs_mutex_t lloop_mutex;
176 static void *ll_iocontrol_magic = NULL;
177
178 static loff_t get_loop_size(struct lloop_device *lo, struct file *file)
179 {
180         loff_t size, offset, loopsize;
181
182         /* Compute loopsize in bytes */
183         size = i_size_read(file->f_mapping->host);
184         offset = lo->lo_offset;
185         loopsize = size - offset;
186         if (lo->lo_sizelimit > 0 && lo->lo_sizelimit < loopsize)
187                 loopsize = lo->lo_sizelimit;
188
189         /*
190          * Unfortunately, if we want to do I/O on the device,
191          * the number of 512-byte sectors has to fit into a sector_t.
192          */
193         return loopsize >> 9;
194 }
195
196 static int do_bio_lustrebacked(struct lloop_device *lo, struct bio *head)
197 {
198         const struct lu_env  *env   = lo->lo_env;
199         struct cl_io         *io    = &lo->lo_io;
200         struct inode         *inode = lo->lo_backing_file->f_dentry->d_inode;
201         struct cl_object     *obj = ll_i2info(inode)->lli_clob;
202         pgoff_t               offset;
203         int                   ret;
204         int                   i;
205         int                   rw;
206         obd_count             page_count = 0;
207         struct bio_vec       *bvec;
208         struct bio           *bio;
209         ssize_t               bytes;
210
211         struct ll_dio_pages  *pvec = &lo->lo_pvec;
212         struct page         **pages = pvec->ldp_pages;
213         loff_t               *offsets = pvec->ldp_offsets;
214
215         truncate_inode_pages(inode->i_mapping, 0);
216
217         /* initialize the IO */
218         memset(io, 0, sizeof(*io));
219         io->ci_obj = obj;
220         ret = cl_io_init(env, io, CIT_MISC, obj);
221         if (ret)
222                 return io->ci_result;
223         io->ci_lockreq = CILR_NEVER;
224
225         LASSERT(head != NULL);
226         rw = head->bi_rw;
227         for (bio = head; bio != NULL; bio = bio->bi_next) {
228                 LASSERT(rw == bio->bi_rw);
229
230                 offset = (pgoff_t)(bio->bi_sector << 9) + lo->lo_offset;
231                 bio_for_each_segment(bvec, bio, i) {
232                         BUG_ON(bvec->bv_offset != 0);
233                         BUG_ON(bvec->bv_len != CFS_PAGE_SIZE);
234
235                         pages[page_count] = bvec->bv_page;
236                         offsets[page_count] = offset;
237                         page_count++;
238                         offset += bvec->bv_len;
239                 }
240                 LASSERT(page_count <= LLOOP_MAX_SEGMENTS);
241         }
242
243         ll_stats_ops_tally(ll_i2sbi(inode),
244                         (rw == WRITE) ? LPROC_LL_BRW_WRITE : LPROC_LL_BRW_READ,
245                         page_count);
246
247         pvec->ldp_size = page_count << PAGE_CACHE_SHIFT;
248         pvec->ldp_nr = page_count;
249
250         /* FIXME: in ll_direct_rw_pages, it has to allocate many cl_page{}s to
251          * write those pages into OST. Even worse case is that more pages
252          * would be asked to write out to swap space, and then finally get here
253          * again.
254          * Unfortunately this is NOT easy to fix.
255          * Thoughts on solution:
256          * 0. Define a reserved pool for cl_pages, which could be a list of
257          *    pre-allocated cl_pages from cl_page_kmem;
258          * 1. Define a new operation in cl_object_operations{}, says clo_depth,
259          *    which measures how many layers for this lustre object. Generally
260          *    speaking, the depth would be 2, one for llite, and one for lovsub.
261          *    However, for SNS, there will be more since we need additional page
262          *    to store parity;
263          * 2. Reserve the # of (page_count * depth) cl_pages from the reserved
264          *    pool. Afterwards, the clio would allocate the pages from reserved 
265          *    pool, this guarantees we neeedn't allocate the cl_pages from
266          *    generic cl_page slab cache.
267          *    Of course, if there is NOT enough pages in the pool, we might
268          *    be asked to write less pages once, this purely depends on
269          *    implementation. Anyway, we should be careful to avoid deadlocking.
270          */
271         LOCK_INODE_MUTEX(inode);
272         bytes = ll_direct_rw_pages(env, io, rw, inode, pvec);
273         UNLOCK_INODE_MUTEX(inode);
274         cl_io_fini(env, io);
275         return (bytes == pvec->ldp_size) ? 0 : (int)bytes;
276 }
277
278 /*
279  * Add bio to back of pending list
280  */
281 static void loop_add_bio(struct lloop_device *lo, struct bio *bio)
282 {
283         unsigned long flags;
284
285         cfs_spin_lock_irqsave(&lo->lo_lock, flags);
286         if (lo->lo_biotail) {
287                 lo->lo_biotail->bi_next = bio;
288                 lo->lo_biotail = bio;
289         } else
290                 lo->lo_bio = lo->lo_biotail = bio;
291         cfs_spin_unlock_irqrestore(&lo->lo_lock, flags);
292
293         cfs_atomic_inc(&lo->lo_pending);
294         if (cfs_waitq_active(&lo->lo_bh_wait))
295                 cfs_waitq_signal(&lo->lo_bh_wait);
296 }
297
298 /*
299  * Grab first pending buffer
300  */
301 static unsigned int loop_get_bio(struct lloop_device *lo, struct bio **req)
302 {
303         struct bio *first;
304         struct bio **bio;
305         unsigned int count = 0;
306         unsigned int page_count = 0;
307         int rw;
308
309         cfs_spin_lock_irq(&lo->lo_lock);
310         first = lo->lo_bio;
311         if (unlikely(first == NULL)) {
312                 cfs_spin_unlock_irq(&lo->lo_lock);
313                 return 0;
314         }
315
316         /* TODO: need to split the bio, too bad. */
317         LASSERT(first->bi_vcnt <= LLOOP_MAX_SEGMENTS);
318
319         rw = first->bi_rw;
320         bio = &lo->lo_bio;
321         while (*bio && (*bio)->bi_rw == rw) {
322                 CDEBUG(D_INFO, "bio sector %llu size %u count %u vcnt%u \n",
323                        (unsigned long long)(*bio)->bi_sector, (*bio)->bi_size,
324                        page_count, (*bio)->bi_vcnt);
325                 if (page_count + (*bio)->bi_vcnt > LLOOP_MAX_SEGMENTS)
326                         break;
327
328
329                 page_count += (*bio)->bi_vcnt;
330                 count++;
331                 bio = &(*bio)->bi_next;
332         }
333         if (*bio) {
334                 /* Some of bios can't be mergable. */
335                 lo->lo_bio = *bio;
336                 *bio = NULL;
337         } else {
338                 /* Hit the end of queue */
339                 lo->lo_biotail = NULL;
340                 lo->lo_bio = NULL;
341         }
342         *req = first;
343         cfs_spin_unlock_irq(&lo->lo_lock);
344         return count;
345 }
346
347 static int loop_make_request(struct request_queue *q, struct bio *old_bio)
348 {
349         struct lloop_device *lo = q->queuedata;
350         int rw = bio_rw(old_bio);
351         int inactive;
352
353         if (!lo)
354                 goto err;
355
356         CDEBUG(D_INFO, "submit bio sector %llu size %u\n",
357                (unsigned long long)old_bio->bi_sector, old_bio->bi_size);
358
359         cfs_spin_lock_irq(&lo->lo_lock);
360         inactive = (lo->lo_state != LLOOP_BOUND);
361         cfs_spin_unlock_irq(&lo->lo_lock);
362         if (inactive)
363                 goto err;
364
365         if (rw == WRITE) {
366                 if (lo->lo_flags & LO_FLAGS_READ_ONLY)
367                         goto err;
368         } else if (rw == READA) {
369                 rw = READ;
370         } else if (rw != READ) {
371                 CERROR("lloop: unknown command (%x)\n", rw);
372                 goto err;
373         }
374         loop_add_bio(lo, old_bio);
375         return 0;
376 err:
377         cfs_bio_io_error(old_bio, old_bio->bi_size);
378         return 0;
379 }
380
381 #ifdef HAVE_REQUEST_QUEUE_UNPLUG_FN
382 /*
383  * kick off io on the underlying address space
384  */
385 static void loop_unplug(struct request_queue *q)
386 {
387         struct lloop_device *lo = q->queuedata;
388
389         clear_bit(QUEUE_FLAG_PLUGGED, &q->queue_flags);
390         blk_run_address_space(lo->lo_backing_file->f_mapping);
391 }
392 #endif
393
394 static inline void loop_handle_bio(struct lloop_device *lo, struct bio *bio)
395 {
396         int ret;
397         ret = do_bio_lustrebacked(lo, bio);
398         while (bio) {
399                 struct bio *tmp = bio->bi_next;
400                 bio->bi_next = NULL;
401                 cfs_bio_endio(bio, bio->bi_size, ret);
402                 bio = tmp;
403         }
404 }
405
406 static inline int loop_active(struct lloop_device *lo)
407 {
408         return cfs_atomic_read(&lo->lo_pending) ||
409                 (lo->lo_state == LLOOP_RUNDOWN);
410 }
411
412 /*
413  * worker thread that handles reads/writes to file backed loop devices,
414  * to avoid blocking in our make_request_fn.
415  */
416 static int loop_thread(void *data)
417 {
418         struct lloop_device *lo = data;
419         struct bio *bio;
420         unsigned int count;
421         unsigned long times = 0;
422         unsigned long total_count = 0;
423
424         struct lu_env *env;
425         int refcheck;
426         int ret = 0;
427
428         daemonize("lloop%d", lo->lo_number);
429
430         set_user_nice(current, -20);
431
432         lo->lo_state = LLOOP_BOUND;
433
434         env = cl_env_get(&refcheck);
435         if (IS_ERR(env))
436                 GOTO(out, ret = PTR_ERR(env));
437
438         lo->lo_env = env;
439         memset(&lo->lo_pvec, 0, sizeof(lo->lo_pvec));
440         lo->lo_pvec.ldp_pages   = lo->lo_requests[0].lrd_pages;
441         lo->lo_pvec.ldp_offsets = lo->lo_requests[0].lrd_offsets;
442
443         /*
444          * up sem, we are running
445          */
446         cfs_up(&lo->lo_sem);
447
448         for (;;) {
449                 cfs_wait_event(lo->lo_bh_wait, loop_active(lo));
450                 if (!cfs_atomic_read(&lo->lo_pending)) {
451                         int exiting = 0;
452                         cfs_spin_lock_irq(&lo->lo_lock);
453                         exiting = (lo->lo_state == LLOOP_RUNDOWN);
454                         cfs_spin_unlock_irq(&lo->lo_lock);
455                         if (exiting)
456                                 break;
457                 }
458
459                 bio = NULL;
460                 count = loop_get_bio(lo, &bio);
461                 if (!count) {
462                         CWARN("lloop(minor: %d): missing bio\n", lo->lo_number);
463                         continue;
464                 }
465
466                 total_count += count;
467                 if (total_count < count) {     /* overflow */
468                         total_count = count;
469                         times = 1;
470                 } else {
471                         times++;
472                 }
473                 if ((times & 127) == 0) {
474                         CDEBUG(D_INFO, "total: %lu, count: %lu, avg: %lu\n",
475                                total_count, times, total_count / times);
476                 }
477
478                 LASSERT(bio != NULL);
479                 LASSERT(count <= cfs_atomic_read(&lo->lo_pending));
480                 loop_handle_bio(lo, bio);
481                 cfs_atomic_sub(count, &lo->lo_pending);
482         }
483         cl_env_put(env, &refcheck);
484
485 out:
486         cfs_up(&lo->lo_sem);
487         return ret;
488 }
489
490 static int loop_set_fd(struct lloop_device *lo, struct file *unused,
491                        struct block_device *bdev, struct file *file)
492 {
493         struct inode         *inode;
494         struct address_space *mapping;
495         int                   lo_flags = 0;
496         int                   error;
497         loff_t                size;
498
499         if (!cfs_try_module_get(THIS_MODULE))
500                 return -ENODEV;
501
502         error = -EBUSY;
503         if (lo->lo_state != LLOOP_UNBOUND)
504                 goto out;
505
506         mapping = file->f_mapping;
507         inode = mapping->host;
508
509         error = -EINVAL;
510         if (!S_ISREG(inode->i_mode) || inode->i_sb->s_magic != LL_SUPER_MAGIC)
511                 goto out;
512
513         if (!(file->f_mode & FMODE_WRITE))
514                 lo_flags |= LO_FLAGS_READ_ONLY;
515
516         size = get_loop_size(lo, file);
517
518         if ((loff_t)(sector_t)size != size) {
519                 error = -EFBIG;
520                 goto out;
521         }
522
523         /* remove all pages in cache so as dirty pages not to be existent. */
524         truncate_inode_pages(mapping, 0);
525
526         set_device_ro(bdev, (lo_flags & LO_FLAGS_READ_ONLY) != 0);
527
528         lo->lo_blocksize = CFS_PAGE_SIZE;
529         lo->lo_device = bdev;
530         lo->lo_flags = lo_flags;
531         lo->lo_backing_file = file;
532         lo->ioctl = NULL;
533         lo->lo_sizelimit = 0;
534         lo->old_gfp_mask = mapping_gfp_mask(mapping);
535         mapping_set_gfp_mask(mapping, lo->old_gfp_mask & ~(__GFP_IO|__GFP_FS));
536
537         lo->lo_bio = lo->lo_biotail = NULL;
538
539         /*
540          * set queue make_request_fn, and add limits based on lower level
541          * device
542          */
543         blk_queue_make_request(lo->lo_queue, loop_make_request);
544         lo->lo_queue->queuedata = lo;
545 #ifdef HAVE_REQUEST_QUEUE_UNPLUG_FN
546         lo->lo_queue->unplug_fn = loop_unplug;
547 #endif
548
549         /* queue parameters */
550         CLASSERT(CFS_PAGE_SIZE < (1 << (sizeof(unsigned short) * 8)));
551         blk_queue_logical_block_size(lo->lo_queue,
552                                      (unsigned short)CFS_PAGE_SIZE);
553         blk_queue_max_hw_sectors(lo->lo_queue,
554                                  LLOOP_MAX_SEGMENTS << (CFS_PAGE_SHIFT - 9));
555         blk_queue_max_segments(lo->lo_queue, LLOOP_MAX_SEGMENTS);
556
557         set_capacity(disks[lo->lo_number], size);
558         bd_set_size(bdev, size << 9);
559
560         set_blocksize(bdev, lo->lo_blocksize);
561
562         cfs_create_thread(loop_thread, lo, CLONE_KERNEL);
563         cfs_down(&lo->lo_sem);
564         return 0;
565
566  out:
567         /* This is safe: open() is still holding a reference. */
568         cfs_module_put(THIS_MODULE);
569         return error;
570 }
571
572 static int loop_clr_fd(struct lloop_device *lo, struct block_device *bdev,
573                        int count)
574 {
575         struct file *filp = lo->lo_backing_file;
576         int gfp = lo->old_gfp_mask;
577
578         if (lo->lo_state != LLOOP_BOUND)
579                 return -ENXIO;
580
581         if (lo->lo_refcnt > count)        /* we needed one fd for the ioctl */
582                 return -EBUSY;
583
584         if (filp == NULL)
585                 return -EINVAL;
586
587         cfs_spin_lock_irq(&lo->lo_lock);
588         lo->lo_state = LLOOP_RUNDOWN;
589         cfs_spin_unlock_irq(&lo->lo_lock);
590         cfs_waitq_signal(&lo->lo_bh_wait);
591
592         cfs_down(&lo->lo_sem);
593         lo->lo_backing_file = NULL;
594         lo->ioctl = NULL;
595         lo->lo_device = NULL;
596         lo->lo_offset = 0;
597         lo->lo_sizelimit = 0;
598         lo->lo_flags = 0;
599         ll_invalidate_bdev(bdev, 0);
600         set_capacity(disks[lo->lo_number], 0);
601         bd_set_size(bdev, 0);
602         mapping_set_gfp_mask(filp->f_mapping, gfp);
603         lo->lo_state = LLOOP_UNBOUND;
604         fput(filp);
605         /* This is safe: open() is still holding a reference. */
606         cfs_module_put(THIS_MODULE);
607         return 0;
608 }
609
610 #ifdef HAVE_BLKDEV_PUT_2ARGS
611 static int lo_open(struct block_device *bdev, fmode_t mode)
612 {
613         struct lloop_device *lo = bdev->bd_disk->private_data;
614 #else
615 static int lo_open(struct inode *inode, struct file *file)
616 {
617         struct lloop_device *lo = inode->i_bdev->bd_disk->private_data;
618 #endif
619
620         cfs_mutex_lock(&lo->lo_ctl_mutex);
621         lo->lo_refcnt++;
622         cfs_mutex_unlock(&lo->lo_ctl_mutex);
623
624         return 0;
625 }
626
627 #ifdef HAVE_BLKDEV_PUT_2ARGS
628 static int lo_release(struct gendisk *disk, fmode_t mode)
629 {
630         struct lloop_device *lo = disk->private_data;
631 #else
632 static int lo_release(struct inode *inode, struct file *file)
633 {
634         struct lloop_device *lo = inode->i_bdev->bd_disk->private_data;
635 #endif
636
637         cfs_mutex_lock(&lo->lo_ctl_mutex);
638         --lo->lo_refcnt;
639         cfs_mutex_unlock(&lo->lo_ctl_mutex);
640
641         return 0;
642 }
643
644 /* lloop device node's ioctl function. */
645 #ifdef HAVE_BLKDEV_PUT_2ARGS
646 static int lo_ioctl(struct block_device *bdev, fmode_t mode,
647                     unsigned int cmd, unsigned long arg)
648 {
649         struct lloop_device *lo = bdev->bd_disk->private_data;
650         struct inode *inode = NULL;
651         int err = 0;
652 #else
653 static int lo_ioctl(struct inode *inode, struct file *unused,
654                     unsigned int cmd, unsigned long arg)
655 {
656         struct lloop_device *lo = inode->i_bdev->bd_disk->private_data;
657         struct block_device *bdev = inode->i_bdev;
658         int err = 0;
659 #endif
660
661         cfs_mutex_lock(&lloop_mutex);
662         switch (cmd) {
663         case LL_IOC_LLOOP_DETACH: {
664                 err = loop_clr_fd(lo, bdev, 2);
665                 if (err == 0)
666                         ll_blkdev_put(bdev, 0); /* grabbed in LLOOP_ATTACH */
667                 break;
668         }
669
670         case LL_IOC_LLOOP_INFO: {
671                 struct lu_fid fid;
672
673                 LASSERT(lo->lo_backing_file != NULL);
674                 if (inode == NULL)
675                         inode = lo->lo_backing_file->f_dentry->d_inode;
676                 if (lo->lo_state == LLOOP_BOUND)
677                         fid = ll_i2info(inode)->lli_fid;
678                 else
679                         fid_zero(&fid);
680
681                 if (copy_to_user((struct lu_fid *)arg, &fid, sizeof(fid)))
682                         err = -EFAULT;
683                 break;
684         }
685
686         default:
687                 err = -EINVAL;
688                 break;
689         }
690         cfs_mutex_unlock(&lloop_mutex);
691
692         return err;
693 }
694
695 static struct block_device_operations lo_fops = {
696         .owner =        THIS_MODULE,
697         .open =         lo_open,
698         .release =      lo_release,
699         .ioctl =        lo_ioctl,
700 };
701
702 /* dynamic iocontrol callback.
703  * This callback is registered in lloop_init and will be called by
704  * ll_iocontrol_call.
705  *
706  * This is a llite regular file ioctl function. It takes the responsibility
707  * of attaching or detaching a file by a lloop's device numner.
708  */
709 static enum llioc_iter lloop_ioctl(struct inode *unused, struct file *file,
710                                    unsigned int cmd, unsigned long arg,
711                                    void *magic, int *rcp)
712 {
713         struct lloop_device *lo = NULL;
714         struct block_device *bdev = NULL;
715         int err = 0;
716         dev_t dev;
717
718         if (magic != ll_iocontrol_magic)
719                 return LLIOC_CONT;
720
721         if (disks == NULL)
722                 GOTO(out1, err = -ENODEV);
723
724         CWARN("Enter llop_ioctl\n");
725
726         cfs_mutex_lock(&lloop_mutex);
727         switch (cmd) {
728         case LL_IOC_LLOOP_ATTACH: {
729                 struct lloop_device *lo_free = NULL;
730                 int i;
731
732                 for (i = 0; i < max_loop; i++, lo = NULL) {
733                         lo = &loop_dev[i];
734                         if (lo->lo_state == LLOOP_UNBOUND) {
735                                 if (!lo_free)
736                                         lo_free = lo;
737                                 continue;
738                         }
739                         if (lo->lo_backing_file->f_dentry->d_inode ==
740                             file->f_dentry->d_inode)
741                                 break;
742                 }
743                 if (lo || !lo_free)
744                         GOTO(out, err = -EBUSY);
745
746                 lo = lo_free;
747                 dev = MKDEV(lloop_major, lo->lo_number);
748
749                 /* quit if the used pointer is writable */
750                 if (put_user((long)old_encode_dev(dev), (long*)arg))
751                         GOTO(out, err = -EFAULT);
752
753                 bdev = blkdev_get_by_dev(dev, file->f_mode, NULL);
754                 if (IS_ERR(bdev))
755                         GOTO(out, err = PTR_ERR(bdev));
756
757                 get_file(file);
758                 err = loop_set_fd(lo, NULL, bdev, file);
759                 if (err) {
760                         fput(file);
761                         ll_blkdev_put(bdev, 0);
762                 }
763
764                 break;
765         }
766
767         case LL_IOC_LLOOP_DETACH_BYDEV: {
768                 int minor;
769
770                 dev = old_decode_dev(arg);
771                 if (MAJOR(dev) != lloop_major)
772                         GOTO(out, err = -EINVAL);
773
774                 minor = MINOR(dev);
775                 if (minor > max_loop - 1)
776                         GOTO(out, err = -EINVAL);
777
778                 lo = &loop_dev[minor];
779                 if (lo->lo_state != LLOOP_BOUND)
780                         GOTO(out, err = -EINVAL);
781
782                 bdev = lo->lo_device;
783                 err = loop_clr_fd(lo, bdev, 1);
784                 if (err == 0)
785                         ll_blkdev_put(bdev, 0); /* grabbed in LLOOP_ATTACH */
786
787                 break;
788         }
789
790         default:
791                 err = -EINVAL;
792                 break;
793         }
794
795 out:
796         cfs_mutex_unlock(&lloop_mutex);
797 out1:
798         if (rcp)
799                 *rcp = err;
800         return LLIOC_STOP;
801 }
802
803 static int __init lloop_init(void)
804 {
805         int        i;
806         unsigned int cmdlist[] = {
807                 LL_IOC_LLOOP_ATTACH,
808                 LL_IOC_LLOOP_DETACH_BYDEV,
809         };
810
811         if (max_loop < 1 || max_loop > 256) {
812                 max_loop = MAX_LOOP_DEFAULT;
813                 CWARN("lloop: invalid max_loop (must be between"
814                       " 1 and 256), using default (%u)\n", max_loop);
815         }
816
817         lloop_major = register_blkdev(0, "lloop");
818         if (lloop_major < 0)
819                 return -EIO;
820
821         CDEBUG(D_CONFIG, "registered lloop major %d with %u minors\n",
822                lloop_major, max_loop);
823
824         ll_iocontrol_magic = ll_iocontrol_register(lloop_ioctl, 2, cmdlist);
825         if (ll_iocontrol_magic == NULL)
826                 goto out_mem1;
827
828         OBD_ALLOC_WAIT(loop_dev, max_loop * sizeof(*loop_dev));
829         if (!loop_dev)
830                 goto out_mem1;
831
832         OBD_ALLOC_WAIT(disks, max_loop * sizeof(*disks));
833         if (!disks)
834                 goto out_mem2;
835
836         for (i = 0; i < max_loop; i++) {
837                 disks[i] = alloc_disk(1);
838                 if (!disks[i])
839                         goto out_mem3;
840         }
841
842         cfs_mutex_init(&lloop_mutex);
843
844         for (i = 0; i < max_loop; i++) {
845                 struct lloop_device *lo = &loop_dev[i];
846                 struct gendisk *disk = disks[i];
847
848                 lo->lo_queue = blk_alloc_queue(GFP_KERNEL);
849                 if (!lo->lo_queue)
850                         goto out_mem4;
851
852                 cfs_mutex_init(&lo->lo_ctl_mutex);
853                 cfs_sema_init(&lo->lo_sem, 0);
854                 cfs_waitq_init(&lo->lo_bh_wait);
855                 lo->lo_number = i;
856                 cfs_spin_lock_init(&lo->lo_lock);
857                 disk->major = lloop_major;
858                 disk->first_minor = i;
859                 disk->fops = &lo_fops;
860                 sprintf(disk->disk_name, "lloop%d", i);
861                 disk->private_data = lo;
862                 disk->queue = lo->lo_queue;
863         }
864
865         /* We cannot fail after we call this, so another loop!*/
866         for (i = 0; i < max_loop; i++)
867                 add_disk(disks[i]);
868         return 0;
869
870 out_mem4:
871         while (i--)
872                 blk_cleanup_queue(loop_dev[i].lo_queue);
873         i = max_loop;
874 out_mem3:
875         while (i--)
876                 put_disk(disks[i]);
877         OBD_FREE(disks, max_loop * sizeof(*disks));
878 out_mem2:
879         OBD_FREE(loop_dev, max_loop * sizeof(*loop_dev));
880 out_mem1:
881         unregister_blkdev(lloop_major, "lloop");
882         ll_iocontrol_unregister(ll_iocontrol_magic);
883         CERROR("lloop: ran out of memory\n");
884         return -ENOMEM;
885 }
886
887 static void lloop_exit(void)
888 {
889         int i;
890
891         ll_iocontrol_unregister(ll_iocontrol_magic);
892         for (i = 0; i < max_loop; i++) {
893                 del_gendisk(disks[i]);
894                 blk_cleanup_queue(loop_dev[i].lo_queue);
895                 put_disk(disks[i]);
896         }
897         if (ll_unregister_blkdev(lloop_major, "lloop"))
898                 CWARN("lloop: cannot unregister blkdev\n");
899         else
900                 CDEBUG(D_CONFIG, "unregistered lloop major %d\n", lloop_major);
901
902         OBD_FREE(disks, max_loop * sizeof(*disks));
903         OBD_FREE(loop_dev, max_loop * sizeof(*loop_dev));
904 }
905
906 module_init(lloop_init);
907 module_exit(lloop_exit);
908
909 CFS_MODULE_PARM(max_loop, "i", int, 0444, "maximum of lloop_device");
910 MODULE_AUTHOR("Sun Microsystems, Inc. <http://www.lustre.org/>");
911 MODULE_DESCRIPTION("Lustre virtual block device");
912 MODULE_LICENSE("GPL");