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