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