xfs: kill xfs_bawrite
[safe/jmp/linux-2.6] / fs / xfs / linux-2.6 / xfs_buf.c
1 /*
2  * Copyright (c) 2000-2006 Silicon Graphics, Inc.
3  * All Rights Reserved.
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License as
7  * published by the Free Software Foundation.
8  *
9  * This program is distributed in the hope that it would be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write the Free Software Foundation,
16  * Inc.,  51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
17  */
18 #include "xfs.h"
19 #include <linux/stddef.h>
20 #include <linux/errno.h>
21 #include <linux/slab.h>
22 #include <linux/pagemap.h>
23 #include <linux/init.h>
24 #include <linux/vmalloc.h>
25 #include <linux/bio.h>
26 #include <linux/sysctl.h>
27 #include <linux/proc_fs.h>
28 #include <linux/workqueue.h>
29 #include <linux/percpu.h>
30 #include <linux/blkdev.h>
31 #include <linux/hash.h>
32 #include <linux/kthread.h>
33 #include <linux/migrate.h>
34 #include <linux/backing-dev.h>
35 #include <linux/freezer.h>
36 #include <linux/list_sort.h>
37
38 #include "xfs_sb.h"
39 #include "xfs_inum.h"
40 #include "xfs_ag.h"
41 #include "xfs_dmapi.h"
42 #include "xfs_mount.h"
43 #include "xfs_trace.h"
44
45 static kmem_zone_t *xfs_buf_zone;
46 STATIC int xfsbufd(void *);
47 STATIC int xfsbufd_wakeup(int, gfp_t);
48 STATIC void xfs_buf_delwri_queue(xfs_buf_t *, int);
49 static struct shrinker xfs_buf_shake = {
50         .shrink = xfsbufd_wakeup,
51         .seeks = DEFAULT_SEEKS,
52 };
53
54 static struct workqueue_struct *xfslogd_workqueue;
55 struct workqueue_struct *xfsdatad_workqueue;
56 struct workqueue_struct *xfsconvertd_workqueue;
57
58 #ifdef XFS_BUF_LOCK_TRACKING
59 # define XB_SET_OWNER(bp)       ((bp)->b_last_holder = current->pid)
60 # define XB_CLEAR_OWNER(bp)     ((bp)->b_last_holder = -1)
61 # define XB_GET_OWNER(bp)       ((bp)->b_last_holder)
62 #else
63 # define XB_SET_OWNER(bp)       do { } while (0)
64 # define XB_CLEAR_OWNER(bp)     do { } while (0)
65 # define XB_GET_OWNER(bp)       do { } while (0)
66 #endif
67
68 #define xb_to_gfp(flags) \
69         ((((flags) & XBF_READ_AHEAD) ? __GFP_NORETRY : \
70           ((flags) & XBF_DONT_BLOCK) ? GFP_NOFS : GFP_KERNEL) | __GFP_NOWARN)
71
72 #define xb_to_km(flags) \
73          (((flags) & XBF_DONT_BLOCK) ? KM_NOFS : KM_SLEEP)
74
75 #define xfs_buf_allocate(flags) \
76         kmem_zone_alloc(xfs_buf_zone, xb_to_km(flags))
77 #define xfs_buf_deallocate(bp) \
78         kmem_zone_free(xfs_buf_zone, (bp));
79
80 /*
81  *      Page Region interfaces.
82  *
83  *      For pages in filesystems where the blocksize is smaller than the
84  *      pagesize, we use the page->private field (long) to hold a bitmap
85  *      of uptodate regions within the page.
86  *
87  *      Each such region is "bytes per page / bits per long" bytes long.
88  *
89  *      NBPPR == number-of-bytes-per-page-region
90  *      BTOPR == bytes-to-page-region (rounded up)
91  *      BTOPRT == bytes-to-page-region-truncated (rounded down)
92  */
93 #if (BITS_PER_LONG == 32)
94 #define PRSHIFT         (PAGE_CACHE_SHIFT - 5)  /* (32 == 1<<5) */
95 #elif (BITS_PER_LONG == 64)
96 #define PRSHIFT         (PAGE_CACHE_SHIFT - 6)  /* (64 == 1<<6) */
97 #else
98 #error BITS_PER_LONG must be 32 or 64
99 #endif
100 #define NBPPR           (PAGE_CACHE_SIZE/BITS_PER_LONG)
101 #define BTOPR(b)        (((unsigned int)(b) + (NBPPR - 1)) >> PRSHIFT)
102 #define BTOPRT(b)       (((unsigned int)(b) >> PRSHIFT))
103
104 STATIC unsigned long
105 page_region_mask(
106         size_t          offset,
107         size_t          length)
108 {
109         unsigned long   mask;
110         int             first, final;
111
112         first = BTOPR(offset);
113         final = BTOPRT(offset + length - 1);
114         first = min(first, final);
115
116         mask = ~0UL;
117         mask <<= BITS_PER_LONG - (final - first);
118         mask >>= BITS_PER_LONG - (final);
119
120         ASSERT(offset + length <= PAGE_CACHE_SIZE);
121         ASSERT((final - first) < BITS_PER_LONG && (final - first) >= 0);
122
123         return mask;
124 }
125
126 STATIC void
127 set_page_region(
128         struct page     *page,
129         size_t          offset,
130         size_t          length)
131 {
132         set_page_private(page,
133                 page_private(page) | page_region_mask(offset, length));
134         if (page_private(page) == ~0UL)
135                 SetPageUptodate(page);
136 }
137
138 STATIC int
139 test_page_region(
140         struct page     *page,
141         size_t          offset,
142         size_t          length)
143 {
144         unsigned long   mask = page_region_mask(offset, length);
145
146         return (mask && (page_private(page) & mask) == mask);
147 }
148
149 /*
150  *      Mapping of multi-page buffers into contiguous virtual space
151  */
152
153 typedef struct a_list {
154         void            *vm_addr;
155         struct a_list   *next;
156 } a_list_t;
157
158 static a_list_t         *as_free_head;
159 static int              as_list_len;
160 static DEFINE_SPINLOCK(as_lock);
161
162 /*
163  *      Try to batch vunmaps because they are costly.
164  */
165 STATIC void
166 free_address(
167         void            *addr)
168 {
169         a_list_t        *aentry;
170
171 #ifdef CONFIG_XEN
172         /*
173          * Xen needs to be able to make sure it can get an exclusive
174          * RO mapping of pages it wants to turn into a pagetable.  If
175          * a newly allocated page is also still being vmap()ed by xfs,
176          * it will cause pagetable construction to fail.  This is a
177          * quick workaround to always eagerly unmap pages so that Xen
178          * is happy.
179          */
180         vunmap(addr);
181         return;
182 #endif
183
184         aentry = kmalloc(sizeof(a_list_t), GFP_NOWAIT);
185         if (likely(aentry)) {
186                 spin_lock(&as_lock);
187                 aentry->next = as_free_head;
188                 aentry->vm_addr = addr;
189                 as_free_head = aentry;
190                 as_list_len++;
191                 spin_unlock(&as_lock);
192         } else {
193                 vunmap(addr);
194         }
195 }
196
197 STATIC void
198 purge_addresses(void)
199 {
200         a_list_t        *aentry, *old;
201
202         if (as_free_head == NULL)
203                 return;
204
205         spin_lock(&as_lock);
206         aentry = as_free_head;
207         as_free_head = NULL;
208         as_list_len = 0;
209         spin_unlock(&as_lock);
210
211         while ((old = aentry) != NULL) {
212                 vunmap(aentry->vm_addr);
213                 aentry = aentry->next;
214                 kfree(old);
215         }
216 }
217
218 /*
219  *      Internal xfs_buf_t object manipulation
220  */
221
222 STATIC void
223 _xfs_buf_initialize(
224         xfs_buf_t               *bp,
225         xfs_buftarg_t           *target,
226         xfs_off_t               range_base,
227         size_t                  range_length,
228         xfs_buf_flags_t         flags)
229 {
230         /*
231          * We don't want certain flags to appear in b_flags.
232          */
233         flags &= ~(XBF_LOCK|XBF_MAPPED|XBF_DONT_BLOCK|XBF_READ_AHEAD);
234
235         memset(bp, 0, sizeof(xfs_buf_t));
236         atomic_set(&bp->b_hold, 1);
237         init_completion(&bp->b_iowait);
238         INIT_LIST_HEAD(&bp->b_list);
239         INIT_LIST_HEAD(&bp->b_hash_list);
240         init_MUTEX_LOCKED(&bp->b_sema); /* held, no waiters */
241         XB_SET_OWNER(bp);
242         bp->b_target = target;
243         bp->b_file_offset = range_base;
244         /*
245          * Set buffer_length and count_desired to the same value initially.
246          * I/O routines should use count_desired, which will be the same in
247          * most cases but may be reset (e.g. XFS recovery).
248          */
249         bp->b_buffer_length = bp->b_count_desired = range_length;
250         bp->b_flags = flags;
251         bp->b_bn = XFS_BUF_DADDR_NULL;
252         atomic_set(&bp->b_pin_count, 0);
253         init_waitqueue_head(&bp->b_waiters);
254
255         XFS_STATS_INC(xb_create);
256
257         trace_xfs_buf_init(bp, _RET_IP_);
258 }
259
260 /*
261  *      Allocate a page array capable of holding a specified number
262  *      of pages, and point the page buf at it.
263  */
264 STATIC int
265 _xfs_buf_get_pages(
266         xfs_buf_t               *bp,
267         int                     page_count,
268         xfs_buf_flags_t         flags)
269 {
270         /* Make sure that we have a page list */
271         if (bp->b_pages == NULL) {
272                 bp->b_offset = xfs_buf_poff(bp->b_file_offset);
273                 bp->b_page_count = page_count;
274                 if (page_count <= XB_PAGES) {
275                         bp->b_pages = bp->b_page_array;
276                 } else {
277                         bp->b_pages = kmem_alloc(sizeof(struct page *) *
278                                         page_count, xb_to_km(flags));
279                         if (bp->b_pages == NULL)
280                                 return -ENOMEM;
281                 }
282                 memset(bp->b_pages, 0, sizeof(struct page *) * page_count);
283         }
284         return 0;
285 }
286
287 /*
288  *      Frees b_pages if it was allocated.
289  */
290 STATIC void
291 _xfs_buf_free_pages(
292         xfs_buf_t       *bp)
293 {
294         if (bp->b_pages != bp->b_page_array) {
295                 kmem_free(bp->b_pages);
296                 bp->b_pages = NULL;
297         }
298 }
299
300 /*
301  *      Releases the specified buffer.
302  *
303  *      The modification state of any associated pages is left unchanged.
304  *      The buffer most not be on any hash - use xfs_buf_rele instead for
305  *      hashed and refcounted buffers
306  */
307 void
308 xfs_buf_free(
309         xfs_buf_t               *bp)
310 {
311         trace_xfs_buf_free(bp, _RET_IP_);
312
313         ASSERT(list_empty(&bp->b_hash_list));
314
315         if (bp->b_flags & (_XBF_PAGE_CACHE|_XBF_PAGES)) {
316                 uint            i;
317
318                 if ((bp->b_flags & XBF_MAPPED) && (bp->b_page_count > 1))
319                         free_address(bp->b_addr - bp->b_offset);
320
321                 for (i = 0; i < bp->b_page_count; i++) {
322                         struct page     *page = bp->b_pages[i];
323
324                         if (bp->b_flags & _XBF_PAGE_CACHE)
325                                 ASSERT(!PagePrivate(page));
326                         page_cache_release(page);
327                 }
328         }
329         _xfs_buf_free_pages(bp);
330         xfs_buf_deallocate(bp);
331 }
332
333 /*
334  *      Finds all pages for buffer in question and builds it's page list.
335  */
336 STATIC int
337 _xfs_buf_lookup_pages(
338         xfs_buf_t               *bp,
339         uint                    flags)
340 {
341         struct address_space    *mapping = bp->b_target->bt_mapping;
342         size_t                  blocksize = bp->b_target->bt_bsize;
343         size_t                  size = bp->b_count_desired;
344         size_t                  nbytes, offset;
345         gfp_t                   gfp_mask = xb_to_gfp(flags);
346         unsigned short          page_count, i;
347         pgoff_t                 first;
348         xfs_off_t               end;
349         int                     error;
350
351         end = bp->b_file_offset + bp->b_buffer_length;
352         page_count = xfs_buf_btoc(end) - xfs_buf_btoct(bp->b_file_offset);
353
354         error = _xfs_buf_get_pages(bp, page_count, flags);
355         if (unlikely(error))
356                 return error;
357         bp->b_flags |= _XBF_PAGE_CACHE;
358
359         offset = bp->b_offset;
360         first = bp->b_file_offset >> PAGE_CACHE_SHIFT;
361
362         for (i = 0; i < bp->b_page_count; i++) {
363                 struct page     *page;
364                 uint            retries = 0;
365
366               retry:
367                 page = find_or_create_page(mapping, first + i, gfp_mask);
368                 if (unlikely(page == NULL)) {
369                         if (flags & XBF_READ_AHEAD) {
370                                 bp->b_page_count = i;
371                                 for (i = 0; i < bp->b_page_count; i++)
372                                         unlock_page(bp->b_pages[i]);
373                                 return -ENOMEM;
374                         }
375
376                         /*
377                          * This could deadlock.
378                          *
379                          * But until all the XFS lowlevel code is revamped to
380                          * handle buffer allocation failures we can't do much.
381                          */
382                         if (!(++retries % 100))
383                                 printk(KERN_ERR
384                                         "XFS: possible memory allocation "
385                                         "deadlock in %s (mode:0x%x)\n",
386                                         __func__, gfp_mask);
387
388                         XFS_STATS_INC(xb_page_retries);
389                         xfsbufd_wakeup(0, gfp_mask);
390                         congestion_wait(BLK_RW_ASYNC, HZ/50);
391                         goto retry;
392                 }
393
394                 XFS_STATS_INC(xb_page_found);
395
396                 nbytes = min_t(size_t, size, PAGE_CACHE_SIZE - offset);
397                 size -= nbytes;
398
399                 ASSERT(!PagePrivate(page));
400                 if (!PageUptodate(page)) {
401                         page_count--;
402                         if (blocksize >= PAGE_CACHE_SIZE) {
403                                 if (flags & XBF_READ)
404                                         bp->b_flags |= _XBF_PAGE_LOCKED;
405                         } else if (!PagePrivate(page)) {
406                                 if (test_page_region(page, offset, nbytes))
407                                         page_count++;
408                         }
409                 }
410
411                 bp->b_pages[i] = page;
412                 offset = 0;
413         }
414
415         if (!(bp->b_flags & _XBF_PAGE_LOCKED)) {
416                 for (i = 0; i < bp->b_page_count; i++)
417                         unlock_page(bp->b_pages[i]);
418         }
419
420         if (page_count == bp->b_page_count)
421                 bp->b_flags |= XBF_DONE;
422
423         return error;
424 }
425
426 /*
427  *      Map buffer into kernel address-space if nessecary.
428  */
429 STATIC int
430 _xfs_buf_map_pages(
431         xfs_buf_t               *bp,
432         uint                    flags)
433 {
434         /* A single page buffer is always mappable */
435         if (bp->b_page_count == 1) {
436                 bp->b_addr = page_address(bp->b_pages[0]) + bp->b_offset;
437                 bp->b_flags |= XBF_MAPPED;
438         } else if (flags & XBF_MAPPED) {
439                 if (as_list_len > 64)
440                         purge_addresses();
441                 bp->b_addr = vmap(bp->b_pages, bp->b_page_count,
442                                         VM_MAP, PAGE_KERNEL);
443                 if (unlikely(bp->b_addr == NULL))
444                         return -ENOMEM;
445                 bp->b_addr += bp->b_offset;
446                 bp->b_flags |= XBF_MAPPED;
447         }
448
449         return 0;
450 }
451
452 /*
453  *      Finding and Reading Buffers
454  */
455
456 /*
457  *      Look up, and creates if absent, a lockable buffer for
458  *      a given range of an inode.  The buffer is returned
459  *      locked.  If other overlapping buffers exist, they are
460  *      released before the new buffer is created and locked,
461  *      which may imply that this call will block until those buffers
462  *      are unlocked.  No I/O is implied by this call.
463  */
464 xfs_buf_t *
465 _xfs_buf_find(
466         xfs_buftarg_t           *btp,   /* block device target          */
467         xfs_off_t               ioff,   /* starting offset of range     */
468         size_t                  isize,  /* length of range              */
469         xfs_buf_flags_t         flags,
470         xfs_buf_t               *new_bp)
471 {
472         xfs_off_t               range_base;
473         size_t                  range_length;
474         xfs_bufhash_t           *hash;
475         xfs_buf_t               *bp, *n;
476
477         range_base = (ioff << BBSHIFT);
478         range_length = (isize << BBSHIFT);
479
480         /* Check for IOs smaller than the sector size / not sector aligned */
481         ASSERT(!(range_length < (1 << btp->bt_sshift)));
482         ASSERT(!(range_base & (xfs_off_t)btp->bt_smask));
483
484         hash = &btp->bt_hash[hash_long((unsigned long)ioff, btp->bt_hashshift)];
485
486         spin_lock(&hash->bh_lock);
487
488         list_for_each_entry_safe(bp, n, &hash->bh_list, b_hash_list) {
489                 ASSERT(btp == bp->b_target);
490                 if (bp->b_file_offset == range_base &&
491                     bp->b_buffer_length == range_length) {
492                         /*
493                          * If we look at something, bring it to the
494                          * front of the list for next time.
495                          */
496                         atomic_inc(&bp->b_hold);
497                         list_move(&bp->b_hash_list, &hash->bh_list);
498                         goto found;
499                 }
500         }
501
502         /* No match found */
503         if (new_bp) {
504                 _xfs_buf_initialize(new_bp, btp, range_base,
505                                 range_length, flags);
506                 new_bp->b_hash = hash;
507                 list_add(&new_bp->b_hash_list, &hash->bh_list);
508         } else {
509                 XFS_STATS_INC(xb_miss_locked);
510         }
511
512         spin_unlock(&hash->bh_lock);
513         return new_bp;
514
515 found:
516         spin_unlock(&hash->bh_lock);
517
518         /* Attempt to get the semaphore without sleeping,
519          * if this does not work then we need to drop the
520          * spinlock and do a hard attempt on the semaphore.
521          */
522         if (down_trylock(&bp->b_sema)) {
523                 if (!(flags & XBF_TRYLOCK)) {
524                         /* wait for buffer ownership */
525                         xfs_buf_lock(bp);
526                         XFS_STATS_INC(xb_get_locked_waited);
527                 } else {
528                         /* We asked for a trylock and failed, no need
529                          * to look at file offset and length here, we
530                          * know that this buffer at least overlaps our
531                          * buffer and is locked, therefore our buffer
532                          * either does not exist, or is this buffer.
533                          */
534                         xfs_buf_rele(bp);
535                         XFS_STATS_INC(xb_busy_locked);
536                         return NULL;
537                 }
538         } else {
539                 /* trylock worked */
540                 XB_SET_OWNER(bp);
541         }
542
543         if (bp->b_flags & XBF_STALE) {
544                 ASSERT((bp->b_flags & _XBF_DELWRI_Q) == 0);
545                 bp->b_flags &= XBF_MAPPED;
546         }
547
548         trace_xfs_buf_find(bp, flags, _RET_IP_);
549         XFS_STATS_INC(xb_get_locked);
550         return bp;
551 }
552
553 /*
554  *      Assembles a buffer covering the specified range.
555  *      Storage in memory for all portions of the buffer will be allocated,
556  *      although backing storage may not be.
557  */
558 xfs_buf_t *
559 xfs_buf_get(
560         xfs_buftarg_t           *target,/* target for buffer            */
561         xfs_off_t               ioff,   /* starting offset of range     */
562         size_t                  isize,  /* length of range              */
563         xfs_buf_flags_t         flags)
564 {
565         xfs_buf_t               *bp, *new_bp;
566         int                     error = 0, i;
567
568         new_bp = xfs_buf_allocate(flags);
569         if (unlikely(!new_bp))
570                 return NULL;
571
572         bp = _xfs_buf_find(target, ioff, isize, flags, new_bp);
573         if (bp == new_bp) {
574                 error = _xfs_buf_lookup_pages(bp, flags);
575                 if (error)
576                         goto no_buffer;
577         } else {
578                 xfs_buf_deallocate(new_bp);
579                 if (unlikely(bp == NULL))
580                         return NULL;
581         }
582
583         for (i = 0; i < bp->b_page_count; i++)
584                 mark_page_accessed(bp->b_pages[i]);
585
586         if (!(bp->b_flags & XBF_MAPPED)) {
587                 error = _xfs_buf_map_pages(bp, flags);
588                 if (unlikely(error)) {
589                         printk(KERN_WARNING "%s: failed to map pages\n",
590                                         __func__);
591                         goto no_buffer;
592                 }
593         }
594
595         XFS_STATS_INC(xb_get);
596
597         /*
598          * Always fill in the block number now, the mapped cases can do
599          * their own overlay of this later.
600          */
601         bp->b_bn = ioff;
602         bp->b_count_desired = bp->b_buffer_length;
603
604         trace_xfs_buf_get(bp, flags, _RET_IP_);
605         return bp;
606
607  no_buffer:
608         if (flags & (XBF_LOCK | XBF_TRYLOCK))
609                 xfs_buf_unlock(bp);
610         xfs_buf_rele(bp);
611         return NULL;
612 }
613
614 STATIC int
615 _xfs_buf_read(
616         xfs_buf_t               *bp,
617         xfs_buf_flags_t         flags)
618 {
619         int                     status;
620
621         ASSERT(!(flags & (XBF_DELWRI|XBF_WRITE)));
622         ASSERT(bp->b_bn != XFS_BUF_DADDR_NULL);
623
624         bp->b_flags &= ~(XBF_WRITE | XBF_ASYNC | XBF_DELWRI | \
625                         XBF_READ_AHEAD | _XBF_RUN_QUEUES);
626         bp->b_flags |= flags & (XBF_READ | XBF_ASYNC | \
627                         XBF_READ_AHEAD | _XBF_RUN_QUEUES);
628
629         status = xfs_buf_iorequest(bp);
630         if (!status && !(flags & XBF_ASYNC))
631                 status = xfs_buf_iowait(bp);
632         return status;
633 }
634
635 xfs_buf_t *
636 xfs_buf_read(
637         xfs_buftarg_t           *target,
638         xfs_off_t               ioff,
639         size_t                  isize,
640         xfs_buf_flags_t         flags)
641 {
642         xfs_buf_t               *bp;
643
644         flags |= XBF_READ;
645
646         bp = xfs_buf_get(target, ioff, isize, flags);
647         if (bp) {
648                 trace_xfs_buf_read(bp, flags, _RET_IP_);
649
650                 if (!XFS_BUF_ISDONE(bp)) {
651                         XFS_STATS_INC(xb_get_read);
652                         _xfs_buf_read(bp, flags);
653                 } else if (flags & XBF_ASYNC) {
654                         /*
655                          * Read ahead call which is already satisfied,
656                          * drop the buffer
657                          */
658                         goto no_buffer;
659                 } else {
660                         /* We do not want read in the flags */
661                         bp->b_flags &= ~XBF_READ;
662                 }
663         }
664
665         return bp;
666
667  no_buffer:
668         if (flags & (XBF_LOCK | XBF_TRYLOCK))
669                 xfs_buf_unlock(bp);
670         xfs_buf_rele(bp);
671         return NULL;
672 }
673
674 /*
675  *      If we are not low on memory then do the readahead in a deadlock
676  *      safe manner.
677  */
678 void
679 xfs_buf_readahead(
680         xfs_buftarg_t           *target,
681         xfs_off_t               ioff,
682         size_t                  isize,
683         xfs_buf_flags_t         flags)
684 {
685         struct backing_dev_info *bdi;
686
687         bdi = target->bt_mapping->backing_dev_info;
688         if (bdi_read_congested(bdi))
689                 return;
690
691         flags |= (XBF_TRYLOCK|XBF_ASYNC|XBF_READ_AHEAD);
692         xfs_buf_read(target, ioff, isize, flags);
693 }
694
695 xfs_buf_t *
696 xfs_buf_get_empty(
697         size_t                  len,
698         xfs_buftarg_t           *target)
699 {
700         xfs_buf_t               *bp;
701
702         bp = xfs_buf_allocate(0);
703         if (bp)
704                 _xfs_buf_initialize(bp, target, 0, len, 0);
705         return bp;
706 }
707
708 static inline struct page *
709 mem_to_page(
710         void                    *addr)
711 {
712         if ((!is_vmalloc_addr(addr))) {
713                 return virt_to_page(addr);
714         } else {
715                 return vmalloc_to_page(addr);
716         }
717 }
718
719 int
720 xfs_buf_associate_memory(
721         xfs_buf_t               *bp,
722         void                    *mem,
723         size_t                  len)
724 {
725         int                     rval;
726         int                     i = 0;
727         unsigned long           pageaddr;
728         unsigned long           offset;
729         size_t                  buflen;
730         int                     page_count;
731
732         pageaddr = (unsigned long)mem & PAGE_CACHE_MASK;
733         offset = (unsigned long)mem - pageaddr;
734         buflen = PAGE_CACHE_ALIGN(len + offset);
735         page_count = buflen >> PAGE_CACHE_SHIFT;
736
737         /* Free any previous set of page pointers */
738         if (bp->b_pages)
739                 _xfs_buf_free_pages(bp);
740
741         bp->b_pages = NULL;
742         bp->b_addr = mem;
743
744         rval = _xfs_buf_get_pages(bp, page_count, XBF_DONT_BLOCK);
745         if (rval)
746                 return rval;
747
748         bp->b_offset = offset;
749
750         for (i = 0; i < bp->b_page_count; i++) {
751                 bp->b_pages[i] = mem_to_page((void *)pageaddr);
752                 pageaddr += PAGE_CACHE_SIZE;
753         }
754
755         bp->b_count_desired = len;
756         bp->b_buffer_length = buflen;
757         bp->b_flags |= XBF_MAPPED;
758         bp->b_flags &= ~_XBF_PAGE_LOCKED;
759
760         return 0;
761 }
762
763 xfs_buf_t *
764 xfs_buf_get_noaddr(
765         size_t                  len,
766         xfs_buftarg_t           *target)
767 {
768         unsigned long           page_count = PAGE_ALIGN(len) >> PAGE_SHIFT;
769         int                     error, i;
770         xfs_buf_t               *bp;
771
772         bp = xfs_buf_allocate(0);
773         if (unlikely(bp == NULL))
774                 goto fail;
775         _xfs_buf_initialize(bp, target, 0, len, 0);
776
777         error = _xfs_buf_get_pages(bp, page_count, 0);
778         if (error)
779                 goto fail_free_buf;
780
781         for (i = 0; i < page_count; i++) {
782                 bp->b_pages[i] = alloc_page(GFP_KERNEL);
783                 if (!bp->b_pages[i])
784                         goto fail_free_mem;
785         }
786         bp->b_flags |= _XBF_PAGES;
787
788         error = _xfs_buf_map_pages(bp, XBF_MAPPED);
789         if (unlikely(error)) {
790                 printk(KERN_WARNING "%s: failed to map pages\n",
791                                 __func__);
792                 goto fail_free_mem;
793         }
794
795         xfs_buf_unlock(bp);
796
797         trace_xfs_buf_get_noaddr(bp, _RET_IP_);
798         return bp;
799
800  fail_free_mem:
801         while (--i >= 0)
802                 __free_page(bp->b_pages[i]);
803         _xfs_buf_free_pages(bp);
804  fail_free_buf:
805         xfs_buf_deallocate(bp);
806  fail:
807         return NULL;
808 }
809
810 /*
811  *      Increment reference count on buffer, to hold the buffer concurrently
812  *      with another thread which may release (free) the buffer asynchronously.
813  *      Must hold the buffer already to call this function.
814  */
815 void
816 xfs_buf_hold(
817         xfs_buf_t               *bp)
818 {
819         trace_xfs_buf_hold(bp, _RET_IP_);
820         atomic_inc(&bp->b_hold);
821 }
822
823 /*
824  *      Releases a hold on the specified buffer.  If the
825  *      the hold count is 1, calls xfs_buf_free.
826  */
827 void
828 xfs_buf_rele(
829         xfs_buf_t               *bp)
830 {
831         xfs_bufhash_t           *hash = bp->b_hash;
832
833         trace_xfs_buf_rele(bp, _RET_IP_);
834
835         if (unlikely(!hash)) {
836                 ASSERT(!bp->b_relse);
837                 if (atomic_dec_and_test(&bp->b_hold))
838                         xfs_buf_free(bp);
839                 return;
840         }
841
842         ASSERT(atomic_read(&bp->b_hold) > 0);
843         if (atomic_dec_and_lock(&bp->b_hold, &hash->bh_lock)) {
844                 if (bp->b_relse) {
845                         atomic_inc(&bp->b_hold);
846                         spin_unlock(&hash->bh_lock);
847                         (*(bp->b_relse)) (bp);
848                 } else if (bp->b_flags & XBF_FS_MANAGED) {
849                         spin_unlock(&hash->bh_lock);
850                 } else {
851                         ASSERT(!(bp->b_flags & (XBF_DELWRI|_XBF_DELWRI_Q)));
852                         list_del_init(&bp->b_hash_list);
853                         spin_unlock(&hash->bh_lock);
854                         xfs_buf_free(bp);
855                 }
856         }
857 }
858
859
860 /*
861  *      Mutual exclusion on buffers.  Locking model:
862  *
863  *      Buffers associated with inodes for which buffer locking
864  *      is not enabled are not protected by semaphores, and are
865  *      assumed to be exclusively owned by the caller.  There is a
866  *      spinlock in the buffer, used by the caller when concurrent
867  *      access is possible.
868  */
869
870 /*
871  *      Locks a buffer object, if it is not already locked.
872  *      Note that this in no way locks the underlying pages, so it is only
873  *      useful for synchronizing concurrent use of buffer objects, not for
874  *      synchronizing independent access to the underlying pages.
875  */
876 int
877 xfs_buf_cond_lock(
878         xfs_buf_t               *bp)
879 {
880         int                     locked;
881
882         locked = down_trylock(&bp->b_sema) == 0;
883         if (locked)
884                 XB_SET_OWNER(bp);
885
886         trace_xfs_buf_cond_lock(bp, _RET_IP_);
887         return locked ? 0 : -EBUSY;
888 }
889
890 int
891 xfs_buf_lock_value(
892         xfs_buf_t               *bp)
893 {
894         return bp->b_sema.count;
895 }
896
897 /*
898  *      Locks a buffer object.
899  *      Note that this in no way locks the underlying pages, so it is only
900  *      useful for synchronizing concurrent use of buffer objects, not for
901  *      synchronizing independent access to the underlying pages.
902  */
903 void
904 xfs_buf_lock(
905         xfs_buf_t               *bp)
906 {
907         trace_xfs_buf_lock(bp, _RET_IP_);
908
909         if (atomic_read(&bp->b_io_remaining))
910                 blk_run_address_space(bp->b_target->bt_mapping);
911         down(&bp->b_sema);
912         XB_SET_OWNER(bp);
913
914         trace_xfs_buf_lock_done(bp, _RET_IP_);
915 }
916
917 /*
918  *      Releases the lock on the buffer object.
919  *      If the buffer is marked delwri but is not queued, do so before we
920  *      unlock the buffer as we need to set flags correctly.  We also need to
921  *      take a reference for the delwri queue because the unlocker is going to
922  *      drop their's and they don't know we just queued it.
923  */
924 void
925 xfs_buf_unlock(
926         xfs_buf_t               *bp)
927 {
928         if ((bp->b_flags & (XBF_DELWRI|_XBF_DELWRI_Q)) == XBF_DELWRI) {
929                 atomic_inc(&bp->b_hold);
930                 bp->b_flags |= XBF_ASYNC;
931                 xfs_buf_delwri_queue(bp, 0);
932         }
933
934         XB_CLEAR_OWNER(bp);
935         up(&bp->b_sema);
936
937         trace_xfs_buf_unlock(bp, _RET_IP_);
938 }
939
940
941 /*
942  *      Pinning Buffer Storage in Memory
943  *      Ensure that no attempt to force a buffer to disk will succeed.
944  */
945 void
946 xfs_buf_pin(
947         xfs_buf_t               *bp)
948 {
949         trace_xfs_buf_pin(bp, _RET_IP_);
950         atomic_inc(&bp->b_pin_count);
951 }
952
953 void
954 xfs_buf_unpin(
955         xfs_buf_t               *bp)
956 {
957         trace_xfs_buf_unpin(bp, _RET_IP_);
958
959         if (atomic_dec_and_test(&bp->b_pin_count))
960                 wake_up_all(&bp->b_waiters);
961 }
962
963 int
964 xfs_buf_ispin(
965         xfs_buf_t               *bp)
966 {
967         return atomic_read(&bp->b_pin_count);
968 }
969
970 STATIC void
971 xfs_buf_wait_unpin(
972         xfs_buf_t               *bp)
973 {
974         DECLARE_WAITQUEUE       (wait, current);
975
976         if (atomic_read(&bp->b_pin_count) == 0)
977                 return;
978
979         add_wait_queue(&bp->b_waiters, &wait);
980         for (;;) {
981                 set_current_state(TASK_UNINTERRUPTIBLE);
982                 if (atomic_read(&bp->b_pin_count) == 0)
983                         break;
984                 if (atomic_read(&bp->b_io_remaining))
985                         blk_run_address_space(bp->b_target->bt_mapping);
986                 schedule();
987         }
988         remove_wait_queue(&bp->b_waiters, &wait);
989         set_current_state(TASK_RUNNING);
990 }
991
992 /*
993  *      Buffer Utility Routines
994  */
995
996 STATIC void
997 xfs_buf_iodone_work(
998         struct work_struct      *work)
999 {
1000         xfs_buf_t               *bp =
1001                 container_of(work, xfs_buf_t, b_iodone_work);
1002
1003         /*
1004          * We can get an EOPNOTSUPP to ordered writes.  Here we clear the
1005          * ordered flag and reissue them.  Because we can't tell the higher
1006          * layers directly that they should not issue ordered I/O anymore, they
1007          * need to check if the _XFS_BARRIER_FAILED flag was set during I/O completion.
1008          */
1009         if ((bp->b_error == EOPNOTSUPP) &&
1010             (bp->b_flags & (XBF_ORDERED|XBF_ASYNC)) == (XBF_ORDERED|XBF_ASYNC)) {
1011                 trace_xfs_buf_ordered_retry(bp, _RET_IP_);
1012                 bp->b_flags &= ~XBF_ORDERED;
1013                 bp->b_flags |= _XFS_BARRIER_FAILED;
1014                 xfs_buf_iorequest(bp);
1015         } else if (bp->b_iodone)
1016                 (*(bp->b_iodone))(bp);
1017         else if (bp->b_flags & XBF_ASYNC)
1018                 xfs_buf_relse(bp);
1019 }
1020
1021 void
1022 xfs_buf_ioend(
1023         xfs_buf_t               *bp,
1024         int                     schedule)
1025 {
1026         trace_xfs_buf_iodone(bp, _RET_IP_);
1027
1028         bp->b_flags &= ~(XBF_READ | XBF_WRITE | XBF_READ_AHEAD);
1029         if (bp->b_error == 0)
1030                 bp->b_flags |= XBF_DONE;
1031
1032         if ((bp->b_iodone) || (bp->b_flags & XBF_ASYNC)) {
1033                 if (schedule) {
1034                         INIT_WORK(&bp->b_iodone_work, xfs_buf_iodone_work);
1035                         queue_work(xfslogd_workqueue, &bp->b_iodone_work);
1036                 } else {
1037                         xfs_buf_iodone_work(&bp->b_iodone_work);
1038                 }
1039         } else {
1040                 complete(&bp->b_iowait);
1041         }
1042 }
1043
1044 void
1045 xfs_buf_ioerror(
1046         xfs_buf_t               *bp,
1047         int                     error)
1048 {
1049         ASSERT(error >= 0 && error <= 0xffff);
1050         bp->b_error = (unsigned short)error;
1051         trace_xfs_buf_ioerror(bp, error, _RET_IP_);
1052 }
1053
1054 int
1055 xfs_bwrite(
1056         struct xfs_mount        *mp,
1057         struct xfs_buf          *bp)
1058 {
1059         int                     iowait = (bp->b_flags & XBF_ASYNC) == 0;
1060         int                     error = 0;
1061
1062         bp->b_strat = xfs_bdstrat_cb;
1063         bp->b_mount = mp;
1064         bp->b_flags |= XBF_WRITE;
1065         if (!iowait)
1066                 bp->b_flags |= _XBF_RUN_QUEUES;
1067
1068         xfs_buf_delwri_dequeue(bp);
1069         xfs_buf_iostrategy(bp);
1070
1071         if (iowait) {
1072                 error = xfs_buf_iowait(bp);
1073                 if (error)
1074                         xfs_force_shutdown(mp, SHUTDOWN_META_IO_ERROR);
1075                 xfs_buf_relse(bp);
1076         }
1077
1078         return error;
1079 }
1080
1081 void
1082 xfs_bdwrite(
1083         void                    *mp,
1084         struct xfs_buf          *bp)
1085 {
1086         trace_xfs_buf_bdwrite(bp, _RET_IP_);
1087
1088         bp->b_strat = xfs_bdstrat_cb;
1089         bp->b_mount = mp;
1090
1091         bp->b_flags &= ~XBF_READ;
1092         bp->b_flags |= (XBF_DELWRI | XBF_ASYNC);
1093
1094         xfs_buf_delwri_queue(bp, 1);
1095 }
1096
1097 /*
1098  * Called when we want to stop a buffer from getting written or read.
1099  * We attach the EIO error, muck with its flags, and call biodone
1100  * so that the proper iodone callbacks get called.
1101  */
1102 STATIC int
1103 xfs_bioerror(
1104         xfs_buf_t *bp)
1105 {
1106 #ifdef XFSERRORDEBUG
1107         ASSERT(XFS_BUF_ISREAD(bp) || bp->b_iodone);
1108 #endif
1109
1110         /*
1111          * No need to wait until the buffer is unpinned, we aren't flushing it.
1112          */
1113         XFS_BUF_ERROR(bp, EIO);
1114
1115         /*
1116          * We're calling biodone, so delete XBF_DONE flag.
1117          */
1118         XFS_BUF_UNREAD(bp);
1119         XFS_BUF_UNDELAYWRITE(bp);
1120         XFS_BUF_UNDONE(bp);
1121         XFS_BUF_STALE(bp);
1122
1123         XFS_BUF_CLR_BDSTRAT_FUNC(bp);
1124         xfs_biodone(bp);
1125
1126         return EIO;
1127 }
1128
1129 /*
1130  * Same as xfs_bioerror, except that we are releasing the buffer
1131  * here ourselves, and avoiding the biodone call.
1132  * This is meant for userdata errors; metadata bufs come with
1133  * iodone functions attached, so that we can track down errors.
1134  */
1135 STATIC int
1136 xfs_bioerror_relse(
1137         struct xfs_buf  *bp)
1138 {
1139         int64_t         fl = XFS_BUF_BFLAGS(bp);
1140         /*
1141          * No need to wait until the buffer is unpinned.
1142          * We aren't flushing it.
1143          *
1144          * chunkhold expects B_DONE to be set, whether
1145          * we actually finish the I/O or not. We don't want to
1146          * change that interface.
1147          */
1148         XFS_BUF_UNREAD(bp);
1149         XFS_BUF_UNDELAYWRITE(bp);
1150         XFS_BUF_DONE(bp);
1151         XFS_BUF_STALE(bp);
1152         XFS_BUF_CLR_IODONE_FUNC(bp);
1153         XFS_BUF_CLR_BDSTRAT_FUNC(bp);
1154         if (!(fl & XBF_ASYNC)) {
1155                 /*
1156                  * Mark b_error and B_ERROR _both_.
1157                  * Lot's of chunkcache code assumes that.
1158                  * There's no reason to mark error for
1159                  * ASYNC buffers.
1160                  */
1161                 XFS_BUF_ERROR(bp, EIO);
1162                 XFS_BUF_FINISH_IOWAIT(bp);
1163         } else {
1164                 xfs_buf_relse(bp);
1165         }
1166
1167         return EIO;
1168 }
1169
1170
1171 /*
1172  * All xfs metadata buffers except log state machine buffers
1173  * get this attached as their b_bdstrat callback function.
1174  * This is so that we can catch a buffer
1175  * after prematurely unpinning it to forcibly shutdown the filesystem.
1176  */
1177 int
1178 xfs_bdstrat_cb(
1179         struct xfs_buf  *bp)
1180 {
1181         if (XFS_FORCED_SHUTDOWN(bp->b_mount)) {
1182                 trace_xfs_bdstrat_shut(bp, _RET_IP_);
1183                 /*
1184                  * Metadata write that didn't get logged but
1185                  * written delayed anyway. These aren't associated
1186                  * with a transaction, and can be ignored.
1187                  */
1188                 if (!bp->b_iodone && !XFS_BUF_ISREAD(bp))
1189                         return xfs_bioerror_relse(bp);
1190                 else
1191                         return xfs_bioerror(bp);
1192         }
1193
1194         xfs_buf_iorequest(bp);
1195         return 0;
1196 }
1197
1198 /*
1199  * Wrapper around bdstrat so that we can stop data from going to disk in case
1200  * we are shutting down the filesystem.  Typically user data goes thru this
1201  * path; one of the exceptions is the superblock.
1202  */
1203 void
1204 xfsbdstrat(
1205         struct xfs_mount        *mp,
1206         struct xfs_buf          *bp)
1207 {
1208         if (XFS_FORCED_SHUTDOWN(mp)) {
1209                 trace_xfs_bdstrat_shut(bp, _RET_IP_);
1210                 xfs_bioerror_relse(bp);
1211                 return;
1212         }
1213
1214         xfs_buf_iorequest(bp);
1215 }
1216
1217 STATIC void
1218 _xfs_buf_ioend(
1219         xfs_buf_t               *bp,
1220         int                     schedule)
1221 {
1222         if (atomic_dec_and_test(&bp->b_io_remaining) == 1) {
1223                 bp->b_flags &= ~_XBF_PAGE_LOCKED;
1224                 xfs_buf_ioend(bp, schedule);
1225         }
1226 }
1227
1228 STATIC void
1229 xfs_buf_bio_end_io(
1230         struct bio              *bio,
1231         int                     error)
1232 {
1233         xfs_buf_t               *bp = (xfs_buf_t *)bio->bi_private;
1234         unsigned int            blocksize = bp->b_target->bt_bsize;
1235         struct bio_vec          *bvec = bio->bi_io_vec + bio->bi_vcnt - 1;
1236
1237         xfs_buf_ioerror(bp, -error);
1238
1239         do {
1240                 struct page     *page = bvec->bv_page;
1241
1242                 ASSERT(!PagePrivate(page));
1243                 if (unlikely(bp->b_error)) {
1244                         if (bp->b_flags & XBF_READ)
1245                                 ClearPageUptodate(page);
1246                 } else if (blocksize >= PAGE_CACHE_SIZE) {
1247                         SetPageUptodate(page);
1248                 } else if (!PagePrivate(page) &&
1249                                 (bp->b_flags & _XBF_PAGE_CACHE)) {
1250                         set_page_region(page, bvec->bv_offset, bvec->bv_len);
1251                 }
1252
1253                 if (--bvec >= bio->bi_io_vec)
1254                         prefetchw(&bvec->bv_page->flags);
1255
1256                 if (bp->b_flags & _XBF_PAGE_LOCKED)
1257                         unlock_page(page);
1258         } while (bvec >= bio->bi_io_vec);
1259
1260         _xfs_buf_ioend(bp, 1);
1261         bio_put(bio);
1262 }
1263
1264 STATIC void
1265 _xfs_buf_ioapply(
1266         xfs_buf_t               *bp)
1267 {
1268         int                     rw, map_i, total_nr_pages, nr_pages;
1269         struct bio              *bio;
1270         int                     offset = bp->b_offset;
1271         int                     size = bp->b_count_desired;
1272         sector_t                sector = bp->b_bn;
1273         unsigned int            blocksize = bp->b_target->bt_bsize;
1274
1275         total_nr_pages = bp->b_page_count;
1276         map_i = 0;
1277
1278         if (bp->b_flags & XBF_ORDERED) {
1279                 ASSERT(!(bp->b_flags & XBF_READ));
1280                 rw = WRITE_BARRIER;
1281         } else if (bp->b_flags & XBF_LOG_BUFFER) {
1282                 ASSERT(!(bp->b_flags & XBF_READ_AHEAD));
1283                 bp->b_flags &= ~_XBF_RUN_QUEUES;
1284                 rw = (bp->b_flags & XBF_WRITE) ? WRITE_SYNC : READ_SYNC;
1285         } else if (bp->b_flags & _XBF_RUN_QUEUES) {
1286                 ASSERT(!(bp->b_flags & XBF_READ_AHEAD));
1287                 bp->b_flags &= ~_XBF_RUN_QUEUES;
1288                 rw = (bp->b_flags & XBF_WRITE) ? WRITE_META : READ_META;
1289         } else {
1290                 rw = (bp->b_flags & XBF_WRITE) ? WRITE :
1291                      (bp->b_flags & XBF_READ_AHEAD) ? READA : READ;
1292         }
1293
1294         /* Special code path for reading a sub page size buffer in --
1295          * we populate up the whole page, and hence the other metadata
1296          * in the same page.  This optimization is only valid when the
1297          * filesystem block size is not smaller than the page size.
1298          */
1299         if ((bp->b_buffer_length < PAGE_CACHE_SIZE) &&
1300             ((bp->b_flags & (XBF_READ|_XBF_PAGE_LOCKED)) ==
1301               (XBF_READ|_XBF_PAGE_LOCKED)) &&
1302             (blocksize >= PAGE_CACHE_SIZE)) {
1303                 bio = bio_alloc(GFP_NOIO, 1);
1304
1305                 bio->bi_bdev = bp->b_target->bt_bdev;
1306                 bio->bi_sector = sector - (offset >> BBSHIFT);
1307                 bio->bi_end_io = xfs_buf_bio_end_io;
1308                 bio->bi_private = bp;
1309
1310                 bio_add_page(bio, bp->b_pages[0], PAGE_CACHE_SIZE, 0);
1311                 size = 0;
1312
1313                 atomic_inc(&bp->b_io_remaining);
1314
1315                 goto submit_io;
1316         }
1317
1318 next_chunk:
1319         atomic_inc(&bp->b_io_remaining);
1320         nr_pages = BIO_MAX_SECTORS >> (PAGE_SHIFT - BBSHIFT);
1321         if (nr_pages > total_nr_pages)
1322                 nr_pages = total_nr_pages;
1323
1324         bio = bio_alloc(GFP_NOIO, nr_pages);
1325         bio->bi_bdev = bp->b_target->bt_bdev;
1326         bio->bi_sector = sector;
1327         bio->bi_end_io = xfs_buf_bio_end_io;
1328         bio->bi_private = bp;
1329
1330         for (; size && nr_pages; nr_pages--, map_i++) {
1331                 int     rbytes, nbytes = PAGE_CACHE_SIZE - offset;
1332
1333                 if (nbytes > size)
1334                         nbytes = size;
1335
1336                 rbytes = bio_add_page(bio, bp->b_pages[map_i], nbytes, offset);
1337                 if (rbytes < nbytes)
1338                         break;
1339
1340                 offset = 0;
1341                 sector += nbytes >> BBSHIFT;
1342                 size -= nbytes;
1343                 total_nr_pages--;
1344         }
1345
1346 submit_io:
1347         if (likely(bio->bi_size)) {
1348                 submit_bio(rw, bio);
1349                 if (size)
1350                         goto next_chunk;
1351         } else {
1352                 bio_put(bio);
1353                 xfs_buf_ioerror(bp, EIO);
1354         }
1355 }
1356
1357 int
1358 xfs_buf_iorequest(
1359         xfs_buf_t               *bp)
1360 {
1361         trace_xfs_buf_iorequest(bp, _RET_IP_);
1362
1363         if (bp->b_flags & XBF_DELWRI) {
1364                 xfs_buf_delwri_queue(bp, 1);
1365                 return 0;
1366         }
1367
1368         if (bp->b_flags & XBF_WRITE) {
1369                 xfs_buf_wait_unpin(bp);
1370         }
1371
1372         xfs_buf_hold(bp);
1373
1374         /* Set the count to 1 initially, this will stop an I/O
1375          * completion callout which happens before we have started
1376          * all the I/O from calling xfs_buf_ioend too early.
1377          */
1378         atomic_set(&bp->b_io_remaining, 1);
1379         _xfs_buf_ioapply(bp);
1380         _xfs_buf_ioend(bp, 0);
1381
1382         xfs_buf_rele(bp);
1383         return 0;
1384 }
1385
1386 /*
1387  *      Waits for I/O to complete on the buffer supplied.
1388  *      It returns immediately if no I/O is pending.
1389  *      It returns the I/O error code, if any, or 0 if there was no error.
1390  */
1391 int
1392 xfs_buf_iowait(
1393         xfs_buf_t               *bp)
1394 {
1395         trace_xfs_buf_iowait(bp, _RET_IP_);
1396
1397         if (atomic_read(&bp->b_io_remaining))
1398                 blk_run_address_space(bp->b_target->bt_mapping);
1399         wait_for_completion(&bp->b_iowait);
1400
1401         trace_xfs_buf_iowait_done(bp, _RET_IP_);
1402         return bp->b_error;
1403 }
1404
1405 xfs_caddr_t
1406 xfs_buf_offset(
1407         xfs_buf_t               *bp,
1408         size_t                  offset)
1409 {
1410         struct page             *page;
1411
1412         if (bp->b_flags & XBF_MAPPED)
1413                 return XFS_BUF_PTR(bp) + offset;
1414
1415         offset += bp->b_offset;
1416         page = bp->b_pages[offset >> PAGE_CACHE_SHIFT];
1417         return (xfs_caddr_t)page_address(page) + (offset & (PAGE_CACHE_SIZE-1));
1418 }
1419
1420 /*
1421  *      Move data into or out of a buffer.
1422  */
1423 void
1424 xfs_buf_iomove(
1425         xfs_buf_t               *bp,    /* buffer to process            */
1426         size_t                  boff,   /* starting buffer offset       */
1427         size_t                  bsize,  /* length to copy               */
1428         void                    *data,  /* data address                 */
1429         xfs_buf_rw_t            mode)   /* read/write/zero flag         */
1430 {
1431         size_t                  bend, cpoff, csize;
1432         struct page             *page;
1433
1434         bend = boff + bsize;
1435         while (boff < bend) {
1436                 page = bp->b_pages[xfs_buf_btoct(boff + bp->b_offset)];
1437                 cpoff = xfs_buf_poff(boff + bp->b_offset);
1438                 csize = min_t(size_t,
1439                               PAGE_CACHE_SIZE-cpoff, bp->b_count_desired-boff);
1440
1441                 ASSERT(((csize + cpoff) <= PAGE_CACHE_SIZE));
1442
1443                 switch (mode) {
1444                 case XBRW_ZERO:
1445                         memset(page_address(page) + cpoff, 0, csize);
1446                         break;
1447                 case XBRW_READ:
1448                         memcpy(data, page_address(page) + cpoff, csize);
1449                         break;
1450                 case XBRW_WRITE:
1451                         memcpy(page_address(page) + cpoff, data, csize);
1452                 }
1453
1454                 boff += csize;
1455                 data += csize;
1456         }
1457 }
1458
1459 /*
1460  *      Handling of buffer targets (buftargs).
1461  */
1462
1463 /*
1464  *      Wait for any bufs with callbacks that have been submitted but
1465  *      have not yet returned... walk the hash list for the target.
1466  */
1467 void
1468 xfs_wait_buftarg(
1469         xfs_buftarg_t   *btp)
1470 {
1471         xfs_buf_t       *bp, *n;
1472         xfs_bufhash_t   *hash;
1473         uint            i;
1474
1475         for (i = 0; i < (1 << btp->bt_hashshift); i++) {
1476                 hash = &btp->bt_hash[i];
1477 again:
1478                 spin_lock(&hash->bh_lock);
1479                 list_for_each_entry_safe(bp, n, &hash->bh_list, b_hash_list) {
1480                         ASSERT(btp == bp->b_target);
1481                         if (!(bp->b_flags & XBF_FS_MANAGED)) {
1482                                 spin_unlock(&hash->bh_lock);
1483                                 /*
1484                                  * Catch superblock reference count leaks
1485                                  * immediately
1486                                  */
1487                                 BUG_ON(bp->b_bn == 0);
1488                                 delay(100);
1489                                 goto again;
1490                         }
1491                 }
1492                 spin_unlock(&hash->bh_lock);
1493         }
1494 }
1495
1496 /*
1497  *      Allocate buffer hash table for a given target.
1498  *      For devices containing metadata (i.e. not the log/realtime devices)
1499  *      we need to allocate a much larger hash table.
1500  */
1501 STATIC void
1502 xfs_alloc_bufhash(
1503         xfs_buftarg_t           *btp,
1504         int                     external)
1505 {
1506         unsigned int            i;
1507
1508         btp->bt_hashshift = external ? 3 : 8;   /* 8 or 256 buckets */
1509         btp->bt_hashmask = (1 << btp->bt_hashshift) - 1;
1510         btp->bt_hash = kmem_zalloc_large((1 << btp->bt_hashshift) *
1511                                          sizeof(xfs_bufhash_t));
1512         for (i = 0; i < (1 << btp->bt_hashshift); i++) {
1513                 spin_lock_init(&btp->bt_hash[i].bh_lock);
1514                 INIT_LIST_HEAD(&btp->bt_hash[i].bh_list);
1515         }
1516 }
1517
1518 STATIC void
1519 xfs_free_bufhash(
1520         xfs_buftarg_t           *btp)
1521 {
1522         kmem_free_large(btp->bt_hash);
1523         btp->bt_hash = NULL;
1524 }
1525
1526 /*
1527  *      buftarg list for delwrite queue processing
1528  */
1529 static LIST_HEAD(xfs_buftarg_list);
1530 static DEFINE_SPINLOCK(xfs_buftarg_lock);
1531
1532 STATIC void
1533 xfs_register_buftarg(
1534         xfs_buftarg_t           *btp)
1535 {
1536         spin_lock(&xfs_buftarg_lock);
1537         list_add(&btp->bt_list, &xfs_buftarg_list);
1538         spin_unlock(&xfs_buftarg_lock);
1539 }
1540
1541 STATIC void
1542 xfs_unregister_buftarg(
1543         xfs_buftarg_t           *btp)
1544 {
1545         spin_lock(&xfs_buftarg_lock);
1546         list_del(&btp->bt_list);
1547         spin_unlock(&xfs_buftarg_lock);
1548 }
1549
1550 void
1551 xfs_free_buftarg(
1552         struct xfs_mount        *mp,
1553         struct xfs_buftarg      *btp)
1554 {
1555         xfs_flush_buftarg(btp, 1);
1556         if (mp->m_flags & XFS_MOUNT_BARRIER)
1557                 xfs_blkdev_issue_flush(btp);
1558         xfs_free_bufhash(btp);
1559         iput(btp->bt_mapping->host);
1560
1561         /* Unregister the buftarg first so that we don't get a
1562          * wakeup finding a non-existent task
1563          */
1564         xfs_unregister_buftarg(btp);
1565         kthread_stop(btp->bt_task);
1566
1567         kmem_free(btp);
1568 }
1569
1570 STATIC int
1571 xfs_setsize_buftarg_flags(
1572         xfs_buftarg_t           *btp,
1573         unsigned int            blocksize,
1574         unsigned int            sectorsize,
1575         int                     verbose)
1576 {
1577         btp->bt_bsize = blocksize;
1578         btp->bt_sshift = ffs(sectorsize) - 1;
1579         btp->bt_smask = sectorsize - 1;
1580
1581         if (set_blocksize(btp->bt_bdev, sectorsize)) {
1582                 printk(KERN_WARNING
1583                         "XFS: Cannot set_blocksize to %u on device %s\n",
1584                         sectorsize, XFS_BUFTARG_NAME(btp));
1585                 return EINVAL;
1586         }
1587
1588         if (verbose &&
1589             (PAGE_CACHE_SIZE / BITS_PER_LONG) > sectorsize) {
1590                 printk(KERN_WARNING
1591                         "XFS: %u byte sectors in use on device %s.  "
1592                         "This is suboptimal; %u or greater is ideal.\n",
1593                         sectorsize, XFS_BUFTARG_NAME(btp),
1594                         (unsigned int)PAGE_CACHE_SIZE / BITS_PER_LONG);
1595         }
1596
1597         return 0;
1598 }
1599
1600 /*
1601  *      When allocating the initial buffer target we have not yet
1602  *      read in the superblock, so don't know what sized sectors
1603  *      are being used is at this early stage.  Play safe.
1604  */
1605 STATIC int
1606 xfs_setsize_buftarg_early(
1607         xfs_buftarg_t           *btp,
1608         struct block_device     *bdev)
1609 {
1610         return xfs_setsize_buftarg_flags(btp,
1611                         PAGE_CACHE_SIZE, bdev_logical_block_size(bdev), 0);
1612 }
1613
1614 int
1615 xfs_setsize_buftarg(
1616         xfs_buftarg_t           *btp,
1617         unsigned int            blocksize,
1618         unsigned int            sectorsize)
1619 {
1620         return xfs_setsize_buftarg_flags(btp, blocksize, sectorsize, 1);
1621 }
1622
1623 STATIC int
1624 xfs_mapping_buftarg(
1625         xfs_buftarg_t           *btp,
1626         struct block_device     *bdev)
1627 {
1628         struct backing_dev_info *bdi;
1629         struct inode            *inode;
1630         struct address_space    *mapping;
1631         static const struct address_space_operations mapping_aops = {
1632                 .sync_page = block_sync_page,
1633                 .migratepage = fail_migrate_page,
1634         };
1635
1636         inode = new_inode(bdev->bd_inode->i_sb);
1637         if (!inode) {
1638                 printk(KERN_WARNING
1639                         "XFS: Cannot allocate mapping inode for device %s\n",
1640                         XFS_BUFTARG_NAME(btp));
1641                 return ENOMEM;
1642         }
1643         inode->i_mode = S_IFBLK;
1644         inode->i_bdev = bdev;
1645         inode->i_rdev = bdev->bd_dev;
1646         bdi = blk_get_backing_dev_info(bdev);
1647         if (!bdi)
1648                 bdi = &default_backing_dev_info;
1649         mapping = &inode->i_data;
1650         mapping->a_ops = &mapping_aops;
1651         mapping->backing_dev_info = bdi;
1652         mapping_set_gfp_mask(mapping, GFP_NOFS);
1653         btp->bt_mapping = mapping;
1654         return 0;
1655 }
1656
1657 STATIC int
1658 xfs_alloc_delwrite_queue(
1659         xfs_buftarg_t           *btp)
1660 {
1661         int     error = 0;
1662
1663         INIT_LIST_HEAD(&btp->bt_list);
1664         INIT_LIST_HEAD(&btp->bt_delwrite_queue);
1665         spin_lock_init(&btp->bt_delwrite_lock);
1666         btp->bt_flags = 0;
1667         btp->bt_task = kthread_run(xfsbufd, btp, "xfsbufd");
1668         if (IS_ERR(btp->bt_task)) {
1669                 error = PTR_ERR(btp->bt_task);
1670                 goto out_error;
1671         }
1672         xfs_register_buftarg(btp);
1673 out_error:
1674         return error;
1675 }
1676
1677 xfs_buftarg_t *
1678 xfs_alloc_buftarg(
1679         struct block_device     *bdev,
1680         int                     external)
1681 {
1682         xfs_buftarg_t           *btp;
1683
1684         btp = kmem_zalloc(sizeof(*btp), KM_SLEEP);
1685
1686         btp->bt_dev =  bdev->bd_dev;
1687         btp->bt_bdev = bdev;
1688         if (xfs_setsize_buftarg_early(btp, bdev))
1689                 goto error;
1690         if (xfs_mapping_buftarg(btp, bdev))
1691                 goto error;
1692         if (xfs_alloc_delwrite_queue(btp))
1693                 goto error;
1694         xfs_alloc_bufhash(btp, external);
1695         return btp;
1696
1697 error:
1698         kmem_free(btp);
1699         return NULL;
1700 }
1701
1702
1703 /*
1704  *      Delayed write buffer handling
1705  */
1706 STATIC void
1707 xfs_buf_delwri_queue(
1708         xfs_buf_t               *bp,
1709         int                     unlock)
1710 {
1711         struct list_head        *dwq = &bp->b_target->bt_delwrite_queue;
1712         spinlock_t              *dwlk = &bp->b_target->bt_delwrite_lock;
1713
1714         trace_xfs_buf_delwri_queue(bp, _RET_IP_);
1715
1716         ASSERT((bp->b_flags&(XBF_DELWRI|XBF_ASYNC)) == (XBF_DELWRI|XBF_ASYNC));
1717
1718         spin_lock(dwlk);
1719         /* If already in the queue, dequeue and place at tail */
1720         if (!list_empty(&bp->b_list)) {
1721                 ASSERT(bp->b_flags & _XBF_DELWRI_Q);
1722                 if (unlock)
1723                         atomic_dec(&bp->b_hold);
1724                 list_del(&bp->b_list);
1725         }
1726
1727         if (list_empty(dwq)) {
1728                 /* start xfsbufd as it is about to have something to do */
1729                 wake_up_process(bp->b_target->bt_task);
1730         }
1731
1732         bp->b_flags |= _XBF_DELWRI_Q;
1733         list_add_tail(&bp->b_list, dwq);
1734         bp->b_queuetime = jiffies;
1735         spin_unlock(dwlk);
1736
1737         if (unlock)
1738                 xfs_buf_unlock(bp);
1739 }
1740
1741 void
1742 xfs_buf_delwri_dequeue(
1743         xfs_buf_t               *bp)
1744 {
1745         spinlock_t              *dwlk = &bp->b_target->bt_delwrite_lock;
1746         int                     dequeued = 0;
1747
1748         spin_lock(dwlk);
1749         if ((bp->b_flags & XBF_DELWRI) && !list_empty(&bp->b_list)) {
1750                 ASSERT(bp->b_flags & _XBF_DELWRI_Q);
1751                 list_del_init(&bp->b_list);
1752                 dequeued = 1;
1753         }
1754         bp->b_flags &= ~(XBF_DELWRI|_XBF_DELWRI_Q);
1755         spin_unlock(dwlk);
1756
1757         if (dequeued)
1758                 xfs_buf_rele(bp);
1759
1760         trace_xfs_buf_delwri_dequeue(bp, _RET_IP_);
1761 }
1762
1763 /*
1764  * If a delwri buffer needs to be pushed before it has aged out, then promote
1765  * it to the head of the delwri queue so that it will be flushed on the next
1766  * xfsbufd run. We do this by resetting the queuetime of the buffer to be older
1767  * than the age currently needed to flush the buffer. Hence the next time the
1768  * xfsbufd sees it is guaranteed to be considered old enough to flush.
1769  */
1770 void
1771 xfs_buf_delwri_promote(
1772         struct xfs_buf  *bp)
1773 {
1774         struct xfs_buftarg *btp = bp->b_target;
1775         long            age = xfs_buf_age_centisecs * msecs_to_jiffies(10) + 1;
1776
1777         ASSERT(bp->b_flags & XBF_DELWRI);
1778         ASSERT(bp->b_flags & _XBF_DELWRI_Q);
1779
1780         /*
1781          * Check the buffer age before locking the delayed write queue as we
1782          * don't need to promote buffers that are already past the flush age.
1783          */
1784         if (bp->b_queuetime < jiffies - age)
1785                 return;
1786         bp->b_queuetime = jiffies - age;
1787         spin_lock(&btp->bt_delwrite_lock);
1788         list_move(&bp->b_list, &btp->bt_delwrite_queue);
1789         spin_unlock(&btp->bt_delwrite_lock);
1790 }
1791
1792 STATIC void
1793 xfs_buf_runall_queues(
1794         struct workqueue_struct *queue)
1795 {
1796         flush_workqueue(queue);
1797 }
1798
1799 STATIC int
1800 xfsbufd_wakeup(
1801         int                     priority,
1802         gfp_t                   mask)
1803 {
1804         xfs_buftarg_t           *btp;
1805
1806         spin_lock(&xfs_buftarg_lock);
1807         list_for_each_entry(btp, &xfs_buftarg_list, bt_list) {
1808                 if (test_bit(XBT_FORCE_SLEEP, &btp->bt_flags))
1809                         continue;
1810                 if (list_empty(&btp->bt_delwrite_queue))
1811                         continue;
1812                 set_bit(XBT_FORCE_FLUSH, &btp->bt_flags);
1813                 wake_up_process(btp->bt_task);
1814         }
1815         spin_unlock(&xfs_buftarg_lock);
1816         return 0;
1817 }
1818
1819 /*
1820  * Move as many buffers as specified to the supplied list
1821  * idicating if we skipped any buffers to prevent deadlocks.
1822  */
1823 STATIC int
1824 xfs_buf_delwri_split(
1825         xfs_buftarg_t   *target,
1826         struct list_head *list,
1827         unsigned long   age)
1828 {
1829         xfs_buf_t       *bp, *n;
1830         struct list_head *dwq = &target->bt_delwrite_queue;
1831         spinlock_t      *dwlk = &target->bt_delwrite_lock;
1832         int             skipped = 0;
1833         int             force;
1834
1835         force = test_and_clear_bit(XBT_FORCE_FLUSH, &target->bt_flags);
1836         INIT_LIST_HEAD(list);
1837         spin_lock(dwlk);
1838         list_for_each_entry_safe(bp, n, dwq, b_list) {
1839                 trace_xfs_buf_delwri_split(bp, _RET_IP_);
1840                 ASSERT(bp->b_flags & XBF_DELWRI);
1841
1842                 if (!xfs_buf_ispin(bp) && !xfs_buf_cond_lock(bp)) {
1843                         if (!force &&
1844                             time_before(jiffies, bp->b_queuetime + age)) {
1845                                 xfs_buf_unlock(bp);
1846                                 break;
1847                         }
1848
1849                         bp->b_flags &= ~(XBF_DELWRI|_XBF_DELWRI_Q|
1850                                          _XBF_RUN_QUEUES);
1851                         bp->b_flags |= XBF_WRITE;
1852                         list_move_tail(&bp->b_list, list);
1853                 } else
1854                         skipped++;
1855         }
1856         spin_unlock(dwlk);
1857
1858         return skipped;
1859
1860 }
1861
1862 /*
1863  * Compare function is more complex than it needs to be because
1864  * the return value is only 32 bits and we are doing comparisons
1865  * on 64 bit values
1866  */
1867 static int
1868 xfs_buf_cmp(
1869         void            *priv,
1870         struct list_head *a,
1871         struct list_head *b)
1872 {
1873         struct xfs_buf  *ap = container_of(a, struct xfs_buf, b_list);
1874         struct xfs_buf  *bp = container_of(b, struct xfs_buf, b_list);
1875         xfs_daddr_t             diff;
1876
1877         diff = ap->b_bn - bp->b_bn;
1878         if (diff < 0)
1879                 return -1;
1880         if (diff > 0)
1881                 return 1;
1882         return 0;
1883 }
1884
1885 void
1886 xfs_buf_delwri_sort(
1887         xfs_buftarg_t   *target,
1888         struct list_head *list)
1889 {
1890         list_sort(NULL, list, xfs_buf_cmp);
1891 }
1892
1893 STATIC int
1894 xfsbufd(
1895         void            *data)
1896 {
1897         xfs_buftarg_t   *target = (xfs_buftarg_t *)data;
1898
1899         current->flags |= PF_MEMALLOC;
1900
1901         set_freezable();
1902
1903         do {
1904                 long    age = xfs_buf_age_centisecs * msecs_to_jiffies(10);
1905                 long    tout = xfs_buf_timer_centisecs * msecs_to_jiffies(10);
1906                 int     count = 0;
1907                 struct list_head tmp;
1908
1909                 if (unlikely(freezing(current))) {
1910                         set_bit(XBT_FORCE_SLEEP, &target->bt_flags);
1911                         refrigerator();
1912                 } else {
1913                         clear_bit(XBT_FORCE_SLEEP, &target->bt_flags);
1914                 }
1915
1916                 /* sleep for a long time if there is nothing to do. */
1917                 if (list_empty(&target->bt_delwrite_queue))
1918                         tout = MAX_SCHEDULE_TIMEOUT;
1919                 schedule_timeout_interruptible(tout);
1920
1921                 xfs_buf_delwri_split(target, &tmp, age);
1922                 list_sort(NULL, &tmp, xfs_buf_cmp);
1923                 while (!list_empty(&tmp)) {
1924                         struct xfs_buf *bp;
1925                         bp = list_first_entry(&tmp, struct xfs_buf, b_list);
1926                         list_del_init(&bp->b_list);
1927                         xfs_buf_iostrategy(bp);
1928                         count++;
1929                 }
1930
1931                 if (as_list_len > 0)
1932                         purge_addresses();
1933                 if (count)
1934                         blk_run_address_space(target->bt_mapping);
1935
1936         } while (!kthread_should_stop());
1937
1938         return 0;
1939 }
1940
1941 /*
1942  *      Go through all incore buffers, and release buffers if they belong to
1943  *      the given device. This is used in filesystem error handling to
1944  *      preserve the consistency of its metadata.
1945  */
1946 int
1947 xfs_flush_buftarg(
1948         xfs_buftarg_t   *target,
1949         int             wait)
1950 {
1951         xfs_buf_t       *bp;
1952         int             pincount = 0;
1953         LIST_HEAD(tmp_list);
1954         LIST_HEAD(wait_list);
1955
1956         xfs_buf_runall_queues(xfsconvertd_workqueue);
1957         xfs_buf_runall_queues(xfsdatad_workqueue);
1958         xfs_buf_runall_queues(xfslogd_workqueue);
1959
1960         set_bit(XBT_FORCE_FLUSH, &target->bt_flags);
1961         pincount = xfs_buf_delwri_split(target, &tmp_list, 0);
1962
1963         /*
1964          * Dropped the delayed write list lock, now walk the temporary list.
1965          * All I/O is issued async and then if we need to wait for completion
1966          * we do that after issuing all the IO.
1967          */
1968         list_sort(NULL, &tmp_list, xfs_buf_cmp);
1969         while (!list_empty(&tmp_list)) {
1970                 bp = list_first_entry(&tmp_list, struct xfs_buf, b_list);
1971                 ASSERT(target == bp->b_target);
1972                 list_del_init(&bp->b_list);
1973                 if (wait) {
1974                         bp->b_flags &= ~XBF_ASYNC;
1975                         list_add(&bp->b_list, &wait_list);
1976                 }
1977                 xfs_buf_iostrategy(bp);
1978         }
1979
1980         if (wait) {
1981                 /* Expedite and wait for IO to complete. */
1982                 blk_run_address_space(target->bt_mapping);
1983                 while (!list_empty(&wait_list)) {
1984                         bp = list_first_entry(&wait_list, struct xfs_buf, b_list);
1985
1986                         list_del_init(&bp->b_list);
1987                         xfs_iowait(bp);
1988                         xfs_buf_relse(bp);
1989                 }
1990         }
1991
1992         return pincount;
1993 }
1994
1995 int __init
1996 xfs_buf_init(void)
1997 {
1998         xfs_buf_zone = kmem_zone_init_flags(sizeof(xfs_buf_t), "xfs_buf",
1999                                                 KM_ZONE_HWALIGN, NULL);
2000         if (!xfs_buf_zone)
2001                 goto out;
2002
2003         xfslogd_workqueue = create_workqueue("xfslogd");
2004         if (!xfslogd_workqueue)
2005                 goto out_free_buf_zone;
2006
2007         xfsdatad_workqueue = create_workqueue("xfsdatad");
2008         if (!xfsdatad_workqueue)
2009                 goto out_destroy_xfslogd_workqueue;
2010
2011         xfsconvertd_workqueue = create_workqueue("xfsconvertd");
2012         if (!xfsconvertd_workqueue)
2013                 goto out_destroy_xfsdatad_workqueue;
2014
2015         register_shrinker(&xfs_buf_shake);
2016         return 0;
2017
2018  out_destroy_xfsdatad_workqueue:
2019         destroy_workqueue(xfsdatad_workqueue);
2020  out_destroy_xfslogd_workqueue:
2021         destroy_workqueue(xfslogd_workqueue);
2022  out_free_buf_zone:
2023         kmem_zone_destroy(xfs_buf_zone);
2024  out:
2025         return -ENOMEM;
2026 }
2027
2028 void
2029 xfs_buf_terminate(void)
2030 {
2031         unregister_shrinker(&xfs_buf_shake);
2032         destroy_workqueue(xfsconvertd_workqueue);
2033         destroy_workqueue(xfsdatad_workqueue);
2034         destroy_workqueue(xfslogd_workqueue);
2035         kmem_zone_destroy(xfs_buf_zone);
2036 }
2037
2038 #ifdef CONFIG_KDB_MODULES
2039 struct list_head *
2040 xfs_get_buftarg_list(void)
2041 {
2042         return &xfs_buftarg_list;
2043 }
2044 #endif