]> git.kernelconcepts.de Git - karo-tx-linux.git/blob - fs/nfs/direct.c
pnfs/blocklayout: include vmalloc.h for __vmalloc
[karo-tx-linux.git] / fs / nfs / direct.c
1 /*
2  * linux/fs/nfs/direct.c
3  *
4  * Copyright (C) 2003 by Chuck Lever <cel@netapp.com>
5  *
6  * High-performance uncached I/O for the Linux NFS client
7  *
8  * There are important applications whose performance or correctness
9  * depends on uncached access to file data.  Database clusters
10  * (multiple copies of the same instance running on separate hosts)
11  * implement their own cache coherency protocol that subsumes file
12  * system cache protocols.  Applications that process datasets
13  * considerably larger than the client's memory do not always benefit
14  * from a local cache.  A streaming video server, for instance, has no
15  * need to cache the contents of a file.
16  *
17  * When an application requests uncached I/O, all read and write requests
18  * are made directly to the server; data stored or fetched via these
19  * requests is not cached in the Linux page cache.  The client does not
20  * correct unaligned requests from applications.  All requested bytes are
21  * held on permanent storage before a direct write system call returns to
22  * an application.
23  *
24  * Solaris implements an uncached I/O facility called directio() that
25  * is used for backups and sequential I/O to very large files.  Solaris
26  * also supports uncaching whole NFS partitions with "-o forcedirectio,"
27  * an undocumented mount option.
28  *
29  * Designed by Jeff Kimmel, Chuck Lever, and Trond Myklebust, with
30  * help from Andrew Morton.
31  *
32  * 18 Dec 2001  Initial implementation for 2.4  --cel
33  * 08 Jul 2002  Version for 2.4.19, with bug fixes --trondmy
34  * 08 Jun 2003  Port to 2.5 APIs  --cel
35  * 31 Mar 2004  Handle direct I/O without VFS support  --cel
36  * 15 Sep 2004  Parallel async reads  --cel
37  * 04 May 2005  support O_DIRECT with aio  --cel
38  *
39  */
40
41 #include <linux/errno.h>
42 #include <linux/sched.h>
43 #include <linux/kernel.h>
44 #include <linux/file.h>
45 #include <linux/pagemap.h>
46 #include <linux/kref.h>
47 #include <linux/slab.h>
48 #include <linux/task_io_accounting_ops.h>
49 #include <linux/module.h>
50
51 #include <linux/nfs_fs.h>
52 #include <linux/nfs_page.h>
53 #include <linux/sunrpc/clnt.h>
54
55 #include <asm/uaccess.h>
56 #include <linux/atomic.h>
57
58 #include "internal.h"
59 #include "iostat.h"
60 #include "pnfs.h"
61
62 #define NFSDBG_FACILITY         NFSDBG_VFS
63
64 static struct kmem_cache *nfs_direct_cachep;
65
66 /*
67  * This represents a set of asynchronous requests that we're waiting on
68  */
69 struct nfs_direct_req {
70         struct kref             kref;           /* release manager */
71
72         /* I/O parameters */
73         struct nfs_open_context *ctx;           /* file open context info */
74         struct nfs_lock_context *l_ctx;         /* Lock context info */
75         struct kiocb *          iocb;           /* controlling i/o request */
76         struct inode *          inode;          /* target file of i/o */
77
78         /* completion state */
79         atomic_t                io_count;       /* i/os we're waiting for */
80         spinlock_t              lock;           /* protect completion state */
81         ssize_t                 count,          /* bytes actually processed */
82                                 bytes_left,     /* bytes left to be sent */
83                                 error;          /* any reported error */
84         struct completion       completion;     /* wait for i/o completion */
85
86         /* commit state */
87         struct nfs_mds_commit_info mds_cinfo;   /* Storage for cinfo */
88         struct pnfs_ds_commit_info ds_cinfo;    /* Storage for cinfo */
89         struct work_struct      work;
90         int                     flags;
91 #define NFS_ODIRECT_DO_COMMIT           (1)     /* an unstable reply was received */
92 #define NFS_ODIRECT_RESCHED_WRITES      (2)     /* write verification failed */
93         struct nfs_writeverf    verf;           /* unstable write verifier */
94 };
95
96 static const struct nfs_pgio_completion_ops nfs_direct_write_completion_ops;
97 static const struct nfs_commit_completion_ops nfs_direct_commit_completion_ops;
98 static void nfs_direct_write_complete(struct nfs_direct_req *dreq, struct inode *inode);
99 static void nfs_direct_write_schedule_work(struct work_struct *work);
100
101 static inline void get_dreq(struct nfs_direct_req *dreq)
102 {
103         atomic_inc(&dreq->io_count);
104 }
105
106 static inline int put_dreq(struct nfs_direct_req *dreq)
107 {
108         return atomic_dec_and_test(&dreq->io_count);
109 }
110
111 /*
112  * nfs_direct_select_verf - select the right verifier
113  * @dreq - direct request possibly spanning multiple servers
114  * @ds_clp - nfs_client of data server or NULL if MDS / non-pnfs
115  * @ds_idx - index of data server in data server list, only valid if ds_clp set
116  *
117  * returns the correct verifier to use given the role of the server
118  */
119 static struct nfs_writeverf *
120 nfs_direct_select_verf(struct nfs_direct_req *dreq,
121                        struct nfs_client *ds_clp,
122                        int ds_idx)
123 {
124         struct nfs_writeverf *verfp = &dreq->verf;
125
126 #ifdef CONFIG_NFS_V4_1
127         if (ds_clp) {
128                 /* pNFS is in use, use the DS verf */
129                 if (ds_idx >= 0 && ds_idx < dreq->ds_cinfo.nbuckets)
130                         verfp = &dreq->ds_cinfo.buckets[ds_idx].direct_verf;
131                 else
132                         WARN_ON_ONCE(1);
133         }
134 #endif
135         return verfp;
136 }
137
138
139 /*
140  * nfs_direct_set_hdr_verf - set the write/commit verifier
141  * @dreq - direct request possibly spanning multiple servers
142  * @hdr - pageio header to validate against previously seen verfs
143  *
144  * Set the server's (MDS or DS) "seen" verifier
145  */
146 static void nfs_direct_set_hdr_verf(struct nfs_direct_req *dreq,
147                                     struct nfs_pgio_header *hdr)
148 {
149         struct nfs_writeverf *verfp;
150
151         verfp = nfs_direct_select_verf(dreq, hdr->ds_clp,
152                                       hdr->ds_idx);
153         WARN_ON_ONCE(verfp->committed >= 0);
154         memcpy(verfp, &hdr->verf, sizeof(struct nfs_writeverf));
155         WARN_ON_ONCE(verfp->committed < 0);
156 }
157
158 /*
159  * nfs_direct_cmp_hdr_verf - compare verifier for pgio header
160  * @dreq - direct request possibly spanning multiple servers
161  * @hdr - pageio header to validate against previously seen verf
162  *
163  * set the server's "seen" verf if not initialized.
164  * returns result of comparison between @hdr->verf and the "seen"
165  * verf of the server used by @hdr (DS or MDS)
166  */
167 static int nfs_direct_set_or_cmp_hdr_verf(struct nfs_direct_req *dreq,
168                                           struct nfs_pgio_header *hdr)
169 {
170         struct nfs_writeverf *verfp;
171
172         verfp = nfs_direct_select_verf(dreq, hdr->ds_clp,
173                                          hdr->ds_idx);
174         if (verfp->committed < 0) {
175                 nfs_direct_set_hdr_verf(dreq, hdr);
176                 return 0;
177         }
178         return memcmp(verfp, &hdr->verf, sizeof(struct nfs_writeverf));
179 }
180
181 /*
182  * nfs_direct_cmp_commit_data_verf - compare verifier for commit data
183  * @dreq - direct request possibly spanning multiple servers
184  * @data - commit data to validate against previously seen verf
185  *
186  * returns result of comparison between @data->verf and the verf of
187  * the server used by @data (DS or MDS)
188  */
189 static int nfs_direct_cmp_commit_data_verf(struct nfs_direct_req *dreq,
190                                            struct nfs_commit_data *data)
191 {
192         struct nfs_writeverf *verfp;
193
194         verfp = nfs_direct_select_verf(dreq, data->ds_clp,
195                                          data->ds_commit_index);
196         WARN_ON_ONCE(verfp->committed < 0);
197         return memcmp(verfp, &data->verf, sizeof(struct nfs_writeverf));
198 }
199
200 /**
201  * nfs_direct_IO - NFS address space operation for direct I/O
202  * @rw: direction (read or write)
203  * @iocb: target I/O control block
204  * @iov: array of vectors that define I/O buffer
205  * @pos: offset in file to begin the operation
206  * @nr_segs: size of iovec array
207  *
208  * The presence of this routine in the address space ops vector means
209  * the NFS client supports direct I/O. However, for most direct IO, we
210  * shunt off direct read and write requests before the VFS gets them,
211  * so this method is only ever called for swap.
212  */
213 ssize_t nfs_direct_IO(int rw, struct kiocb *iocb, struct iov_iter *iter, loff_t pos)
214 {
215 #ifndef CONFIG_NFS_SWAP
216         dprintk("NFS: nfs_direct_IO (%pD) off/no(%Ld/%lu) EINVAL\n",
217                         iocb->ki_filp, (long long) pos, iter->nr_segs);
218
219         return -EINVAL;
220 #else
221         VM_BUG_ON(iocb->ki_nbytes != PAGE_SIZE);
222
223         if (rw == READ || rw == KERNEL_READ)
224                 return nfs_file_direct_read(iocb, iter, pos,
225                                 rw == READ ? true : false);
226         return nfs_file_direct_write(iocb, iter, pos,
227                                 rw == WRITE ? true : false);
228 #endif /* CONFIG_NFS_SWAP */
229 }
230
231 static void nfs_direct_release_pages(struct page **pages, unsigned int npages)
232 {
233         unsigned int i;
234         for (i = 0; i < npages; i++)
235                 page_cache_release(pages[i]);
236 }
237
238 void nfs_init_cinfo_from_dreq(struct nfs_commit_info *cinfo,
239                               struct nfs_direct_req *dreq)
240 {
241         cinfo->lock = &dreq->lock;
242         cinfo->mds = &dreq->mds_cinfo;
243         cinfo->ds = &dreq->ds_cinfo;
244         cinfo->dreq = dreq;
245         cinfo->completion_ops = &nfs_direct_commit_completion_ops;
246 }
247
248 static inline struct nfs_direct_req *nfs_direct_req_alloc(void)
249 {
250         struct nfs_direct_req *dreq;
251
252         dreq = kmem_cache_zalloc(nfs_direct_cachep, GFP_KERNEL);
253         if (!dreq)
254                 return NULL;
255
256         kref_init(&dreq->kref);
257         kref_get(&dreq->kref);
258         init_completion(&dreq->completion);
259         INIT_LIST_HEAD(&dreq->mds_cinfo.list);
260         dreq->verf.committed = NFS_INVALID_STABLE_HOW;  /* not set yet */
261         INIT_WORK(&dreq->work, nfs_direct_write_schedule_work);
262         spin_lock_init(&dreq->lock);
263
264         return dreq;
265 }
266
267 static void nfs_direct_req_free(struct kref *kref)
268 {
269         struct nfs_direct_req *dreq = container_of(kref, struct nfs_direct_req, kref);
270
271         if (dreq->l_ctx != NULL)
272                 nfs_put_lock_context(dreq->l_ctx);
273         if (dreq->ctx != NULL)
274                 put_nfs_open_context(dreq->ctx);
275         kmem_cache_free(nfs_direct_cachep, dreq);
276 }
277
278 static void nfs_direct_req_release(struct nfs_direct_req *dreq)
279 {
280         kref_put(&dreq->kref, nfs_direct_req_free);
281 }
282
283 ssize_t nfs_dreq_bytes_left(struct nfs_direct_req *dreq)
284 {
285         return dreq->bytes_left;
286 }
287 EXPORT_SYMBOL_GPL(nfs_dreq_bytes_left);
288
289 /*
290  * Collects and returns the final error value/byte-count.
291  */
292 static ssize_t nfs_direct_wait(struct nfs_direct_req *dreq)
293 {
294         ssize_t result = -EIOCBQUEUED;
295
296         /* Async requests don't wait here */
297         if (dreq->iocb)
298                 goto out;
299
300         result = wait_for_completion_killable(&dreq->completion);
301
302         if (!result)
303                 result = dreq->error;
304         if (!result)
305                 result = dreq->count;
306
307 out:
308         return (ssize_t) result;
309 }
310
311 /*
312  * Synchronous I/O uses a stack-allocated iocb.  Thus we can't trust
313  * the iocb is still valid here if this is a synchronous request.
314  */
315 static void nfs_direct_complete(struct nfs_direct_req *dreq, bool write)
316 {
317         struct inode *inode = dreq->inode;
318
319         if (dreq->iocb && write) {
320                 loff_t pos = dreq->iocb->ki_pos + dreq->count;
321
322                 spin_lock(&inode->i_lock);
323                 if (i_size_read(inode) < pos)
324                         i_size_write(inode, pos);
325                 spin_unlock(&inode->i_lock);
326         }
327
328         if (write)
329                 nfs_zap_mapping(inode, inode->i_mapping);
330
331         inode_dio_done(inode);
332
333         if (dreq->iocb) {
334                 long res = (long) dreq->error;
335                 if (!res)
336                         res = (long) dreq->count;
337                 aio_complete(dreq->iocb, res, 0);
338         }
339
340         complete_all(&dreq->completion);
341
342         nfs_direct_req_release(dreq);
343 }
344
345 static void nfs_direct_readpage_release(struct nfs_page *req)
346 {
347         dprintk("NFS: direct read done (%s/%llu %d@%lld)\n",
348                 req->wb_context->dentry->d_inode->i_sb->s_id,
349                 (unsigned long long)NFS_FILEID(req->wb_context->dentry->d_inode),
350                 req->wb_bytes,
351                 (long long)req_offset(req));
352         nfs_release_request(req);
353 }
354
355 static void nfs_direct_read_completion(struct nfs_pgio_header *hdr)
356 {
357         unsigned long bytes = 0;
358         struct nfs_direct_req *dreq = hdr->dreq;
359
360         if (test_bit(NFS_IOHDR_REDO, &hdr->flags))
361                 goto out_put;
362
363         spin_lock(&dreq->lock);
364         if (test_bit(NFS_IOHDR_ERROR, &hdr->flags) && (hdr->good_bytes == 0))
365                 dreq->error = hdr->error;
366         else
367                 dreq->count += hdr->good_bytes;
368         spin_unlock(&dreq->lock);
369
370         while (!list_empty(&hdr->pages)) {
371                 struct nfs_page *req = nfs_list_entry(hdr->pages.next);
372                 struct page *page = req->wb_page;
373
374                 if (!PageCompound(page) && bytes < hdr->good_bytes)
375                         set_page_dirty(page);
376                 bytes += req->wb_bytes;
377                 nfs_list_remove_request(req);
378                 nfs_direct_readpage_release(req);
379         }
380 out_put:
381         if (put_dreq(dreq))
382                 nfs_direct_complete(dreq, false);
383         hdr->release(hdr);
384 }
385
386 static void nfs_read_sync_pgio_error(struct list_head *head)
387 {
388         struct nfs_page *req;
389
390         while (!list_empty(head)) {
391                 req = nfs_list_entry(head->next);
392                 nfs_list_remove_request(req);
393                 nfs_release_request(req);
394         }
395 }
396
397 static void nfs_direct_pgio_init(struct nfs_pgio_header *hdr)
398 {
399         get_dreq(hdr->dreq);
400 }
401
402 static const struct nfs_pgio_completion_ops nfs_direct_read_completion_ops = {
403         .error_cleanup = nfs_read_sync_pgio_error,
404         .init_hdr = nfs_direct_pgio_init,
405         .completion = nfs_direct_read_completion,
406 };
407
408 /*
409  * For each rsize'd chunk of the user's buffer, dispatch an NFS READ
410  * operation.  If nfs_readdata_alloc() or get_user_pages() fails,
411  * bail and stop sending more reads.  Read length accounting is
412  * handled automatically by nfs_direct_read_result().  Otherwise, if
413  * no requests have been sent, just return an error.
414  */
415
416 static ssize_t nfs_direct_read_schedule_iovec(struct nfs_direct_req *dreq,
417                                               struct iov_iter *iter,
418                                               loff_t pos)
419 {
420         struct nfs_pageio_descriptor desc;
421         struct inode *inode = dreq->inode;
422         ssize_t result = -EINVAL;
423         size_t requested_bytes = 0;
424         size_t rsize = max_t(size_t, NFS_SERVER(inode)->rsize, PAGE_SIZE);
425
426         nfs_pageio_init_read(&desc, dreq->inode, false,
427                              &nfs_direct_read_completion_ops);
428         get_dreq(dreq);
429         desc.pg_dreq = dreq;
430         atomic_inc(&inode->i_dio_count);
431
432         while (iov_iter_count(iter)) {
433                 struct page **pagevec;
434                 size_t bytes;
435                 size_t pgbase;
436                 unsigned npages, i;
437
438                 result = iov_iter_get_pages_alloc(iter, &pagevec, 
439                                                   rsize, &pgbase);
440                 if (result < 0)
441                         break;
442         
443                 bytes = result;
444                 iov_iter_advance(iter, bytes);
445                 npages = (result + pgbase + PAGE_SIZE - 1) / PAGE_SIZE;
446                 for (i = 0; i < npages; i++) {
447                         struct nfs_page *req;
448                         unsigned int req_len = min_t(size_t, bytes, PAGE_SIZE - pgbase);
449                         /* XXX do we need to do the eof zeroing found in async_filler? */
450                         req = nfs_create_request(dreq->ctx, pagevec[i], NULL,
451                                                  pgbase, req_len);
452                         if (IS_ERR(req)) {
453                                 result = PTR_ERR(req);
454                                 break;
455                         }
456                         req->wb_index = pos >> PAGE_SHIFT;
457                         req->wb_offset = pos & ~PAGE_MASK;
458                         if (!nfs_pageio_add_request(&desc, req)) {
459                                 result = desc.pg_error;
460                                 nfs_release_request(req);
461                                 break;
462                         }
463                         pgbase = 0;
464                         bytes -= req_len;
465                         requested_bytes += req_len;
466                         pos += req_len;
467                         dreq->bytes_left -= req_len;
468                 }
469                 nfs_direct_release_pages(pagevec, npages);
470                 kvfree(pagevec);
471                 if (result < 0)
472                         break;
473         }
474
475         nfs_pageio_complete(&desc);
476
477         /*
478          * If no bytes were started, return the error, and let the
479          * generic layer handle the completion.
480          */
481         if (requested_bytes == 0) {
482                 inode_dio_done(inode);
483                 nfs_direct_req_release(dreq);
484                 return result < 0 ? result : -EIO;
485         }
486
487         if (put_dreq(dreq))
488                 nfs_direct_complete(dreq, false);
489         return 0;
490 }
491
492 /**
493  * nfs_file_direct_read - file direct read operation for NFS files
494  * @iocb: target I/O control block
495  * @iter: vector of user buffers into which to read data
496  * @pos: byte offset in file where reading starts
497  *
498  * We use this function for direct reads instead of calling
499  * generic_file_aio_read() in order to avoid gfar's check to see if
500  * the request starts before the end of the file.  For that check
501  * to work, we must generate a GETATTR before each direct read, and
502  * even then there is a window between the GETATTR and the subsequent
503  * READ where the file size could change.  Our preference is simply
504  * to do all reads the application wants, and the server will take
505  * care of managing the end of file boundary.
506  *
507  * This function also eliminates unnecessarily updating the file's
508  * atime locally, as the NFS server sets the file's atime, and this
509  * client must read the updated atime from the server back into its
510  * cache.
511  */
512 ssize_t nfs_file_direct_read(struct kiocb *iocb, struct iov_iter *iter,
513                                 loff_t pos, bool uio)
514 {
515         struct file *file = iocb->ki_filp;
516         struct address_space *mapping = file->f_mapping;
517         struct inode *inode = mapping->host;
518         struct nfs_direct_req *dreq;
519         struct nfs_lock_context *l_ctx;
520         ssize_t result = -EINVAL;
521         size_t count = iov_iter_count(iter);
522         nfs_add_stats(mapping->host, NFSIOS_DIRECTREADBYTES, count);
523
524         dfprintk(FILE, "NFS: direct read(%pD2, %zd@%Ld)\n",
525                 file, count, (long long) pos);
526
527         result = 0;
528         if (!count)
529                 goto out;
530
531         mutex_lock(&inode->i_mutex);
532         result = nfs_sync_mapping(mapping);
533         if (result)
534                 goto out_unlock;
535
536         task_io_account_read(count);
537
538         result = -ENOMEM;
539         dreq = nfs_direct_req_alloc();
540         if (dreq == NULL)
541                 goto out_unlock;
542
543         dreq->inode = inode;
544         dreq->bytes_left = count;
545         dreq->ctx = get_nfs_open_context(nfs_file_open_context(iocb->ki_filp));
546         l_ctx = nfs_get_lock_context(dreq->ctx);
547         if (IS_ERR(l_ctx)) {
548                 result = PTR_ERR(l_ctx);
549                 goto out_release;
550         }
551         dreq->l_ctx = l_ctx;
552         if (!is_sync_kiocb(iocb))
553                 dreq->iocb = iocb;
554
555         NFS_I(inode)->read_io += count;
556         result = nfs_direct_read_schedule_iovec(dreq, iter, pos);
557
558         mutex_unlock(&inode->i_mutex);
559
560         if (!result) {
561                 result = nfs_direct_wait(dreq);
562                 if (result > 0)
563                         iocb->ki_pos = pos + result;
564         }
565
566         nfs_direct_req_release(dreq);
567         return result;
568
569 out_release:
570         nfs_direct_req_release(dreq);
571 out_unlock:
572         mutex_unlock(&inode->i_mutex);
573 out:
574         return result;
575 }
576
577 static void nfs_direct_write_reschedule(struct nfs_direct_req *dreq)
578 {
579         struct nfs_pageio_descriptor desc;
580         struct nfs_page *req, *tmp;
581         LIST_HEAD(reqs);
582         struct nfs_commit_info cinfo;
583         LIST_HEAD(failed);
584
585         nfs_init_cinfo_from_dreq(&cinfo, dreq);
586         pnfs_recover_commit_reqs(dreq->inode, &reqs, &cinfo);
587         spin_lock(cinfo.lock);
588         nfs_scan_commit_list(&cinfo.mds->list, &reqs, &cinfo, 0);
589         spin_unlock(cinfo.lock);
590
591         dreq->count = 0;
592         get_dreq(dreq);
593
594         nfs_pageio_init_write(&desc, dreq->inode, FLUSH_STABLE, false,
595                               &nfs_direct_write_completion_ops);
596         desc.pg_dreq = dreq;
597
598         list_for_each_entry_safe(req, tmp, &reqs, wb_list) {
599                 if (!nfs_pageio_add_request(&desc, req)) {
600                         nfs_list_remove_request(req);
601                         nfs_list_add_request(req, &failed);
602                         spin_lock(cinfo.lock);
603                         dreq->flags = 0;
604                         dreq->error = -EIO;
605                         spin_unlock(cinfo.lock);
606                 }
607                 nfs_release_request(req);
608         }
609         nfs_pageio_complete(&desc);
610
611         while (!list_empty(&failed)) {
612                 req = nfs_list_entry(failed.next);
613                 nfs_list_remove_request(req);
614                 nfs_unlock_and_release_request(req);
615         }
616
617         if (put_dreq(dreq))
618                 nfs_direct_write_complete(dreq, dreq->inode);
619 }
620
621 static void nfs_direct_commit_complete(struct nfs_commit_data *data)
622 {
623         struct nfs_direct_req *dreq = data->dreq;
624         struct nfs_commit_info cinfo;
625         struct nfs_page *req;
626         int status = data->task.tk_status;
627
628         nfs_init_cinfo_from_dreq(&cinfo, dreq);
629         if (status < 0) {
630                 dprintk("NFS: %5u commit failed with error %d.\n",
631                         data->task.tk_pid, status);
632                 dreq->flags = NFS_ODIRECT_RESCHED_WRITES;
633         } else if (nfs_direct_cmp_commit_data_verf(dreq, data)) {
634                 dprintk("NFS: %5u commit verify failed\n", data->task.tk_pid);
635                 dreq->flags = NFS_ODIRECT_RESCHED_WRITES;
636         }
637
638         dprintk("NFS: %5u commit returned %d\n", data->task.tk_pid, status);
639         while (!list_empty(&data->pages)) {
640                 req = nfs_list_entry(data->pages.next);
641                 nfs_list_remove_request(req);
642                 if (dreq->flags == NFS_ODIRECT_RESCHED_WRITES) {
643                         /* Note the rewrite will go through mds */
644                         nfs_mark_request_commit(req, NULL, &cinfo);
645                 } else
646                         nfs_release_request(req);
647                 nfs_unlock_and_release_request(req);
648         }
649
650         if (atomic_dec_and_test(&cinfo.mds->rpcs_out))
651                 nfs_direct_write_complete(dreq, data->inode);
652 }
653
654 static void nfs_direct_error_cleanup(struct nfs_inode *nfsi)
655 {
656         /* There is no lock to clear */
657 }
658
659 static const struct nfs_commit_completion_ops nfs_direct_commit_completion_ops = {
660         .completion = nfs_direct_commit_complete,
661         .error_cleanup = nfs_direct_error_cleanup,
662 };
663
664 static void nfs_direct_commit_schedule(struct nfs_direct_req *dreq)
665 {
666         int res;
667         struct nfs_commit_info cinfo;
668         LIST_HEAD(mds_list);
669
670         nfs_init_cinfo_from_dreq(&cinfo, dreq);
671         nfs_scan_commit(dreq->inode, &mds_list, &cinfo);
672         res = nfs_generic_commit_list(dreq->inode, &mds_list, 0, &cinfo);
673         if (res < 0) /* res == -ENOMEM */
674                 nfs_direct_write_reschedule(dreq);
675 }
676
677 static void nfs_direct_write_schedule_work(struct work_struct *work)
678 {
679         struct nfs_direct_req *dreq = container_of(work, struct nfs_direct_req, work);
680         int flags = dreq->flags;
681
682         dreq->flags = 0;
683         switch (flags) {
684                 case NFS_ODIRECT_DO_COMMIT:
685                         nfs_direct_commit_schedule(dreq);
686                         break;
687                 case NFS_ODIRECT_RESCHED_WRITES:
688                         nfs_direct_write_reschedule(dreq);
689                         break;
690                 default:
691                         nfs_direct_complete(dreq, true);
692         }
693 }
694
695 static void nfs_direct_write_complete(struct nfs_direct_req *dreq, struct inode *inode)
696 {
697         schedule_work(&dreq->work); /* Calls nfs_direct_write_schedule_work */
698 }
699
700 static void nfs_direct_write_completion(struct nfs_pgio_header *hdr)
701 {
702         struct nfs_direct_req *dreq = hdr->dreq;
703         struct nfs_commit_info cinfo;
704         bool request_commit = false;
705         struct nfs_page *req = nfs_list_entry(hdr->pages.next);
706
707         if (test_bit(NFS_IOHDR_REDO, &hdr->flags))
708                 goto out_put;
709
710         nfs_init_cinfo_from_dreq(&cinfo, dreq);
711
712         spin_lock(&dreq->lock);
713
714         if (test_bit(NFS_IOHDR_ERROR, &hdr->flags)) {
715                 dreq->flags = 0;
716                 dreq->error = hdr->error;
717         }
718         if (dreq->error == 0) {
719                 dreq->count += hdr->good_bytes;
720                 if (nfs_write_need_commit(hdr)) {
721                         if (dreq->flags == NFS_ODIRECT_RESCHED_WRITES)
722                                 request_commit = true;
723                         else if (dreq->flags == 0) {
724                                 nfs_direct_set_hdr_verf(dreq, hdr);
725                                 request_commit = true;
726                                 dreq->flags = NFS_ODIRECT_DO_COMMIT;
727                         } else if (dreq->flags == NFS_ODIRECT_DO_COMMIT) {
728                                 request_commit = true;
729                                 if (nfs_direct_set_or_cmp_hdr_verf(dreq, hdr))
730                                         dreq->flags =
731                                                 NFS_ODIRECT_RESCHED_WRITES;
732                         }
733                 }
734         }
735         spin_unlock(&dreq->lock);
736
737         while (!list_empty(&hdr->pages)) {
738
739                 req = nfs_list_entry(hdr->pages.next);
740                 nfs_list_remove_request(req);
741                 if (request_commit) {
742                         kref_get(&req->wb_kref);
743                         nfs_mark_request_commit(req, hdr->lseg, &cinfo);
744                 }
745                 nfs_unlock_and_release_request(req);
746         }
747
748 out_put:
749         if (put_dreq(dreq))
750                 nfs_direct_write_complete(dreq, hdr->inode);
751         hdr->release(hdr);
752 }
753
754 static void nfs_write_sync_pgio_error(struct list_head *head)
755 {
756         struct nfs_page *req;
757
758         while (!list_empty(head)) {
759                 req = nfs_list_entry(head->next);
760                 nfs_list_remove_request(req);
761                 nfs_unlock_and_release_request(req);
762         }
763 }
764
765 static const struct nfs_pgio_completion_ops nfs_direct_write_completion_ops = {
766         .error_cleanup = nfs_write_sync_pgio_error,
767         .init_hdr = nfs_direct_pgio_init,
768         .completion = nfs_direct_write_completion,
769 };
770
771
772 /*
773  * NB: Return the value of the first error return code.  Subsequent
774  *     errors after the first one are ignored.
775  */
776 /*
777  * For each wsize'd chunk of the user's buffer, dispatch an NFS WRITE
778  * operation.  If nfs_writedata_alloc() or get_user_pages() fails,
779  * bail and stop sending more writes.  Write length accounting is
780  * handled automatically by nfs_direct_write_result().  Otherwise, if
781  * no requests have been sent, just return an error.
782  */
783 static ssize_t nfs_direct_write_schedule_iovec(struct nfs_direct_req *dreq,
784                                                struct iov_iter *iter,
785                                                loff_t pos)
786 {
787         struct nfs_pageio_descriptor desc;
788         struct inode *inode = dreq->inode;
789         ssize_t result = 0;
790         size_t requested_bytes = 0;
791         size_t wsize = max_t(size_t, NFS_SERVER(inode)->wsize, PAGE_SIZE);
792
793         nfs_pageio_init_write(&desc, inode, FLUSH_COND_STABLE, false,
794                               &nfs_direct_write_completion_ops);
795         desc.pg_dreq = dreq;
796         get_dreq(dreq);
797         atomic_inc(&inode->i_dio_count);
798
799         NFS_I(inode)->write_io += iov_iter_count(iter);
800         while (iov_iter_count(iter)) {
801                 struct page **pagevec;
802                 size_t bytes;
803                 size_t pgbase;
804                 unsigned npages, i;
805
806                 result = iov_iter_get_pages_alloc(iter, &pagevec, 
807                                                   wsize, &pgbase);
808                 if (result < 0)
809                         break;
810
811                 bytes = result;
812                 iov_iter_advance(iter, bytes);
813                 npages = (result + pgbase + PAGE_SIZE - 1) / PAGE_SIZE;
814                 for (i = 0; i < npages; i++) {
815                         struct nfs_page *req;
816                         unsigned int req_len = min_t(size_t, bytes, PAGE_SIZE - pgbase);
817
818                         req = nfs_create_request(dreq->ctx, pagevec[i], NULL,
819                                                  pgbase, req_len);
820                         if (IS_ERR(req)) {
821                                 result = PTR_ERR(req);
822                                 break;
823                         }
824                         nfs_lock_request(req);
825                         req->wb_index = pos >> PAGE_SHIFT;
826                         req->wb_offset = pos & ~PAGE_MASK;
827                         if (!nfs_pageio_add_request(&desc, req)) {
828                                 result = desc.pg_error;
829                                 nfs_unlock_and_release_request(req);
830                                 break;
831                         }
832                         pgbase = 0;
833                         bytes -= req_len;
834                         requested_bytes += req_len;
835                         pos += req_len;
836                         dreq->bytes_left -= req_len;
837                 }
838                 nfs_direct_release_pages(pagevec, npages);
839                 kvfree(pagevec);
840                 if (result < 0)
841                         break;
842         }
843         nfs_pageio_complete(&desc);
844
845         /*
846          * If no bytes were started, return the error, and let the
847          * generic layer handle the completion.
848          */
849         if (requested_bytes == 0) {
850                 inode_dio_done(inode);
851                 nfs_direct_req_release(dreq);
852                 return result < 0 ? result : -EIO;
853         }
854
855         if (put_dreq(dreq))
856                 nfs_direct_write_complete(dreq, dreq->inode);
857         return 0;
858 }
859
860 /**
861  * nfs_file_direct_write - file direct write operation for NFS files
862  * @iocb: target I/O control block
863  * @iter: vector of user buffers from which to write data
864  * @pos: byte offset in file where writing starts
865  *
866  * We use this function for direct writes instead of calling
867  * generic_file_aio_write() in order to avoid taking the inode
868  * semaphore and updating the i_size.  The NFS server will set
869  * the new i_size and this client must read the updated size
870  * back into its cache.  We let the server do generic write
871  * parameter checking and report problems.
872  *
873  * We eliminate local atime updates, see direct read above.
874  *
875  * We avoid unnecessary page cache invalidations for normal cached
876  * readers of this file.
877  *
878  * Note that O_APPEND is not supported for NFS direct writes, as there
879  * is no atomic O_APPEND write facility in the NFS protocol.
880  */
881 ssize_t nfs_file_direct_write(struct kiocb *iocb, struct iov_iter *iter,
882                                 loff_t pos, bool uio)
883 {
884         ssize_t result = -EINVAL;
885         struct file *file = iocb->ki_filp;
886         struct address_space *mapping = file->f_mapping;
887         struct inode *inode = mapping->host;
888         struct nfs_direct_req *dreq;
889         struct nfs_lock_context *l_ctx;
890         loff_t end;
891         size_t count = iov_iter_count(iter);
892         end = (pos + count - 1) >> PAGE_CACHE_SHIFT;
893
894         nfs_add_stats(mapping->host, NFSIOS_DIRECTWRITTENBYTES, count);
895
896         dfprintk(FILE, "NFS: direct write(%pD2, %zd@%Ld)\n",
897                 file, count, (long long) pos);
898
899         result = generic_write_checks(file, &pos, &count, 0);
900         if (result)
901                 goto out;
902
903         result = -EINVAL;
904         if ((ssize_t) count < 0)
905                 goto out;
906         result = 0;
907         if (!count)
908                 goto out;
909
910         mutex_lock(&inode->i_mutex);
911
912         result = nfs_sync_mapping(mapping);
913         if (result)
914                 goto out_unlock;
915
916         if (mapping->nrpages) {
917                 result = invalidate_inode_pages2_range(mapping,
918                                         pos >> PAGE_CACHE_SHIFT, end);
919                 if (result)
920                         goto out_unlock;
921         }
922
923         task_io_account_write(count);
924
925         result = -ENOMEM;
926         dreq = nfs_direct_req_alloc();
927         if (!dreq)
928                 goto out_unlock;
929
930         dreq->inode = inode;
931         dreq->bytes_left = count;
932         dreq->ctx = get_nfs_open_context(nfs_file_open_context(iocb->ki_filp));
933         l_ctx = nfs_get_lock_context(dreq->ctx);
934         if (IS_ERR(l_ctx)) {
935                 result = PTR_ERR(l_ctx);
936                 goto out_release;
937         }
938         dreq->l_ctx = l_ctx;
939         if (!is_sync_kiocb(iocb))
940                 dreq->iocb = iocb;
941
942         result = nfs_direct_write_schedule_iovec(dreq, iter, pos);
943
944         if (mapping->nrpages) {
945                 invalidate_inode_pages2_range(mapping,
946                                               pos >> PAGE_CACHE_SHIFT, end);
947         }
948
949         mutex_unlock(&inode->i_mutex);
950
951         if (!result) {
952                 result = nfs_direct_wait(dreq);
953                 if (result > 0) {
954                         struct inode *inode = mapping->host;
955
956                         iocb->ki_pos = pos + result;
957                         spin_lock(&inode->i_lock);
958                         if (i_size_read(inode) < iocb->ki_pos)
959                                 i_size_write(inode, iocb->ki_pos);
960                         spin_unlock(&inode->i_lock);
961                 }
962         }
963         nfs_direct_req_release(dreq);
964         return result;
965
966 out_release:
967         nfs_direct_req_release(dreq);
968 out_unlock:
969         mutex_unlock(&inode->i_mutex);
970 out:
971         return result;
972 }
973
974 /**
975  * nfs_init_directcache - create a slab cache for nfs_direct_req structures
976  *
977  */
978 int __init nfs_init_directcache(void)
979 {
980         nfs_direct_cachep = kmem_cache_create("nfs_direct_cache",
981                                                 sizeof(struct nfs_direct_req),
982                                                 0, (SLAB_RECLAIM_ACCOUNT|
983                                                         SLAB_MEM_SPREAD),
984                                                 NULL);
985         if (nfs_direct_cachep == NULL)
986                 return -ENOMEM;
987
988         return 0;
989 }
990
991 /**
992  * nfs_destroy_directcache - destroy the slab cache for nfs_direct_req structures
993  *
994  */
995 void nfs_destroy_directcache(void)
996 {
997         kmem_cache_destroy(nfs_direct_cachep);
998 }