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