NFS: Remove page group limit in nfs_flush_incompatible()
[sfrench/cifs-2.6.git] / fs / nfs / write.c
1 /*
2  * linux/fs/nfs/write.c
3  *
4  * Write file data over NFS.
5  *
6  * Copyright (C) 1996, 1997, Olaf Kirch <okir@monad.swb.de>
7  */
8
9 #include <linux/types.h>
10 #include <linux/slab.h>
11 #include <linux/mm.h>
12 #include <linux/pagemap.h>
13 #include <linux/file.h>
14 #include <linux/writeback.h>
15 #include <linux/swap.h>
16 #include <linux/migrate.h>
17
18 #include <linux/sunrpc/clnt.h>
19 #include <linux/nfs_fs.h>
20 #include <linux/nfs_mount.h>
21 #include <linux/nfs_page.h>
22 #include <linux/backing-dev.h>
23 #include <linux/export.h>
24 #include <linux/freezer.h>
25 #include <linux/wait.h>
26
27 #include <linux/uaccess.h>
28
29 #include "delegation.h"
30 #include "internal.h"
31 #include "iostat.h"
32 #include "nfs4_fs.h"
33 #include "fscache.h"
34 #include "pnfs.h"
35
36 #include "nfstrace.h"
37
38 #define NFSDBG_FACILITY         NFSDBG_PAGECACHE
39
40 #define MIN_POOL_WRITE          (32)
41 #define MIN_POOL_COMMIT         (4)
42
43 struct nfs_io_completion {
44         void (*complete)(void *data);
45         void *data;
46         struct kref refcount;
47 };
48
49 /*
50  * Local function declarations
51  */
52 static void nfs_redirty_request(struct nfs_page *req);
53 static const struct rpc_call_ops nfs_commit_ops;
54 static const struct nfs_pgio_completion_ops nfs_async_write_completion_ops;
55 static const struct nfs_commit_completion_ops nfs_commit_completion_ops;
56 static const struct nfs_rw_ops nfs_rw_write_ops;
57 static void nfs_clear_request_commit(struct nfs_page *req);
58 static void nfs_init_cinfo_from_inode(struct nfs_commit_info *cinfo,
59                                       struct inode *inode);
60 static struct nfs_page *
61 nfs_page_search_commits_for_head_request_locked(struct nfs_inode *nfsi,
62                                                 struct page *page);
63
64 static struct kmem_cache *nfs_wdata_cachep;
65 static mempool_t *nfs_wdata_mempool;
66 static struct kmem_cache *nfs_cdata_cachep;
67 static mempool_t *nfs_commit_mempool;
68
69 struct nfs_commit_data *nfs_commitdata_alloc(bool never_fail)
70 {
71         struct nfs_commit_data *p;
72
73         if (never_fail)
74                 p = mempool_alloc(nfs_commit_mempool, GFP_NOIO);
75         else {
76                 /* It is OK to do some reclaim, not no safe to wait
77                  * for anything to be returned to the pool.
78                  * mempool_alloc() cannot handle that particular combination,
79                  * so we need two separate attempts.
80                  */
81                 p = mempool_alloc(nfs_commit_mempool, GFP_NOWAIT);
82                 if (!p)
83                         p = kmem_cache_alloc(nfs_cdata_cachep, GFP_NOIO |
84                                              __GFP_NOWARN | __GFP_NORETRY);
85                 if (!p)
86                         return NULL;
87         }
88
89         memset(p, 0, sizeof(*p));
90         INIT_LIST_HEAD(&p->pages);
91         return p;
92 }
93 EXPORT_SYMBOL_GPL(nfs_commitdata_alloc);
94
95 void nfs_commit_free(struct nfs_commit_data *p)
96 {
97         mempool_free(p, nfs_commit_mempool);
98 }
99 EXPORT_SYMBOL_GPL(nfs_commit_free);
100
101 static struct nfs_pgio_header *nfs_writehdr_alloc(void)
102 {
103         struct nfs_pgio_header *p = mempool_alloc(nfs_wdata_mempool, GFP_NOIO);
104
105         if (p) {
106                 memset(p, 0, sizeof(*p));
107                 p->rw_mode = FMODE_WRITE;
108         }
109         return p;
110 }
111
112 static void nfs_writehdr_free(struct nfs_pgio_header *hdr)
113 {
114         mempool_free(hdr, nfs_wdata_mempool);
115 }
116
117 static struct nfs_io_completion *nfs_io_completion_alloc(gfp_t gfp_flags)
118 {
119         return kmalloc(sizeof(struct nfs_io_completion), gfp_flags);
120 }
121
122 static void nfs_io_completion_init(struct nfs_io_completion *ioc,
123                 void (*complete)(void *), void *data)
124 {
125         ioc->complete = complete;
126         ioc->data = data;
127         kref_init(&ioc->refcount);
128 }
129
130 static void nfs_io_completion_release(struct kref *kref)
131 {
132         struct nfs_io_completion *ioc = container_of(kref,
133                         struct nfs_io_completion, refcount);
134         ioc->complete(ioc->data);
135         kfree(ioc);
136 }
137
138 static void nfs_io_completion_get(struct nfs_io_completion *ioc)
139 {
140         if (ioc != NULL)
141                 kref_get(&ioc->refcount);
142 }
143
144 static void nfs_io_completion_put(struct nfs_io_completion *ioc)
145 {
146         if (ioc != NULL)
147                 kref_put(&ioc->refcount, nfs_io_completion_release);
148 }
149
150 static void nfs_context_set_write_error(struct nfs_open_context *ctx, int error)
151 {
152         ctx->error = error;
153         smp_wmb();
154         set_bit(NFS_CONTEXT_ERROR_WRITE, &ctx->flags);
155 }
156
157 /*
158  * nfs_page_find_head_request_locked - find head request associated with @page
159  *
160  * must be called while holding the inode lock.
161  *
162  * returns matching head request with reference held, or NULL if not found.
163  */
164 static struct nfs_page *
165 nfs_page_find_head_request_locked(struct nfs_inode *nfsi, struct page *page)
166 {
167         struct nfs_page *req = NULL;
168
169         if (PagePrivate(page))
170                 req = (struct nfs_page *)page_private(page);
171         else if (unlikely(PageSwapCache(page)))
172                 req = nfs_page_search_commits_for_head_request_locked(nfsi,
173                         page);
174
175         if (req) {
176                 WARN_ON_ONCE(req->wb_head != req);
177                 kref_get(&req->wb_kref);
178         }
179
180         return req;
181 }
182
183 /*
184  * nfs_page_find_head_request - find head request associated with @page
185  *
186  * returns matching head request with reference held, or NULL if not found.
187  */
188 static struct nfs_page *nfs_page_find_head_request(struct page *page)
189 {
190         struct inode *inode = page_file_mapping(page)->host;
191         struct nfs_page *req = NULL;
192
193         if (PagePrivate(page) || PageSwapCache(page)) {
194                 spin_lock(&inode->i_lock);
195                 req = nfs_page_find_head_request_locked(NFS_I(inode), page);
196                 spin_unlock(&inode->i_lock);
197         }
198         return req;
199 }
200
201 /* Adjust the file length if we're writing beyond the end */
202 static void nfs_grow_file(struct page *page, unsigned int offset, unsigned int count)
203 {
204         struct inode *inode = page_file_mapping(page)->host;
205         loff_t end, i_size;
206         pgoff_t end_index;
207
208         spin_lock(&inode->i_lock);
209         i_size = i_size_read(inode);
210         end_index = (i_size - 1) >> PAGE_SHIFT;
211         if (i_size > 0 && page_index(page) < end_index)
212                 goto out;
213         end = page_file_offset(page) + ((loff_t)offset+count);
214         if (i_size >= end)
215                 goto out;
216         i_size_write(inode, end);
217         nfs_inc_stats(inode, NFSIOS_EXTENDWRITE);
218 out:
219         spin_unlock(&inode->i_lock);
220 }
221
222 /* A writeback failed: mark the page as bad, and invalidate the page cache */
223 static void nfs_set_pageerror(struct page *page)
224 {
225         nfs_zap_mapping(page_file_mapping(page)->host, page_file_mapping(page));
226 }
227
228 /*
229  * nfs_page_group_search_locked
230  * @head - head request of page group
231  * @page_offset - offset into page
232  *
233  * Search page group with head @head to find a request that contains the
234  * page offset @page_offset.
235  *
236  * Returns a pointer to the first matching nfs request, or NULL if no
237  * match is found.
238  *
239  * Must be called with the page group lock held
240  */
241 static struct nfs_page *
242 nfs_page_group_search_locked(struct nfs_page *head, unsigned int page_offset)
243 {
244         struct nfs_page *req;
245
246         WARN_ON_ONCE(head != head->wb_head);
247         WARN_ON_ONCE(!test_bit(PG_HEADLOCK, &head->wb_head->wb_flags));
248
249         req = head;
250         do {
251                 if (page_offset >= req->wb_pgbase &&
252                     page_offset < (req->wb_pgbase + req->wb_bytes))
253                         return req;
254
255                 req = req->wb_this_page;
256         } while (req != head);
257
258         return NULL;
259 }
260
261 /*
262  * nfs_page_group_covers_page
263  * @head - head request of page group
264  *
265  * Return true if the page group with head @head covers the whole page,
266  * returns false otherwise
267  */
268 static bool nfs_page_group_covers_page(struct nfs_page *req)
269 {
270         struct nfs_page *tmp;
271         unsigned int pos = 0;
272         unsigned int len = nfs_page_length(req->wb_page);
273
274         nfs_page_group_lock(req, false);
275
276         do {
277                 tmp = nfs_page_group_search_locked(req->wb_head, pos);
278                 if (tmp) {
279                         /* no way this should happen */
280                         WARN_ON_ONCE(tmp->wb_pgbase != pos);
281                         pos += tmp->wb_bytes - (pos - tmp->wb_pgbase);
282                 }
283         } while (tmp && pos < len);
284
285         nfs_page_group_unlock(req);
286         WARN_ON_ONCE(pos > len);
287         return pos == len;
288 }
289
290 /* We can set the PG_uptodate flag if we see that a write request
291  * covers the full page.
292  */
293 static void nfs_mark_uptodate(struct nfs_page *req)
294 {
295         if (PageUptodate(req->wb_page))
296                 return;
297         if (!nfs_page_group_covers_page(req))
298                 return;
299         SetPageUptodate(req->wb_page);
300 }
301
302 static int wb_priority(struct writeback_control *wbc)
303 {
304         int ret = 0;
305
306         if (wbc->sync_mode == WB_SYNC_ALL)
307                 ret = FLUSH_COND_STABLE;
308         return ret;
309 }
310
311 /*
312  * NFS congestion control
313  */
314
315 int nfs_congestion_kb;
316
317 #define NFS_CONGESTION_ON_THRESH        (nfs_congestion_kb >> (PAGE_SHIFT-10))
318 #define NFS_CONGESTION_OFF_THRESH       \
319         (NFS_CONGESTION_ON_THRESH - (NFS_CONGESTION_ON_THRESH >> 2))
320
321 static void nfs_set_page_writeback(struct page *page)
322 {
323         struct inode *inode = page_file_mapping(page)->host;
324         struct nfs_server *nfss = NFS_SERVER(inode);
325         int ret = test_set_page_writeback(page);
326
327         WARN_ON_ONCE(ret != 0);
328
329         if (atomic_long_inc_return(&nfss->writeback) >
330                         NFS_CONGESTION_ON_THRESH)
331                 set_bdi_congested(inode_to_bdi(inode), BLK_RW_ASYNC);
332 }
333
334 static void nfs_end_page_writeback(struct nfs_page *req)
335 {
336         struct inode *inode = page_file_mapping(req->wb_page)->host;
337         struct nfs_server *nfss = NFS_SERVER(inode);
338         bool is_done;
339
340         is_done = nfs_page_group_sync_on_bit(req, PG_WB_END);
341         nfs_unlock_request(req);
342         if (!is_done)
343                 return;
344
345         end_page_writeback(req->wb_page);
346         if (atomic_long_dec_return(&nfss->writeback) < NFS_CONGESTION_OFF_THRESH)
347                 clear_bdi_congested(inode_to_bdi(inode), BLK_RW_ASYNC);
348 }
349
350
351 /* nfs_page_group_clear_bits
352  *   @req - an nfs request
353  * clears all page group related bits from @req
354  */
355 static void
356 nfs_page_group_clear_bits(struct nfs_page *req)
357 {
358         clear_bit(PG_TEARDOWN, &req->wb_flags);
359         clear_bit(PG_UNLOCKPAGE, &req->wb_flags);
360         clear_bit(PG_UPTODATE, &req->wb_flags);
361         clear_bit(PG_WB_END, &req->wb_flags);
362         clear_bit(PG_REMOVE, &req->wb_flags);
363 }
364
365
366 /*
367  * nfs_unroll_locks_and_wait -  unlock all newly locked reqs and wait on @req
368  *
369  * this is a helper function for nfs_lock_and_join_requests
370  *
371  * @inode - inode associated with request page group, must be holding inode lock
372  * @head  - head request of page group, must be holding head lock
373  * @req   - request that couldn't lock and needs to wait on the req bit lock
374  *
375  * NOTE: this must be called holding page_group bit lock and inode spin lock
376  *       and BOTH will be released before returning.
377  *
378  * returns 0 on success, < 0 on error.
379  */
380 static int
381 nfs_unroll_locks_and_wait(struct inode *inode, struct nfs_page *head,
382                           struct nfs_page *req)
383         __releases(&inode->i_lock)
384 {
385         struct nfs_page *tmp;
386         int ret;
387
388         /* relinquish all the locks successfully grabbed this run */
389         for (tmp = head->wb_this_page ; tmp != req; tmp = tmp->wb_this_page)
390                 nfs_unlock_request(tmp);
391
392         WARN_ON_ONCE(test_bit(PG_TEARDOWN, &req->wb_flags));
393
394         /* grab a ref on the request that will be waited on */
395         kref_get(&req->wb_kref);
396
397         nfs_page_group_unlock(head);
398         spin_unlock(&inode->i_lock);
399
400         /* release ref from nfs_page_find_head_request_locked */
401         nfs_unlock_and_release_request(head);
402
403         ret = nfs_wait_on_request(req);
404         nfs_release_request(req);
405
406         return ret;
407 }
408
409 /*
410  * nfs_destroy_unlinked_subrequests - destroy recently unlinked subrequests
411  *
412  * @destroy_list - request list (using wb_this_page) terminated by @old_head
413  * @old_head - the old head of the list
414  *
415  * All subrequests must be locked and removed from all lists, so at this point
416  * they are only "active" in this function, and possibly in nfs_wait_on_request
417  * with a reference held by some other context.
418  */
419 static void
420 nfs_destroy_unlinked_subrequests(struct nfs_page *destroy_list,
421                                  struct nfs_page *old_head,
422                                  struct inode *inode)
423 {
424         while (destroy_list) {
425                 struct nfs_page *subreq = destroy_list;
426
427                 destroy_list = (subreq->wb_this_page == old_head) ?
428                                    NULL : subreq->wb_this_page;
429
430                 WARN_ON_ONCE(old_head != subreq->wb_head);
431
432                 /* make sure old group is not used */
433                 subreq->wb_head = subreq;
434                 subreq->wb_this_page = subreq;
435
436                 /* subreq is now totally disconnected from page group or any
437                  * write / commit lists. last chance to wake any waiters */
438                 nfs_unlock_request(subreq);
439
440                 if (!test_bit(PG_TEARDOWN, &subreq->wb_flags)) {
441                         /* release ref on old head request */
442                         nfs_release_request(old_head);
443
444                         nfs_page_group_clear_bits(subreq);
445
446                         /* release the PG_INODE_REF reference */
447                         if (test_and_clear_bit(PG_INODE_REF, &subreq->wb_flags)) {
448                                 nfs_release_request(subreq);
449                                 spin_lock(&inode->i_lock);
450                                 NFS_I(inode)->nrequests--;
451                                 spin_unlock(&inode->i_lock);
452                         } else
453                                 WARN_ON_ONCE(1);
454                 } else {
455                         WARN_ON_ONCE(test_bit(PG_CLEAN, &subreq->wb_flags));
456                         /* zombie requests have already released the last
457                          * reference and were waiting on the rest of the
458                          * group to complete. Since it's no longer part of a
459                          * group, simply free the request */
460                         nfs_page_group_clear_bits(subreq);
461                         nfs_free_request(subreq);
462                 }
463         }
464 }
465
466 /*
467  * nfs_lock_and_join_requests - join all subreqs to the head req and return
468  *                              a locked reference, cancelling any pending
469  *                              operations for this page.
470  *
471  * @page - the page used to lookup the "page group" of nfs_page structures
472  *
473  * This function joins all sub requests to the head request by first
474  * locking all requests in the group, cancelling any pending operations
475  * and finally updating the head request to cover the whole range covered by
476  * the (former) group.  All subrequests are removed from any write or commit
477  * lists, unlinked from the group and destroyed.
478  *
479  * Returns a locked, referenced pointer to the head request - which after
480  * this call is guaranteed to be the only request associated with the page.
481  * Returns NULL if no requests are found for @page, or a ERR_PTR if an
482  * error was encountered.
483  */
484 static struct nfs_page *
485 nfs_lock_and_join_requests(struct page *page)
486 {
487         struct inode *inode = page_file_mapping(page)->host;
488         struct nfs_page *head, *subreq;
489         struct nfs_page *destroy_list = NULL;
490         unsigned int total_bytes;
491         int ret;
492
493 try_again:
494         spin_lock(&inode->i_lock);
495
496         /*
497          * A reference is taken only on the head request which acts as a
498          * reference to the whole page group - the group will not be destroyed
499          * until the head reference is released.
500          */
501         head = nfs_page_find_head_request_locked(NFS_I(inode), page);
502
503         if (!head) {
504                 spin_unlock(&inode->i_lock);
505                 return NULL;
506         }
507
508         /* lock the page head first in order to avoid an ABBA inefficiency */
509         if (!nfs_lock_request(head)) {
510                 spin_unlock(&inode->i_lock);
511                 ret = nfs_wait_on_request(head);
512                 nfs_release_request(head);
513                 if (ret < 0)
514                         return ERR_PTR(ret);
515                 goto try_again;
516         }
517
518         /* holding inode lock, so always make a non-blocking call to try the
519          * page group lock */
520         ret = nfs_page_group_lock(head, true);
521         if (ret < 0) {
522                 spin_unlock(&inode->i_lock);
523
524                 nfs_page_group_lock_wait(head);
525                 nfs_unlock_and_release_request(head);
526                 goto try_again;
527         }
528
529         /* lock each request in the page group */
530         total_bytes = head->wb_bytes;
531         for (subreq = head->wb_this_page; subreq != head;
532                         subreq = subreq->wb_this_page) {
533                 if (!nfs_lock_request(subreq)) {
534                         /* releases page group bit lock and
535                          * inode spin lock and all references */
536                         ret = nfs_unroll_locks_and_wait(inode, head,
537                                 subreq);
538
539                         if (ret == 0)
540                                 goto try_again;
541
542                         return ERR_PTR(ret);
543                 }
544                 /*
545                  * Subrequests are always contiguous, non overlapping
546                  * and in order - but may be repeated (mirrored writes).
547                  */
548                 if (subreq->wb_offset == (head->wb_offset + total_bytes)) {
549                         /* keep track of how many bytes this group covers */
550                         total_bytes += subreq->wb_bytes;
551                 } else if (WARN_ON_ONCE(subreq->wb_offset < head->wb_offset ||
552                             ((subreq->wb_offset + subreq->wb_bytes) >
553                              (head->wb_offset + total_bytes)))) {
554                         nfs_unlock_request(subreq);
555                         nfs_unroll_locks_and_wait(inode, head, subreq);
556                         return ERR_PTR(-EIO);
557                 }
558         }
559
560         /* Now that all requests are locked, make sure they aren't on any list.
561          * Commit list removal accounting is done after locks are dropped */
562         subreq = head;
563         do {
564                 nfs_clear_request_commit(subreq);
565                 subreq = subreq->wb_this_page;
566         } while (subreq != head);
567
568         /* unlink subrequests from head, destroy them later */
569         if (head->wb_this_page != head) {
570                 /* destroy list will be terminated by head */
571                 destroy_list = head->wb_this_page;
572                 head->wb_this_page = head;
573
574                 /* change head request to cover whole range that
575                  * the former page group covered */
576                 head->wb_bytes = total_bytes;
577         }
578
579         /* Postpone destruction of this request */
580         if (test_and_clear_bit(PG_REMOVE, &head->wb_flags)) {
581                 set_bit(PG_INODE_REF, &head->wb_flags);
582                 kref_get(&head->wb_kref);
583                 NFS_I(inode)->nrequests++;
584         }
585
586         /*
587          * prepare head request to be added to new pgio descriptor
588          */
589         nfs_page_group_clear_bits(head);
590
591         nfs_page_group_unlock(head);
592
593         /* drop lock to clean uprequests on destroy list */
594         spin_unlock(&inode->i_lock);
595
596         nfs_destroy_unlinked_subrequests(destroy_list, head, inode);
597
598         /* still holds ref on head from nfs_page_find_head_request_locked
599          * and still has lock on head from lock loop */
600         return head;
601 }
602
603 static void nfs_write_error_remove_page(struct nfs_page *req)
604 {
605         nfs_end_page_writeback(req);
606         generic_error_remove_page(page_file_mapping(req->wb_page),
607                                   req->wb_page);
608         nfs_release_request(req);
609 }
610
611 static bool
612 nfs_error_is_fatal_on_server(int err)
613 {
614         switch (err) {
615         case 0:
616         case -ERESTARTSYS:
617         case -EINTR:
618                 return false;
619         }
620         return nfs_error_is_fatal(err);
621 }
622
623 /*
624  * Find an associated nfs write request, and prepare to flush it out
625  * May return an error if the user signalled nfs_wait_on_request().
626  */
627 static int nfs_page_async_flush(struct nfs_pageio_descriptor *pgio,
628                                 struct page *page)
629 {
630         struct nfs_page *req;
631         int ret = 0;
632
633         req = nfs_lock_and_join_requests(page);
634         if (!req)
635                 goto out;
636         ret = PTR_ERR(req);
637         if (IS_ERR(req))
638                 goto out;
639
640         nfs_set_page_writeback(page);
641         WARN_ON_ONCE(test_bit(PG_CLEAN, &req->wb_flags));
642
643         ret = 0;
644         /* If there is a fatal error that covers this write, just exit */
645         if (nfs_error_is_fatal_on_server(req->wb_context->error))
646                 goto out_launder;
647
648         if (!nfs_pageio_add_request(pgio, req)) {
649                 ret = pgio->pg_error;
650                 /*
651                  * Remove the problematic req upon fatal errors on the server
652                  */
653                 if (nfs_error_is_fatal(ret)) {
654                         nfs_context_set_write_error(req->wb_context, ret);
655                         if (nfs_error_is_fatal_on_server(ret))
656                                 goto out_launder;
657                 }
658                 nfs_redirty_request(req);
659                 ret = -EAGAIN;
660         } else
661                 nfs_add_stats(page_file_mapping(page)->host,
662                                 NFSIOS_WRITEPAGES, 1);
663 out:
664         return ret;
665 out_launder:
666         nfs_write_error_remove_page(req);
667         return ret;
668 }
669
670 static int nfs_do_writepage(struct page *page, struct writeback_control *wbc,
671                             struct nfs_pageio_descriptor *pgio)
672 {
673         int ret;
674
675         nfs_pageio_cond_complete(pgio, page_index(page));
676         ret = nfs_page_async_flush(pgio, page);
677         if (ret == -EAGAIN) {
678                 redirty_page_for_writepage(wbc, page);
679                 ret = 0;
680         }
681         return ret;
682 }
683
684 /*
685  * Write an mmapped page to the server.
686  */
687 static int nfs_writepage_locked(struct page *page,
688                                 struct writeback_control *wbc)
689 {
690         struct nfs_pageio_descriptor pgio;
691         struct inode *inode = page_file_mapping(page)->host;
692         int err;
693
694         nfs_inc_stats(inode, NFSIOS_VFSWRITEPAGE);
695         nfs_pageio_init_write(&pgio, inode, 0,
696                                 false, &nfs_async_write_completion_ops);
697         err = nfs_do_writepage(page, wbc, &pgio);
698         nfs_pageio_complete(&pgio);
699         if (err < 0)
700                 return err;
701         if (pgio.pg_error < 0)
702                 return pgio.pg_error;
703         return 0;
704 }
705
706 int nfs_writepage(struct page *page, struct writeback_control *wbc)
707 {
708         int ret;
709
710         ret = nfs_writepage_locked(page, wbc);
711         unlock_page(page);
712         return ret;
713 }
714
715 static int nfs_writepages_callback(struct page *page, struct writeback_control *wbc, void *data)
716 {
717         int ret;
718
719         ret = nfs_do_writepage(page, wbc, data);
720         unlock_page(page);
721         return ret;
722 }
723
724 static void nfs_io_completion_commit(void *inode)
725 {
726         nfs_commit_inode(inode, 0);
727 }
728
729 int nfs_writepages(struct address_space *mapping, struct writeback_control *wbc)
730 {
731         struct inode *inode = mapping->host;
732         struct nfs_pageio_descriptor pgio;
733         struct nfs_io_completion *ioc = nfs_io_completion_alloc(GFP_NOFS);
734         int err;
735
736         nfs_inc_stats(inode, NFSIOS_VFSWRITEPAGES);
737
738         if (ioc)
739                 nfs_io_completion_init(ioc, nfs_io_completion_commit, inode);
740
741         nfs_pageio_init_write(&pgio, inode, wb_priority(wbc), false,
742                                 &nfs_async_write_completion_ops);
743         pgio.pg_io_completion = ioc;
744         err = write_cache_pages(mapping, wbc, nfs_writepages_callback, &pgio);
745         nfs_pageio_complete(&pgio);
746         nfs_io_completion_put(ioc);
747
748         if (err < 0)
749                 goto out_err;
750         err = pgio.pg_error;
751         if (err < 0)
752                 goto out_err;
753         return 0;
754 out_err:
755         return err;
756 }
757
758 /*
759  * Insert a write request into an inode
760  */
761 static void nfs_inode_add_request(struct inode *inode, struct nfs_page *req)
762 {
763         struct nfs_inode *nfsi = NFS_I(inode);
764
765         WARN_ON_ONCE(req->wb_this_page != req);
766
767         /* Lock the request! */
768         nfs_lock_request(req);
769
770         spin_lock(&inode->i_lock);
771         if (!nfsi->nrequests &&
772             NFS_PROTO(inode)->have_delegation(inode, FMODE_WRITE))
773                 inode->i_version++;
774         /*
775          * Swap-space should not get truncated. Hence no need to plug the race
776          * with invalidate/truncate.
777          */
778         if (likely(!PageSwapCache(req->wb_page))) {
779                 set_bit(PG_MAPPED, &req->wb_flags);
780                 SetPagePrivate(req->wb_page);
781                 set_page_private(req->wb_page, (unsigned long)req);
782         }
783         nfsi->nrequests++;
784         /* this a head request for a page group - mark it as having an
785          * extra reference so sub groups can follow suit.
786          * This flag also informs pgio layer when to bump nrequests when
787          * adding subrequests. */
788         WARN_ON(test_and_set_bit(PG_INODE_REF, &req->wb_flags));
789         kref_get(&req->wb_kref);
790         spin_unlock(&inode->i_lock);
791 }
792
793 /*
794  * Remove a write request from an inode
795  */
796 static void nfs_inode_remove_request(struct nfs_page *req)
797 {
798         struct inode *inode = d_inode(req->wb_context->dentry);
799         struct nfs_inode *nfsi = NFS_I(inode);
800         struct nfs_page *head;
801
802         if (nfs_page_group_sync_on_bit(req, PG_REMOVE)) {
803                 head = req->wb_head;
804
805                 spin_lock(&inode->i_lock);
806                 if (likely(head->wb_page && !PageSwapCache(head->wb_page))) {
807                         set_page_private(head->wb_page, 0);
808                         ClearPagePrivate(head->wb_page);
809                         clear_bit(PG_MAPPED, &head->wb_flags);
810                 }
811                 nfsi->nrequests--;
812                 spin_unlock(&inode->i_lock);
813         } else {
814                 spin_lock(&inode->i_lock);
815                 nfsi->nrequests--;
816                 spin_unlock(&inode->i_lock);
817         }
818
819         if (test_and_clear_bit(PG_INODE_REF, &req->wb_flags))
820                 nfs_release_request(req);
821 }
822
823 static void
824 nfs_mark_request_dirty(struct nfs_page *req)
825 {
826         if (req->wb_page)
827                 __set_page_dirty_nobuffers(req->wb_page);
828 }
829
830 /*
831  * nfs_page_search_commits_for_head_request_locked
832  *
833  * Search through commit lists on @inode for the head request for @page.
834  * Must be called while holding the inode (which is cinfo) lock.
835  *
836  * Returns the head request if found, or NULL if not found.
837  */
838 static struct nfs_page *
839 nfs_page_search_commits_for_head_request_locked(struct nfs_inode *nfsi,
840                                                 struct page *page)
841 {
842         struct nfs_page *freq, *t;
843         struct nfs_commit_info cinfo;
844         struct inode *inode = &nfsi->vfs_inode;
845
846         nfs_init_cinfo_from_inode(&cinfo, inode);
847
848         /* search through pnfs commit lists */
849         freq = pnfs_search_commit_reqs(inode, &cinfo, page);
850         if (freq)
851                 return freq->wb_head;
852
853         /* Linearly search the commit list for the correct request */
854         list_for_each_entry_safe(freq, t, &cinfo.mds->list, wb_list) {
855                 if (freq->wb_page == page)
856                         return freq->wb_head;
857         }
858
859         return NULL;
860 }
861
862 /**
863  * nfs_request_add_commit_list_locked - add request to a commit list
864  * @req: pointer to a struct nfs_page
865  * @dst: commit list head
866  * @cinfo: holds list lock and accounting info
867  *
868  * This sets the PG_CLEAN bit, updates the cinfo count of
869  * number of outstanding requests requiring a commit as well as
870  * the MM page stats.
871  *
872  * The caller must hold cinfo->inode->i_lock, and the nfs_page lock.
873  */
874 void
875 nfs_request_add_commit_list_locked(struct nfs_page *req, struct list_head *dst,
876                             struct nfs_commit_info *cinfo)
877 {
878         set_bit(PG_CLEAN, &req->wb_flags);
879         nfs_list_add_request(req, dst);
880         cinfo->mds->ncommit++;
881 }
882 EXPORT_SYMBOL_GPL(nfs_request_add_commit_list_locked);
883
884 /**
885  * nfs_request_add_commit_list - add request to a commit list
886  * @req: pointer to a struct nfs_page
887  * @dst: commit list head
888  * @cinfo: holds list lock and accounting info
889  *
890  * This sets the PG_CLEAN bit, updates the cinfo count of
891  * number of outstanding requests requiring a commit as well as
892  * the MM page stats.
893  *
894  * The caller must _not_ hold the cinfo->lock, but must be
895  * holding the nfs_page lock.
896  */
897 void
898 nfs_request_add_commit_list(struct nfs_page *req, struct nfs_commit_info *cinfo)
899 {
900         spin_lock(&cinfo->inode->i_lock);
901         nfs_request_add_commit_list_locked(req, &cinfo->mds->list, cinfo);
902         spin_unlock(&cinfo->inode->i_lock);
903         if (req->wb_page)
904                 nfs_mark_page_unstable(req->wb_page, cinfo);
905 }
906 EXPORT_SYMBOL_GPL(nfs_request_add_commit_list);
907
908 /**
909  * nfs_request_remove_commit_list - Remove request from a commit list
910  * @req: pointer to a nfs_page
911  * @cinfo: holds list lock and accounting info
912  *
913  * This clears the PG_CLEAN bit, and updates the cinfo's count of
914  * number of outstanding requests requiring a commit
915  * It does not update the MM page stats.
916  *
917  * The caller _must_ hold the cinfo->lock and the nfs_page lock.
918  */
919 void
920 nfs_request_remove_commit_list(struct nfs_page *req,
921                                struct nfs_commit_info *cinfo)
922 {
923         if (!test_and_clear_bit(PG_CLEAN, &(req)->wb_flags))
924                 return;
925         nfs_list_remove_request(req);
926         cinfo->mds->ncommit--;
927 }
928 EXPORT_SYMBOL_GPL(nfs_request_remove_commit_list);
929
930 static void nfs_init_cinfo_from_inode(struct nfs_commit_info *cinfo,
931                                       struct inode *inode)
932 {
933         cinfo->inode = inode;
934         cinfo->mds = &NFS_I(inode)->commit_info;
935         cinfo->ds = pnfs_get_ds_info(inode);
936         cinfo->dreq = NULL;
937         cinfo->completion_ops = &nfs_commit_completion_ops;
938 }
939
940 void nfs_init_cinfo(struct nfs_commit_info *cinfo,
941                     struct inode *inode,
942                     struct nfs_direct_req *dreq)
943 {
944         if (dreq)
945                 nfs_init_cinfo_from_dreq(cinfo, dreq);
946         else
947                 nfs_init_cinfo_from_inode(cinfo, inode);
948 }
949 EXPORT_SYMBOL_GPL(nfs_init_cinfo);
950
951 /*
952  * Add a request to the inode's commit list.
953  */
954 void
955 nfs_mark_request_commit(struct nfs_page *req, struct pnfs_layout_segment *lseg,
956                         struct nfs_commit_info *cinfo, u32 ds_commit_idx)
957 {
958         if (pnfs_mark_request_commit(req, lseg, cinfo, ds_commit_idx))
959                 return;
960         nfs_request_add_commit_list(req, cinfo);
961 }
962
963 static void
964 nfs_clear_page_commit(struct page *page)
965 {
966         dec_node_page_state(page, NR_UNSTABLE_NFS);
967         dec_wb_stat(&inode_to_bdi(page_file_mapping(page)->host)->wb,
968                     WB_RECLAIMABLE);
969 }
970
971 /* Called holding inode (/cinfo) lock */
972 static void
973 nfs_clear_request_commit(struct nfs_page *req)
974 {
975         if (test_bit(PG_CLEAN, &req->wb_flags)) {
976                 struct inode *inode = d_inode(req->wb_context->dentry);
977                 struct nfs_commit_info cinfo;
978
979                 nfs_init_cinfo_from_inode(&cinfo, inode);
980                 if (!pnfs_clear_request_commit(req, &cinfo)) {
981                         nfs_request_remove_commit_list(req, &cinfo);
982                 }
983                 nfs_clear_page_commit(req->wb_page);
984         }
985 }
986
987 int nfs_write_need_commit(struct nfs_pgio_header *hdr)
988 {
989         if (hdr->verf.committed == NFS_DATA_SYNC)
990                 return hdr->lseg == NULL;
991         return hdr->verf.committed != NFS_FILE_SYNC;
992 }
993
994 static void nfs_async_write_init(struct nfs_pgio_header *hdr)
995 {
996         nfs_io_completion_get(hdr->io_completion);
997 }
998
999 static void nfs_write_completion(struct nfs_pgio_header *hdr)
1000 {
1001         struct nfs_commit_info cinfo;
1002         unsigned long bytes = 0;
1003
1004         if (test_bit(NFS_IOHDR_REDO, &hdr->flags))
1005                 goto out;
1006         nfs_init_cinfo_from_inode(&cinfo, hdr->inode);
1007         while (!list_empty(&hdr->pages)) {
1008                 struct nfs_page *req = nfs_list_entry(hdr->pages.next);
1009
1010                 bytes += req->wb_bytes;
1011                 nfs_list_remove_request(req);
1012                 if (test_bit(NFS_IOHDR_ERROR, &hdr->flags) &&
1013                     (hdr->good_bytes < bytes)) {
1014                         nfs_set_pageerror(req->wb_page);
1015                         nfs_context_set_write_error(req->wb_context, hdr->error);
1016                         goto remove_req;
1017                 }
1018                 if (nfs_write_need_commit(hdr)) {
1019                         memcpy(&req->wb_verf, &hdr->verf.verifier, sizeof(req->wb_verf));
1020                         nfs_mark_request_commit(req, hdr->lseg, &cinfo,
1021                                 hdr->pgio_mirror_idx);
1022                         goto next;
1023                 }
1024 remove_req:
1025                 nfs_inode_remove_request(req);
1026 next:
1027                 nfs_end_page_writeback(req);
1028                 nfs_release_request(req);
1029         }
1030 out:
1031         nfs_io_completion_put(hdr->io_completion);
1032         hdr->release(hdr);
1033 }
1034
1035 unsigned long
1036 nfs_reqs_to_commit(struct nfs_commit_info *cinfo)
1037 {
1038         return cinfo->mds->ncommit;
1039 }
1040
1041 /* cinfo->inode->i_lock held by caller */
1042 int
1043 nfs_scan_commit_list(struct list_head *src, struct list_head *dst,
1044                      struct nfs_commit_info *cinfo, int max)
1045 {
1046         struct nfs_page *req, *tmp;
1047         int ret = 0;
1048
1049         list_for_each_entry_safe(req, tmp, src, wb_list) {
1050                 if (!nfs_lock_request(req))
1051                         continue;
1052                 kref_get(&req->wb_kref);
1053                 if (cond_resched_lock(&cinfo->inode->i_lock))
1054                         list_safe_reset_next(req, tmp, wb_list);
1055                 nfs_request_remove_commit_list(req, cinfo);
1056                 nfs_list_add_request(req, dst);
1057                 ret++;
1058                 if ((ret == max) && !cinfo->dreq)
1059                         break;
1060         }
1061         return ret;
1062 }
1063
1064 /*
1065  * nfs_scan_commit - Scan an inode for commit requests
1066  * @inode: NFS inode to scan
1067  * @dst: mds destination list
1068  * @cinfo: mds and ds lists of reqs ready to commit
1069  *
1070  * Moves requests from the inode's 'commit' request list.
1071  * The requests are *not* checked to ensure that they form a contiguous set.
1072  */
1073 int
1074 nfs_scan_commit(struct inode *inode, struct list_head *dst,
1075                 struct nfs_commit_info *cinfo)
1076 {
1077         int ret = 0;
1078
1079         spin_lock(&cinfo->inode->i_lock);
1080         if (cinfo->mds->ncommit > 0) {
1081                 const int max = INT_MAX;
1082
1083                 ret = nfs_scan_commit_list(&cinfo->mds->list, dst,
1084                                            cinfo, max);
1085                 ret += pnfs_scan_commit_lists(inode, cinfo, max - ret);
1086         }
1087         spin_unlock(&cinfo->inode->i_lock);
1088         return ret;
1089 }
1090
1091 /*
1092  * Search for an existing write request, and attempt to update
1093  * it to reflect a new dirty region on a given page.
1094  *
1095  * If the attempt fails, then the existing request is flushed out
1096  * to disk.
1097  */
1098 static struct nfs_page *nfs_try_to_update_request(struct inode *inode,
1099                 struct page *page,
1100                 unsigned int offset,
1101                 unsigned int bytes)
1102 {
1103         struct nfs_page *req;
1104         unsigned int rqend;
1105         unsigned int end;
1106         int error;
1107
1108         end = offset + bytes;
1109
1110         req = nfs_lock_and_join_requests(page);
1111         if (IS_ERR_OR_NULL(req))
1112                 return req;
1113
1114         rqend = req->wb_offset + req->wb_bytes;
1115         /*
1116          * Tell the caller to flush out the request if
1117          * the offsets are non-contiguous.
1118          * Note: nfs_flush_incompatible() will already
1119          * have flushed out requests having wrong owners.
1120          */
1121         if (offset > rqend || end < req->wb_offset)
1122                 goto out_flushme;
1123
1124         /* Okay, the request matches. Update the region */
1125         if (offset < req->wb_offset) {
1126                 req->wb_offset = offset;
1127                 req->wb_pgbase = offset;
1128         }
1129         if (end > rqend)
1130                 req->wb_bytes = end - req->wb_offset;
1131         else
1132                 req->wb_bytes = rqend - req->wb_offset;
1133         return req;
1134 out_flushme:
1135         /*
1136          * Note: we mark the request dirty here because
1137          * nfs_lock_and_join_requests() cannot preserve
1138          * commit flags, so we have to replay the write.
1139          */
1140         nfs_mark_request_dirty(req);
1141         nfs_unlock_and_release_request(req);
1142         error = nfs_wb_page(inode, page);
1143         return (error < 0) ? ERR_PTR(error) : NULL;
1144 }
1145
1146 /*
1147  * Try to update an existing write request, or create one if there is none.
1148  *
1149  * Note: Should always be called with the Page Lock held to prevent races
1150  * if we have to add a new request. Also assumes that the caller has
1151  * already called nfs_flush_incompatible() if necessary.
1152  */
1153 static struct nfs_page * nfs_setup_write_request(struct nfs_open_context* ctx,
1154                 struct page *page, unsigned int offset, unsigned int bytes)
1155 {
1156         struct inode *inode = page_file_mapping(page)->host;
1157         struct nfs_page *req;
1158
1159         req = nfs_try_to_update_request(inode, page, offset, bytes);
1160         if (req != NULL)
1161                 goto out;
1162         req = nfs_create_request(ctx, page, NULL, offset, bytes);
1163         if (IS_ERR(req))
1164                 goto out;
1165         nfs_inode_add_request(inode, req);
1166 out:
1167         return req;
1168 }
1169
1170 static int nfs_writepage_setup(struct nfs_open_context *ctx, struct page *page,
1171                 unsigned int offset, unsigned int count)
1172 {
1173         struct nfs_page *req;
1174
1175         req = nfs_setup_write_request(ctx, page, offset, count);
1176         if (IS_ERR(req))
1177                 return PTR_ERR(req);
1178         /* Update file length */
1179         nfs_grow_file(page, offset, count);
1180         nfs_mark_uptodate(req);
1181         nfs_mark_request_dirty(req);
1182         nfs_unlock_and_release_request(req);
1183         return 0;
1184 }
1185
1186 int nfs_flush_incompatible(struct file *file, struct page *page)
1187 {
1188         struct nfs_open_context *ctx = nfs_file_open_context(file);
1189         struct nfs_lock_context *l_ctx;
1190         struct file_lock_context *flctx = file_inode(file)->i_flctx;
1191         struct nfs_page *req;
1192         int do_flush, status;
1193         /*
1194          * Look for a request corresponding to this page. If there
1195          * is one, and it belongs to another file, we flush it out
1196          * before we try to copy anything into the page. Do this
1197          * due to the lack of an ACCESS-type call in NFSv2.
1198          * Also do the same if we find a request from an existing
1199          * dropped page.
1200          */
1201         do {
1202                 req = nfs_page_find_head_request(page);
1203                 if (req == NULL)
1204                         return 0;
1205                 l_ctx = req->wb_lock_context;
1206                 do_flush = req->wb_page != page ||
1207                         !nfs_match_open_context(req->wb_context, ctx);
1208                 if (l_ctx && flctx &&
1209                     !(list_empty_careful(&flctx->flc_posix) &&
1210                       list_empty_careful(&flctx->flc_flock))) {
1211                         do_flush |= l_ctx->lockowner != current->files;
1212                 }
1213                 nfs_release_request(req);
1214                 if (!do_flush)
1215                         return 0;
1216                 status = nfs_wb_page(page_file_mapping(page)->host, page);
1217         } while (status == 0);
1218         return status;
1219 }
1220
1221 /*
1222  * Avoid buffered writes when a open context credential's key would
1223  * expire soon.
1224  *
1225  * Returns -EACCES if the key will expire within RPC_KEY_EXPIRE_FAIL.
1226  *
1227  * Return 0 and set a credential flag which triggers the inode to flush
1228  * and performs  NFS_FILE_SYNC writes if the key will expired within
1229  * RPC_KEY_EXPIRE_TIMEO.
1230  */
1231 int
1232 nfs_key_timeout_notify(struct file *filp, struct inode *inode)
1233 {
1234         struct nfs_open_context *ctx = nfs_file_open_context(filp);
1235         struct rpc_auth *auth = NFS_SERVER(inode)->client->cl_auth;
1236
1237         return rpcauth_key_timeout_notify(auth, ctx->cred);
1238 }
1239
1240 /*
1241  * Test if the open context credential key is marked to expire soon.
1242  */
1243 bool nfs_ctx_key_to_expire(struct nfs_open_context *ctx, struct inode *inode)
1244 {
1245         struct rpc_auth *auth = NFS_SERVER(inode)->client->cl_auth;
1246
1247         return rpcauth_cred_key_to_expire(auth, ctx->cred);
1248 }
1249
1250 /*
1251  * If the page cache is marked as unsafe or invalid, then we can't rely on
1252  * the PageUptodate() flag. In this case, we will need to turn off
1253  * write optimisations that depend on the page contents being correct.
1254  */
1255 static bool nfs_write_pageuptodate(struct page *page, struct inode *inode)
1256 {
1257         struct nfs_inode *nfsi = NFS_I(inode);
1258
1259         if (nfs_have_delegated_attributes(inode))
1260                 goto out;
1261         if (nfsi->cache_validity & NFS_INO_REVAL_PAGECACHE)
1262                 return false;
1263         smp_rmb();
1264         if (test_bit(NFS_INO_INVALIDATING, &nfsi->flags))
1265                 return false;
1266 out:
1267         if (nfsi->cache_validity & NFS_INO_INVALID_DATA)
1268                 return false;
1269         return PageUptodate(page) != 0;
1270 }
1271
1272 static bool
1273 is_whole_file_wrlock(struct file_lock *fl)
1274 {
1275         return fl->fl_start == 0 && fl->fl_end == OFFSET_MAX &&
1276                         fl->fl_type == F_WRLCK;
1277 }
1278
1279 /* If we know the page is up to date, and we're not using byte range locks (or
1280  * if we have the whole file locked for writing), it may be more efficient to
1281  * extend the write to cover the entire page in order to avoid fragmentation
1282  * inefficiencies.
1283  *
1284  * If the file is opened for synchronous writes then we can just skip the rest
1285  * of the checks.
1286  */
1287 static int nfs_can_extend_write(struct file *file, struct page *page, struct inode *inode)
1288 {
1289         int ret;
1290         struct file_lock_context *flctx = inode->i_flctx;
1291         struct file_lock *fl;
1292
1293         if (file->f_flags & O_DSYNC)
1294                 return 0;
1295         if (!nfs_write_pageuptodate(page, inode))
1296                 return 0;
1297         if (NFS_PROTO(inode)->have_delegation(inode, FMODE_WRITE))
1298                 return 1;
1299         if (!flctx || (list_empty_careful(&flctx->flc_flock) &&
1300                        list_empty_careful(&flctx->flc_posix)))
1301                 return 1;
1302
1303         /* Check to see if there are whole file write locks */
1304         ret = 0;
1305         spin_lock(&flctx->flc_lock);
1306         if (!list_empty(&flctx->flc_posix)) {
1307                 fl = list_first_entry(&flctx->flc_posix, struct file_lock,
1308                                         fl_list);
1309                 if (is_whole_file_wrlock(fl))
1310                         ret = 1;
1311         } else if (!list_empty(&flctx->flc_flock)) {
1312                 fl = list_first_entry(&flctx->flc_flock, struct file_lock,
1313                                         fl_list);
1314                 if (fl->fl_type == F_WRLCK)
1315                         ret = 1;
1316         }
1317         spin_unlock(&flctx->flc_lock);
1318         return ret;
1319 }
1320
1321 /*
1322  * Update and possibly write a cached page of an NFS file.
1323  *
1324  * XXX: Keep an eye on generic_file_read to make sure it doesn't do bad
1325  * things with a page scheduled for an RPC call (e.g. invalidate it).
1326  */
1327 int nfs_updatepage(struct file *file, struct page *page,
1328                 unsigned int offset, unsigned int count)
1329 {
1330         struct nfs_open_context *ctx = nfs_file_open_context(file);
1331         struct inode    *inode = page_file_mapping(page)->host;
1332         int             status = 0;
1333
1334         nfs_inc_stats(inode, NFSIOS_VFSUPDATEPAGE);
1335
1336         dprintk("NFS:       nfs_updatepage(%pD2 %d@%lld)\n",
1337                 file, count, (long long)(page_file_offset(page) + offset));
1338
1339         if (!count)
1340                 goto out;
1341
1342         if (nfs_can_extend_write(file, page, inode)) {
1343                 count = max(count + offset, nfs_page_length(page));
1344                 offset = 0;
1345         }
1346
1347         status = nfs_writepage_setup(ctx, page, offset, count);
1348         if (status < 0)
1349                 nfs_set_pageerror(page);
1350         else
1351                 __set_page_dirty_nobuffers(page);
1352 out:
1353         dprintk("NFS:       nfs_updatepage returns %d (isize %lld)\n",
1354                         status, (long long)i_size_read(inode));
1355         return status;
1356 }
1357
1358 static int flush_task_priority(int how)
1359 {
1360         switch (how & (FLUSH_HIGHPRI|FLUSH_LOWPRI)) {
1361                 case FLUSH_HIGHPRI:
1362                         return RPC_PRIORITY_HIGH;
1363                 case FLUSH_LOWPRI:
1364                         return RPC_PRIORITY_LOW;
1365         }
1366         return RPC_PRIORITY_NORMAL;
1367 }
1368
1369 static void nfs_initiate_write(struct nfs_pgio_header *hdr,
1370                                struct rpc_message *msg,
1371                                const struct nfs_rpc_ops *rpc_ops,
1372                                struct rpc_task_setup *task_setup_data, int how)
1373 {
1374         int priority = flush_task_priority(how);
1375
1376         task_setup_data->priority = priority;
1377         rpc_ops->write_setup(hdr, msg);
1378
1379         nfs4_state_protect_write(NFS_SERVER(hdr->inode)->nfs_client,
1380                                  &task_setup_data->rpc_client, msg, hdr);
1381 }
1382
1383 /* If a nfs_flush_* function fails, it should remove reqs from @head and
1384  * call this on each, which will prepare them to be retried on next
1385  * writeback using standard nfs.
1386  */
1387 static void nfs_redirty_request(struct nfs_page *req)
1388 {
1389         nfs_mark_request_dirty(req);
1390         set_bit(NFS_CONTEXT_RESEND_WRITES, &req->wb_context->flags);
1391         nfs_end_page_writeback(req);
1392         nfs_release_request(req);
1393 }
1394
1395 static void nfs_async_write_error(struct list_head *head)
1396 {
1397         struct nfs_page *req;
1398
1399         while (!list_empty(head)) {
1400                 req = nfs_list_entry(head->next);
1401                 nfs_list_remove_request(req);
1402                 nfs_redirty_request(req);
1403         }
1404 }
1405
1406 static void nfs_async_write_reschedule_io(struct nfs_pgio_header *hdr)
1407 {
1408         nfs_async_write_error(&hdr->pages);
1409 }
1410
1411 static const struct nfs_pgio_completion_ops nfs_async_write_completion_ops = {
1412         .init_hdr = nfs_async_write_init,
1413         .error_cleanup = nfs_async_write_error,
1414         .completion = nfs_write_completion,
1415         .reschedule_io = nfs_async_write_reschedule_io,
1416 };
1417
1418 void nfs_pageio_init_write(struct nfs_pageio_descriptor *pgio,
1419                                struct inode *inode, int ioflags, bool force_mds,
1420                                const struct nfs_pgio_completion_ops *compl_ops)
1421 {
1422         struct nfs_server *server = NFS_SERVER(inode);
1423         const struct nfs_pageio_ops *pg_ops = &nfs_pgio_rw_ops;
1424
1425 #ifdef CONFIG_NFS_V4_1
1426         if (server->pnfs_curr_ld && !force_mds)
1427                 pg_ops = server->pnfs_curr_ld->pg_write_ops;
1428 #endif
1429         nfs_pageio_init(pgio, inode, pg_ops, compl_ops, &nfs_rw_write_ops,
1430                         server->wsize, ioflags, GFP_NOIO);
1431 }
1432 EXPORT_SYMBOL_GPL(nfs_pageio_init_write);
1433
1434 void nfs_pageio_reset_write_mds(struct nfs_pageio_descriptor *pgio)
1435 {
1436         struct nfs_pgio_mirror *mirror;
1437
1438         if (pgio->pg_ops && pgio->pg_ops->pg_cleanup)
1439                 pgio->pg_ops->pg_cleanup(pgio);
1440
1441         pgio->pg_ops = &nfs_pgio_rw_ops;
1442
1443         nfs_pageio_stop_mirroring(pgio);
1444
1445         mirror = &pgio->pg_mirrors[0];
1446         mirror->pg_bsize = NFS_SERVER(pgio->pg_inode)->wsize;
1447 }
1448 EXPORT_SYMBOL_GPL(nfs_pageio_reset_write_mds);
1449
1450
1451 void nfs_commit_prepare(struct rpc_task *task, void *calldata)
1452 {
1453         struct nfs_commit_data *data = calldata;
1454
1455         NFS_PROTO(data->inode)->commit_rpc_prepare(task, data);
1456 }
1457
1458 /*
1459  * Special version of should_remove_suid() that ignores capabilities.
1460  */
1461 static int nfs_should_remove_suid(const struct inode *inode)
1462 {
1463         umode_t mode = inode->i_mode;
1464         int kill = 0;
1465
1466         /* suid always must be killed */
1467         if (unlikely(mode & S_ISUID))
1468                 kill = ATTR_KILL_SUID;
1469
1470         /*
1471          * sgid without any exec bits is just a mandatory locking mark; leave
1472          * it alone.  If some exec bits are set, it's a real sgid; kill it.
1473          */
1474         if (unlikely((mode & S_ISGID) && (mode & S_IXGRP)))
1475                 kill |= ATTR_KILL_SGID;
1476
1477         if (unlikely(kill && S_ISREG(mode)))
1478                 return kill;
1479
1480         return 0;
1481 }
1482
1483 static void nfs_writeback_check_extend(struct nfs_pgio_header *hdr,
1484                 struct nfs_fattr *fattr)
1485 {
1486         struct nfs_pgio_args *argp = &hdr->args;
1487         struct nfs_pgio_res *resp = &hdr->res;
1488         u64 size = argp->offset + resp->count;
1489
1490         if (!(fattr->valid & NFS_ATTR_FATTR_SIZE))
1491                 fattr->size = size;
1492         if (nfs_size_to_loff_t(fattr->size) < i_size_read(hdr->inode)) {
1493                 fattr->valid &= ~NFS_ATTR_FATTR_SIZE;
1494                 return;
1495         }
1496         if (size != fattr->size)
1497                 return;
1498         /* Set attribute barrier */
1499         nfs_fattr_set_barrier(fattr);
1500         /* ...and update size */
1501         fattr->valid |= NFS_ATTR_FATTR_SIZE;
1502 }
1503
1504 void nfs_writeback_update_inode(struct nfs_pgio_header *hdr)
1505 {
1506         struct nfs_fattr *fattr = &hdr->fattr;
1507         struct inode *inode = hdr->inode;
1508
1509         spin_lock(&inode->i_lock);
1510         nfs_writeback_check_extend(hdr, fattr);
1511         nfs_post_op_update_inode_force_wcc_locked(inode, fattr);
1512         spin_unlock(&inode->i_lock);
1513 }
1514 EXPORT_SYMBOL_GPL(nfs_writeback_update_inode);
1515
1516 /*
1517  * This function is called when the WRITE call is complete.
1518  */
1519 static int nfs_writeback_done(struct rpc_task *task,
1520                               struct nfs_pgio_header *hdr,
1521                               struct inode *inode)
1522 {
1523         int status;
1524
1525         /*
1526          * ->write_done will attempt to use post-op attributes to detect
1527          * conflicting writes by other clients.  A strict interpretation
1528          * of close-to-open would allow us to continue caching even if
1529          * another writer had changed the file, but some applications
1530          * depend on tighter cache coherency when writing.
1531          */
1532         status = NFS_PROTO(inode)->write_done(task, hdr);
1533         if (status != 0)
1534                 return status;
1535         nfs_add_stats(inode, NFSIOS_SERVERWRITTENBYTES, hdr->res.count);
1536
1537         if (hdr->res.verf->committed < hdr->args.stable &&
1538             task->tk_status >= 0) {
1539                 /* We tried a write call, but the server did not
1540                  * commit data to stable storage even though we
1541                  * requested it.
1542                  * Note: There is a known bug in Tru64 < 5.0 in which
1543                  *       the server reports NFS_DATA_SYNC, but performs
1544                  *       NFS_FILE_SYNC. We therefore implement this checking
1545                  *       as a dprintk() in order to avoid filling syslog.
1546                  */
1547                 static unsigned long    complain;
1548
1549                 /* Note this will print the MDS for a DS write */
1550                 if (time_before(complain, jiffies)) {
1551                         dprintk("NFS:       faulty NFS server %s:"
1552                                 " (committed = %d) != (stable = %d)\n",
1553                                 NFS_SERVER(inode)->nfs_client->cl_hostname,
1554                                 hdr->res.verf->committed, hdr->args.stable);
1555                         complain = jiffies + 300 * HZ;
1556                 }
1557         }
1558
1559         /* Deal with the suid/sgid bit corner case */
1560         if (nfs_should_remove_suid(inode))
1561                 nfs_mark_for_revalidate(inode);
1562         return 0;
1563 }
1564
1565 /*
1566  * This function is called when the WRITE call is complete.
1567  */
1568 static void nfs_writeback_result(struct rpc_task *task,
1569                                  struct nfs_pgio_header *hdr)
1570 {
1571         struct nfs_pgio_args    *argp = &hdr->args;
1572         struct nfs_pgio_res     *resp = &hdr->res;
1573
1574         if (resp->count < argp->count) {
1575                 static unsigned long    complain;
1576
1577                 /* This a short write! */
1578                 nfs_inc_stats(hdr->inode, NFSIOS_SHORTWRITE);
1579
1580                 /* Has the server at least made some progress? */
1581                 if (resp->count == 0) {
1582                         if (time_before(complain, jiffies)) {
1583                                 printk(KERN_WARNING
1584                                        "NFS: Server wrote zero bytes, expected %u.\n",
1585                                        argp->count);
1586                                 complain = jiffies + 300 * HZ;
1587                         }
1588                         nfs_set_pgio_error(hdr, -EIO, argp->offset);
1589                         task->tk_status = -EIO;
1590                         return;
1591                 }
1592
1593                 /* For non rpc-based layout drivers, retry-through-MDS */
1594                 if (!task->tk_ops) {
1595                         hdr->pnfs_error = -EAGAIN;
1596                         return;
1597                 }
1598
1599                 /* Was this an NFSv2 write or an NFSv3 stable write? */
1600                 if (resp->verf->committed != NFS_UNSTABLE) {
1601                         /* Resend from where the server left off */
1602                         hdr->mds_offset += resp->count;
1603                         argp->offset += resp->count;
1604                         argp->pgbase += resp->count;
1605                         argp->count -= resp->count;
1606                 } else {
1607                         /* Resend as a stable write in order to avoid
1608                          * headaches in the case of a server crash.
1609                          */
1610                         argp->stable = NFS_FILE_SYNC;
1611                 }
1612                 rpc_restart_call_prepare(task);
1613         }
1614 }
1615
1616 static int wait_on_commit(struct nfs_mds_commit_info *cinfo)
1617 {
1618         return wait_on_atomic_t(&cinfo->rpcs_out,
1619                         nfs_wait_atomic_killable, TASK_KILLABLE);
1620 }
1621
1622 static void nfs_commit_begin(struct nfs_mds_commit_info *cinfo)
1623 {
1624         atomic_inc(&cinfo->rpcs_out);
1625 }
1626
1627 static void nfs_commit_end(struct nfs_mds_commit_info *cinfo)
1628 {
1629         if (atomic_dec_and_test(&cinfo->rpcs_out))
1630                 wake_up_atomic_t(&cinfo->rpcs_out);
1631 }
1632
1633 void nfs_commitdata_release(struct nfs_commit_data *data)
1634 {
1635         put_nfs_open_context(data->context);
1636         nfs_commit_free(data);
1637 }
1638 EXPORT_SYMBOL_GPL(nfs_commitdata_release);
1639
1640 int nfs_initiate_commit(struct rpc_clnt *clnt, struct nfs_commit_data *data,
1641                         const struct nfs_rpc_ops *nfs_ops,
1642                         const struct rpc_call_ops *call_ops,
1643                         int how, int flags)
1644 {
1645         struct rpc_task *task;
1646         int priority = flush_task_priority(how);
1647         struct rpc_message msg = {
1648                 .rpc_argp = &data->args,
1649                 .rpc_resp = &data->res,
1650                 .rpc_cred = data->cred,
1651         };
1652         struct rpc_task_setup task_setup_data = {
1653                 .task = &data->task,
1654                 .rpc_client = clnt,
1655                 .rpc_message = &msg,
1656                 .callback_ops = call_ops,
1657                 .callback_data = data,
1658                 .workqueue = nfsiod_workqueue,
1659                 .flags = RPC_TASK_ASYNC | flags,
1660                 .priority = priority,
1661         };
1662         /* Set up the initial task struct.  */
1663         nfs_ops->commit_setup(data, &msg);
1664
1665         dprintk("NFS: initiated commit call\n");
1666
1667         nfs4_state_protect(NFS_SERVER(data->inode)->nfs_client,
1668                 NFS_SP4_MACH_CRED_COMMIT, &task_setup_data.rpc_client, &msg);
1669
1670         task = rpc_run_task(&task_setup_data);
1671         if (IS_ERR(task))
1672                 return PTR_ERR(task);
1673         if (how & FLUSH_SYNC)
1674                 rpc_wait_for_completion_task(task);
1675         rpc_put_task(task);
1676         return 0;
1677 }
1678 EXPORT_SYMBOL_GPL(nfs_initiate_commit);
1679
1680 static loff_t nfs_get_lwb(struct list_head *head)
1681 {
1682         loff_t lwb = 0;
1683         struct nfs_page *req;
1684
1685         list_for_each_entry(req, head, wb_list)
1686                 if (lwb < (req_offset(req) + req->wb_bytes))
1687                         lwb = req_offset(req) + req->wb_bytes;
1688
1689         return lwb;
1690 }
1691
1692 /*
1693  * Set up the argument/result storage required for the RPC call.
1694  */
1695 void nfs_init_commit(struct nfs_commit_data *data,
1696                      struct list_head *head,
1697                      struct pnfs_layout_segment *lseg,
1698                      struct nfs_commit_info *cinfo)
1699 {
1700         struct nfs_page *first = nfs_list_entry(head->next);
1701         struct inode *inode = d_inode(first->wb_context->dentry);
1702
1703         /* Set up the RPC argument and reply structs
1704          * NB: take care not to mess about with data->commit et al. */
1705
1706         list_splice_init(head, &data->pages);
1707
1708         data->inode       = inode;
1709         data->cred        = first->wb_context->cred;
1710         data->lseg        = lseg; /* reference transferred */
1711         /* only set lwb for pnfs commit */
1712         if (lseg)
1713                 data->lwb = nfs_get_lwb(&data->pages);
1714         data->mds_ops     = &nfs_commit_ops;
1715         data->completion_ops = cinfo->completion_ops;
1716         data->dreq        = cinfo->dreq;
1717
1718         data->args.fh     = NFS_FH(data->inode);
1719         /* Note: we always request a commit of the entire inode */
1720         data->args.offset = 0;
1721         data->args.count  = 0;
1722         data->context     = get_nfs_open_context(first->wb_context);
1723         data->res.fattr   = &data->fattr;
1724         data->res.verf    = &data->verf;
1725         nfs_fattr_init(&data->fattr);
1726 }
1727 EXPORT_SYMBOL_GPL(nfs_init_commit);
1728
1729 void nfs_retry_commit(struct list_head *page_list,
1730                       struct pnfs_layout_segment *lseg,
1731                       struct nfs_commit_info *cinfo,
1732                       u32 ds_commit_idx)
1733 {
1734         struct nfs_page *req;
1735
1736         while (!list_empty(page_list)) {
1737                 req = nfs_list_entry(page_list->next);
1738                 nfs_list_remove_request(req);
1739                 nfs_mark_request_commit(req, lseg, cinfo, ds_commit_idx);
1740                 if (!cinfo->dreq)
1741                         nfs_clear_page_commit(req->wb_page);
1742                 nfs_unlock_and_release_request(req);
1743         }
1744 }
1745 EXPORT_SYMBOL_GPL(nfs_retry_commit);
1746
1747 static void
1748 nfs_commit_resched_write(struct nfs_commit_info *cinfo,
1749                 struct nfs_page *req)
1750 {
1751         __set_page_dirty_nobuffers(req->wb_page);
1752 }
1753
1754 /*
1755  * Commit dirty pages
1756  */
1757 static int
1758 nfs_commit_list(struct inode *inode, struct list_head *head, int how,
1759                 struct nfs_commit_info *cinfo)
1760 {
1761         struct nfs_commit_data  *data;
1762
1763         /* another commit raced with us */
1764         if (list_empty(head))
1765                 return 0;
1766
1767         data = nfs_commitdata_alloc(true);
1768
1769         /* Set up the argument struct */
1770         nfs_init_commit(data, head, NULL, cinfo);
1771         atomic_inc(&cinfo->mds->rpcs_out);
1772         return nfs_initiate_commit(NFS_CLIENT(inode), data, NFS_PROTO(inode),
1773                                    data->mds_ops, how, 0);
1774 }
1775
1776 /*
1777  * COMMIT call returned
1778  */
1779 static void nfs_commit_done(struct rpc_task *task, void *calldata)
1780 {
1781         struct nfs_commit_data  *data = calldata;
1782
1783         dprintk("NFS: %5u nfs_commit_done (status %d)\n",
1784                                 task->tk_pid, task->tk_status);
1785
1786         /* Call the NFS version-specific code */
1787         NFS_PROTO(data->inode)->commit_done(task, data);
1788 }
1789
1790 static void nfs_commit_release_pages(struct nfs_commit_data *data)
1791 {
1792         struct nfs_page *req;
1793         int status = data->task.tk_status;
1794         struct nfs_commit_info cinfo;
1795         struct nfs_server *nfss;
1796
1797         while (!list_empty(&data->pages)) {
1798                 req = nfs_list_entry(data->pages.next);
1799                 nfs_list_remove_request(req);
1800                 if (req->wb_page)
1801                         nfs_clear_page_commit(req->wb_page);
1802
1803                 dprintk("NFS:       commit (%s/%llu %d@%lld)",
1804                         req->wb_context->dentry->d_sb->s_id,
1805                         (unsigned long long)NFS_FILEID(d_inode(req->wb_context->dentry)),
1806                         req->wb_bytes,
1807                         (long long)req_offset(req));
1808                 if (status < 0) {
1809                         nfs_context_set_write_error(req->wb_context, status);
1810                         if (req->wb_page)
1811                                 nfs_inode_remove_request(req);
1812                         dprintk_cont(", error = %d\n", status);
1813                         goto next;
1814                 }
1815
1816                 /* Okay, COMMIT succeeded, apparently. Check the verifier
1817                  * returned by the server against all stored verfs. */
1818                 if (!nfs_write_verifier_cmp(&req->wb_verf, &data->verf.verifier)) {
1819                         /* We have a match */
1820                         if (req->wb_page)
1821                                 nfs_inode_remove_request(req);
1822                         dprintk_cont(" OK\n");
1823                         goto next;
1824                 }
1825                 /* We have a mismatch. Write the page again */
1826                 dprintk_cont(" mismatch\n");
1827                 nfs_mark_request_dirty(req);
1828                 set_bit(NFS_CONTEXT_RESEND_WRITES, &req->wb_context->flags);
1829         next:
1830                 nfs_unlock_and_release_request(req);
1831         }
1832         nfss = NFS_SERVER(data->inode);
1833         if (atomic_long_read(&nfss->writeback) < NFS_CONGESTION_OFF_THRESH)
1834                 clear_bdi_congested(inode_to_bdi(data->inode), BLK_RW_ASYNC);
1835
1836         nfs_init_cinfo(&cinfo, data->inode, data->dreq);
1837         nfs_commit_end(cinfo.mds);
1838 }
1839
1840 static void nfs_commit_release(void *calldata)
1841 {
1842         struct nfs_commit_data *data = calldata;
1843
1844         data->completion_ops->completion(data);
1845         nfs_commitdata_release(calldata);
1846 }
1847
1848 static const struct rpc_call_ops nfs_commit_ops = {
1849         .rpc_call_prepare = nfs_commit_prepare,
1850         .rpc_call_done = nfs_commit_done,
1851         .rpc_release = nfs_commit_release,
1852 };
1853
1854 static const struct nfs_commit_completion_ops nfs_commit_completion_ops = {
1855         .completion = nfs_commit_release_pages,
1856         .resched_write = nfs_commit_resched_write,
1857 };
1858
1859 int nfs_generic_commit_list(struct inode *inode, struct list_head *head,
1860                             int how, struct nfs_commit_info *cinfo)
1861 {
1862         int status;
1863
1864         status = pnfs_commit_list(inode, head, how, cinfo);
1865         if (status == PNFS_NOT_ATTEMPTED)
1866                 status = nfs_commit_list(inode, head, how, cinfo);
1867         return status;
1868 }
1869
1870 int nfs_commit_inode(struct inode *inode, int how)
1871 {
1872         LIST_HEAD(head);
1873         struct nfs_commit_info cinfo;
1874         int may_wait = how & FLUSH_SYNC;
1875         int error = 0;
1876         int res;
1877
1878         nfs_init_cinfo_from_inode(&cinfo, inode);
1879         nfs_commit_begin(cinfo.mds);
1880         res = nfs_scan_commit(inode, &head, &cinfo);
1881         if (res)
1882                 error = nfs_generic_commit_list(inode, &head, how, &cinfo);
1883         nfs_commit_end(cinfo.mds);
1884         if (error < 0)
1885                 goto out_error;
1886         if (!may_wait)
1887                 goto out_mark_dirty;
1888         error = wait_on_commit(cinfo.mds);
1889         if (error < 0)
1890                 return error;
1891         return res;
1892 out_error:
1893         res = error;
1894         /* Note: If we exit without ensuring that the commit is complete,
1895          * we must mark the inode as dirty. Otherwise, future calls to
1896          * sync_inode() with the WB_SYNC_ALL flag set will fail to ensure
1897          * that the data is on the disk.
1898          */
1899 out_mark_dirty:
1900         __mark_inode_dirty(inode, I_DIRTY_DATASYNC);
1901         return res;
1902 }
1903 EXPORT_SYMBOL_GPL(nfs_commit_inode);
1904
1905 int nfs_write_inode(struct inode *inode, struct writeback_control *wbc)
1906 {
1907         struct nfs_inode *nfsi = NFS_I(inode);
1908         int flags = FLUSH_SYNC;
1909         int ret = 0;
1910
1911         /* no commits means nothing needs to be done */
1912         if (!nfsi->commit_info.ncommit)
1913                 return ret;
1914
1915         if (wbc->sync_mode == WB_SYNC_NONE) {
1916                 /* Don't commit yet if this is a non-blocking flush and there
1917                  * are a lot of outstanding writes for this mapping.
1918                  */
1919                 if (mapping_tagged(inode->i_mapping, PAGECACHE_TAG_WRITEBACK))
1920                         goto out_mark_dirty;
1921
1922                 /* don't wait for the COMMIT response */
1923                 flags = 0;
1924         }
1925
1926         ret = nfs_commit_inode(inode, flags);
1927         if (ret >= 0) {
1928                 if (wbc->sync_mode == WB_SYNC_NONE) {
1929                         if (ret < wbc->nr_to_write)
1930                                 wbc->nr_to_write -= ret;
1931                         else
1932                                 wbc->nr_to_write = 0;
1933                 }
1934                 return 0;
1935         }
1936 out_mark_dirty:
1937         __mark_inode_dirty(inode, I_DIRTY_DATASYNC);
1938         return ret;
1939 }
1940 EXPORT_SYMBOL_GPL(nfs_write_inode);
1941
1942 /*
1943  * Wrapper for filemap_write_and_wait_range()
1944  *
1945  * Needed for pNFS in order to ensure data becomes visible to the
1946  * client.
1947  */
1948 int nfs_filemap_write_and_wait_range(struct address_space *mapping,
1949                 loff_t lstart, loff_t lend)
1950 {
1951         int ret;
1952
1953         ret = filemap_write_and_wait_range(mapping, lstart, lend);
1954         if (ret == 0)
1955                 ret = pnfs_sync_inode(mapping->host, true);
1956         return ret;
1957 }
1958 EXPORT_SYMBOL_GPL(nfs_filemap_write_and_wait_range);
1959
1960 /*
1961  * flush the inode to disk.
1962  */
1963 int nfs_wb_all(struct inode *inode)
1964 {
1965         int ret;
1966
1967         trace_nfs_writeback_inode_enter(inode);
1968
1969         ret = filemap_write_and_wait(inode->i_mapping);
1970         if (ret)
1971                 goto out;
1972         ret = nfs_commit_inode(inode, FLUSH_SYNC);
1973         if (ret < 0)
1974                 goto out;
1975         pnfs_sync_inode(inode, true);
1976         ret = 0;
1977
1978 out:
1979         trace_nfs_writeback_inode_exit(inode, ret);
1980         return ret;
1981 }
1982 EXPORT_SYMBOL_GPL(nfs_wb_all);
1983
1984 int nfs_wb_page_cancel(struct inode *inode, struct page *page)
1985 {
1986         struct nfs_page *req;
1987         int ret = 0;
1988
1989         wait_on_page_writeback(page);
1990
1991         /* blocking call to cancel all requests and join to a single (head)
1992          * request */
1993         req = nfs_lock_and_join_requests(page);
1994
1995         if (IS_ERR(req)) {
1996                 ret = PTR_ERR(req);
1997         } else if (req) {
1998                 /* all requests from this page have been cancelled by
1999                  * nfs_lock_and_join_requests, so just remove the head
2000                  * request from the inode / page_private pointer and
2001                  * release it */
2002                 nfs_inode_remove_request(req);
2003                 nfs_unlock_and_release_request(req);
2004         }
2005
2006         return ret;
2007 }
2008
2009 /*
2010  * Write back all requests on one page - we do this before reading it.
2011  */
2012 int nfs_wb_page(struct inode *inode, struct page *page)
2013 {
2014         loff_t range_start = page_file_offset(page);
2015         loff_t range_end = range_start + (loff_t)(PAGE_SIZE - 1);
2016         struct writeback_control wbc = {
2017                 .sync_mode = WB_SYNC_ALL,
2018                 .nr_to_write = 0,
2019                 .range_start = range_start,
2020                 .range_end = range_end,
2021         };
2022         int ret;
2023
2024         trace_nfs_writeback_page_enter(inode);
2025
2026         for (;;) {
2027                 wait_on_page_writeback(page);
2028                 if (clear_page_dirty_for_io(page)) {
2029                         ret = nfs_writepage_locked(page, &wbc);
2030                         if (ret < 0)
2031                                 goto out_error;
2032                         continue;
2033                 }
2034                 ret = 0;
2035                 if (!PagePrivate(page))
2036                         break;
2037                 ret = nfs_commit_inode(inode, FLUSH_SYNC);
2038                 if (ret < 0)
2039                         goto out_error;
2040         }
2041 out_error:
2042         trace_nfs_writeback_page_exit(inode, ret);
2043         return ret;
2044 }
2045
2046 #ifdef CONFIG_MIGRATION
2047 int nfs_migrate_page(struct address_space *mapping, struct page *newpage,
2048                 struct page *page, enum migrate_mode mode)
2049 {
2050         /*
2051          * If PagePrivate is set, then the page is currently associated with
2052          * an in-progress read or write request. Don't try to migrate it.
2053          *
2054          * FIXME: we could do this in principle, but we'll need a way to ensure
2055          *        that we can safely release the inode reference while holding
2056          *        the page lock.
2057          */
2058         if (PagePrivate(page))
2059                 return -EBUSY;
2060
2061         if (!nfs_fscache_release_page(page, GFP_KERNEL))
2062                 return -EBUSY;
2063
2064         return migrate_page(mapping, newpage, page, mode);
2065 }
2066 #endif
2067
2068 int __init nfs_init_writepagecache(void)
2069 {
2070         nfs_wdata_cachep = kmem_cache_create("nfs_write_data",
2071                                              sizeof(struct nfs_pgio_header),
2072                                              0, SLAB_HWCACHE_ALIGN,
2073                                              NULL);
2074         if (nfs_wdata_cachep == NULL)
2075                 return -ENOMEM;
2076
2077         nfs_wdata_mempool = mempool_create_slab_pool(MIN_POOL_WRITE,
2078                                                      nfs_wdata_cachep);
2079         if (nfs_wdata_mempool == NULL)
2080                 goto out_destroy_write_cache;
2081
2082         nfs_cdata_cachep = kmem_cache_create("nfs_commit_data",
2083                                              sizeof(struct nfs_commit_data),
2084                                              0, SLAB_HWCACHE_ALIGN,
2085                                              NULL);
2086         if (nfs_cdata_cachep == NULL)
2087                 goto out_destroy_write_mempool;
2088
2089         nfs_commit_mempool = mempool_create_slab_pool(MIN_POOL_COMMIT,
2090                                                       nfs_cdata_cachep);
2091         if (nfs_commit_mempool == NULL)
2092                 goto out_destroy_commit_cache;
2093
2094         /*
2095          * NFS congestion size, scale with available memory.
2096          *
2097          *  64MB:    8192k
2098          * 128MB:   11585k
2099          * 256MB:   16384k
2100          * 512MB:   23170k
2101          *   1GB:   32768k
2102          *   2GB:   46340k
2103          *   4GB:   65536k
2104          *   8GB:   92681k
2105          *  16GB:  131072k
2106          *
2107          * This allows larger machines to have larger/more transfers.
2108          * Limit the default to 256M
2109          */
2110         nfs_congestion_kb = (16*int_sqrt(totalram_pages)) << (PAGE_SHIFT-10);
2111         if (nfs_congestion_kb > 256*1024)
2112                 nfs_congestion_kb = 256*1024;
2113
2114         return 0;
2115
2116 out_destroy_commit_cache:
2117         kmem_cache_destroy(nfs_cdata_cachep);
2118 out_destroy_write_mempool:
2119         mempool_destroy(nfs_wdata_mempool);
2120 out_destroy_write_cache:
2121         kmem_cache_destroy(nfs_wdata_cachep);
2122         return -ENOMEM;
2123 }
2124
2125 void nfs_destroy_writepagecache(void)
2126 {
2127         mempool_destroy(nfs_commit_mempool);
2128         kmem_cache_destroy(nfs_cdata_cachep);
2129         mempool_destroy(nfs_wdata_mempool);
2130         kmem_cache_destroy(nfs_wdata_cachep);
2131 }
2132
2133 static const struct nfs_rw_ops nfs_rw_write_ops = {
2134         .rw_alloc_header        = nfs_writehdr_alloc,
2135         .rw_free_header         = nfs_writehdr_free,
2136         .rw_done                = nfs_writeback_done,
2137         .rw_result              = nfs_writeback_result,
2138         .rw_initiate            = nfs_initiate_write,
2139 };