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