clean
[linux-2.4.21-pre4.git] / fs / nfs / write.c
1 /*
2  * linux/fs/nfs/write.c
3  *
4  * Writing file data over NFS.
5  *
6  * We do it like this: When a (user) process wishes to write data to an
7  * NFS file, a write request is allocated that contains the RPC task data
8  * plus some info on the page to be written, and added to the inode's
9  * write chain. If the process writes past the end of the page, an async
10  * RPC call to write the page is scheduled immediately; otherwise, the call
11  * is delayed for a few seconds.
12  *
13  * Just like readahead, no async I/O is performed if wsize < PAGE_SIZE.
14  *
15  * Write requests are kept on the inode's writeback list. Each entry in
16  * that list references the page (portion) to be written. When the
17  * cache timeout has expired, the RPC task is woken up, and tries to
18  * lock the page. As soon as it manages to do so, the request is moved
19  * from the writeback list to the writelock list.
20  *
21  * Note: we must make sure never to confuse the inode passed in the
22  * write_page request with the one in page->inode. As far as I understand
23  * it, these are different when doing a swap-out.
24  *
25  * To understand everything that goes on here and in the NFS read code,
26  * one should be aware that a page is locked in exactly one of the following
27  * cases:
28  *
29  *  -   A write request is in progress.
30  *  -   A user process is in generic_file_write/nfs_update_page
31  *  -   A user process is in generic_file_read
32  *
33  * Also note that because of the way pages are invalidated in
34  * nfs_revalidate_inode, the following assertions hold:
35  *
36  *  -   If a page is dirty, there will be no read requests (a page will
37  *      not be re-read unless invalidated by nfs_revalidate_inode).
38  *  -   If the page is not uptodate, there will be no pending write
39  *      requests, and no process will be in nfs_update_page.
40  *
41  * FIXME: Interaction with the vmscan routines is not optimal yet.
42  * Either vmscan must be made nfs-savvy, or we need a different page
43  * reclaim concept that supports something like FS-independent
44  * buffer_heads with a b_ops-> field.
45  *
46  * Copyright (C) 1996, 1997, Olaf Kirch <okir@monad.swb.de>
47  */
48
49 #include <linux/config.h>
50 #include <linux/types.h>
51 #include <linux/slab.h>
52 #include <linux/swap.h>
53 #include <linux/pagemap.h>
54 #include <linux/file.h>
55
56 #include <linux/sunrpc/clnt.h>
57 #include <linux/nfs_fs.h>
58 #include <linux/nfs_mount.h>
59 #include <linux/nfs_flushd.h>
60 #include <linux/nfs_page.h>
61 #include <asm/uaccess.h>
62 #include <linux/smp_lock.h>
63
64 #define NFSDBG_FACILITY         NFSDBG_PAGECACHE
65
66 /*
67  * Local structures
68  *
69  * This is the struct where the WRITE/COMMIT arguments go.
70  */
71 struct nfs_write_data {
72         struct rpc_task         task;
73         struct inode            *inode;
74         struct rpc_cred         *cred;
75         struct nfs_writeargs    args;           /* argument struct */
76         struct nfs_writeres     res;            /* result struct */
77         struct nfs_fattr        fattr;
78         struct nfs_writeverf    verf;
79         struct list_head        pages;          /* Coalesced requests we wish to flush */
80         struct page             *pagevec[NFS_WRITE_MAXIOV];
81 };
82
83 /*
84  * Local function declarations
85  */
86 static struct nfs_page * nfs_update_request(struct file*, struct inode *,
87                                             struct page *,
88                                             unsigned int, unsigned int);
89 static void     nfs_strategy(struct inode *inode);
90 static void     nfs_writeback_done(struct rpc_task *);
91 #ifdef CONFIG_NFS_V3
92 static void     nfs_commit_done(struct rpc_task *);
93 #endif
94
95 /* Hack for future NFS swap support */
96 #ifndef IS_SWAPFILE
97 # define IS_SWAPFILE(inode)     (0)
98 #endif
99
100 static kmem_cache_t *nfs_wdata_cachep;
101
102 static __inline__ struct nfs_write_data *nfs_writedata_alloc(void)
103 {
104         struct nfs_write_data   *p;
105         p = kmem_cache_alloc(nfs_wdata_cachep, SLAB_NOFS);
106         if (p) {
107                 memset(p, 0, sizeof(*p));
108                 INIT_LIST_HEAD(&p->pages);
109                 p->args.pages = p->pagevec;
110         }
111         return p;
112 }
113
114 static __inline__ void nfs_writedata_free(struct nfs_write_data *p)
115 {
116         kmem_cache_free(nfs_wdata_cachep, p);
117 }
118
119 static void nfs_writedata_release(struct rpc_task *task)
120 {
121         struct nfs_write_data   *wdata = (struct nfs_write_data *)task->tk_calldata;
122         nfs_writedata_free(wdata);
123 }
124
125 /*
126  * This function will be used to simulate weak cache consistency
127  * under NFSv2 when the NFSv3 attribute patch is included.
128  * For the moment, we just call nfs_refresh_inode().
129  */
130 static __inline__ int
131 nfs_write_attributes(struct inode *inode, struct nfs_fattr *fattr)
132 {
133         if ((fattr->valid & NFS_ATTR_FATTR) && !(fattr->valid & NFS_ATTR_WCC)) {
134                 fattr->pre_size  = NFS_CACHE_ISIZE(inode);
135                 fattr->pre_mtime = NFS_CACHE_MTIME(inode);
136                 fattr->pre_ctime = NFS_CACHE_CTIME(inode);
137                 fattr->valid |= NFS_ATTR_WCC;
138         }
139         return nfs_refresh_inode(inode, fattr);
140 }
141
142 /*
143  * Write a page synchronously.
144  * Offset is the data offset within the page.
145  */
146 static int
147 nfs_writepage_sync(struct file *file, struct inode *inode, struct page *page,
148                    unsigned int offset, unsigned int count)
149 {
150         struct rpc_cred *cred = NULL;
151         loff_t          base;
152         unsigned int    wsize = NFS_SERVER(inode)->wsize;
153         int             result, refresh = 0, written = 0, flags;
154         u8              *buffer;
155         struct nfs_fattr fattr;
156         struct nfs_writeverf verf;
157
158
159         if (file)
160                 cred = get_rpccred(nfs_file_cred(file));
161         if (!cred)
162                 cred = get_rpccred(NFS_I(inode)->mm_cred);
163
164         dprintk("NFS:      nfs_writepage_sync(%x/%Ld %d@%Ld)\n",
165                 inode->i_dev, (long long)NFS_FILEID(inode),
166                 count, (long long)(page_offset(page) + offset));
167
168         base = page_offset(page) + offset;
169
170         flags = ((IS_SWAPFILE(inode)) ? NFS_RW_SWAP : 0) | NFS_RW_SYNC;
171
172         do {
173                 if (count < wsize && !IS_SWAPFILE(inode))
174                         wsize = count;
175
176                 result = NFS_PROTO(inode)->write(inode, cred, &fattr, flags,
177                                                  offset, wsize, page, &verf);
178                 nfs_write_attributes(inode, &fattr);
179
180                 if (result < 0) {
181                         /* Must mark the page invalid after I/O error */
182                         ClearPageUptodate(page);
183                         goto io_error;
184                 }
185                 if (result != wsize)
186                         printk("NFS: short write, wsize=%u, result=%d\n",
187                         wsize, result);
188                 refresh = 1;
189                 buffer  += wsize;
190                 base    += wsize;
191                 offset  += wsize;
192                 written += wsize;
193                 count   -= wsize;
194                 /*
195                  * If we've extended the file, update the inode
196                  * now so we don't invalidate the cache.
197                  */
198                 if (base > inode->i_size)
199                         inode->i_size = base;
200         } while (count);
201
202         if (PageError(page))
203                 ClearPageError(page);
204
205 io_error:
206         if (cred)
207                 put_rpccred(cred);
208
209         return written? written : result;
210 }
211
212 static int
213 nfs_writepage_async(struct file *file, struct inode *inode, struct page *page,
214                     unsigned int offset, unsigned int count)
215 {
216         struct nfs_page *req;
217         loff_t          end;
218         int             status;
219
220         req = nfs_update_request(file, inode, page, offset, count);
221         status = (IS_ERR(req)) ? PTR_ERR(req) : 0;
222         if (status < 0)
223                 goto out;
224         if (!req->wb_cred)
225                 req->wb_cred = get_rpccred(NFS_I(inode)->mm_cred);
226         nfs_unlock_request(req);
227         nfs_strategy(inode);
228         end = ((loff_t)page->index<<PAGE_CACHE_SHIFT) + (loff_t)(offset + count);
229         if (inode->i_size < end)
230                 inode->i_size = end;
231
232  out:
233         return status;
234 }
235
236 /*
237  * Write an mmapped page to the server.
238  */
239 int
240 nfs_writepage(struct page *page)
241 {
242         struct inode *inode = page->mapping->host;
243         unsigned long end_index;
244         unsigned offset = PAGE_CACHE_SIZE;
245         int err;
246
247         end_index = inode->i_size >> PAGE_CACHE_SHIFT;
248
249         /* Ensure we've flushed out any previous writes */
250         nfs_wb_page(inode,page);
251
252         /* easy case */
253         if (page->index < end_index)
254                 goto do_it;
255         /* things got complicated... */
256         offset = inode->i_size & (PAGE_CACHE_SIZE-1);
257
258         /* OK, are we completely out? */
259         err = -EIO;
260         if (page->index >= end_index+1 || !offset)
261                 goto out;
262 do_it:
263         lock_kernel();
264         if (NFS_SERVER(inode)->wsize >= PAGE_CACHE_SIZE && !IS_SYNC(inode)) {
265                 err = nfs_writepage_async(NULL, inode, page, 0, offset);
266                 if (err >= 0)
267                         err = 0;
268         } else {
269                 err = nfs_writepage_sync(NULL, inode, page, 0, offset); 
270                 if (err == offset)
271                         err = 0;
272         }
273         unlock_kernel();
274 out:
275         UnlockPage(page);
276         return err; 
277 }
278
279 /*
280  * Check whether the file range we want to write to is locked by
281  * us.
282  */
283 static int
284 region_locked(struct inode *inode, struct nfs_page *req)
285 {
286         struct file_lock        *fl;
287         loff_t                  rqstart, rqend;
288
289         /* Don't optimize writes if we don't use NLM */
290         if (NFS_SERVER(inode)->flags & NFS_MOUNT_NONLM)
291                 return 0;
292
293         rqstart = page_offset(req->wb_page) + req->wb_offset;
294         rqend = rqstart + req->wb_bytes;
295         for (fl = inode->i_flock; fl; fl = fl->fl_next) {
296                 if (fl->fl_owner == current->files && (fl->fl_flags & FL_POSIX)
297                     && fl->fl_type == F_WRLCK
298                     && fl->fl_start <= rqstart && rqend <= fl->fl_end) {
299                         return 1;
300                 }
301         }
302
303         return 0;
304 }
305
306 /*
307  * Insert a write request into an inode
308  * Note: we sort the list in order to be able to optimize nfs_find_request()
309  *       & co. for the 'write append' case. For 2.5 we may want to consider
310  *       some form of hashing so as to perform well on random writes.
311  */
312 static inline void
313 nfs_inode_add_request(struct inode *inode, struct nfs_page *req)
314 {
315         struct list_head *pos, *head;
316         unsigned long pg_idx = page_index(req->wb_page);
317
318         if (!list_empty(&req->wb_hash))
319                 return;
320         if (!NFS_WBACK_BUSY(req))
321                 printk(KERN_ERR "NFS: unlocked request attempted hashed!\n");
322         head = &inode->u.nfs_i.writeback;
323         if (list_empty(head))
324                 igrab(inode);
325         list_for_each_prev(pos, head) {
326                 struct nfs_page *entry = nfs_inode_wb_entry(pos);
327                 if (page_index(entry->wb_page) < pg_idx)
328                         break;
329         }
330         inode->u.nfs_i.npages++;
331         list_add(&req->wb_hash, pos);
332         req->wb_count++;
333 }
334
335 /*
336  * Insert a write request into an inode
337  */
338 static inline void
339 nfs_inode_remove_request(struct nfs_page *req)
340 {
341         struct inode *inode;
342         spin_lock(&nfs_wreq_lock);
343         if (list_empty(&req->wb_hash)) {
344                 spin_unlock(&nfs_wreq_lock);
345                 return;
346         }
347         if (!NFS_WBACK_BUSY(req))
348                 printk(KERN_ERR "NFS: unlocked request attempted unhashed!\n");
349         inode = req->wb_inode;
350         list_del(&req->wb_hash);
351         INIT_LIST_HEAD(&req->wb_hash);
352         inode->u.nfs_i.npages--;
353         if ((inode->u.nfs_i.npages == 0) != list_empty(&inode->u.nfs_i.writeback))
354                 printk(KERN_ERR "NFS: desynchronized value of nfs_i.npages.\n");
355         if (list_empty(&inode->u.nfs_i.writeback)) {
356                 spin_unlock(&nfs_wreq_lock);
357                 iput(inode);
358         } else
359                 spin_unlock(&nfs_wreq_lock);
360         nfs_clear_request(req);
361         nfs_release_request(req);
362 }
363
364 /*
365  * Find a request
366  */
367 static inline struct nfs_page *
368 _nfs_find_request(struct inode *inode, struct page *page)
369 {
370         struct list_head        *head, *pos;
371         unsigned long pg_idx = page_index(page);
372
373         head = &inode->u.nfs_i.writeback;
374         list_for_each_prev(pos, head) {
375                 struct nfs_page *req = nfs_inode_wb_entry(pos);
376                 unsigned long found_idx = page_index(req->wb_page);
377
378                 if (pg_idx < found_idx)
379                         continue;
380                 if (pg_idx != found_idx)
381                         break;
382                 req->wb_count++;
383                 return req;
384         }
385         return NULL;
386 }
387
388 static struct nfs_page *
389 nfs_find_request(struct inode *inode, struct page *page)
390 {
391         struct nfs_page         *req;
392
393         spin_lock(&nfs_wreq_lock);
394         req = _nfs_find_request(inode, page);
395         spin_unlock(&nfs_wreq_lock);
396         return req;
397 }
398
399 /*
400  * Add a request to the inode's dirty list.
401  */
402 static inline void
403 nfs_mark_request_dirty(struct nfs_page *req)
404 {
405         struct inode *inode = req->wb_inode;
406
407         spin_lock(&nfs_wreq_lock);
408         nfs_list_add_request(req, &inode->u.nfs_i.dirty);
409         inode->u.nfs_i.ndirty++;
410         __nfs_del_lru(req);
411         __nfs_add_lru(&NFS_SERVER(inode)->lru_dirty, req);
412         spin_unlock(&nfs_wreq_lock);
413         mark_inode_dirty(inode);
414 }
415
416 /*
417  * Check if a request is dirty
418  */
419 static inline int
420 nfs_dirty_request(struct nfs_page *req)
421 {
422         struct inode *inode = req->wb_inode;
423         return !list_empty(&req->wb_list) && req->wb_list_head == &inode->u.nfs_i.dirty;
424 }
425
426 #ifdef CONFIG_NFS_V3
427 /*
428  * Add a request to the inode's commit list.
429  */
430 static inline void
431 nfs_mark_request_commit(struct nfs_page *req)
432 {
433         struct inode *inode = req->wb_inode;
434
435         spin_lock(&nfs_wreq_lock);
436         nfs_list_add_request(req, &inode->u.nfs_i.commit);
437         inode->u.nfs_i.ncommit++;
438         __nfs_del_lru(req);
439         __nfs_add_lru(&NFS_SERVER(inode)->lru_commit, req);
440         spin_unlock(&nfs_wreq_lock);
441         mark_inode_dirty(inode);
442 }
443 #endif
444
445 /*
446  * Wait for a request to complete.
447  *
448  * Interruptible by signals only if mounted with intr flag.
449  */
450 static int
451 nfs_wait_on_requests(struct inode *inode, struct file *file, unsigned long idx_start, unsigned int npages)
452 {
453         struct list_head        *p, *head;
454         unsigned long           idx_end;
455         unsigned int            res = 0;
456         int                     error;
457
458         if (npages == 0)
459                 idx_end = ~0;
460         else
461                 idx_end = idx_start + npages - 1;
462
463         head = &inode->u.nfs_i.writeback;
464  restart:
465         spin_lock(&nfs_wreq_lock);
466         list_for_each_prev(p, head) {
467                 unsigned long pg_idx;
468                 struct nfs_page *req = nfs_inode_wb_entry(p);
469
470                 if (file && req->wb_file != file)
471                         continue;
472
473                 pg_idx = page_index(req->wb_page);
474                 if (pg_idx < idx_start)
475                         break;
476                 if (pg_idx > idx_end)
477                         continue;
478
479                 if (!NFS_WBACK_BUSY(req))
480                         continue;
481                 req->wb_count++;
482                 spin_unlock(&nfs_wreq_lock);
483                 error = nfs_wait_on_request(req);
484                 nfs_release_request(req);
485                 if (error < 0)
486                         return error;
487                 res++;
488                 goto restart;
489         }
490         spin_unlock(&nfs_wreq_lock);
491         return res;
492 }
493
494 /**
495  * nfs_scan_lru_dirty_timeout - Scan LRU list for timed out dirty requests
496  * @server: NFS superblock data
497  * @dst: destination list
498  *
499  * Moves a maximum of 'wpages' requests from the NFS dirty page LRU list.
500  * The elements are checked to ensure that they form a contiguous set
501  * of pages, and that they originated from the same file.
502  */
503 int
504 nfs_scan_lru_dirty_timeout(struct nfs_server *server, struct list_head *dst)
505 {
506         struct inode *inode;
507         int npages;
508
509         npages = nfs_scan_lru_timeout(&server->lru_dirty, dst, server->wpages);
510         if (npages) {
511                 inode = nfs_list_entry(dst->next)->wb_inode;
512                 inode->u.nfs_i.ndirty -= npages;
513         }
514         return npages;
515 }
516
517 /**
518  * nfs_scan_lru_dirty - Scan LRU list for dirty requests
519  * @server: NFS superblock data
520  * @dst: destination list
521  *
522  * Moves a maximum of 'wpages' requests from the NFS dirty page LRU list.
523  * The elements are checked to ensure that they form a contiguous set
524  * of pages, and that they originated from the same file.
525  */
526 int
527 nfs_scan_lru_dirty(struct nfs_server *server, struct list_head *dst)
528 {
529         struct inode *inode;
530         int npages;
531
532         npages = nfs_scan_lru(&server->lru_dirty, dst, server->wpages);
533         if (npages) {
534                 inode = nfs_list_entry(dst->next)->wb_inode;
535                 inode->u.nfs_i.ndirty -= npages;
536         }
537         return npages;
538 }
539
540 /*
541  * nfs_scan_dirty - Scan an inode for dirty requests
542  * @inode: NFS inode to scan
543  * @dst: destination list
544  * @file: if set, ensure we match requests from this file
545  * @idx_start: lower bound of page->index to scan.
546  * @npages: idx_start + npages sets the upper bound to scan.
547  *
548  * Moves requests from the inode's dirty page list.
549  * The requests are *not* checked to ensure that they form a contiguous set.
550  */
551 static int
552 nfs_scan_dirty(struct inode *inode, struct list_head *dst, struct file *file, unsigned long idx_start, unsigned int npages)
553 {
554         int     res;
555         res = nfs_scan_list(&inode->u.nfs_i.dirty, dst, file, idx_start, npages);
556         inode->u.nfs_i.ndirty -= res;
557         if ((inode->u.nfs_i.ndirty == 0) != list_empty(&inode->u.nfs_i.dirty))
558                 printk(KERN_ERR "NFS: desynchronized value of nfs_i.ndirty.\n");
559         return res;
560 }
561
562 #ifdef CONFIG_NFS_V3
563 /**
564  * nfs_scan_lru_commit_timeout - Scan LRU list for timed out commit requests
565  * @server: NFS superblock data
566  * @dst: destination list
567  *
568  * Finds the first a timed out request in the NFS commit LRU list and moves it
569  * to the list dst. If such an element is found, we move all other commit
570  * requests that apply to the same inode.
571  * The assumption is that doing everything in a single commit-to-disk is
572  * the cheaper alternative.
573  */
574 int
575 nfs_scan_lru_commit_timeout(struct nfs_server *server, struct list_head *dst)
576 {
577         struct inode *inode;
578         int npages;
579
580         npages = nfs_scan_lru_timeout(&server->lru_commit, dst, 1);
581         if (npages) {
582                 inode = nfs_list_entry(dst->next)->wb_inode;
583                 npages += nfs_scan_list(&inode->u.nfs_i.commit, dst, NULL, 0, 0);
584                 inode->u.nfs_i.ncommit -= npages;
585         }
586         return npages;
587 }
588
589
590 /**
591  * nfs_scan_lru_commit_timeout - Scan LRU list for timed out commit requests
592  * @server: NFS superblock data
593  * @dst: destination list
594  *
595  * Finds the first request in the NFS commit LRU list and moves it
596  * to the list dst. If such an element is found, we move all other commit
597  * requests that apply to the same inode.
598  * The assumption is that doing everything in a single commit-to-disk is
599  * the cheaper alternative.
600  */
601 int
602 nfs_scan_lru_commit(struct nfs_server *server, struct list_head *dst)
603 {
604         struct inode *inode;
605         int npages;
606
607         npages = nfs_scan_lru(&server->lru_commit, dst, 1);
608         if (npages) {
609                 inode = nfs_list_entry(dst->next)->wb_inode;
610                 npages += nfs_scan_list(&inode->u.nfs_i.commit, dst, NULL, 0, 0);
611                 inode->u.nfs_i.ncommit -= npages;
612         }
613         return npages;
614 }
615
616 /*
617  * nfs_scan_commit - Scan an inode for commit requests
618  * @inode: NFS inode to scan
619  * @dst: destination list
620  * @file: if set, ensure we collect requests from this file only.
621  * @idx_start: lower bound of page->index to scan.
622  * @npages: idx_start + npages sets the upper bound to scan.
623  *
624  * Moves requests from the inode's 'commit' request list.
625  * The requests are *not* checked to ensure that they form a contiguous set.
626  */
627 static int
628 nfs_scan_commit(struct inode *inode, struct list_head *dst, struct file *file, unsigned long idx_start, unsigned int npages)
629 {
630         int     res;
631         res = nfs_scan_list(&inode->u.nfs_i.commit, dst, file, idx_start, npages);
632         inode->u.nfs_i.ncommit -= res;
633         if ((inode->u.nfs_i.ncommit == 0) != list_empty(&inode->u.nfs_i.commit))
634                 printk(KERN_ERR "NFS: desynchronized value of nfs_i.ncommit.\n");
635         return res;
636 }
637 #endif
638
639
640 /*
641  * Try to update any existing write request, or create one if there is none.
642  * In order to match, the request's credentials must match those of
643  * the calling process.
644  *
645  * Note: Should always be called with the Page Lock held!
646  */
647 static struct nfs_page *
648 nfs_update_request(struct file* file, struct inode *inode, struct page *page,
649                    unsigned int offset, unsigned int bytes)
650 {
651         struct nfs_page         *req, *new = NULL;
652         unsigned long           rqend, end;
653
654         end = offset + bytes;
655
656         for (;;) {
657                 /* Loop over all inode entries and see if we find
658                  * A request for the page we wish to update
659                  */
660                 spin_lock(&nfs_wreq_lock);
661                 req = _nfs_find_request(inode, page);
662                 if (req) {
663                         if (!nfs_lock_request_dontget(req)) {
664                                 int error;
665                                 spin_unlock(&nfs_wreq_lock);
666                                 error = nfs_wait_on_request(req);
667                                 nfs_release_request(req);
668                                 if (error < 0)
669                                         return ERR_PTR(error);
670                                 continue;
671                         }
672                         spin_unlock(&nfs_wreq_lock);
673                         if (new)
674                                 nfs_release_request(new);
675                         break;
676                 }
677
678                 if (new) {
679                         nfs_lock_request_dontget(new);
680                         nfs_inode_add_request(inode, new);
681                         spin_unlock(&nfs_wreq_lock);
682                         nfs_mark_request_dirty(new);
683                         return new;
684                 }
685                 spin_unlock(&nfs_wreq_lock);
686
687                 new = nfs_create_request(nfs_file_cred(file), inode, page, offset, bytes);
688                 if (IS_ERR(new))
689                         return new;
690                 if (file) {
691                         new->wb_file = file;
692                         get_file(file);
693                 }
694                 /* If the region is locked, adjust the timeout */
695                 if (region_locked(inode, new))
696                         new->wb_timeout = jiffies + NFS_WRITEBACK_LOCKDELAY;
697                 else
698                         new->wb_timeout = jiffies + NFS_WRITEBACK_DELAY;
699         }
700
701         /* We have a request for our page.
702          * If the creds don't match, or the
703          * page addresses don't match,
704          * tell the caller to wait on the conflicting
705          * request.
706          */
707         rqend = req->wb_offset + req->wb_bytes;
708         if (req->wb_file != file
709             || req->wb_page != page
710             || !nfs_dirty_request(req)
711             || offset > rqend || end < req->wb_offset) {
712                 nfs_unlock_request(req);
713                 return ERR_PTR(-EBUSY);
714         }
715
716         /* Okay, the request matches. Update the region */
717         if (offset < req->wb_offset) {
718                 req->wb_offset = offset;
719                 req->wb_bytes = rqend - req->wb_offset;
720         }
721
722         if (end > rqend)
723                 req->wb_bytes = end - req->wb_offset;
724
725         return req;
726 }
727
728 /*
729  * This is the strategy routine for NFS.
730  * It is called by nfs_updatepage whenever the user wrote up to the end
731  * of a page.
732  *
733  * We always try to submit a set of requests in parallel so that the
734  * server's write code can gather writes. This is mainly for the benefit
735  * of NFSv2.
736  *
737  * We never submit more requests than we think the remote can handle.
738  * For UDP sockets, we make sure we don't exceed the congestion window;
739  * for TCP, we limit the number of requests to 8.
740  *
741  * NFS_STRATEGY_PAGES gives the minimum number of requests for NFSv2 that
742  * should be sent out in one go. This is for the benefit of NFSv2 servers
743  * that perform write gathering.
744  *
745  * FIXME: Different servers may have different sweet spots.
746  * Record the average congestion window in server struct?
747  */
748 #define NFS_STRATEGY_PAGES      8
749 static void
750 nfs_strategy(struct inode *inode)
751 {
752         unsigned int    dirty, wpages;
753
754         dirty  = inode->u.nfs_i.ndirty;
755         wpages = NFS_SERVER(inode)->wpages;
756 #ifdef CONFIG_NFS_V3
757         if (NFS_PROTO(inode)->version == 2) {
758                 if (dirty >= NFS_STRATEGY_PAGES * wpages)
759                         nfs_flush_file(inode, NULL, 0, 0, 0);
760         } else if (dirty >= wpages)
761                 nfs_flush_file(inode, NULL, 0, 0, 0);
762 #else
763         if (dirty >= NFS_STRATEGY_PAGES * wpages)
764                 nfs_flush_file(inode, NULL, 0, 0, 0);
765 #endif
766 }
767
768 int
769 nfs_flush_incompatible(struct file *file, struct page *page)
770 {
771         struct rpc_cred *cred = nfs_file_cred(file);
772         struct inode    *inode = page->mapping->host;
773         struct nfs_page *req;
774         int             status = 0;
775         /*
776          * Look for a request corresponding to this page. If there
777          * is one, and it belongs to another file, we flush it out
778          * before we try to copy anything into the page. Do this
779          * due to the lack of an ACCESS-type call in NFSv2.
780          * Also do the same if we find a request from an existing
781          * dropped page.
782          */
783         req = nfs_find_request(inode,page);
784         if (req) {
785                 if (req->wb_file != file || req->wb_cred != cred || req->wb_page != page)
786                         status = nfs_wb_page(inode, page);
787                 nfs_release_request(req);
788         }
789         return (status < 0) ? status : 0;
790 }
791
792 /*
793  * Update and possibly write a cached page of an NFS file.
794  *
795  * XXX: Keep an eye on generic_file_read to make sure it doesn't do bad
796  * things with a page scheduled for an RPC call (e.g. invalidate it).
797  */
798 int
799 nfs_updatepage(struct file *file, struct page *page, unsigned int offset, unsigned int count)
800 {
801         struct dentry   *dentry = file->f_dentry;
802         struct inode    *inode = page->mapping->host;
803         struct nfs_page *req;
804         loff_t          end;
805         int             status = 0;
806
807         dprintk("NFS:      nfs_updatepage(%s/%s %d@%Ld)\n",
808                 dentry->d_parent->d_name.name, dentry->d_name.name,
809                 count, (long long)(page_offset(page) +offset));
810
811         /*
812          * If wsize is smaller than page size, update and write
813          * page synchronously.
814          */
815         if (NFS_SERVER(inode)->wsize < PAGE_CACHE_SIZE || IS_SYNC(inode))
816                 return nfs_writepage_sync(file, inode, page, offset, count);
817
818         /*
819          * Try to find an NFS request corresponding to this page
820          * and update it.
821          * If the existing request cannot be updated, we must flush
822          * it out now.
823          */
824         do {
825                 req = nfs_update_request(file, inode, page, offset, count);
826                 status = (IS_ERR(req)) ? PTR_ERR(req) : 0;
827                 if (status != -EBUSY)
828                         break;
829                 /* Request could not be updated. Flush it out and try again */
830                 status = nfs_wb_page(inode, page);
831         } while (status >= 0);
832         if (status < 0)
833                 goto done;
834
835         status = 0;
836         end = ((loff_t)page->index<<PAGE_CACHE_SHIFT) + (loff_t)(offset + count);
837         if (inode->i_size < end)
838                 inode->i_size = end;
839
840         /* If we wrote past the end of the page.
841          * Call the strategy routine so it can send out a bunch
842          * of requests.
843          */
844         if (req->wb_offset == 0 && req->wb_bytes == PAGE_CACHE_SIZE) {
845                 SetPageUptodate(page);
846                 nfs_unlock_request(req);
847                 nfs_strategy(inode);
848         } else
849                 nfs_unlock_request(req);
850 done:
851         dprintk("NFS:      nfs_updatepage returns %d (isize %Ld)\n",
852                                                 status, (long long)inode->i_size);
853         if (status < 0)
854                 ClearPageUptodate(page);
855         return status;
856 }
857
858 /*
859  * Set up the argument/result storage required for the RPC call.
860  */
861 static void
862 nfs_write_rpcsetup(struct list_head *head, struct nfs_write_data *data)
863 {
864         struct nfs_page         *req;
865         struct page             **pages;
866         unsigned int            count;
867
868         /* Set up the RPC argument and reply structs
869          * NB: take care not to mess about with data->commit et al. */
870
871         pages = data->args.pages;
872         count = 0;
873         while (!list_empty(head)) {
874                 struct nfs_page *req = nfs_list_entry(head->next);
875                 nfs_list_remove_request(req);
876                 nfs_list_add_request(req, &data->pages);
877                 *pages++ = req->wb_page;
878                 count += req->wb_bytes;
879         }
880         req = nfs_list_entry(data->pages.next);
881         data->inode = req->wb_inode;
882         data->cred = req->wb_cred;
883         data->args.fh     = NFS_FH(req->wb_inode);
884         data->args.offset = page_offset(req->wb_page) + req->wb_offset;
885         data->args.pgbase = req->wb_offset;
886         data->args.count  = count;
887         data->res.fattr   = &data->fattr;
888         data->res.count   = count;
889         data->res.verf    = &data->verf;
890 }
891
892
893 /*
894  * Create an RPC task for the given write request and kick it.
895  * The page must have been locked by the caller.
896  *
897  * It may happen that the page we're passed is not marked dirty.
898  * This is the case if nfs_updatepage detects a conflicting request
899  * that has been written but not committed.
900  */
901 static int
902 nfs_flush_one(struct list_head *head, struct inode *inode, int how)
903 {
904         struct rpc_clnt         *clnt = NFS_CLIENT(inode);
905         struct nfs_write_data   *data;
906         struct rpc_task         *task;
907         struct rpc_message      msg;
908         int                     flags,
909                                 nfsvers = NFS_PROTO(inode)->version,
910                                 async = !(how & FLUSH_SYNC),
911                                 stable = (how & FLUSH_STABLE);
912         sigset_t                oldset;
913
914
915         data = nfs_writedata_alloc();
916         if (!data)
917                 goto out_bad;
918         task = &data->task;
919
920         /* Set the initial flags for the task.  */
921         flags = (async) ? RPC_TASK_ASYNC : 0;
922
923         /* Set up the argument struct */
924         nfs_write_rpcsetup(head, data);
925         if (nfsvers < 3)
926                 data->args.stable = NFS_FILE_SYNC;
927         else if (stable) {
928                 if (!inode->u.nfs_i.ncommit)
929                         data->args.stable = NFS_FILE_SYNC;
930                 else
931                         data->args.stable = NFS_DATA_SYNC;
932         } else
933                 data->args.stable = NFS_UNSTABLE;
934
935         /* Finalize the task. */
936         rpc_init_task(task, clnt, nfs_writeback_done, flags);
937         task->tk_calldata = data;
938         /* Release requests */
939         task->tk_release = nfs_writedata_release;
940
941 #ifdef CONFIG_NFS_V3
942         msg.rpc_proc = (nfsvers == 3) ? NFS3PROC_WRITE : NFSPROC_WRITE;
943 #else
944         msg.rpc_proc = NFSPROC_WRITE;
945 #endif
946         msg.rpc_argp = &data->args;
947         msg.rpc_resp = &data->res;
948         msg.rpc_cred = data->cred;
949
950         dprintk("NFS: %4d initiated write call (req %x/%Ld count %u)\n",
951                 task->tk_pid, 
952                 inode->i_dev,
953                 (long long)NFS_FILEID(inode),
954                 data->args.count);
955
956         rpc_clnt_sigmask(clnt, &oldset);
957         rpc_call_setup(task, &msg, 0);
958         lock_kernel();
959         rpc_execute(task);
960         unlock_kernel();
961         rpc_clnt_sigunmask(clnt, &oldset);
962         return 0;
963  out_bad:
964         while (!list_empty(head)) {
965                 struct nfs_page *req = nfs_list_entry(head->next);
966                 nfs_list_remove_request(req);
967                 nfs_mark_request_dirty(req);
968                 nfs_unlock_request(req);
969         }
970         return -ENOMEM;
971 }
972
973 int
974 nfs_flush_list(struct list_head *head, int wpages, int how)
975 {
976         LIST_HEAD(one_request);
977         struct nfs_page         *req;
978         int                     error = 0;
979         unsigned int            pages = 0;
980
981         while (!list_empty(head)) {
982                 pages += nfs_coalesce_requests(head, &one_request, wpages);
983                 req = nfs_list_entry(one_request.next);
984                 error = nfs_flush_one(&one_request, req->wb_inode, how);
985                 if (error < 0)
986                         break;
987         }
988         if (error >= 0)
989                 return pages;
990
991         while (!list_empty(head)) {
992                 req = nfs_list_entry(head->next);
993                 nfs_list_remove_request(req);
994                 nfs_mark_request_dirty(req);
995                 nfs_unlock_request(req);
996         }
997         return error;
998 }
999
1000
1001 /*
1002  * This function is called when the WRITE call is complete.
1003  */
1004 static void
1005 nfs_writeback_done(struct rpc_task *task)
1006 {
1007         struct nfs_write_data   *data = (struct nfs_write_data *) task->tk_calldata;
1008         struct nfs_writeargs    *argp = &data->args;
1009         struct nfs_writeres     *resp = &data->res;
1010         struct inode            *inode = data->inode;
1011         struct nfs_page         *req;
1012         struct page             *page;
1013
1014         dprintk("NFS: %4d nfs_writeback_done (status %d)\n",
1015                 task->tk_pid, task->tk_status);
1016
1017         if (nfs_async_handle_jukebox(task))
1018                 return;
1019
1020         /* We can't handle that yet but we check for it nevertheless */
1021         if (resp->count < argp->count && task->tk_status >= 0) {
1022                 static unsigned long    complain;
1023                 if (time_before(complain, jiffies)) {
1024                         printk(KERN_WARNING
1025                                "NFS: Server wrote less than requested.\n");
1026                         complain = jiffies + 300 * HZ;
1027                 }
1028                 /* Can't do anything about it right now except throw
1029                  * an error. */
1030                 task->tk_status = -EIO;
1031         }
1032 #ifdef CONFIG_NFS_V3
1033         if (resp->verf->committed < argp->stable && task->tk_status >= 0) {
1034                 /* We tried a write call, but the server did not
1035                  * commit data to stable storage even though we
1036                  * requested it.
1037                  * Note: There is a known bug in Tru64 < 5.0 in which
1038                  *       the server reports NFS_DATA_SYNC, but performs
1039                  *       NFS_FILE_SYNC. We therefore implement this checking
1040                  *       as a dprintk() in order to avoid filling syslog.
1041                  */
1042                 static unsigned long    complain;
1043
1044                 if (time_before(complain, jiffies)) {
1045                         dprintk("NFS: faulty NFSv3 server %s:"
1046                                 " (committed = %d) != (stable = %d)\n",
1047                                 NFS_SERVER(inode)->hostname,
1048                                 resp->verf->committed, argp->stable);
1049                         complain = jiffies + 300 * HZ;
1050                 }
1051         }
1052 #endif
1053
1054         /*
1055          * Update attributes as result of writeback.
1056          * FIXME: There is an inherent race with invalidate_inode_pages and
1057          *        writebacks since the page->count is kept > 1 for as long
1058          *        as the page has a write request pending.
1059          */
1060         nfs_write_attributes(inode, resp->fattr);
1061         while (!list_empty(&data->pages)) {
1062                 req = nfs_list_entry(data->pages.next);
1063                 nfs_list_remove_request(req);
1064                 page = req->wb_page;
1065
1066                 dprintk("NFS: write (%x/%Ld %d@%Ld)",
1067                         req->wb_inode->i_dev,
1068                         (long long)NFS_FILEID(req->wb_inode),
1069                         req->wb_bytes,
1070                         (long long)(page_offset(page) + req->wb_offset));
1071
1072                 if (task->tk_status < 0) {
1073                         ClearPageUptodate(page);
1074                         SetPageError(page);
1075                         if (req->wb_file)
1076                                 req->wb_file->f_error = task->tk_status;
1077                         nfs_inode_remove_request(req);
1078                         dprintk(", error = %d\n", task->tk_status);
1079                         goto next;
1080                 }
1081
1082 #ifdef CONFIG_NFS_V3
1083                 if (argp->stable != NFS_UNSTABLE || resp->verf->committed == NFS_FILE_SYNC) {
1084                         nfs_inode_remove_request(req);
1085                         dprintk(" OK\n");
1086                         goto next;
1087                 }
1088                 memcpy(&req->wb_verf, resp->verf, sizeof(req->wb_verf));
1089                 req->wb_timeout = jiffies + NFS_COMMIT_DELAY;
1090                 nfs_mark_request_commit(req);
1091                 dprintk(" marked for commit\n");
1092 #else
1093                 nfs_inode_remove_request(req);
1094 #endif
1095         next:
1096                 nfs_unlock_request(req);
1097         }
1098 }
1099
1100
1101 #ifdef CONFIG_NFS_V3
1102 /*
1103  * Set up the argument/result storage required for the RPC call.
1104  */
1105 static void
1106 nfs_commit_rpcsetup(struct list_head *head, struct nfs_write_data *data)
1107 {
1108         struct nfs_page         *first, *last;
1109         struct inode            *inode;
1110         loff_t                  start, end, len;
1111
1112         /* Set up the RPC argument and reply structs
1113          * NB: take care not to mess about with data->commit et al. */
1114
1115         list_splice(head, &data->pages);
1116         INIT_LIST_HEAD(head);
1117         first = nfs_list_entry(data->pages.next);
1118         last = nfs_list_entry(data->pages.prev);
1119         inode = first->wb_inode;
1120
1121         /*
1122          * Determine the offset range of requests in the COMMIT call.
1123          * We rely on the fact that data->pages is an ordered list...
1124          */
1125         start = page_offset(first->wb_page) + first->wb_offset;
1126         end = page_offset(last->wb_page) + (last->wb_offset + last->wb_bytes);
1127         len = end - start;
1128         /* If 'len' is not a 32-bit quantity, pass '0' in the COMMIT call */
1129         if (end >= inode->i_size || len < 0 || len > (~((u32)0) >> 1))
1130                 len = 0;
1131
1132         data->inode       = inode;
1133         data->cred        = first->wb_cred;
1134         data->args.fh     = NFS_FH(inode);
1135         data->args.offset = start;
1136         data->res.count   = data->args.count = (u32)len;
1137         data->res.fattr   = &data->fattr;
1138         data->res.verf    = &data->verf;
1139 }
1140
1141 /*
1142  * Commit dirty pages
1143  */
1144 int
1145 nfs_commit_list(struct list_head *head, int how)
1146 {
1147         struct rpc_message      msg;
1148         struct rpc_clnt         *clnt;
1149         struct nfs_write_data   *data;
1150         struct rpc_task         *task;
1151         struct nfs_page         *req;
1152         int                     flags,
1153                                 async = !(how & FLUSH_SYNC);
1154         sigset_t                oldset;
1155
1156         data = nfs_writedata_alloc();
1157
1158         if (!data)
1159                 goto out_bad;
1160         task = &data->task;
1161
1162         flags = (async) ? RPC_TASK_ASYNC : 0;
1163
1164         /* Set up the argument struct */
1165         nfs_commit_rpcsetup(head, data);
1166         req = nfs_list_entry(data->pages.next);
1167         clnt = NFS_CLIENT(req->wb_inode);
1168
1169         rpc_init_task(task, clnt, nfs_commit_done, flags);
1170         task->tk_calldata = data;
1171         /* Release requests */
1172         task->tk_release = nfs_writedata_release;
1173
1174         msg.rpc_proc = NFS3PROC_COMMIT;
1175         msg.rpc_argp = &data->args;
1176         msg.rpc_resp = &data->res;
1177         msg.rpc_cred = data->cred;
1178
1179         dprintk("NFS: %4d initiated commit call\n", task->tk_pid);
1180         rpc_clnt_sigmask(clnt, &oldset);
1181         rpc_call_setup(task, &msg, 0);
1182         lock_kernel();
1183         rpc_execute(task);
1184         unlock_kernel();
1185         rpc_clnt_sigunmask(clnt, &oldset);
1186         return 0;
1187  out_bad:
1188         while (!list_empty(head)) {
1189                 req = nfs_list_entry(head->next);
1190                 nfs_list_remove_request(req);
1191                 nfs_mark_request_commit(req);
1192                 nfs_unlock_request(req);
1193         }
1194         return -ENOMEM;
1195 }
1196
1197 /*
1198  * COMMIT call returned
1199  */
1200 static void
1201 nfs_commit_done(struct rpc_task *task)
1202 {
1203         struct nfs_write_data   *data = (struct nfs_write_data *)task->tk_calldata;
1204         struct nfs_writeres     *resp = &data->res;
1205         struct nfs_page         *req;
1206         struct inode            *inode = data->inode;
1207
1208         dprintk("NFS: %4d nfs_commit_done (status %d)\n",
1209                                 task->tk_pid, task->tk_status);
1210
1211         if (nfs_async_handle_jukebox(task))
1212                 return;
1213
1214         nfs_write_attributes(inode, resp->fattr);
1215         while (!list_empty(&data->pages)) {
1216                 req = nfs_list_entry(data->pages.next);
1217                 nfs_list_remove_request(req);
1218
1219                 dprintk("NFS: commit (%x/%Ld %d@%Ld)",
1220                         req->wb_inode->i_dev,
1221                         (long long)NFS_FILEID(req->wb_inode),
1222                         req->wb_bytes,
1223                         (long long)(page_offset(req->wb_page) + req->wb_offset));
1224                 if (task->tk_status < 0) {
1225                         if (req->wb_file)
1226                                 req->wb_file->f_error = task->tk_status;
1227                         nfs_inode_remove_request(req);
1228                         dprintk(", error = %d\n", task->tk_status);
1229                         goto next;
1230                 }
1231
1232                 /* Okay, COMMIT succeeded, apparently. Check the verifier
1233                  * returned by the server against all stored verfs. */
1234                 if (!memcmp(req->wb_verf.verifier, data->verf.verifier, sizeof(data->verf.verifier))) {
1235                         /* We have a match */
1236                         nfs_inode_remove_request(req);
1237                         dprintk(" OK\n");
1238                         goto next;
1239                 }
1240                 /* We have a mismatch. Write the page again */
1241                 dprintk(" mismatch\n");
1242                 nfs_mark_request_dirty(req);
1243         next:
1244                 nfs_unlock_request(req);
1245         }
1246 }
1247 #endif
1248
1249 int nfs_flush_file(struct inode *inode, struct file *file, unsigned long idx_start,
1250                    unsigned int npages, int how)
1251 {
1252         LIST_HEAD(head);
1253         int                     res,
1254                                 error = 0;
1255
1256         spin_lock(&nfs_wreq_lock);
1257         res = nfs_scan_dirty(inode, &head, file, idx_start, npages);
1258         spin_unlock(&nfs_wreq_lock);
1259         if (res)
1260                 error = nfs_flush_list(&head, NFS_SERVER(inode)->wpages, how);
1261         if (error < 0)
1262                 return error;
1263         return res;
1264 }
1265
1266 #ifdef CONFIG_NFS_V3
1267 int nfs_commit_file(struct inode *inode, struct file *file, unsigned long idx_start,
1268                     unsigned int npages, int how)
1269 {
1270         LIST_HEAD(head);
1271         int                     res,
1272                                 error = 0;
1273
1274         spin_lock(&nfs_wreq_lock);
1275         res = nfs_scan_commit(inode, &head, file, idx_start, npages);
1276         spin_unlock(&nfs_wreq_lock);
1277         if (res)
1278                 error = nfs_commit_list(&head, how);
1279         if (error < 0)
1280                 return error;
1281         return res;
1282 }
1283 #endif
1284
1285 int nfs_sync_file(struct inode *inode, struct file *file, unsigned long idx_start,
1286                   unsigned int npages, int how)
1287 {
1288         int     error,
1289                 wait;
1290
1291         wait = how & FLUSH_WAIT;
1292         how &= ~FLUSH_WAIT;
1293
1294         if (!inode && file)
1295                 inode = file->f_dentry->d_inode;
1296
1297         do {
1298                 error = 0;
1299                 if (wait)
1300                         error = nfs_wait_on_requests(inode, file, idx_start, npages);
1301                 if (error == 0)
1302                         error = nfs_flush_file(inode, file, idx_start, npages, how);
1303 #ifdef CONFIG_NFS_V3
1304                 if (error == 0)
1305                         error = nfs_commit_file(inode, file, idx_start, npages, how);
1306 #endif
1307         } while (error > 0);
1308         return error;
1309 }
1310
1311 int nfs_init_writepagecache(void)
1312 {
1313         nfs_wdata_cachep = kmem_cache_create("nfs_write_data",
1314                                              sizeof(struct nfs_write_data),
1315                                              0, SLAB_HWCACHE_ALIGN,
1316                                              NULL, NULL);
1317         if (nfs_wdata_cachep == NULL)
1318                 return -ENOMEM;
1319
1320         return 0;
1321 }
1322
1323 void nfs_destroy_writepagecache(void)
1324 {
1325         if (kmem_cache_destroy(nfs_wdata_cachep))
1326                 printk(KERN_INFO "nfs_write_data: not all structures were freed\n");
1327 }
1328