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