VServer 1.9.2 (patch-2.6.8.1-vs1.9.2.diff)
[linux-2.6.git] / fs / xfs / linux-2.6 / xfs_buf.c
1 /*
2  * Copyright (c) 2000-2004 Silicon Graphics, Inc.  All Rights Reserved.
3  *
4  * This program is free software; you can redistribute it and/or modify it
5  * under the terms of version 2 of the GNU General Public License as
6  * published by the Free Software Foundation.
7  *
8  * This program is distributed in the hope that it would be useful, but
9  * WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
11  *
12  * Further, this software is distributed without any warranty that it is
13  * free of the rightful claim of any third person regarding infringement
14  * or the like.  Any license provided herein, whether implied or
15  * otherwise, applies only to this software file.  Patent licenses, if
16  * any, provided herein do not apply to combinations of this program with
17  * other software, or any other product whatsoever.
18  *
19  * You should have received a copy of the GNU General Public License along
20  * with this program; if not, write the Free Software Foundation, Inc., 59
21  * Temple Place - Suite 330, Boston MA 02111-1307, USA.
22  *
23  * Contact information: Silicon Graphics, Inc., 1600 Amphitheatre Pkwy,
24  * Mountain View, CA  94043, or:
25  *
26  * http://www.sgi.com
27  *
28  * For further information regarding this notice, see:
29  *
30  * http://oss.sgi.com/projects/GenInfo/SGIGPLNoticeExplan/
31  */
32
33 /*
34  *      The xfs_buf.c code provides an abstract buffer cache model on top
35  *      of the Linux page cache.  Cached metadata blocks for a file system
36  *      are hashed to the inode for the block device.  xfs_buf.c assembles
37  *      buffers (xfs_buf_t) on demand to aggregate such cached pages for I/O.
38  *
39  *      Written by Steve Lord, Jim Mostek, Russell Cattelan
40  *                  and Rajagopal Ananthanarayanan ("ananth") at SGI.
41  *
42  */
43
44 #include <linux/stddef.h>
45 #include <linux/errno.h>
46 #include <linux/slab.h>
47 #include <linux/pagemap.h>
48 #include <linux/init.h>
49 #include <linux/vmalloc.h>
50 #include <linux/bio.h>
51 #include <linux/sysctl.h>
52 #include <linux/proc_fs.h>
53 #include <linux/workqueue.h>
54 #include <linux/suspend.h>
55 #include <linux/percpu.h>
56
57 #include "xfs_linux.h"
58
59 #ifndef GFP_READAHEAD
60 #define GFP_READAHEAD   (__GFP_NOWARN|__GFP_NORETRY)
61 #endif
62
63 /*
64  * File wide globals
65  */
66
67 STATIC kmem_cache_t *pagebuf_cache;
68 STATIC kmem_shaker_t pagebuf_shake;
69 STATIC int pagebuf_daemon_wakeup(int, unsigned int);
70 STATIC void pagebuf_delwri_queue(xfs_buf_t *, int);
71 STATIC struct workqueue_struct *pagebuf_logio_workqueue;
72 STATIC struct workqueue_struct *pagebuf_dataio_workqueue;
73
74 /*
75  * Pagebuf debugging
76  */
77
78 #ifdef PAGEBUF_TRACE
79 void
80 pagebuf_trace(
81         xfs_buf_t       *pb,
82         char            *id,
83         void            *data,
84         void            *ra)
85 {
86         ktrace_enter(pagebuf_trace_buf,
87                 pb, id,
88                 (void *)(unsigned long)pb->pb_flags,
89                 (void *)(unsigned long)pb->pb_hold.counter,
90                 (void *)(unsigned long)pb->pb_sema.count.counter,
91                 (void *)current,
92                 data, ra,
93                 (void *)(unsigned long)((pb->pb_file_offset>>32) & 0xffffffff),
94                 (void *)(unsigned long)(pb->pb_file_offset & 0xffffffff),
95                 (void *)(unsigned long)pb->pb_buffer_length,
96                 NULL, NULL, NULL, NULL, NULL);
97 }
98 ktrace_t *pagebuf_trace_buf;
99 #define PAGEBUF_TRACE_SIZE      4096
100 #define PB_TRACE(pb, id, data)  \
101         pagebuf_trace(pb, id, (void *)data, (void *)__builtin_return_address(0))
102 #else
103 #define PB_TRACE(pb, id, data)  do { } while (0)
104 #endif
105
106 #ifdef PAGEBUF_LOCK_TRACKING
107 # define PB_SET_OWNER(pb)       ((pb)->pb_last_holder = current->pid)
108 # define PB_CLEAR_OWNER(pb)     ((pb)->pb_last_holder = -1)
109 # define PB_GET_OWNER(pb)       ((pb)->pb_last_holder)
110 #else
111 # define PB_SET_OWNER(pb)       do { } while (0)
112 # define PB_CLEAR_OWNER(pb)     do { } while (0)
113 # define PB_GET_OWNER(pb)       do { } while (0)
114 #endif
115
116 /*
117  * Pagebuf allocation / freeing.
118  */
119
120 #define pb_to_gfp(flags) \
121         (((flags) & PBF_READ_AHEAD) ? GFP_READAHEAD : \
122          ((flags) & PBF_DONT_BLOCK) ? GFP_NOFS : GFP_KERNEL)
123
124 #define pb_to_km(flags) \
125          (((flags) & PBF_DONT_BLOCK) ? KM_NOFS : KM_SLEEP)
126
127
128 #define pagebuf_allocate(flags) \
129         kmem_zone_alloc(pagebuf_cache, pb_to_km(flags))
130 #define pagebuf_deallocate(pb) \
131         kmem_zone_free(pagebuf_cache, (pb));
132
133 /*
134  * Pagebuf hashing
135  */
136
137 #define NBITS   8
138 #define NHASH   (1<<NBITS)
139
140 typedef struct {
141         struct list_head        pb_hash;
142         spinlock_t              pb_hash_lock;
143 } pb_hash_t;
144
145 STATIC pb_hash_t        pbhash[NHASH];
146 #define pb_hash(pb)     &pbhash[pb->pb_hash_index]
147
148 STATIC int
149 _bhash(
150         struct block_device *bdev,
151         loff_t          base)
152 {
153         int             bit, hval;
154
155         base >>= 9;
156         base ^= (unsigned long)bdev / L1_CACHE_BYTES;
157         for (bit = hval = 0; base && bit < sizeof(base) * 8; bit += NBITS) {
158                 hval ^= (int)base & (NHASH-1);
159                 base >>= NBITS;
160         }
161         return hval;
162 }
163
164 /*
165  * Mapping of multi-page buffers into contiguous virtual space
166  */
167
168 typedef struct a_list {
169         void            *vm_addr;
170         struct a_list   *next;
171 } a_list_t;
172
173 STATIC a_list_t         *as_free_head;
174 STATIC int              as_list_len;
175 STATIC spinlock_t       as_lock = SPIN_LOCK_UNLOCKED;
176
177 /*
178  * Try to batch vunmaps because they are costly.
179  */
180 STATIC void
181 free_address(
182         void            *addr)
183 {
184         a_list_t        *aentry;
185
186         aentry = kmalloc(sizeof(a_list_t), GFP_ATOMIC);
187         if (aentry) {
188                 spin_lock(&as_lock);
189                 aentry->next = as_free_head;
190                 aentry->vm_addr = addr;
191                 as_free_head = aentry;
192                 as_list_len++;
193                 spin_unlock(&as_lock);
194         } else {
195                 vunmap(addr);
196         }
197 }
198
199 STATIC void
200 purge_addresses(void)
201 {
202         a_list_t        *aentry, *old;
203
204         if (as_free_head == NULL)
205                 return;
206
207         spin_lock(&as_lock);
208         aentry = as_free_head;
209         as_free_head = NULL;
210         as_list_len = 0;
211         spin_unlock(&as_lock);
212
213         while ((old = aentry) != NULL) {
214                 vunmap(aentry->vm_addr);
215                 aentry = aentry->next;
216                 kfree(old);
217         }
218 }
219
220 /*
221  *      Internal pagebuf object manipulation
222  */
223
224 STATIC void
225 _pagebuf_initialize(
226         xfs_buf_t               *pb,
227         xfs_buftarg_t           *target,
228         loff_t                  range_base,
229         size_t                  range_length,
230         page_buf_flags_t        flags)
231 {
232         /*
233          * We don't want certain flags to appear in pb->pb_flags.
234          */
235         flags &= ~(PBF_LOCK|PBF_MAPPED|PBF_DONT_BLOCK|PBF_READ_AHEAD);
236
237         memset(pb, 0, sizeof(xfs_buf_t));
238         atomic_set(&pb->pb_hold, 1);
239         init_MUTEX_LOCKED(&pb->pb_iodonesema);
240         INIT_LIST_HEAD(&pb->pb_list);
241         INIT_LIST_HEAD(&pb->pb_hash_list);
242         init_MUTEX_LOCKED(&pb->pb_sema); /* held, no waiters */
243         PB_SET_OWNER(pb);
244         pb->pb_target = target;
245         pb->pb_file_offset = range_base;
246         /*
247          * Set buffer_length and count_desired to the same value initially.
248          * I/O routines should use count_desired, which will be the same in
249          * most cases but may be reset (e.g. XFS recovery).
250          */
251         pb->pb_buffer_length = pb->pb_count_desired = range_length;
252         pb->pb_flags = flags | PBF_NONE;
253         pb->pb_bn = XFS_BUF_DADDR_NULL;
254         atomic_set(&pb->pb_pin_count, 0);
255         init_waitqueue_head(&pb->pb_waiters);
256
257         XFS_STATS_INC(pb_create);
258         PB_TRACE(pb, "initialize", target);
259 }
260
261 /*
262  * Allocate a page array capable of holding a specified number
263  * of pages, and point the page buf at it.
264  */
265 STATIC int
266 _pagebuf_get_pages(
267         xfs_buf_t               *pb,
268         int                     page_count,
269         page_buf_flags_t        flags)
270 {
271         /* Make sure that we have a page list */
272         if (pb->pb_pages == NULL) {
273                 pb->pb_offset = page_buf_poff(pb->pb_file_offset);
274                 pb->pb_page_count = page_count;
275                 if (page_count <= PB_PAGES) {
276                         pb->pb_pages = pb->pb_page_array;
277                 } else {
278                         pb->pb_pages = kmem_alloc(sizeof(struct page *) *
279                                         page_count, pb_to_km(flags));
280                         if (pb->pb_pages == NULL)
281                                 return -ENOMEM;
282                 }
283                 memset(pb->pb_pages, 0, sizeof(struct page *) * page_count);
284         }
285         return 0;
286 }
287
288 /*
289  *      Frees pb_pages if it was malloced.
290  */
291 STATIC void
292 _pagebuf_free_pages(
293         xfs_buf_t       *bp)
294 {
295         if (bp->pb_pages != bp->pb_page_array) {
296                 kmem_free(bp->pb_pages,
297                           bp->pb_page_count * sizeof(struct page *));
298         }
299 }
300
301 /*
302  *      Releases the specified buffer.
303  *
304  *      The modification state of any associated pages is left unchanged.
305  *      The buffer most not be on any hash - use pagebuf_rele instead for
306  *      hashed and refcounted buffers
307  */
308 void
309 pagebuf_free(
310         xfs_buf_t               *bp)
311 {
312         PB_TRACE(bp, "free", 0);
313
314         ASSERT(list_empty(&bp->pb_hash_list));
315
316         if (bp->pb_flags & _PBF_PAGE_CACHE) {
317                 uint            i;
318
319                 if ((bp->pb_flags & PBF_MAPPED) && (bp->pb_page_count > 1))
320                         free_address(bp->pb_addr - bp->pb_offset);
321
322                 for (i = 0; i < bp->pb_page_count; i++)
323                         page_cache_release(bp->pb_pages[i]);
324                 _pagebuf_free_pages(bp);
325         } else if (bp->pb_flags & _PBF_KMEM_ALLOC) {
326                  /*
327                   * XXX(hch): bp->pb_count_desired might be incorrect (see
328                   * pagebuf_associate_memory for details), but fortunately
329                   * the Linux version of kmem_free ignores the len argument..
330                   */
331                 kmem_free(bp->pb_addr, bp->pb_count_desired);
332                 _pagebuf_free_pages(bp);
333         }
334
335         pagebuf_deallocate(bp);
336 }
337
338 /*
339  *      Finds all pages for buffer in question and builds it's page list.
340  */
341 STATIC int
342 _pagebuf_lookup_pages(
343         xfs_buf_t               *bp,
344         uint                    flags)
345 {
346         struct address_space    *mapping = bp->pb_target->pbr_mapping;
347         unsigned int            sectorshift = bp->pb_target->pbr_sshift;
348         size_t                  blocksize = bp->pb_target->pbr_bsize;
349         size_t                  size = bp->pb_count_desired;
350         size_t                  nbytes, offset;
351         int                     gfp_mask = pb_to_gfp(flags);
352         unsigned short          page_count, i;
353         pgoff_t                 first;
354         loff_t                  end;
355         int                     error;
356
357         end = bp->pb_file_offset + bp->pb_buffer_length;
358         page_count = page_buf_btoc(end) - page_buf_btoct(bp->pb_file_offset);
359
360         error = _pagebuf_get_pages(bp, page_count, flags);
361         if (unlikely(error))
362                 return error;
363         bp->pb_flags |= _PBF_PAGE_CACHE;
364
365         offset = bp->pb_offset;
366         first = bp->pb_file_offset >> PAGE_CACHE_SHIFT;
367
368         for (i = 0; i < bp->pb_page_count; i++) {
369                 struct page     *page;
370                 uint            retries = 0;
371
372               retry:
373                 page = find_or_create_page(mapping, first + i, gfp_mask);
374                 if (unlikely(page == NULL)) {
375                         if (flags & PBF_READ_AHEAD) {
376                                 bp->pb_page_count = i;
377                                 for (i = 0; i < bp->pb_page_count; i++)
378                                         unlock_page(bp->pb_pages[i]);
379                                 return -ENOMEM;
380                         }
381
382                         /*
383                          * This could deadlock.
384                          *
385                          * But until all the XFS lowlevel code is revamped to
386                          * handle buffer allocation failures we can't do much.
387                          */
388                         if (!(++retries % 100))
389                                 printk(KERN_ERR
390                                         "possible deadlock in %s (mode:0x%x)\n",
391                                         __FUNCTION__, gfp_mask);
392
393                         XFS_STATS_INC(pb_page_retries);
394                         pagebuf_daemon_wakeup(0, gfp_mask);
395                         set_current_state(TASK_UNINTERRUPTIBLE);
396                         schedule_timeout(10);
397                         goto retry;
398                 }
399
400                 XFS_STATS_INC(pb_page_found);
401
402                 nbytes = min_t(size_t, size, PAGE_CACHE_SIZE - offset);
403                 size -= nbytes;
404
405                 if (!PageUptodate(page)) {
406                         page_count--;
407                         if (blocksize == PAGE_CACHE_SIZE) {
408                                 if (flags & PBF_READ)
409                                         bp->pb_locked = 1;
410                         } else if (!PagePrivate(page)) {
411                                 unsigned long   j, range;
412
413                                 /*
414                                  * In this case page->private holds a bitmap
415                                  * of uptodate sectors within the page
416                                  */
417                                 ASSERT(blocksize < PAGE_CACHE_SIZE);
418                                 range = (offset + nbytes) >> sectorshift;
419                                 for (j = offset >> sectorshift; j < range; j++)
420                                         if (!test_bit(j, &page->private))
421                                                 break;
422                                 if (j == range)
423                                         page_count++;
424                         }
425                 }
426
427                 bp->pb_pages[i] = page;
428                 offset = 0;
429         }
430
431         if (!bp->pb_locked) {
432                 for (i = 0; i < bp->pb_page_count; i++)
433                         unlock_page(bp->pb_pages[i]);
434         }
435
436         if (page_count) {
437                 /* if we have any uptodate pages, mark that in the buffer */
438                 bp->pb_flags &= ~PBF_NONE;
439
440                 /* if some pages aren't uptodate, mark that in the buffer */
441                 if (page_count != bp->pb_page_count)
442                         bp->pb_flags |= PBF_PARTIAL;
443         }
444
445         PB_TRACE(bp, "lookup_pages", (long)page_count);
446         return error;
447 }
448
449 /*
450  *      Map buffer into kernel address-space if nessecary.
451  */
452 STATIC int
453 _pagebuf_map_pages(
454         xfs_buf_t               *bp,
455         uint                    flags)
456 {
457         /* A single page buffer is always mappable */
458         if (bp->pb_page_count == 1) {
459                 bp->pb_addr = page_address(bp->pb_pages[0]) + bp->pb_offset;
460                 bp->pb_flags |= PBF_MAPPED;
461         } else if (flags & PBF_MAPPED) {
462                 if (as_list_len > 64)
463                         purge_addresses();
464                 bp->pb_addr = vmap(bp->pb_pages, bp->pb_page_count,
465                                 VM_MAP, PAGE_KERNEL);
466                 if (unlikely(bp->pb_addr == NULL))
467                         return -ENOMEM;
468                 bp->pb_addr += bp->pb_offset;
469                 bp->pb_flags |= PBF_MAPPED;
470         }
471
472         return 0;
473 }
474
475 /*
476  *      Finding and Reading Buffers
477  */
478
479 /*
480  *      _pagebuf_find
481  *
482  *      Looks up, and creates if absent, a lockable buffer for
483  *      a given range of an inode.  The buffer is returned
484  *      locked.  If other overlapping buffers exist, they are
485  *      released before the new buffer is created and locked,
486  *      which may imply that this call will block until those buffers
487  *      are unlocked.  No I/O is implied by this call.
488  */
489 STATIC xfs_buf_t *
490 _pagebuf_find(                          /* find buffer for block        */
491         xfs_buftarg_t           *target,/* target for block             */
492         loff_t                  ioff,   /* starting offset of range     */
493         size_t                  isize,  /* length of range              */
494         page_buf_flags_t        flags,  /* PBF_TRYLOCK                  */
495         xfs_buf_t               *new_pb)/* newly allocated buffer       */
496 {
497         loff_t                  range_base;
498         size_t                  range_length;
499         int                     hval;
500         pb_hash_t               *h;
501         xfs_buf_t               *pb, *n;
502         int                     not_locked;
503
504         range_base = (ioff << BBSHIFT);
505         range_length = (isize << BBSHIFT);
506
507         /* Ensure we never do IOs smaller than the sector size */
508         BUG_ON(range_length < (1 << target->pbr_sshift));
509
510         /* Ensure we never do IOs that are not sector aligned */
511         BUG_ON(range_base & (loff_t)target->pbr_smask);
512
513         hval = _bhash(target->pbr_bdev, range_base);
514         h = &pbhash[hval];
515
516         spin_lock(&h->pb_hash_lock);
517         list_for_each_entry_safe(pb, n, &h->pb_hash, pb_hash_list) {
518                 if (pb->pb_target == target &&
519                     pb->pb_file_offset == range_base &&
520                     pb->pb_buffer_length == range_length) {
521                         /* If we look at something bring it to the
522                          * front of the list for next time
523                          */
524                         atomic_inc(&pb->pb_hold);
525                         list_move(&pb->pb_hash_list, &h->pb_hash);
526                         goto found;
527                 }
528         }
529
530         /* No match found */
531         if (new_pb) {
532                 _pagebuf_initialize(new_pb, target, range_base,
533                                 range_length, flags);
534                 new_pb->pb_hash_index = hval;
535                 list_add(&new_pb->pb_hash_list, &h->pb_hash);
536         } else {
537                 XFS_STATS_INC(pb_miss_locked);
538         }
539
540         spin_unlock(&h->pb_hash_lock);
541         return (new_pb);
542
543 found:
544         spin_unlock(&h->pb_hash_lock);
545
546         /* Attempt to get the semaphore without sleeping,
547          * if this does not work then we need to drop the
548          * spinlock and do a hard attempt on the semaphore.
549          */
550         not_locked = down_trylock(&pb->pb_sema);
551         if (not_locked) {
552                 if (!(flags & PBF_TRYLOCK)) {
553                         /* wait for buffer ownership */
554                         PB_TRACE(pb, "get_lock", 0);
555                         pagebuf_lock(pb);
556                         XFS_STATS_INC(pb_get_locked_waited);
557                 } else {
558                         /* We asked for a trylock and failed, no need
559                          * to look at file offset and length here, we
560                          * know that this pagebuf at least overlaps our
561                          * pagebuf and is locked, therefore our buffer
562                          * either does not exist, or is this buffer
563                          */
564
565                         pagebuf_rele(pb);
566                         XFS_STATS_INC(pb_busy_locked);
567                         return (NULL);
568                 }
569         } else {
570                 /* trylock worked */
571                 PB_SET_OWNER(pb);
572         }
573
574         if (pb->pb_flags & PBF_STALE)
575                 pb->pb_flags &= PBF_MAPPED;
576         PB_TRACE(pb, "got_lock", 0);
577         XFS_STATS_INC(pb_get_locked);
578         return (pb);
579 }
580
581
582 /*
583  *      pagebuf_find
584  *
585  *      pagebuf_find returns a buffer matching the specified range of
586  *      data for the specified target, if any of the relevant blocks
587  *      are in memory.  The buffer may have unallocated holes, if
588  *      some, but not all, of the blocks are in memory.  Even where
589  *      pages are present in the buffer, not all of every page may be
590  *      valid.
591  */
592 xfs_buf_t *
593 pagebuf_find(                           /* find buffer for block        */
594                                         /* if the block is in memory    */
595         xfs_buftarg_t           *target,/* target for block             */
596         loff_t                  ioff,   /* starting offset of range     */
597         size_t                  isize,  /* length of range              */
598         page_buf_flags_t        flags)  /* PBF_TRYLOCK                  */
599 {
600         return _pagebuf_find(target, ioff, isize, flags, NULL);
601 }
602
603 /*
604  *      pagebuf_get
605  *
606  *      pagebuf_get assembles a buffer covering the specified range.
607  *      Some or all of the blocks in the range may be valid.  Storage
608  *      in memory for all portions of the buffer will be allocated,
609  *      although backing storage may not be.  If PBF_READ is set in
610  *      flags, pagebuf_iostart is called also.
611  */
612 xfs_buf_t *
613 pagebuf_get(                            /* allocate a buffer            */
614         xfs_buftarg_t           *target,/* target for buffer            */
615         loff_t                  ioff,   /* starting offset of range     */
616         size_t                  isize,  /* length of range              */
617         page_buf_flags_t        flags)  /* PBF_TRYLOCK                  */
618 {
619         xfs_buf_t               *pb, *new_pb;
620         int                     error = 0, i;
621
622         new_pb = pagebuf_allocate(flags);
623         if (unlikely(!new_pb))
624                 return NULL;
625
626         pb = _pagebuf_find(target, ioff, isize, flags, new_pb);
627         if (pb == new_pb) {
628                 error = _pagebuf_lookup_pages(pb, flags);
629                 if (unlikely(error)) {
630                         printk(KERN_WARNING
631                                "pagebuf_get: failed to lookup pages\n");
632                         goto no_buffer;
633                 }
634         } else {
635                 pagebuf_deallocate(new_pb);
636                 if (unlikely(pb == NULL))
637                         return NULL;
638         }
639
640         for (i = 0; i < pb->pb_page_count; i++)
641                 mark_page_accessed(pb->pb_pages[i]);
642
643         if (!(pb->pb_flags & PBF_MAPPED)) {
644                 error = _pagebuf_map_pages(pb, flags);
645                 if (unlikely(error)) {
646                         printk(KERN_WARNING
647                                "pagebuf_get: failed to map pages\n");
648                         goto no_buffer;
649                 }
650         }
651
652         XFS_STATS_INC(pb_get);
653
654         /*
655          * Always fill in the block number now, the mapped cases can do
656          * their own overlay of this later.
657          */
658         pb->pb_bn = ioff;
659         pb->pb_count_desired = pb->pb_buffer_length;
660
661         if (flags & PBF_READ) {
662                 if (PBF_NOT_DONE(pb)) {
663                         PB_TRACE(pb, "get_read", (unsigned long)flags);
664                         XFS_STATS_INC(pb_get_read);
665                         pagebuf_iostart(pb, flags);
666                 } else if (flags & PBF_ASYNC) {
667                         PB_TRACE(pb, "get_read_async", (unsigned long)flags);
668                         /*
669                          * Read ahead call which is already satisfied,
670                          * drop the buffer
671                          */
672                         goto no_buffer;
673                 } else {
674                         PB_TRACE(pb, "get_read_done", (unsigned long)flags);
675                         /* We do not want read in the flags */
676                         pb->pb_flags &= ~PBF_READ;
677                 }
678         } else {
679                 PB_TRACE(pb, "get_write", (unsigned long)flags);
680         }
681
682         return pb;
683
684 no_buffer:
685         if (flags & (PBF_LOCK | PBF_TRYLOCK))
686                 pagebuf_unlock(pb);
687         pagebuf_rele(pb);
688         return NULL;
689 }
690
691 /*
692  * Create a skeletal pagebuf (no pages associated with it).
693  */
694 xfs_buf_t *
695 pagebuf_lookup(
696         xfs_buftarg_t           *target,
697         loff_t                  ioff,
698         size_t                  isize,
699         page_buf_flags_t        flags)
700 {
701         xfs_buf_t               *pb;
702
703         pb = pagebuf_allocate(flags);
704         if (pb) {
705                 _pagebuf_initialize(pb, target, ioff, isize, flags);
706         }
707         return pb;
708 }
709
710 /*
711  * If we are not low on memory then do the readahead in a deadlock
712  * safe manner.
713  */
714 void
715 pagebuf_readahead(
716         xfs_buftarg_t           *target,
717         loff_t                  ioff,
718         size_t                  isize,
719         page_buf_flags_t        flags)
720 {
721         struct backing_dev_info *bdi;
722
723         bdi = target->pbr_mapping->backing_dev_info;
724         if (bdi_read_congested(bdi))
725                 return;
726         if (bdi_write_congested(bdi))
727                 return;
728
729         flags |= (PBF_TRYLOCK|PBF_READ|PBF_ASYNC|PBF_READ_AHEAD);
730         pagebuf_get(target, ioff, isize, flags);
731 }
732
733 xfs_buf_t *
734 pagebuf_get_empty(
735         size_t                  len,
736         xfs_buftarg_t           *target)
737 {
738         xfs_buf_t               *pb;
739
740         pb = pagebuf_allocate(0);
741         if (pb)
742                 _pagebuf_initialize(pb, target, 0, len, 0);
743         return pb;
744 }
745
746 static inline struct page *
747 mem_to_page(
748         void                    *addr)
749 {
750         if (((unsigned long)addr < VMALLOC_START) ||
751             ((unsigned long)addr >= VMALLOC_END)) {
752                 return virt_to_page(addr);
753         } else {
754                 return vmalloc_to_page(addr);
755         }
756 }
757
758 int
759 pagebuf_associate_memory(
760         xfs_buf_t               *pb,
761         void                    *mem,
762         size_t                  len)
763 {
764         int                     rval;
765         int                     i = 0;
766         size_t                  ptr;
767         size_t                  end, end_cur;
768         off_t                   offset;
769         int                     page_count;
770
771         page_count = PAGE_CACHE_ALIGN(len) >> PAGE_CACHE_SHIFT;
772         offset = (off_t) mem - ((off_t)mem & PAGE_CACHE_MASK);
773         if (offset && (len > PAGE_CACHE_SIZE))
774                 page_count++;
775
776         /* Free any previous set of page pointers */
777         if (pb->pb_pages)
778                 _pagebuf_free_pages(pb);
779
780         pb->pb_pages = NULL;
781         pb->pb_addr = mem;
782
783         rval = _pagebuf_get_pages(pb, page_count, 0);
784         if (rval)
785                 return rval;
786
787         pb->pb_offset = offset;
788         ptr = (size_t) mem & PAGE_CACHE_MASK;
789         end = PAGE_CACHE_ALIGN((size_t) mem + len);
790         end_cur = end;
791         /* set up first page */
792         pb->pb_pages[0] = mem_to_page(mem);
793
794         ptr += PAGE_CACHE_SIZE;
795         pb->pb_page_count = ++i;
796         while (ptr < end) {
797                 pb->pb_pages[i] = mem_to_page((void *)ptr);
798                 pb->pb_page_count = ++i;
799                 ptr += PAGE_CACHE_SIZE;
800         }
801         pb->pb_locked = 0;
802
803         pb->pb_count_desired = pb->pb_buffer_length = len;
804         pb->pb_flags |= PBF_MAPPED;
805
806         return 0;
807 }
808
809 xfs_buf_t *
810 pagebuf_get_no_daddr(
811         size_t                  len,
812         xfs_buftarg_t           *target)
813 {
814         size_t                  malloc_len = len;
815         xfs_buf_t               *bp;
816         void                    *data;
817         int                     error;
818
819         bp = pagebuf_allocate(0);
820         if (unlikely(bp == NULL))
821                 goto fail;
822         _pagebuf_initialize(bp, target, 0, len, PBF_FORCEIO);
823
824  try_again:
825         data = kmem_alloc(malloc_len, KM_SLEEP | KM_MAYFAIL);
826         if (unlikely(data == NULL))
827                 goto fail_free_buf;
828
829         /* check whether alignment matches.. */
830         if ((__psunsigned_t)data !=
831             ((__psunsigned_t)data & ~target->pbr_smask)) {
832                 /* .. else double the size and try again */
833                 kmem_free(data, malloc_len);
834                 malloc_len <<= 1;
835                 goto try_again;
836         }
837
838         error = pagebuf_associate_memory(bp, data, len);
839         if (error)
840                 goto fail_free_mem;
841         bp->pb_flags |= _PBF_KMEM_ALLOC;
842
843         pagebuf_unlock(bp);
844
845         PB_TRACE(bp, "no_daddr", data);
846         return bp;
847  fail_free_mem:
848         kmem_free(data, malloc_len);
849  fail_free_buf:
850         pagebuf_free(bp);
851  fail:
852         return NULL;
853 }
854
855 /*
856  *      pagebuf_hold
857  *
858  *      Increment reference count on buffer, to hold the buffer concurrently
859  *      with another thread which may release (free) the buffer asynchronously.
860  *
861  *      Must hold the buffer already to call this function.
862  */
863 void
864 pagebuf_hold(
865         xfs_buf_t               *pb)
866 {
867         atomic_inc(&pb->pb_hold);
868         PB_TRACE(pb, "hold", 0);
869 }
870
871 /*
872  *      pagebuf_rele
873  *
874  *      pagebuf_rele releases a hold on the specified buffer.  If the
875  *      the hold count is 1, pagebuf_rele calls pagebuf_free.
876  */
877 void
878 pagebuf_rele(
879         xfs_buf_t               *pb)
880 {
881         pb_hash_t               *hash = pb_hash(pb);
882
883         PB_TRACE(pb, "rele", pb->pb_relse);
884
885         if (atomic_dec_and_lock(&pb->pb_hold, &hash->pb_hash_lock)) {
886                 int             do_free = 1;
887
888                 if (pb->pb_relse) {
889                         atomic_inc(&pb->pb_hold);
890                         spin_unlock(&hash->pb_hash_lock);
891                         (*(pb->pb_relse)) (pb);
892                         spin_lock(&hash->pb_hash_lock);
893                         do_free = 0;
894                 }
895
896                 if (pb->pb_flags & PBF_DELWRI) {
897                         pb->pb_flags |= PBF_ASYNC;
898                         atomic_inc(&pb->pb_hold);
899                         pagebuf_delwri_queue(pb, 0);
900                         do_free = 0;
901                 } else if (pb->pb_flags & PBF_FS_MANAGED) {
902                         do_free = 0;
903                 }
904
905                 if (do_free) {
906                         list_del_init(&pb->pb_hash_list);
907                         spin_unlock(&hash->pb_hash_lock);
908                         pagebuf_free(pb);
909                 } else {
910                         spin_unlock(&hash->pb_hash_lock);
911                 }
912         }
913 }
914
915
916 /*
917  *      Mutual exclusion on buffers.  Locking model:
918  *
919  *      Buffers associated with inodes for which buffer locking
920  *      is not enabled are not protected by semaphores, and are
921  *      assumed to be exclusively owned by the caller.  There is a
922  *      spinlock in the buffer, used by the caller when concurrent
923  *      access is possible.
924  */
925
926 /*
927  *      pagebuf_cond_lock
928  *
929  *      pagebuf_cond_lock locks a buffer object, if it is not already locked.
930  *      Note that this in no way
931  *      locks the underlying pages, so it is only useful for synchronizing
932  *      concurrent use of page buffer objects, not for synchronizing independent
933  *      access to the underlying pages.
934  */
935 int
936 pagebuf_cond_lock(                      /* lock buffer, if not locked   */
937                                         /* returns -EBUSY if locked)    */
938         xfs_buf_t               *pb)
939 {
940         int                     locked;
941
942         locked = down_trylock(&pb->pb_sema) == 0;
943         if (locked) {
944                 PB_SET_OWNER(pb);
945         }
946         PB_TRACE(pb, "cond_lock", (long)locked);
947         return(locked ? 0 : -EBUSY);
948 }
949
950 /*
951  *      pagebuf_lock_value
952  *
953  *      Return lock value for a pagebuf
954  */
955 int
956 pagebuf_lock_value(
957         xfs_buf_t               *pb)
958 {
959         return(atomic_read(&pb->pb_sema.count));
960 }
961
962 /*
963  *      pagebuf_lock
964  *
965  *      pagebuf_lock locks a buffer object.  Note that this in no way
966  *      locks the underlying pages, so it is only useful for synchronizing
967  *      concurrent use of page buffer objects, not for synchronizing independent
968  *      access to the underlying pages.
969  */
970 int
971 pagebuf_lock(
972         xfs_buf_t               *pb)
973 {
974         PB_TRACE(pb, "lock", 0);
975         if (atomic_read(&pb->pb_io_remaining))
976                 blk_run_address_space(pb->pb_target->pbr_mapping);
977         down(&pb->pb_sema);
978         PB_SET_OWNER(pb);
979         PB_TRACE(pb, "locked", 0);
980         return 0;
981 }
982
983 /*
984  *      pagebuf_unlock
985  *
986  *      pagebuf_unlock releases the lock on the buffer object created by
987  *      pagebuf_lock or pagebuf_cond_lock (not any
988  *      pinning of underlying pages created by pagebuf_pin).
989  */
990 void
991 pagebuf_unlock(                         /* unlock buffer                */
992         xfs_buf_t               *pb)    /* buffer to unlock             */
993 {
994         PB_CLEAR_OWNER(pb);
995         up(&pb->pb_sema);
996         PB_TRACE(pb, "unlock", 0);
997 }
998
999
1000 /*
1001  *      Pinning Buffer Storage in Memory
1002  */
1003
1004 /*
1005  *      pagebuf_pin
1006  *
1007  *      pagebuf_pin locks all of the memory represented by a buffer in
1008  *      memory.  Multiple calls to pagebuf_pin and pagebuf_unpin, for
1009  *      the same or different buffers affecting a given page, will
1010  *      properly count the number of outstanding "pin" requests.  The
1011  *      buffer may be released after the pagebuf_pin and a different
1012  *      buffer used when calling pagebuf_unpin, if desired.
1013  *      pagebuf_pin should be used by the file system when it wants be
1014  *      assured that no attempt will be made to force the affected
1015  *      memory to disk.  It does not assure that a given logical page
1016  *      will not be moved to a different physical page.
1017  */
1018 void
1019 pagebuf_pin(
1020         xfs_buf_t               *pb)
1021 {
1022         atomic_inc(&pb->pb_pin_count);
1023         PB_TRACE(pb, "pin", (long)pb->pb_pin_count.counter);
1024 }
1025
1026 /*
1027  *      pagebuf_unpin
1028  *
1029  *      pagebuf_unpin reverses the locking of memory performed by
1030  *      pagebuf_pin.  Note that both functions affected the logical
1031  *      pages associated with the buffer, not the buffer itself.
1032  */
1033 void
1034 pagebuf_unpin(
1035         xfs_buf_t               *pb)
1036 {
1037         if (atomic_dec_and_test(&pb->pb_pin_count)) {
1038                 wake_up_all(&pb->pb_waiters);
1039         }
1040         PB_TRACE(pb, "unpin", (long)pb->pb_pin_count.counter);
1041 }
1042
1043 int
1044 pagebuf_ispin(
1045         xfs_buf_t               *pb)
1046 {
1047         return atomic_read(&pb->pb_pin_count);
1048 }
1049
1050 /*
1051  *      pagebuf_wait_unpin
1052  *
1053  *      pagebuf_wait_unpin waits until all of the memory associated
1054  *      with the buffer is not longer locked in memory.  It returns
1055  *      immediately if none of the affected pages are locked.
1056  */
1057 static inline void
1058 _pagebuf_wait_unpin(
1059         xfs_buf_t               *pb)
1060 {
1061         DECLARE_WAITQUEUE       (wait, current);
1062
1063         if (atomic_read(&pb->pb_pin_count) == 0)
1064                 return;
1065
1066         add_wait_queue(&pb->pb_waiters, &wait);
1067         for (;;) {
1068                 set_current_state(TASK_UNINTERRUPTIBLE);
1069                 if (atomic_read(&pb->pb_pin_count) == 0)
1070                         break;
1071                 if (atomic_read(&pb->pb_io_remaining))
1072                         blk_run_address_space(pb->pb_target->pbr_mapping);
1073                 schedule();
1074         }
1075         remove_wait_queue(&pb->pb_waiters, &wait);
1076         set_current_state(TASK_RUNNING);
1077 }
1078
1079 /*
1080  *      Buffer Utility Routines
1081  */
1082
1083 /*
1084  *      pagebuf_iodone
1085  *
1086  *      pagebuf_iodone marks a buffer for which I/O is in progress
1087  *      done with respect to that I/O.  The pb_iodone routine, if
1088  *      present, will be called as a side-effect.
1089  */
1090 void
1091 pagebuf_iodone_work(
1092         void                    *v)
1093 {
1094         xfs_buf_t               *bp = (xfs_buf_t *)v;
1095
1096         if (bp->pb_iodone)
1097                 (*(bp->pb_iodone))(bp);
1098         else if (bp->pb_flags & PBF_ASYNC)
1099                 xfs_buf_relse(bp);
1100 }
1101
1102 void
1103 pagebuf_iodone(
1104         xfs_buf_t               *pb,
1105         int                     dataio,
1106         int                     schedule)
1107 {
1108         pb->pb_flags &= ~(PBF_READ | PBF_WRITE);
1109         if (pb->pb_error == 0) {
1110                 pb->pb_flags &= ~(PBF_PARTIAL | PBF_NONE);
1111         }
1112
1113         PB_TRACE(pb, "iodone", pb->pb_iodone);
1114
1115         if ((pb->pb_iodone) || (pb->pb_flags & PBF_ASYNC)) {
1116                 if (schedule) {
1117                         INIT_WORK(&pb->pb_iodone_work, pagebuf_iodone_work, pb);
1118                         queue_work(dataio ? pagebuf_dataio_workqueue :
1119                                 pagebuf_logio_workqueue, &pb->pb_iodone_work);
1120                 } else {
1121                         pagebuf_iodone_work(pb);
1122                 }
1123         } else {
1124                 up(&pb->pb_iodonesema);
1125         }
1126 }
1127
1128 /*
1129  *      pagebuf_ioerror
1130  *
1131  *      pagebuf_ioerror sets the error code for a buffer.
1132  */
1133 void
1134 pagebuf_ioerror(                        /* mark/clear buffer error flag */
1135         xfs_buf_t               *pb,    /* buffer to mark               */
1136         int                     error)  /* error to store (0 if none)   */
1137 {
1138         ASSERT(error >= 0 && error <= 0xffff);
1139         pb->pb_error = (unsigned short)error;
1140         PB_TRACE(pb, "ioerror", (unsigned long)error);
1141 }
1142
1143 /*
1144  *      pagebuf_iostart
1145  *
1146  *      pagebuf_iostart initiates I/O on a buffer, based on the flags supplied.
1147  *      If necessary, it will arrange for any disk space allocation required,
1148  *      and it will break up the request if the block mappings require it.
1149  *      The pb_iodone routine in the buffer supplied will only be called
1150  *      when all of the subsidiary I/O requests, if any, have been completed.
1151  *      pagebuf_iostart calls the pagebuf_ioinitiate routine or
1152  *      pagebuf_iorequest, if the former routine is not defined, to start
1153  *      the I/O on a given low-level request.
1154  */
1155 int
1156 pagebuf_iostart(                        /* start I/O on a buffer          */
1157         xfs_buf_t               *pb,    /* buffer to start                */
1158         page_buf_flags_t        flags)  /* PBF_LOCK, PBF_ASYNC, PBF_READ, */
1159                                         /* PBF_WRITE, PBF_DELWRI,         */
1160                                         /* PBF_DONT_BLOCK                 */
1161 {
1162         int                     status = 0;
1163
1164         PB_TRACE(pb, "iostart", (unsigned long)flags);
1165
1166         if (flags & PBF_DELWRI) {
1167                 pb->pb_flags &= ~(PBF_READ | PBF_WRITE | PBF_ASYNC);
1168                 pb->pb_flags |= flags & (PBF_DELWRI | PBF_ASYNC);
1169                 pagebuf_delwri_queue(pb, 1);
1170                 return status;
1171         }
1172
1173         pb->pb_flags &= ~(PBF_READ | PBF_WRITE | PBF_ASYNC | PBF_DELWRI | \
1174                         PBF_READ_AHEAD | _PBF_RUN_QUEUES);
1175         pb->pb_flags |= flags & (PBF_READ | PBF_WRITE | PBF_ASYNC | \
1176                         PBF_READ_AHEAD | _PBF_RUN_QUEUES);
1177
1178         BUG_ON(pb->pb_bn == XFS_BUF_DADDR_NULL);
1179
1180         /* For writes allow an alternate strategy routine to precede
1181          * the actual I/O request (which may not be issued at all in
1182          * a shutdown situation, for example).
1183          */
1184         status = (flags & PBF_WRITE) ?
1185                 pagebuf_iostrategy(pb) : pagebuf_iorequest(pb);
1186
1187         /* Wait for I/O if we are not an async request.
1188          * Note: async I/O request completion will release the buffer,
1189          * and that can already be done by this point.  So using the
1190          * buffer pointer from here on, after async I/O, is invalid.
1191          */
1192         if (!status && !(flags & PBF_ASYNC))
1193                 status = pagebuf_iowait(pb);
1194
1195         return status;
1196 }
1197
1198 /*
1199  * Helper routine for pagebuf_iorequest
1200  */
1201
1202 STATIC __inline__ int
1203 _pagebuf_iolocked(
1204         xfs_buf_t               *pb)
1205 {
1206         ASSERT(pb->pb_flags & (PBF_READ|PBF_WRITE));
1207         if (pb->pb_flags & PBF_READ)
1208                 return pb->pb_locked;
1209         return 0;
1210 }
1211
1212 STATIC __inline__ void
1213 _pagebuf_iodone(
1214         xfs_buf_t               *pb,
1215         int                     schedule)
1216 {
1217         if (atomic_dec_and_test(&pb->pb_io_remaining) == 1) {
1218                 pb->pb_locked = 0;
1219                 pagebuf_iodone(pb, (pb->pb_flags & PBF_FS_DATAIOD), schedule);
1220         }
1221 }
1222
1223 STATIC int
1224 bio_end_io_pagebuf(
1225         struct bio              *bio,
1226         unsigned int            bytes_done,
1227         int                     error)
1228 {
1229         xfs_buf_t               *pb = (xfs_buf_t *)bio->bi_private;
1230         unsigned int            i, blocksize = pb->pb_target->pbr_bsize;
1231         unsigned int            sectorshift = pb->pb_target->pbr_sshift;
1232         struct bio_vec          *bvec = bio->bi_io_vec;
1233
1234         if (bio->bi_size)
1235                 return 1;
1236
1237         if (!test_bit(BIO_UPTODATE, &bio->bi_flags))
1238                 pb->pb_error = EIO;
1239
1240         for (i = 0; i < bio->bi_vcnt; i++, bvec++) {
1241                 struct page     *page = bvec->bv_page;
1242
1243                 if (pb->pb_error) {
1244                         SetPageError(page);
1245                 } else if (blocksize == PAGE_CACHE_SIZE) {
1246                         SetPageUptodate(page);
1247                 } else if (!PagePrivate(page) &&
1248                                 (pb->pb_flags & _PBF_PAGE_CACHE)) {
1249                         unsigned long   j, range;
1250
1251                         ASSERT(blocksize < PAGE_CACHE_SIZE);
1252                         range = (bvec->bv_offset + bvec->bv_len) >> sectorshift;
1253                         for (j = bvec->bv_offset >> sectorshift; j < range; j++)
1254                                 set_bit(j, &page->private);
1255                         if (page->private == (unsigned long)(PAGE_CACHE_SIZE-1))
1256                                 SetPageUptodate(page);
1257                 }
1258
1259                 if (_pagebuf_iolocked(pb)) {
1260                         unlock_page(page);
1261                 }
1262         }
1263
1264         _pagebuf_iodone(pb, 1);
1265         bio_put(bio);
1266         return 0;
1267 }
1268
1269 void
1270 _pagebuf_ioapply(
1271         xfs_buf_t               *pb)
1272 {
1273         int                     i, map_i, total_nr_pages, nr_pages;
1274         struct bio              *bio;
1275         int                     offset = pb->pb_offset;
1276         int                     size = pb->pb_count_desired;
1277         sector_t                sector = pb->pb_bn;
1278         unsigned int            blocksize = pb->pb_target->pbr_bsize;
1279         int                     locking = _pagebuf_iolocked(pb);
1280
1281         total_nr_pages = pb->pb_page_count;
1282         map_i = 0;
1283
1284         /* Special code path for reading a sub page size pagebuf in --
1285          * we populate up the whole page, and hence the other metadata
1286          * in the same page.  This optimization is only valid when the
1287          * filesystem block size and the page size are equal.
1288          */
1289         if ((pb->pb_buffer_length < PAGE_CACHE_SIZE) &&
1290             (pb->pb_flags & PBF_READ) && locking &&
1291             (blocksize == PAGE_CACHE_SIZE)) {
1292                 bio = bio_alloc(GFP_NOIO, 1);
1293
1294                 bio->bi_bdev = pb->pb_target->pbr_bdev;
1295                 bio->bi_sector = sector - (offset >> BBSHIFT);
1296                 bio->bi_end_io = bio_end_io_pagebuf;
1297                 bio->bi_private = pb;
1298
1299                 bio_add_page(bio, pb->pb_pages[0], PAGE_CACHE_SIZE, 0);
1300                 size = 0;
1301
1302                 atomic_inc(&pb->pb_io_remaining);
1303
1304                 goto submit_io;
1305         }
1306
1307         /* Lock down the pages which we need to for the request */
1308         if (locking && (pb->pb_flags & PBF_WRITE) && (pb->pb_locked == 0)) {
1309                 for (i = 0; size; i++) {
1310                         int             nbytes = PAGE_CACHE_SIZE - offset;
1311                         struct page     *page = pb->pb_pages[i];
1312
1313                         if (nbytes > size)
1314                                 nbytes = size;
1315
1316                         lock_page(page);
1317
1318                         size -= nbytes;
1319                         offset = 0;
1320                 }
1321                 offset = pb->pb_offset;
1322                 size = pb->pb_count_desired;
1323         }
1324
1325 next_chunk:
1326         atomic_inc(&pb->pb_io_remaining);
1327         nr_pages = BIO_MAX_SECTORS >> (PAGE_SHIFT - BBSHIFT);
1328         if (nr_pages > total_nr_pages)
1329                 nr_pages = total_nr_pages;
1330
1331         bio = bio_alloc(GFP_NOIO, nr_pages);
1332         bio->bi_bdev = pb->pb_target->pbr_bdev;
1333         bio->bi_sector = sector;
1334         bio->bi_end_io = bio_end_io_pagebuf;
1335         bio->bi_private = pb;
1336
1337         for (; size && nr_pages; nr_pages--, map_i++) {
1338                 int     nbytes = PAGE_CACHE_SIZE - offset;
1339
1340                 if (nbytes > size)
1341                         nbytes = size;
1342
1343                 if (bio_add_page(bio, pb->pb_pages[map_i],
1344                                         nbytes, offset) < nbytes)
1345                         break;
1346
1347                 offset = 0;
1348                 sector += nbytes >> BBSHIFT;
1349                 size -= nbytes;
1350                 total_nr_pages--;
1351         }
1352
1353 submit_io:
1354         if (likely(bio->bi_size)) {
1355                 submit_bio((pb->pb_flags & PBF_READ) ? READ : WRITE, bio);
1356                 if (size)
1357                         goto next_chunk;
1358         } else {
1359                 bio_put(bio);
1360                 pagebuf_ioerror(pb, EIO);
1361         }
1362
1363         if (pb->pb_flags & _PBF_RUN_QUEUES) {
1364                 pb->pb_flags &= ~_PBF_RUN_QUEUES;
1365                 if (atomic_read(&pb->pb_io_remaining) > 1)
1366                         blk_run_address_space(pb->pb_target->pbr_mapping);
1367         }
1368 }
1369
1370 /*
1371  *      pagebuf_iorequest -- the core I/O request routine.
1372  */
1373 int
1374 pagebuf_iorequest(                      /* start real I/O               */
1375         xfs_buf_t               *pb)    /* buffer to convey to device   */
1376 {
1377         PB_TRACE(pb, "iorequest", 0);
1378
1379         if (pb->pb_flags & PBF_DELWRI) {
1380                 pagebuf_delwri_queue(pb, 1);
1381                 return 0;
1382         }
1383
1384         if (pb->pb_flags & PBF_WRITE) {
1385                 _pagebuf_wait_unpin(pb);
1386         }
1387
1388         pagebuf_hold(pb);
1389
1390         /* Set the count to 1 initially, this will stop an I/O
1391          * completion callout which happens before we have started
1392          * all the I/O from calling pagebuf_iodone too early.
1393          */
1394         atomic_set(&pb->pb_io_remaining, 1);
1395         _pagebuf_ioapply(pb);
1396         _pagebuf_iodone(pb, 0);
1397
1398         pagebuf_rele(pb);
1399         return 0;
1400 }
1401
1402 /*
1403  *      pagebuf_iowait
1404  *
1405  *      pagebuf_iowait waits for I/O to complete on the buffer supplied.
1406  *      It returns immediately if no I/O is pending.  In any case, it returns
1407  *      the error code, if any, or 0 if there is no error.
1408  */
1409 int
1410 pagebuf_iowait(
1411         xfs_buf_t               *pb)
1412 {
1413         PB_TRACE(pb, "iowait", 0);
1414         if (atomic_read(&pb->pb_io_remaining))
1415                 blk_run_address_space(pb->pb_target->pbr_mapping);
1416         down(&pb->pb_iodonesema);
1417         PB_TRACE(pb, "iowaited", (long)pb->pb_error);
1418         return pb->pb_error;
1419 }
1420
1421 caddr_t
1422 pagebuf_offset(
1423         xfs_buf_t               *pb,
1424         size_t                  offset)
1425 {
1426         struct page             *page;
1427
1428         offset += pb->pb_offset;
1429
1430         page = pb->pb_pages[offset >> PAGE_CACHE_SHIFT];
1431         return (caddr_t) page_address(page) + (offset & (PAGE_CACHE_SIZE - 1));
1432 }
1433
1434 /*
1435  *      pagebuf_iomove
1436  *
1437  *      Move data into or out of a buffer.
1438  */
1439 void
1440 pagebuf_iomove(
1441         xfs_buf_t               *pb,    /* buffer to process            */
1442         size_t                  boff,   /* starting buffer offset       */
1443         size_t                  bsize,  /* length to copy               */
1444         caddr_t                 data,   /* data address                 */
1445         page_buf_rw_t           mode)   /* read/write flag              */
1446 {
1447         size_t                  bend, cpoff, csize;
1448         struct page             *page;
1449
1450         bend = boff + bsize;
1451         while (boff < bend) {
1452                 page = pb->pb_pages[page_buf_btoct(boff + pb->pb_offset)];
1453                 cpoff = page_buf_poff(boff + pb->pb_offset);
1454                 csize = min_t(size_t,
1455                               PAGE_CACHE_SIZE-cpoff, pb->pb_count_desired-boff);
1456
1457                 ASSERT(((csize + cpoff) <= PAGE_CACHE_SIZE));
1458
1459                 switch (mode) {
1460                 case PBRW_ZERO:
1461                         memset(page_address(page) + cpoff, 0, csize);
1462                         break;
1463                 case PBRW_READ:
1464                         memcpy(data, page_address(page) + cpoff, csize);
1465                         break;
1466                 case PBRW_WRITE:
1467                         memcpy(page_address(page) + cpoff, data, csize);
1468                 }
1469
1470                 boff += csize;
1471                 data += csize;
1472         }
1473 }
1474
1475 /*
1476  *      Handling of buftargs.
1477  */
1478
1479 void
1480 xfs_free_buftarg(
1481         xfs_buftarg_t           *btp,
1482         int                     external)
1483 {
1484         xfs_flush_buftarg(btp, 1);
1485         if (external)
1486                 xfs_blkdev_put(btp->pbr_bdev);
1487         kmem_free(btp, sizeof(*btp));
1488 }
1489
1490 void
1491 xfs_incore_relse(
1492         xfs_buftarg_t           *btp,
1493         int                     delwri_only,
1494         int                     wait)
1495 {
1496         invalidate_bdev(btp->pbr_bdev, 1);
1497         truncate_inode_pages(btp->pbr_mapping, 0LL);
1498 }
1499
1500 void
1501 xfs_setsize_buftarg(
1502         xfs_buftarg_t           *btp,
1503         unsigned int            blocksize,
1504         unsigned int            sectorsize)
1505 {
1506         btp->pbr_bsize = blocksize;
1507         btp->pbr_sshift = ffs(sectorsize) - 1;
1508         btp->pbr_smask = sectorsize - 1;
1509
1510         if (set_blocksize(btp->pbr_bdev, sectorsize)) {
1511                 printk(KERN_WARNING
1512                         "XFS: Cannot set_blocksize to %u on device %s\n",
1513                         sectorsize, XFS_BUFTARG_NAME(btp));
1514         }
1515 }
1516
1517 xfs_buftarg_t *
1518 xfs_alloc_buftarg(
1519         struct block_device     *bdev)
1520 {
1521         xfs_buftarg_t           *btp;
1522
1523         btp = kmem_zalloc(sizeof(*btp), KM_SLEEP);
1524
1525         btp->pbr_dev =  bdev->bd_dev;
1526         btp->pbr_bdev = bdev;
1527         btp->pbr_mapping = bdev->bd_inode->i_mapping;
1528         xfs_setsize_buftarg(btp, PAGE_CACHE_SIZE, bdev_hardsect_size(bdev));
1529
1530         return btp;
1531 }
1532
1533
1534 /*
1535  * Pagebuf delayed write buffer handling
1536  */
1537
1538 STATIC LIST_HEAD(pbd_delwrite_queue);
1539 STATIC spinlock_t pbd_delwrite_lock = SPIN_LOCK_UNLOCKED;
1540
1541 STATIC void
1542 pagebuf_delwri_queue(
1543         xfs_buf_t               *pb,
1544         int                     unlock)
1545 {
1546         PB_TRACE(pb, "delwri_q", (long)unlock);
1547         ASSERT(pb->pb_flags & PBF_DELWRI);
1548
1549         spin_lock(&pbd_delwrite_lock);
1550         /* If already in the queue, dequeue and place at tail */
1551         if (!list_empty(&pb->pb_list)) {
1552                 if (unlock) {
1553                         atomic_dec(&pb->pb_hold);
1554                 }
1555                 list_del(&pb->pb_list);
1556         }
1557
1558         list_add_tail(&pb->pb_list, &pbd_delwrite_queue);
1559         pb->pb_queuetime = jiffies;
1560         spin_unlock(&pbd_delwrite_lock);
1561
1562         if (unlock)
1563                 pagebuf_unlock(pb);
1564 }
1565
1566 void
1567 pagebuf_delwri_dequeue(
1568         xfs_buf_t               *pb)
1569 {
1570         int                     dequeued = 0;
1571
1572         spin_lock(&pbd_delwrite_lock);
1573         if ((pb->pb_flags & PBF_DELWRI) && !list_empty(&pb->pb_list)) {
1574                 list_del_init(&pb->pb_list);
1575                 dequeued = 1;
1576         }
1577         pb->pb_flags &= ~PBF_DELWRI;
1578         spin_unlock(&pbd_delwrite_lock);
1579
1580         if (dequeued)
1581                 pagebuf_rele(pb);
1582
1583         PB_TRACE(pb, "delwri_dq", (long)dequeued);
1584 }
1585
1586 STATIC void
1587 pagebuf_runall_queues(
1588         struct workqueue_struct *queue)
1589 {
1590         flush_workqueue(queue);
1591 }
1592
1593 /* Defines for pagebuf daemon */
1594 STATIC DECLARE_COMPLETION(pagebuf_daemon_done);
1595 STATIC struct task_struct *pagebuf_daemon_task;
1596 STATIC int pagebuf_daemon_active;
1597 STATIC int force_flush;
1598
1599
1600 STATIC int
1601 pagebuf_daemon_wakeup(
1602         int                     priority,
1603         unsigned int            mask)
1604 {
1605         force_flush = 1;
1606         barrier();
1607         wake_up_process(pagebuf_daemon_task);
1608         return 0;
1609 }
1610
1611 STATIC int
1612 pagebuf_daemon(
1613         void                    *data)
1614 {
1615         struct list_head        tmp;
1616         unsigned long           age;
1617         xfs_buftarg_t           *target;
1618         xfs_buf_t               *pb, *n;
1619
1620         /*  Set up the thread  */
1621         daemonize("xfsbufd");
1622         current->flags |= PF_MEMALLOC;
1623
1624         pagebuf_daemon_task = current;
1625         pagebuf_daemon_active = 1;
1626         barrier();
1627
1628         INIT_LIST_HEAD(&tmp);
1629         do {
1630                 /* swsusp */
1631                 if (current->flags & PF_FREEZE)
1632                         refrigerator(PF_FREEZE);
1633
1634                 set_current_state(TASK_INTERRUPTIBLE);
1635                 schedule_timeout((xfs_buf_timer_centisecs * HZ) / 100);
1636
1637                 age = (xfs_buf_age_centisecs * HZ) / 100;
1638                 spin_lock(&pbd_delwrite_lock);
1639                 list_for_each_entry_safe(pb, n, &pbd_delwrite_queue, pb_list) {
1640                         PB_TRACE(pb, "walkq1", (long)pagebuf_ispin(pb));
1641                         ASSERT(pb->pb_flags & PBF_DELWRI);
1642
1643                         if (!pagebuf_ispin(pb) && !pagebuf_cond_lock(pb)) {
1644                                 if (!force_flush &&
1645                                     time_before(jiffies,
1646                                                 pb->pb_queuetime + age)) {
1647                                         pagebuf_unlock(pb);
1648                                         break;
1649                                 }
1650
1651                                 pb->pb_flags &= ~PBF_DELWRI;
1652                                 pb->pb_flags |= PBF_WRITE;
1653                                 list_move(&pb->pb_list, &tmp);
1654                         }
1655                 }
1656                 spin_unlock(&pbd_delwrite_lock);
1657
1658                 while (!list_empty(&tmp)) {
1659                         pb = list_entry(tmp.next, xfs_buf_t, pb_list);
1660                         target = pb->pb_target;
1661
1662                         list_del_init(&pb->pb_list);
1663                         pagebuf_iostrategy(pb);
1664
1665                         blk_run_address_space(target->pbr_mapping);
1666                 }
1667
1668                 if (as_list_len > 0)
1669                         purge_addresses();
1670
1671                 force_flush = 0;
1672         } while (pagebuf_daemon_active);
1673
1674         complete_and_exit(&pagebuf_daemon_done, 0);
1675 }
1676
1677 /*
1678  * Go through all incore buffers, and release buffers if they belong to
1679  * the given device. This is used in filesystem error handling to
1680  * preserve the consistency of its metadata.
1681  */
1682 int
1683 xfs_flush_buftarg(
1684         xfs_buftarg_t           *target,
1685         int                     wait)
1686 {
1687         struct list_head        tmp;
1688         xfs_buf_t               *pb, *n;
1689         int                     pincount = 0;
1690
1691         pagebuf_runall_queues(pagebuf_dataio_workqueue);
1692         pagebuf_runall_queues(pagebuf_logio_workqueue);
1693
1694         INIT_LIST_HEAD(&tmp);
1695         spin_lock(&pbd_delwrite_lock);
1696         list_for_each_entry_safe(pb, n, &pbd_delwrite_queue, pb_list) {
1697
1698                 if (pb->pb_target != target)
1699                         continue;
1700
1701                 ASSERT(pb->pb_flags & PBF_DELWRI);
1702                 PB_TRACE(pb, "walkq2", (long)pagebuf_ispin(pb));
1703                 if (pagebuf_ispin(pb)) {
1704                         pincount++;
1705                         continue;
1706                 }
1707
1708                 pb->pb_flags &= ~PBF_DELWRI;
1709                 pb->pb_flags |= PBF_WRITE;
1710                 list_move(&pb->pb_list, &tmp);
1711         }
1712         spin_unlock(&pbd_delwrite_lock);
1713
1714         /*
1715          * Dropped the delayed write list lock, now walk the temporary list
1716          */
1717         list_for_each_entry_safe(pb, n, &tmp, pb_list) {
1718                 if (wait)
1719                         pb->pb_flags &= ~PBF_ASYNC;
1720                 else
1721                         list_del_init(&pb->pb_list);
1722
1723                 pagebuf_lock(pb);
1724                 pagebuf_iostrategy(pb);
1725         }
1726
1727         /*
1728          * Remaining list items must be flushed before returning
1729          */
1730         while (!list_empty(&tmp)) {
1731                 pb = list_entry(tmp.next, xfs_buf_t, pb_list);
1732
1733                 list_del_init(&pb->pb_list);
1734                 xfs_iowait(pb);
1735                 xfs_buf_relse(pb);
1736         }
1737
1738         if (wait)
1739                 blk_run_address_space(target->pbr_mapping);
1740
1741         return pincount;
1742 }
1743
1744 STATIC int
1745 pagebuf_daemon_start(void)
1746 {
1747         int             rval;
1748
1749         pagebuf_logio_workqueue = create_workqueue("xfslogd");
1750         if (!pagebuf_logio_workqueue)
1751                 return -ENOMEM;
1752
1753         pagebuf_dataio_workqueue = create_workqueue("xfsdatad");
1754         if (!pagebuf_dataio_workqueue) {
1755                 destroy_workqueue(pagebuf_logio_workqueue);
1756                 return -ENOMEM;
1757         }
1758
1759         rval = kernel_thread(pagebuf_daemon, NULL, CLONE_FS|CLONE_FILES);
1760         if (rval < 0) {
1761                 destroy_workqueue(pagebuf_logio_workqueue);
1762                 destroy_workqueue(pagebuf_dataio_workqueue);
1763         }
1764
1765         return rval;
1766 }
1767
1768 /*
1769  * pagebuf_daemon_stop
1770  *
1771  * Note: do not mark as __exit, it is called from pagebuf_terminate.
1772  */
1773 STATIC void
1774 pagebuf_daemon_stop(void)
1775 {
1776         pagebuf_daemon_active = 0;
1777         barrier();
1778         wait_for_completion(&pagebuf_daemon_done);
1779
1780         destroy_workqueue(pagebuf_logio_workqueue);
1781         destroy_workqueue(pagebuf_dataio_workqueue);
1782 }
1783
1784 /*
1785  *      Initialization and Termination
1786  */
1787
1788 int __init
1789 pagebuf_init(void)
1790 {
1791         int                     i;
1792
1793         pagebuf_cache = kmem_cache_create("xfs_buf_t", sizeof(xfs_buf_t), 0,
1794                         SLAB_HWCACHE_ALIGN, NULL, NULL);
1795         if (pagebuf_cache == NULL) {
1796                 printk("XFS: couldn't init xfs_buf_t cache\n");
1797                 pagebuf_terminate();
1798                 return -ENOMEM;
1799         }
1800
1801 #ifdef PAGEBUF_TRACE
1802         pagebuf_trace_buf = ktrace_alloc(PAGEBUF_TRACE_SIZE, KM_SLEEP);
1803 #endif
1804
1805         pagebuf_daemon_start();
1806
1807         pagebuf_shake = kmem_shake_register(pagebuf_daemon_wakeup);
1808         if (pagebuf_shake == NULL) {
1809                 pagebuf_terminate();
1810                 return -ENOMEM;
1811         }
1812
1813         for (i = 0; i < NHASH; i++) {
1814                 spin_lock_init(&pbhash[i].pb_hash_lock);
1815                 INIT_LIST_HEAD(&pbhash[i].pb_hash);
1816         }
1817
1818         return 0;
1819 }
1820
1821
1822 /*
1823  *      pagebuf_terminate.
1824  *
1825  *      Note: do not mark as __exit, this is also called from the __init code.
1826  */
1827 void
1828 pagebuf_terminate(void)
1829 {
1830         pagebuf_daemon_stop();
1831
1832 #ifdef PAGEBUF_TRACE
1833         ktrace_free(pagebuf_trace_buf);
1834 #endif
1835
1836         kmem_zone_destroy(pagebuf_cache);
1837         kmem_shake_deregister(pagebuf_shake);
1838 }