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