cifs: have find_writeable_file prefer filehandles opened by same task
[safe/jmp/linux-2.6] / fs / cifs / file.c
1 /*
2  *   fs/cifs/file.c
3  *
4  *   vfs operations that deal with files
5  *
6  *   Copyright (C) International Business Machines  Corp., 2002,2007
7  *   Author(s): Steve French (sfrench@us.ibm.com)
8  *              Jeremy Allison (jra@samba.org)
9  *
10  *   This library is free software; you can redistribute it and/or modify
11  *   it under the terms of the GNU Lesser General Public License as published
12  *   by the Free Software Foundation; either version 2.1 of the License, or
13  *   (at your option) any later version.
14  *
15  *   This library is distributed in the hope that it will be useful,
16  *   but WITHOUT ANY WARRANTY; without even the implied warranty of
17  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See
18  *   the GNU Lesser General Public License for more details.
19  *
20  *   You should have received a copy of the GNU Lesser General Public License
21  *   along with this library; if not, write to the Free Software
22  *   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23  */
24 #include <linux/fs.h>
25 #include <linux/backing-dev.h>
26 #include <linux/stat.h>
27 #include <linux/fcntl.h>
28 #include <linux/pagemap.h>
29 #include <linux/pagevec.h>
30 #include <linux/writeback.h>
31 #include <linux/task_io_accounting_ops.h>
32 #include <linux/delay.h>
33 #include <asm/div64.h>
34 #include "cifsfs.h"
35 #include "cifspdu.h"
36 #include "cifsglob.h"
37 #include "cifsproto.h"
38 #include "cifs_unicode.h"
39 #include "cifs_debug.h"
40 #include "cifs_fs_sb.h"
41
42 static inline struct cifsFileInfo *cifs_init_private(
43         struct cifsFileInfo *private_data, struct inode *inode,
44         struct file *file, __u16 netfid)
45 {
46         memset(private_data, 0, sizeof(struct cifsFileInfo));
47         private_data->netfid = netfid;
48         private_data->pid = current->tgid;
49         init_MUTEX(&private_data->fh_sem);
50         mutex_init(&private_data->lock_mutex);
51         INIT_LIST_HEAD(&private_data->llist);
52         private_data->pfile = file; /* needed for writepage */
53         private_data->pInode = inode;
54         private_data->invalidHandle = false;
55         private_data->closePend = false;
56         /* we have to track num writers to the inode, since writepages
57         does not tell us which handle the write is for so there can
58         be a close (overlapping with write) of the filehandle that
59         cifs_writepages chose to use */
60         atomic_set(&private_data->wrtPending, 0);
61
62         return private_data;
63 }
64
65 static inline int cifs_convert_flags(unsigned int flags)
66 {
67         if ((flags & O_ACCMODE) == O_RDONLY)
68                 return GENERIC_READ;
69         else if ((flags & O_ACCMODE) == O_WRONLY)
70                 return GENERIC_WRITE;
71         else if ((flags & O_ACCMODE) == O_RDWR) {
72                 /* GENERIC_ALL is too much permission to request
73                    can cause unnecessary access denied on create */
74                 /* return GENERIC_ALL; */
75                 return (GENERIC_READ | GENERIC_WRITE);
76         }
77
78         return (READ_CONTROL | FILE_WRITE_ATTRIBUTES | FILE_READ_ATTRIBUTES |
79                 FILE_WRITE_EA | FILE_APPEND_DATA | FILE_WRITE_DATA |
80                 FILE_READ_DATA);
81
82
83 }
84
85 static inline int cifs_get_disposition(unsigned int flags)
86 {
87         if ((flags & (O_CREAT | O_EXCL)) == (O_CREAT | O_EXCL))
88                 return FILE_CREATE;
89         else if ((flags & (O_CREAT | O_TRUNC)) == (O_CREAT | O_TRUNC))
90                 return FILE_OVERWRITE_IF;
91         else if ((flags & O_CREAT) == O_CREAT)
92                 return FILE_OPEN_IF;
93         else if ((flags & O_TRUNC) == O_TRUNC)
94                 return FILE_OVERWRITE;
95         else
96                 return FILE_OPEN;
97 }
98
99 /* all arguments to this function must be checked for validity in caller */
100 static inline int cifs_open_inode_helper(struct inode *inode, struct file *file,
101         struct cifsInodeInfo *pCifsInode, struct cifsFileInfo *pCifsFile,
102         struct cifsTconInfo *pTcon, int *oplock, FILE_ALL_INFO *buf,
103         char *full_path, int xid)
104 {
105         struct timespec temp;
106         int rc;
107
108         /* want handles we can use to read with first
109            in the list so we do not have to walk the
110            list to search for one in prepare_write */
111         if ((file->f_flags & O_ACCMODE) == O_WRONLY) {
112                 list_add_tail(&pCifsFile->flist,
113                               &pCifsInode->openFileList);
114         } else {
115                 list_add(&pCifsFile->flist,
116                          &pCifsInode->openFileList);
117         }
118         write_unlock(&GlobalSMBSeslock);
119         if (pCifsInode->clientCanCacheRead) {
120                 /* we have the inode open somewhere else
121                    no need to discard cache data */
122                 goto client_can_cache;
123         }
124
125         /* BB need same check in cifs_create too? */
126         /* if not oplocked, invalidate inode pages if mtime or file
127            size changed */
128         temp = cifs_NTtimeToUnix(le64_to_cpu(buf->LastWriteTime));
129         if (timespec_equal(&file->f_path.dentry->d_inode->i_mtime, &temp) &&
130                            (file->f_path.dentry->d_inode->i_size ==
131                             (loff_t)le64_to_cpu(buf->EndOfFile))) {
132                 cFYI(1, ("inode unchanged on server"));
133         } else {
134                 if (file->f_path.dentry->d_inode->i_mapping) {
135                 /* BB no need to lock inode until after invalidate
136                    since namei code should already have it locked? */
137                         rc = filemap_write_and_wait(file->f_path.dentry->d_inode->i_mapping);
138                         if (rc != 0)
139                                 CIFS_I(file->f_path.dentry->d_inode)->write_behind_rc = rc;
140                 }
141                 cFYI(1, ("invalidating remote inode since open detected it "
142                          "changed"));
143                 invalidate_remote_inode(file->f_path.dentry->d_inode);
144         }
145
146 client_can_cache:
147         if (pTcon->unix_ext)
148                 rc = cifs_get_inode_info_unix(&file->f_path.dentry->d_inode,
149                         full_path, inode->i_sb, xid);
150         else
151                 rc = cifs_get_inode_info(&file->f_path.dentry->d_inode,
152                         full_path, buf, inode->i_sb, xid, NULL);
153
154         if ((*oplock & 0xF) == OPLOCK_EXCLUSIVE) {
155                 pCifsInode->clientCanCacheAll = true;
156                 pCifsInode->clientCanCacheRead = true;
157                 cFYI(1, ("Exclusive Oplock granted on inode %p",
158                          file->f_path.dentry->d_inode));
159         } else if ((*oplock & 0xF) == OPLOCK_READ)
160                 pCifsInode->clientCanCacheRead = true;
161
162         return rc;
163 }
164
165 int cifs_open(struct inode *inode, struct file *file)
166 {
167         int rc = -EACCES;
168         int xid, oplock;
169         struct cifs_sb_info *cifs_sb;
170         struct cifsTconInfo *pTcon;
171         struct cifsFileInfo *pCifsFile;
172         struct cifsInodeInfo *pCifsInode;
173         struct list_head *tmp;
174         char *full_path = NULL;
175         int desiredAccess;
176         int disposition;
177         __u16 netfid;
178         FILE_ALL_INFO *buf = NULL;
179
180         xid = GetXid();
181
182         cifs_sb = CIFS_SB(inode->i_sb);
183         pTcon = cifs_sb->tcon;
184
185         if (file->f_flags & O_CREAT) {
186                 /* search inode for this file and fill in file->private_data */
187                 pCifsInode = CIFS_I(file->f_path.dentry->d_inode);
188                 read_lock(&GlobalSMBSeslock);
189                 list_for_each(tmp, &pCifsInode->openFileList) {
190                         pCifsFile = list_entry(tmp, struct cifsFileInfo,
191                                                flist);
192                         if ((pCifsFile->pfile == NULL) &&
193                             (pCifsFile->pid == current->tgid)) {
194                                 /* mode set in cifs_create */
195
196                                 /* needed for writepage */
197                                 pCifsFile->pfile = file;
198
199                                 file->private_data = pCifsFile;
200                                 break;
201                         }
202                 }
203                 read_unlock(&GlobalSMBSeslock);
204                 if (file->private_data != NULL) {
205                         rc = 0;
206                         FreeXid(xid);
207                         return rc;
208                 } else {
209                         if (file->f_flags & O_EXCL)
210                                 cERROR(1, ("could not find file instance for "
211                                            "new file %p", file));
212                 }
213         }
214
215         full_path = build_path_from_dentry(file->f_path.dentry);
216         if (full_path == NULL) {
217                 FreeXid(xid);
218                 return -ENOMEM;
219         }
220
221         cFYI(1, ("inode = 0x%p file flags are 0x%x for %s",
222                  inode, file->f_flags, full_path));
223         desiredAccess = cifs_convert_flags(file->f_flags);
224
225 /*********************************************************************
226  *  open flag mapping table:
227  *
228  *      POSIX Flag            CIFS Disposition
229  *      ----------            ----------------
230  *      O_CREAT               FILE_OPEN_IF
231  *      O_CREAT | O_EXCL      FILE_CREATE
232  *      O_CREAT | O_TRUNC     FILE_OVERWRITE_IF
233  *      O_TRUNC               FILE_OVERWRITE
234  *      none of the above     FILE_OPEN
235  *
236  *      Note that there is not a direct match between disposition
237  *      FILE_SUPERSEDE (ie create whether or not file exists although
238  *      O_CREAT | O_TRUNC is similar but truncates the existing
239  *      file rather than creating a new file as FILE_SUPERSEDE does
240  *      (which uses the attributes / metadata passed in on open call)
241  *?
242  *?  O_SYNC is a reasonable match to CIFS writethrough flag
243  *?  and the read write flags match reasonably.  O_LARGEFILE
244  *?  is irrelevant because largefile support is always used
245  *?  by this client. Flags O_APPEND, O_DIRECT, O_DIRECTORY,
246  *       O_FASYNC, O_NOFOLLOW, O_NONBLOCK need further investigation
247  *********************************************************************/
248
249         disposition = cifs_get_disposition(file->f_flags);
250
251         if (oplockEnabled)
252                 oplock = REQ_OPLOCK;
253         else
254                 oplock = 0;
255
256         /* BB pass O_SYNC flag through on file attributes .. BB */
257
258         /* Also refresh inode by passing in file_info buf returned by SMBOpen
259            and calling get_inode_info with returned buf (at least helps
260            non-Unix server case) */
261
262         /* BB we can not do this if this is the second open of a file
263            and the first handle has writebehind data, we might be
264            able to simply do a filemap_fdatawrite/filemap_fdatawait first */
265         buf = kmalloc(sizeof(FILE_ALL_INFO), GFP_KERNEL);
266         if (!buf) {
267                 rc = -ENOMEM;
268                 goto out;
269         }
270
271         if (cifs_sb->tcon->ses->capabilities & CAP_NT_SMBS)
272                 rc = CIFSSMBOpen(xid, pTcon, full_path, disposition,
273                          desiredAccess, CREATE_NOT_DIR, &netfid, &oplock, buf,
274                          cifs_sb->local_nls, cifs_sb->mnt_cifs_flags
275                                  & CIFS_MOUNT_MAP_SPECIAL_CHR);
276         else
277                 rc = -EIO; /* no NT SMB support fall into legacy open below */
278
279         if (rc == -EIO) {
280                 /* Old server, try legacy style OpenX */
281                 rc = SMBLegacyOpen(xid, pTcon, full_path, disposition,
282                         desiredAccess, CREATE_NOT_DIR, &netfid, &oplock, buf,
283                         cifs_sb->local_nls, cifs_sb->mnt_cifs_flags
284                                 & CIFS_MOUNT_MAP_SPECIAL_CHR);
285         }
286         if (rc) {
287                 cFYI(1, ("cifs_open returned 0x%x", rc));
288                 goto out;
289         }
290         file->private_data =
291                 kmalloc(sizeof(struct cifsFileInfo), GFP_KERNEL);
292         if (file->private_data == NULL) {
293                 rc = -ENOMEM;
294                 goto out;
295         }
296         pCifsFile = cifs_init_private(file->private_data, inode, file, netfid);
297         write_lock(&GlobalSMBSeslock);
298         list_add(&pCifsFile->tlist, &pTcon->openFileList);
299
300         pCifsInode = CIFS_I(file->f_path.dentry->d_inode);
301         if (pCifsInode) {
302                 rc = cifs_open_inode_helper(inode, file, pCifsInode,
303                                             pCifsFile, pTcon,
304                                             &oplock, buf, full_path, xid);
305         } else {
306                 write_unlock(&GlobalSMBSeslock);
307         }
308
309         if (oplock & CIFS_CREATE_ACTION) {
310                 /* time to set mode which we can not set earlier due to
311                    problems creating new read-only files */
312                 if (pTcon->unix_ext) {
313                         struct cifs_unix_set_info_args args = {
314                                 .mode   = inode->i_mode,
315                                 .uid    = NO_CHANGE_64,
316                                 .gid    = NO_CHANGE_64,
317                                 .ctime  = NO_CHANGE_64,
318                                 .atime  = NO_CHANGE_64,
319                                 .mtime  = NO_CHANGE_64,
320                                 .device = 0,
321                         };
322                         CIFSSMBUnixSetInfo(xid, pTcon, full_path, &args,
323                                             cifs_sb->local_nls,
324                                             cifs_sb->mnt_cifs_flags &
325                                                 CIFS_MOUNT_MAP_SPECIAL_CHR);
326                 }
327         }
328
329 out:
330         kfree(buf);
331         kfree(full_path);
332         FreeXid(xid);
333         return rc;
334 }
335
336 /* Try to reacquire byte range locks that were released when session */
337 /* to server was lost */
338 static int cifs_relock_file(struct cifsFileInfo *cifsFile)
339 {
340         int rc = 0;
341
342 /* BB list all locks open on this file and relock */
343
344         return rc;
345 }
346
347 static int cifs_reopen_file(struct file *file, bool can_flush)
348 {
349         int rc = -EACCES;
350         int xid, oplock;
351         struct cifs_sb_info *cifs_sb;
352         struct cifsTconInfo *pTcon;
353         struct cifsFileInfo *pCifsFile;
354         struct cifsInodeInfo *pCifsInode;
355         struct inode *inode;
356         char *full_path = NULL;
357         int desiredAccess;
358         int disposition = FILE_OPEN;
359         __u16 netfid;
360
361         if (file->private_data)
362                 pCifsFile = (struct cifsFileInfo *)file->private_data;
363         else
364                 return -EBADF;
365
366         xid = GetXid();
367         down(&pCifsFile->fh_sem);
368         if (!pCifsFile->invalidHandle) {
369                 up(&pCifsFile->fh_sem);
370                 FreeXid(xid);
371                 return 0;
372         }
373
374         if (file->f_path.dentry == NULL) {
375                 cERROR(1, ("no valid name if dentry freed"));
376                 dump_stack();
377                 rc = -EBADF;
378                 goto reopen_error_exit;
379         }
380
381         inode = file->f_path.dentry->d_inode;
382         if (inode == NULL) {
383                 cERROR(1, ("inode not valid"));
384                 dump_stack();
385                 rc = -EBADF;
386                 goto reopen_error_exit;
387         }
388
389         cifs_sb = CIFS_SB(inode->i_sb);
390         pTcon = cifs_sb->tcon;
391
392 /* can not grab rename sem here because various ops, including
393    those that already have the rename sem can end up causing writepage
394    to get called and if the server was down that means we end up here,
395    and we can never tell if the caller already has the rename_sem */
396         full_path = build_path_from_dentry(file->f_path.dentry);
397         if (full_path == NULL) {
398                 rc = -ENOMEM;
399 reopen_error_exit:
400                 up(&pCifsFile->fh_sem);
401                 FreeXid(xid);
402                 return rc;
403         }
404
405         cFYI(1, ("inode = 0x%p file flags 0x%x for %s",
406                  inode, file->f_flags, full_path));
407         desiredAccess = cifs_convert_flags(file->f_flags);
408
409         if (oplockEnabled)
410                 oplock = REQ_OPLOCK;
411         else
412                 oplock = 0;
413
414         /* Can not refresh inode by passing in file_info buf to be returned
415            by SMBOpen and then calling get_inode_info with returned buf
416            since file might have write behind data that needs to be flushed
417            and server version of file size can be stale. If we knew for sure
418            that inode was not dirty locally we could do this */
419
420         rc = CIFSSMBOpen(xid, pTcon, full_path, disposition, desiredAccess,
421                          CREATE_NOT_DIR, &netfid, &oplock, NULL,
422                          cifs_sb->local_nls, cifs_sb->mnt_cifs_flags &
423                                 CIFS_MOUNT_MAP_SPECIAL_CHR);
424         if (rc) {
425                 up(&pCifsFile->fh_sem);
426                 cFYI(1, ("cifs_open returned 0x%x", rc));
427                 cFYI(1, ("oplock: %d", oplock));
428         } else {
429                 pCifsFile->netfid = netfid;
430                 pCifsFile->invalidHandle = false;
431                 up(&pCifsFile->fh_sem);
432                 pCifsInode = CIFS_I(inode);
433                 if (pCifsInode) {
434                         if (can_flush) {
435                                 rc = filemap_write_and_wait(inode->i_mapping);
436                                 if (rc != 0)
437                                         CIFS_I(inode)->write_behind_rc = rc;
438                         /* temporarily disable caching while we
439                            go to server to get inode info */
440                                 pCifsInode->clientCanCacheAll = false;
441                                 pCifsInode->clientCanCacheRead = false;
442                                 if (pTcon->unix_ext)
443                                         rc = cifs_get_inode_info_unix(&inode,
444                                                 full_path, inode->i_sb, xid);
445                                 else
446                                         rc = cifs_get_inode_info(&inode,
447                                                 full_path, NULL, inode->i_sb,
448                                                 xid, NULL);
449                         } /* else we are writing out data to server already
450                              and could deadlock if we tried to flush data, and
451                              since we do not know if we have data that would
452                              invalidate the current end of file on the server
453                              we can not go to the server to get the new inod
454                              info */
455                         if ((oplock & 0xF) == OPLOCK_EXCLUSIVE) {
456                                 pCifsInode->clientCanCacheAll = true;
457                                 pCifsInode->clientCanCacheRead = true;
458                                 cFYI(1, ("Exclusive Oplock granted on inode %p",
459                                          file->f_path.dentry->d_inode));
460                         } else if ((oplock & 0xF) == OPLOCK_READ) {
461                                 pCifsInode->clientCanCacheRead = true;
462                                 pCifsInode->clientCanCacheAll = false;
463                         } else {
464                                 pCifsInode->clientCanCacheRead = false;
465                                 pCifsInode->clientCanCacheAll = false;
466                         }
467                         cifs_relock_file(pCifsFile);
468                 }
469         }
470
471         kfree(full_path);
472         FreeXid(xid);
473         return rc;
474 }
475
476 int cifs_close(struct inode *inode, struct file *file)
477 {
478         int rc = 0;
479         int xid, timeout;
480         struct cifs_sb_info *cifs_sb;
481         struct cifsTconInfo *pTcon;
482         struct cifsFileInfo *pSMBFile =
483                 (struct cifsFileInfo *)file->private_data;
484
485         xid = GetXid();
486
487         cifs_sb = CIFS_SB(inode->i_sb);
488         pTcon = cifs_sb->tcon;
489         if (pSMBFile) {
490                 struct cifsLockInfo *li, *tmp;
491
492                 pSMBFile->closePend = true;
493                 if (pTcon) {
494                         /* no sense reconnecting to close a file that is
495                            already closed */
496                         if (pTcon->tidStatus != CifsNeedReconnect) {
497                                 timeout = 2;
498                                 while ((atomic_read(&pSMBFile->wrtPending) != 0)
499                                         && (timeout <= 2048)) {
500                                         /* Give write a better chance to get to
501                                         server ahead of the close.  We do not
502                                         want to add a wait_q here as it would
503                                         increase the memory utilization as
504                                         the struct would be in each open file,
505                                         but this should give enough time to
506                                         clear the socket */
507                                         cFYI(DBG2,
508                                                 ("close delay, write pending"));
509                                         msleep(timeout);
510                                         timeout *= 4;
511                                 }
512                                 if (atomic_read(&pSMBFile->wrtPending))
513                                         cERROR(1,
514                                                 ("close with pending writes"));
515                                 rc = CIFSSMBClose(xid, pTcon,
516                                                   pSMBFile->netfid);
517                         }
518                 }
519
520                 /* Delete any outstanding lock records.
521                    We'll lose them when the file is closed anyway. */
522                 mutex_lock(&pSMBFile->lock_mutex);
523                 list_for_each_entry_safe(li, tmp, &pSMBFile->llist, llist) {
524                         list_del(&li->llist);
525                         kfree(li);
526                 }
527                 mutex_unlock(&pSMBFile->lock_mutex);
528
529                 write_lock(&GlobalSMBSeslock);
530                 list_del(&pSMBFile->flist);
531                 list_del(&pSMBFile->tlist);
532                 write_unlock(&GlobalSMBSeslock);
533                 timeout = 10;
534                 /* We waited above to give the SMBWrite a chance to issue
535                    on the wire (so we do not get SMBWrite returning EBADF
536                    if writepages is racing with close.  Note that writepages
537                    does not specify a file handle, so it is possible for a file
538                    to be opened twice, and the application close the "wrong"
539                    file handle - in these cases we delay long enough to allow
540                    the SMBWrite to get on the wire before the SMB Close.
541                    We allow total wait here over 45 seconds, more than
542                    oplock break time, and more than enough to allow any write
543                    to complete on the server, or to time out on the client */
544                 while ((atomic_read(&pSMBFile->wrtPending) != 0)
545                                 && (timeout <= 50000)) {
546                         cERROR(1, ("writes pending, delay free of handle"));
547                         msleep(timeout);
548                         timeout *= 8;
549                 }
550                 kfree(file->private_data);
551                 file->private_data = NULL;
552         } else
553                 rc = -EBADF;
554
555         read_lock(&GlobalSMBSeslock);
556         if (list_empty(&(CIFS_I(inode)->openFileList))) {
557                 cFYI(1, ("closing last open instance for inode %p", inode));
558                 /* if the file is not open we do not know if we can cache info
559                    on this inode, much less write behind and read ahead */
560                 CIFS_I(inode)->clientCanCacheRead = false;
561                 CIFS_I(inode)->clientCanCacheAll  = false;
562         }
563         read_unlock(&GlobalSMBSeslock);
564         if ((rc == 0) && CIFS_I(inode)->write_behind_rc)
565                 rc = CIFS_I(inode)->write_behind_rc;
566         FreeXid(xid);
567         return rc;
568 }
569
570 int cifs_closedir(struct inode *inode, struct file *file)
571 {
572         int rc = 0;
573         int xid;
574         struct cifsFileInfo *pCFileStruct =
575             (struct cifsFileInfo *)file->private_data;
576         char *ptmp;
577
578         cFYI(1, ("Closedir inode = 0x%p", inode));
579
580         xid = GetXid();
581
582         if (pCFileStruct) {
583                 struct cifsTconInfo *pTcon;
584                 struct cifs_sb_info *cifs_sb =
585                         CIFS_SB(file->f_path.dentry->d_sb);
586
587                 pTcon = cifs_sb->tcon;
588
589                 cFYI(1, ("Freeing private data in close dir"));
590                 if (!pCFileStruct->srch_inf.endOfSearch &&
591                     !pCFileStruct->invalidHandle) {
592                         pCFileStruct->invalidHandle = true;
593                         rc = CIFSFindClose(xid, pTcon, pCFileStruct->netfid);
594                         cFYI(1, ("Closing uncompleted readdir with rc %d",
595                                  rc));
596                         /* not much we can do if it fails anyway, ignore rc */
597                         rc = 0;
598                 }
599                 ptmp = pCFileStruct->srch_inf.ntwrk_buf_start;
600                 if (ptmp) {
601                         cFYI(1, ("closedir free smb buf in srch struct"));
602                         pCFileStruct->srch_inf.ntwrk_buf_start = NULL;
603                         if (pCFileStruct->srch_inf.smallBuf)
604                                 cifs_small_buf_release(ptmp);
605                         else
606                                 cifs_buf_release(ptmp);
607                 }
608                 kfree(file->private_data);
609                 file->private_data = NULL;
610         }
611         /* BB can we lock the filestruct while this is going on? */
612         FreeXid(xid);
613         return rc;
614 }
615
616 static int store_file_lock(struct cifsFileInfo *fid, __u64 len,
617                                 __u64 offset, __u8 lockType)
618 {
619         struct cifsLockInfo *li =
620                 kmalloc(sizeof(struct cifsLockInfo), GFP_KERNEL);
621         if (li == NULL)
622                 return -ENOMEM;
623         li->offset = offset;
624         li->length = len;
625         li->type = lockType;
626         mutex_lock(&fid->lock_mutex);
627         list_add(&li->llist, &fid->llist);
628         mutex_unlock(&fid->lock_mutex);
629         return 0;
630 }
631
632 int cifs_lock(struct file *file, int cmd, struct file_lock *pfLock)
633 {
634         int rc, xid;
635         __u32 numLock = 0;
636         __u32 numUnlock = 0;
637         __u64 length;
638         bool wait_flag = false;
639         struct cifs_sb_info *cifs_sb;
640         struct cifsTconInfo *pTcon;
641         __u16 netfid;
642         __u8 lockType = LOCKING_ANDX_LARGE_FILES;
643         bool posix_locking;
644
645         length = 1 + pfLock->fl_end - pfLock->fl_start;
646         rc = -EACCES;
647         xid = GetXid();
648
649         cFYI(1, ("Lock parm: 0x%x flockflags: "
650                  "0x%x flocktype: 0x%x start: %lld end: %lld",
651                 cmd, pfLock->fl_flags, pfLock->fl_type, pfLock->fl_start,
652                 pfLock->fl_end));
653
654         if (pfLock->fl_flags & FL_POSIX)
655                 cFYI(1, ("Posix"));
656         if (pfLock->fl_flags & FL_FLOCK)
657                 cFYI(1, ("Flock"));
658         if (pfLock->fl_flags & FL_SLEEP) {
659                 cFYI(1, ("Blocking lock"));
660                 wait_flag = true;
661         }
662         if (pfLock->fl_flags & FL_ACCESS)
663                 cFYI(1, ("Process suspended by mandatory locking - "
664                          "not implemented yet"));
665         if (pfLock->fl_flags & FL_LEASE)
666                 cFYI(1, ("Lease on file - not implemented yet"));
667         if (pfLock->fl_flags &
668             (~(FL_POSIX | FL_FLOCK | FL_SLEEP | FL_ACCESS | FL_LEASE)))
669                 cFYI(1, ("Unknown lock flags 0x%x", pfLock->fl_flags));
670
671         if (pfLock->fl_type == F_WRLCK) {
672                 cFYI(1, ("F_WRLCK "));
673                 numLock = 1;
674         } else if (pfLock->fl_type == F_UNLCK) {
675                 cFYI(1, ("F_UNLCK"));
676                 numUnlock = 1;
677                 /* Check if unlock includes more than
678                 one lock range */
679         } else if (pfLock->fl_type == F_RDLCK) {
680                 cFYI(1, ("F_RDLCK"));
681                 lockType |= LOCKING_ANDX_SHARED_LOCK;
682                 numLock = 1;
683         } else if (pfLock->fl_type == F_EXLCK) {
684                 cFYI(1, ("F_EXLCK"));
685                 numLock = 1;
686         } else if (pfLock->fl_type == F_SHLCK) {
687                 cFYI(1, ("F_SHLCK"));
688                 lockType |= LOCKING_ANDX_SHARED_LOCK;
689                 numLock = 1;
690         } else
691                 cFYI(1, ("Unknown type of lock"));
692
693         cifs_sb = CIFS_SB(file->f_path.dentry->d_sb);
694         pTcon = cifs_sb->tcon;
695
696         if (file->private_data == NULL) {
697                 FreeXid(xid);
698                 return -EBADF;
699         }
700         netfid = ((struct cifsFileInfo *)file->private_data)->netfid;
701
702         posix_locking = (cifs_sb->tcon->ses->capabilities & CAP_UNIX) &&
703                         (CIFS_UNIX_FCNTL_CAP & le64_to_cpu(cifs_sb->tcon->fsUnixInfo.Capability));
704
705         /* BB add code here to normalize offset and length to
706         account for negative length which we can not accept over the
707         wire */
708         if (IS_GETLK(cmd)) {
709                 if (posix_locking) {
710                         int posix_lock_type;
711                         if (lockType & LOCKING_ANDX_SHARED_LOCK)
712                                 posix_lock_type = CIFS_RDLCK;
713                         else
714                                 posix_lock_type = CIFS_WRLCK;
715                         rc = CIFSSMBPosixLock(xid, pTcon, netfid, 1 /* get */,
716                                         length, pfLock,
717                                         posix_lock_type, wait_flag);
718                         FreeXid(xid);
719                         return rc;
720                 }
721
722                 /* BB we could chain these into one lock request BB */
723                 rc = CIFSSMBLock(xid, pTcon, netfid, length, pfLock->fl_start,
724                                  0, 1, lockType, 0 /* wait flag */ );
725                 if (rc == 0) {
726                         rc = CIFSSMBLock(xid, pTcon, netfid, length,
727                                          pfLock->fl_start, 1 /* numUnlock */ ,
728                                          0 /* numLock */ , lockType,
729                                          0 /* wait flag */ );
730                         pfLock->fl_type = F_UNLCK;
731                         if (rc != 0)
732                                 cERROR(1, ("Error unlocking previously locked "
733                                            "range %d during test of lock", rc));
734                         rc = 0;
735
736                 } else {
737                         /* if rc == ERR_SHARING_VIOLATION ? */
738                         rc = 0; /* do not change lock type to unlock
739                                    since range in use */
740                 }
741
742                 FreeXid(xid);
743                 return rc;
744         }
745
746         if (!numLock && !numUnlock) {
747                 /* if no lock or unlock then nothing
748                 to do since we do not know what it is */
749                 FreeXid(xid);
750                 return -EOPNOTSUPP;
751         }
752
753         if (posix_locking) {
754                 int posix_lock_type;
755                 if (lockType & LOCKING_ANDX_SHARED_LOCK)
756                         posix_lock_type = CIFS_RDLCK;
757                 else
758                         posix_lock_type = CIFS_WRLCK;
759
760                 if (numUnlock == 1)
761                         posix_lock_type = CIFS_UNLCK;
762
763                 rc = CIFSSMBPosixLock(xid, pTcon, netfid, 0 /* set */,
764                                       length, pfLock,
765                                       posix_lock_type, wait_flag);
766         } else {
767                 struct cifsFileInfo *fid =
768                         (struct cifsFileInfo *)file->private_data;
769
770                 if (numLock) {
771                         rc = CIFSSMBLock(xid, pTcon, netfid, length,
772                                         pfLock->fl_start,
773                                         0, numLock, lockType, wait_flag);
774
775                         if (rc == 0) {
776                                 /* For Windows locks we must store them. */
777                                 rc = store_file_lock(fid, length,
778                                                 pfLock->fl_start, lockType);
779                         }
780                 } else if (numUnlock) {
781                         /* For each stored lock that this unlock overlaps
782                            completely, unlock it. */
783                         int stored_rc = 0;
784                         struct cifsLockInfo *li, *tmp;
785
786                         rc = 0;
787                         mutex_lock(&fid->lock_mutex);
788                         list_for_each_entry_safe(li, tmp, &fid->llist, llist) {
789                                 if (pfLock->fl_start <= li->offset &&
790                                                 (pfLock->fl_start + length) >=
791                                                 (li->offset + li->length)) {
792                                         stored_rc = CIFSSMBLock(xid, pTcon,
793                                                         netfid,
794                                                         li->length, li->offset,
795                                                         1, 0, li->type, false);
796                                         if (stored_rc)
797                                                 rc = stored_rc;
798
799                                         list_del(&li->llist);
800                                         kfree(li);
801                                 }
802                         }
803                         mutex_unlock(&fid->lock_mutex);
804                 }
805         }
806
807         if (pfLock->fl_flags & FL_POSIX)
808                 posix_lock_file_wait(file, pfLock);
809         FreeXid(xid);
810         return rc;
811 }
812
813 ssize_t cifs_user_write(struct file *file, const char __user *write_data,
814         size_t write_size, loff_t *poffset)
815 {
816         int rc = 0;
817         unsigned int bytes_written = 0;
818         unsigned int total_written;
819         struct cifs_sb_info *cifs_sb;
820         struct cifsTconInfo *pTcon;
821         int xid, long_op;
822         struct cifsFileInfo *open_file;
823
824         cifs_sb = CIFS_SB(file->f_path.dentry->d_sb);
825
826         pTcon = cifs_sb->tcon;
827
828         /* cFYI(1,
829            (" write %d bytes to offset %lld of %s", write_size,
830            *poffset, file->f_path.dentry->d_name.name)); */
831
832         if (file->private_data == NULL)
833                 return -EBADF;
834         open_file = (struct cifsFileInfo *) file->private_data;
835
836         rc = generic_write_checks(file, poffset, &write_size, 0);
837         if (rc)
838                 return rc;
839
840         xid = GetXid();
841
842         if (*poffset > file->f_path.dentry->d_inode->i_size)
843                 long_op = CIFS_VLONG_OP; /* writes past EOF take long time */
844         else
845                 long_op = CIFS_LONG_OP;
846
847         for (total_written = 0; write_size > total_written;
848              total_written += bytes_written) {
849                 rc = -EAGAIN;
850                 while (rc == -EAGAIN) {
851                         if (file->private_data == NULL) {
852                                 /* file has been closed on us */
853                                 FreeXid(xid);
854                         /* if we have gotten here we have written some data
855                            and blocked, and the file has been freed on us while
856                            we blocked so return what we managed to write */
857                                 return total_written;
858                         }
859                         if (open_file->closePend) {
860                                 FreeXid(xid);
861                                 if (total_written)
862                                         return total_written;
863                                 else
864                                         return -EBADF;
865                         }
866                         if (open_file->invalidHandle) {
867                                 /* we could deadlock if we called
868                                    filemap_fdatawait from here so tell
869                                    reopen_file not to flush data to server
870                                    now */
871                                 rc = cifs_reopen_file(file, false);
872                                 if (rc != 0)
873                                         break;
874                         }
875
876                         rc = CIFSSMBWrite(xid, pTcon,
877                                 open_file->netfid,
878                                 min_t(const int, cifs_sb->wsize,
879                                       write_size - total_written),
880                                 *poffset, &bytes_written,
881                                 NULL, write_data + total_written, long_op);
882                 }
883                 if (rc || (bytes_written == 0)) {
884                         if (total_written)
885                                 break;
886                         else {
887                                 FreeXid(xid);
888                                 return rc;
889                         }
890                 } else
891                         *poffset += bytes_written;
892                 long_op = CIFS_STD_OP; /* subsequent writes fast -
893                                     15 seconds is plenty */
894         }
895
896         cifs_stats_bytes_written(pTcon, total_written);
897
898         /* since the write may have blocked check these pointers again */
899         if ((file->f_path.dentry) && (file->f_path.dentry->d_inode)) {
900                 struct inode *inode = file->f_path.dentry->d_inode;
901 /* Do not update local mtime - server will set its actual value on write
902  *              inode->i_ctime = inode->i_mtime =
903  *                      current_fs_time(inode->i_sb);*/
904                 if (total_written > 0) {
905                         spin_lock(&inode->i_lock);
906                         if (*poffset > file->f_path.dentry->d_inode->i_size)
907                                 i_size_write(file->f_path.dentry->d_inode,
908                                         *poffset);
909                         spin_unlock(&inode->i_lock);
910                 }
911                 mark_inode_dirty_sync(file->f_path.dentry->d_inode);
912         }
913         FreeXid(xid);
914         return total_written;
915 }
916
917 static ssize_t cifs_write(struct file *file, const char *write_data,
918         size_t write_size, loff_t *poffset)
919 {
920         int rc = 0;
921         unsigned int bytes_written = 0;
922         unsigned int total_written;
923         struct cifs_sb_info *cifs_sb;
924         struct cifsTconInfo *pTcon;
925         int xid, long_op;
926         struct cifsFileInfo *open_file;
927
928         cifs_sb = CIFS_SB(file->f_path.dentry->d_sb);
929
930         pTcon = cifs_sb->tcon;
931
932         cFYI(1, ("write %zd bytes to offset %lld of %s", write_size,
933            *poffset, file->f_path.dentry->d_name.name));
934
935         if (file->private_data == NULL)
936                 return -EBADF;
937         open_file = (struct cifsFileInfo *)file->private_data;
938
939         xid = GetXid();
940
941         if (*poffset > file->f_path.dentry->d_inode->i_size)
942                 long_op = CIFS_VLONG_OP; /* writes past EOF can be slow */
943         else
944                 long_op = CIFS_LONG_OP;
945
946         for (total_written = 0; write_size > total_written;
947              total_written += bytes_written) {
948                 rc = -EAGAIN;
949                 while (rc == -EAGAIN) {
950                         if (file->private_data == NULL) {
951                                 /* file has been closed on us */
952                                 FreeXid(xid);
953                         /* if we have gotten here we have written some data
954                            and blocked, and the file has been freed on us
955                            while we blocked so return what we managed to
956                            write */
957                                 return total_written;
958                         }
959                         if (open_file->closePend) {
960                                 FreeXid(xid);
961                                 if (total_written)
962                                         return total_written;
963                                 else
964                                         return -EBADF;
965                         }
966                         if (open_file->invalidHandle) {
967                                 /* we could deadlock if we called
968                                    filemap_fdatawait from here so tell
969                                    reopen_file not to flush data to
970                                    server now */
971                                 rc = cifs_reopen_file(file, false);
972                                 if (rc != 0)
973                                         break;
974                         }
975                         if (experimEnabled || (pTcon->ses->server &&
976                                 ((pTcon->ses->server->secMode &
977                                 (SECMODE_SIGN_REQUIRED | SECMODE_SIGN_ENABLED))
978                                 == 0))) {
979                                 struct kvec iov[2];
980                                 unsigned int len;
981
982                                 len = min((size_t)cifs_sb->wsize,
983                                           write_size - total_written);
984                                 /* iov[0] is reserved for smb header */
985                                 iov[1].iov_base = (char *)write_data +
986                                                   total_written;
987                                 iov[1].iov_len = len;
988                                 rc = CIFSSMBWrite2(xid, pTcon,
989                                                 open_file->netfid, len,
990                                                 *poffset, &bytes_written,
991                                                 iov, 1, long_op);
992                         } else
993                                 rc = CIFSSMBWrite(xid, pTcon,
994                                          open_file->netfid,
995                                          min_t(const int, cifs_sb->wsize,
996                                                write_size - total_written),
997                                          *poffset, &bytes_written,
998                                          write_data + total_written,
999                                          NULL, long_op);
1000                 }
1001                 if (rc || (bytes_written == 0)) {
1002                         if (total_written)
1003                                 break;
1004                         else {
1005                                 FreeXid(xid);
1006                                 return rc;
1007                         }
1008                 } else
1009                         *poffset += bytes_written;
1010                 long_op = CIFS_STD_OP; /* subsequent writes fast -
1011                                     15 seconds is plenty */
1012         }
1013
1014         cifs_stats_bytes_written(pTcon, total_written);
1015
1016         /* since the write may have blocked check these pointers again */
1017         if ((file->f_path.dentry) && (file->f_path.dentry->d_inode)) {
1018 /*BB We could make this contingent on superblock ATIME flag too */
1019 /*              file->f_path.dentry->d_inode->i_ctime =
1020                 file->f_path.dentry->d_inode->i_mtime = CURRENT_TIME;*/
1021                 if (total_written > 0) {
1022                         spin_lock(&file->f_path.dentry->d_inode->i_lock);
1023                         if (*poffset > file->f_path.dentry->d_inode->i_size)
1024                                 i_size_write(file->f_path.dentry->d_inode,
1025                                              *poffset);
1026                         spin_unlock(&file->f_path.dentry->d_inode->i_lock);
1027                 }
1028                 mark_inode_dirty_sync(file->f_path.dentry->d_inode);
1029         }
1030         FreeXid(xid);
1031         return total_written;
1032 }
1033
1034 #ifdef CONFIG_CIFS_EXPERIMENTAL
1035 struct cifsFileInfo *find_readable_file(struct cifsInodeInfo *cifs_inode)
1036 {
1037         struct cifsFileInfo *open_file = NULL;
1038
1039         read_lock(&GlobalSMBSeslock);
1040         /* we could simply get the first_list_entry since write-only entries
1041            are always at the end of the list but since the first entry might
1042            have a close pending, we go through the whole list */
1043         list_for_each_entry(open_file, &cifs_inode->openFileList, flist) {
1044                 if (open_file->closePend)
1045                         continue;
1046                 if (open_file->pfile && ((open_file->pfile->f_flags & O_RDWR) ||
1047                     (open_file->pfile->f_flags & O_RDONLY))) {
1048                         if (!open_file->invalidHandle) {
1049                                 /* found a good file */
1050                                 /* lock it so it will not be closed on us */
1051                                 atomic_inc(&open_file->wrtPending);
1052                                 read_unlock(&GlobalSMBSeslock);
1053                                 return open_file;
1054                         } /* else might as well continue, and look for
1055                              another, or simply have the caller reopen it
1056                              again rather than trying to fix this handle */
1057                 } else /* write only file */
1058                         break; /* write only files are last so must be done */
1059         }
1060         read_unlock(&GlobalSMBSeslock);
1061         return NULL;
1062 }
1063 #endif
1064
1065 struct cifsFileInfo *find_writable_file(struct cifsInodeInfo *cifs_inode)
1066 {
1067         struct cifsFileInfo *open_file;
1068         bool any_available = false;
1069         int rc;
1070
1071         /* Having a null inode here (because mapping->host was set to zero by
1072         the VFS or MM) should not happen but we had reports of on oops (due to
1073         it being zero) during stress testcases so we need to check for it */
1074
1075         if (cifs_inode == NULL) {
1076                 cERROR(1, ("Null inode passed to cifs_writeable_file"));
1077                 dump_stack();
1078                 return NULL;
1079         }
1080
1081         read_lock(&GlobalSMBSeslock);
1082 refind_writable:
1083         list_for_each_entry(open_file, &cifs_inode->openFileList, flist) {
1084                 if (open_file->closePend ||
1085                     (!any_available && open_file->pid != current->tgid))
1086                         continue;
1087
1088                 if (open_file->pfile &&
1089                     ((open_file->pfile->f_flags & O_RDWR) ||
1090                      (open_file->pfile->f_flags & O_WRONLY))) {
1091                         atomic_inc(&open_file->wrtPending);
1092
1093                         if (!open_file->invalidHandle) {
1094                                 /* found a good writable file */
1095                                 read_unlock(&GlobalSMBSeslock);
1096                                 return open_file;
1097                         }
1098
1099                         read_unlock(&GlobalSMBSeslock);
1100                         /* Had to unlock since following call can block */
1101                         rc = cifs_reopen_file(open_file->pfile, false);
1102                         if (!rc) {
1103                                 if (!open_file->closePend)
1104                                         return open_file;
1105                                 else { /* start over in case this was deleted */
1106                                        /* since the list could be modified */
1107                                         read_lock(&GlobalSMBSeslock);
1108                                         atomic_dec(&open_file->wrtPending);
1109                                         goto refind_writable;
1110                                 }
1111                         }
1112
1113                         /* if it fails, try another handle if possible -
1114                         (we can not do this if closePending since
1115                         loop could be modified - in which case we
1116                         have to start at the beginning of the list
1117                         again. Note that it would be bad
1118                         to hold up writepages here (rather than
1119                         in caller) with continuous retries */
1120                         cFYI(1, ("wp failed on reopen file"));
1121                         read_lock(&GlobalSMBSeslock);
1122                         /* can not use this handle, no write
1123                            pending on this one after all */
1124                         atomic_dec(&open_file->wrtPending);
1125
1126                         if (open_file->closePend) /* list could have changed */
1127                                 goto refind_writable;
1128                         /* else we simply continue to the next entry. Thus
1129                            we do not loop on reopen errors.  If we
1130                            can not reopen the file, for example if we
1131                            reconnected to a server with another client
1132                            racing to delete or lock the file we would not
1133                            make progress if we restarted before the beginning
1134                            of the loop here. */
1135                 }
1136         }
1137         /* couldn't find useable FH with same pid, try any available */
1138         if (!any_available) {
1139                 any_available = true;
1140                 goto refind_writable;
1141         }
1142         read_unlock(&GlobalSMBSeslock);
1143         return NULL;
1144 }
1145
1146 static int cifs_partialpagewrite(struct page *page, unsigned from, unsigned to)
1147 {
1148         struct address_space *mapping = page->mapping;
1149         loff_t offset = (loff_t)page->index << PAGE_CACHE_SHIFT;
1150         char *write_data;
1151         int rc = -EFAULT;
1152         int bytes_written = 0;
1153         struct cifs_sb_info *cifs_sb;
1154         struct cifsTconInfo *pTcon;
1155         struct inode *inode;
1156         struct cifsFileInfo *open_file;
1157
1158         if (!mapping || !mapping->host)
1159                 return -EFAULT;
1160
1161         inode = page->mapping->host;
1162         cifs_sb = CIFS_SB(inode->i_sb);
1163         pTcon = cifs_sb->tcon;
1164
1165         offset += (loff_t)from;
1166         write_data = kmap(page);
1167         write_data += from;
1168
1169         if ((to > PAGE_CACHE_SIZE) || (from > to)) {
1170                 kunmap(page);
1171                 return -EIO;
1172         }
1173
1174         /* racing with truncate? */
1175         if (offset > mapping->host->i_size) {
1176                 kunmap(page);
1177                 return 0; /* don't care */
1178         }
1179
1180         /* check to make sure that we are not extending the file */
1181         if (mapping->host->i_size - offset < (loff_t)to)
1182                 to = (unsigned)(mapping->host->i_size - offset);
1183
1184         open_file = find_writable_file(CIFS_I(mapping->host));
1185         if (open_file) {
1186                 bytes_written = cifs_write(open_file->pfile, write_data,
1187                                            to-from, &offset);
1188                 atomic_dec(&open_file->wrtPending);
1189                 /* Does mm or vfs already set times? */
1190                 inode->i_atime = inode->i_mtime = current_fs_time(inode->i_sb);
1191                 if ((bytes_written > 0) && (offset))
1192                         rc = 0;
1193                 else if (bytes_written < 0)
1194                         rc = bytes_written;
1195         } else {
1196                 cFYI(1, ("No writeable filehandles for inode"));
1197                 rc = -EIO;
1198         }
1199
1200         kunmap(page);
1201         return rc;
1202 }
1203
1204 static int cifs_writepages(struct address_space *mapping,
1205                            struct writeback_control *wbc)
1206 {
1207         struct backing_dev_info *bdi = mapping->backing_dev_info;
1208         unsigned int bytes_to_write;
1209         unsigned int bytes_written;
1210         struct cifs_sb_info *cifs_sb;
1211         int done = 0;
1212         pgoff_t end;
1213         pgoff_t index;
1214         int range_whole = 0;
1215         struct kvec *iov;
1216         int len;
1217         int n_iov = 0;
1218         pgoff_t next;
1219         int nr_pages;
1220         __u64 offset = 0;
1221         struct cifsFileInfo *open_file;
1222         struct page *page;
1223         struct pagevec pvec;
1224         int rc = 0;
1225         int scanned = 0;
1226         int xid;
1227
1228         cifs_sb = CIFS_SB(mapping->host->i_sb);
1229
1230         /*
1231          * If wsize is smaller that the page cache size, default to writing
1232          * one page at a time via cifs_writepage
1233          */
1234         if (cifs_sb->wsize < PAGE_CACHE_SIZE)
1235                 return generic_writepages(mapping, wbc);
1236
1237         if ((cifs_sb->tcon->ses) && (cifs_sb->tcon->ses->server))
1238                 if (cifs_sb->tcon->ses->server->secMode &
1239                                 (SECMODE_SIGN_REQUIRED | SECMODE_SIGN_ENABLED))
1240                         if (!experimEnabled)
1241                                 return generic_writepages(mapping, wbc);
1242
1243         iov = kmalloc(32 * sizeof(struct kvec), GFP_KERNEL);
1244         if (iov == NULL)
1245                 return generic_writepages(mapping, wbc);
1246
1247
1248         /*
1249          * BB: Is this meaningful for a non-block-device file system?
1250          * If it is, we should test it again after we do I/O
1251          */
1252         if (wbc->nonblocking && bdi_write_congested(bdi)) {
1253                 wbc->encountered_congestion = 1;
1254                 kfree(iov);
1255                 return 0;
1256         }
1257
1258         xid = GetXid();
1259
1260         pagevec_init(&pvec, 0);
1261         if (wbc->range_cyclic) {
1262                 index = mapping->writeback_index; /* Start from prev offset */
1263                 end = -1;
1264         } else {
1265                 index = wbc->range_start >> PAGE_CACHE_SHIFT;
1266                 end = wbc->range_end >> PAGE_CACHE_SHIFT;
1267                 if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX)
1268                         range_whole = 1;
1269                 scanned = 1;
1270         }
1271 retry:
1272         while (!done && (index <= end) &&
1273                (nr_pages = pagevec_lookup_tag(&pvec, mapping, &index,
1274                         PAGECACHE_TAG_DIRTY,
1275                         min(end - index, (pgoff_t)PAGEVEC_SIZE - 1) + 1))) {
1276                 int first;
1277                 unsigned int i;
1278
1279                 first = -1;
1280                 next = 0;
1281                 n_iov = 0;
1282                 bytes_to_write = 0;
1283
1284                 for (i = 0; i < nr_pages; i++) {
1285                         page = pvec.pages[i];
1286                         /*
1287                          * At this point we hold neither mapping->tree_lock nor
1288                          * lock on the page itself: the page may be truncated or
1289                          * invalidated (changing page->mapping to NULL), or even
1290                          * swizzled back from swapper_space to tmpfs file
1291                          * mapping
1292                          */
1293
1294                         if (first < 0)
1295                                 lock_page(page);
1296                         else if (!trylock_page(page))
1297                                 break;
1298
1299                         if (unlikely(page->mapping != mapping)) {
1300                                 unlock_page(page);
1301                                 break;
1302                         }
1303
1304                         if (!wbc->range_cyclic && page->index > end) {
1305                                 done = 1;
1306                                 unlock_page(page);
1307                                 break;
1308                         }
1309
1310                         if (next && (page->index != next)) {
1311                                 /* Not next consecutive page */
1312                                 unlock_page(page);
1313                                 break;
1314                         }
1315
1316                         if (wbc->sync_mode != WB_SYNC_NONE)
1317                                 wait_on_page_writeback(page);
1318
1319                         if (PageWriteback(page) ||
1320                                         !clear_page_dirty_for_io(page)) {
1321                                 unlock_page(page);
1322                                 break;
1323                         }
1324
1325                         /*
1326                          * This actually clears the dirty bit in the radix tree.
1327                          * See cifs_writepage() for more commentary.
1328                          */
1329                         set_page_writeback(page);
1330
1331                         if (page_offset(page) >= mapping->host->i_size) {
1332                                 done = 1;
1333                                 unlock_page(page);
1334                                 end_page_writeback(page);
1335                                 break;
1336                         }
1337
1338                         /*
1339                          * BB can we get rid of this?  pages are held by pvec
1340                          */
1341                         page_cache_get(page);
1342
1343                         len = min(mapping->host->i_size - page_offset(page),
1344                                   (loff_t)PAGE_CACHE_SIZE);
1345
1346                         /* reserve iov[0] for the smb header */
1347                         n_iov++;
1348                         iov[n_iov].iov_base = kmap(page);
1349                         iov[n_iov].iov_len = len;
1350                         bytes_to_write += len;
1351
1352                         if (first < 0) {
1353                                 first = i;
1354                                 offset = page_offset(page);
1355                         }
1356                         next = page->index + 1;
1357                         if (bytes_to_write + PAGE_CACHE_SIZE > cifs_sb->wsize)
1358                                 break;
1359                 }
1360                 if (n_iov) {
1361                         /* Search for a writable handle every time we call
1362                          * CIFSSMBWrite2.  We can't rely on the last handle
1363                          * we used to still be valid
1364                          */
1365                         open_file = find_writable_file(CIFS_I(mapping->host));
1366                         if (!open_file) {
1367                                 cERROR(1, ("No writable handles for inode"));
1368                                 rc = -EBADF;
1369                         } else {
1370                                 rc = CIFSSMBWrite2(xid, cifs_sb->tcon,
1371                                                    open_file->netfid,
1372                                                    bytes_to_write, offset,
1373                                                    &bytes_written, iov, n_iov,
1374                                                    CIFS_LONG_OP);
1375                                 atomic_dec(&open_file->wrtPending);
1376                                 if (rc || bytes_written < bytes_to_write) {
1377                                         cERROR(1, ("Write2 ret %d, wrote %d",
1378                                                   rc, bytes_written));
1379                                         /* BB what if continued retry is
1380                                            requested via mount flags? */
1381                                         if (rc == -ENOSPC)
1382                                                 set_bit(AS_ENOSPC, &mapping->flags);
1383                                         else
1384                                                 set_bit(AS_EIO, &mapping->flags);
1385                                 } else {
1386                                         cifs_stats_bytes_written(cifs_sb->tcon,
1387                                                                  bytes_written);
1388                                 }
1389                         }
1390                         for (i = 0; i < n_iov; i++) {
1391                                 page = pvec.pages[first + i];
1392                                 /* Should we also set page error on
1393                                 success rc but too little data written? */
1394                                 /* BB investigate retry logic on temporary
1395                                 server crash cases and how recovery works
1396                                 when page marked as error */
1397                                 if (rc)
1398                                         SetPageError(page);
1399                                 kunmap(page);
1400                                 unlock_page(page);
1401                                 end_page_writeback(page);
1402                                 page_cache_release(page);
1403                         }
1404                         if ((wbc->nr_to_write -= n_iov) <= 0)
1405                                 done = 1;
1406                         index = next;
1407                 }
1408                 pagevec_release(&pvec);
1409         }
1410         if (!scanned && !done) {
1411                 /*
1412                  * We hit the last page and there is more work to be done: wrap
1413                  * back to the start of the file
1414                  */
1415                 scanned = 1;
1416                 index = 0;
1417                 goto retry;
1418         }
1419         if (wbc->range_cyclic || (range_whole && wbc->nr_to_write > 0))
1420                 mapping->writeback_index = index;
1421
1422         FreeXid(xid);
1423         kfree(iov);
1424         return rc;
1425 }
1426
1427 static int cifs_writepage(struct page *page, struct writeback_control *wbc)
1428 {
1429         int rc = -EFAULT;
1430         int xid;
1431
1432         xid = GetXid();
1433 /* BB add check for wbc flags */
1434         page_cache_get(page);
1435         if (!PageUptodate(page))
1436                 cFYI(1, ("ppw - page not up to date"));
1437
1438         /*
1439          * Set the "writeback" flag, and clear "dirty" in the radix tree.
1440          *
1441          * A writepage() implementation always needs to do either this,
1442          * or re-dirty the page with "redirty_page_for_writepage()" in
1443          * the case of a failure.
1444          *
1445          * Just unlocking the page will cause the radix tree tag-bits
1446          * to fail to update with the state of the page correctly.
1447          */
1448         set_page_writeback(page);
1449         rc = cifs_partialpagewrite(page, 0, PAGE_CACHE_SIZE);
1450         SetPageUptodate(page); /* BB add check for error and Clearuptodate? */
1451         unlock_page(page);
1452         end_page_writeback(page);
1453         page_cache_release(page);
1454         FreeXid(xid);
1455         return rc;
1456 }
1457
1458 static int cifs_commit_write(struct file *file, struct page *page,
1459         unsigned offset, unsigned to)
1460 {
1461         int xid;
1462         int rc = 0;
1463         struct inode *inode = page->mapping->host;
1464         loff_t position = ((loff_t)page->index << PAGE_CACHE_SHIFT) + to;
1465         char *page_data;
1466
1467         xid = GetXid();
1468         cFYI(1, ("commit write for page %p up to position %lld for %d",
1469                  page, position, to));
1470         spin_lock(&inode->i_lock);
1471         if (position > inode->i_size)
1472                 i_size_write(inode, position);
1473
1474         spin_unlock(&inode->i_lock);
1475         if (!PageUptodate(page)) {
1476                 position =  ((loff_t)page->index << PAGE_CACHE_SHIFT) + offset;
1477                 /* can not rely on (or let) writepage write this data */
1478                 if (to < offset) {
1479                         cFYI(1, ("Illegal offsets, can not copy from %d to %d",
1480                                 offset, to));
1481                         FreeXid(xid);
1482                         return rc;
1483                 }
1484                 /* this is probably better than directly calling
1485                    partialpage_write since in this function the file handle is
1486                    known which we might as well leverage */
1487                 /* BB check if anything else missing out of ppw
1488                    such as updating last write time */
1489                 page_data = kmap(page);
1490                 rc = cifs_write(file, page_data + offset, to-offset,
1491                                 &position);
1492                 if (rc > 0)
1493                         rc = 0;
1494                 /* else if (rc < 0) should we set writebehind rc? */
1495                 kunmap(page);
1496         } else {
1497                 set_page_dirty(page);
1498         }
1499
1500         FreeXid(xid);
1501         return rc;
1502 }
1503
1504 int cifs_fsync(struct file *file, struct dentry *dentry, int datasync)
1505 {
1506         int xid;
1507         int rc = 0;
1508         struct inode *inode = file->f_path.dentry->d_inode;
1509
1510         xid = GetXid();
1511
1512         cFYI(1, ("Sync file - name: %s datasync: 0x%x",
1513                 dentry->d_name.name, datasync));
1514
1515         rc = filemap_write_and_wait(inode->i_mapping);
1516         if (rc == 0) {
1517                 rc = CIFS_I(inode)->write_behind_rc;
1518                 CIFS_I(inode)->write_behind_rc = 0;
1519         }
1520         FreeXid(xid);
1521         return rc;
1522 }
1523
1524 /* static void cifs_sync_page(struct page *page)
1525 {
1526         struct address_space *mapping;
1527         struct inode *inode;
1528         unsigned long index = page->index;
1529         unsigned int rpages = 0;
1530         int rc = 0;
1531
1532         cFYI(1, ("sync page %p",page));
1533         mapping = page->mapping;
1534         if (!mapping)
1535                 return 0;
1536         inode = mapping->host;
1537         if (!inode)
1538                 return; */
1539
1540 /*      fill in rpages then
1541         result = cifs_pagein_inode(inode, index, rpages); */ /* BB finish */
1542
1543 /*      cFYI(1, ("rpages is %d for sync page of Index %ld", rpages, index));
1544
1545 #if 0
1546         if (rc < 0)
1547                 return rc;
1548         return 0;
1549 #endif
1550 } */
1551
1552 /*
1553  * As file closes, flush all cached write data for this inode checking
1554  * for write behind errors.
1555  */
1556 int cifs_flush(struct file *file, fl_owner_t id)
1557 {
1558         struct inode *inode = file->f_path.dentry->d_inode;
1559         int rc = 0;
1560
1561         /* Rather than do the steps manually:
1562            lock the inode for writing
1563            loop through pages looking for write behind data (dirty pages)
1564            coalesce into contiguous 16K (or smaller) chunks to write to server
1565            send to server (prefer in parallel)
1566            deal with writebehind errors
1567            unlock inode for writing
1568            filemapfdatawrite appears easier for the time being */
1569
1570         rc = filemap_fdatawrite(inode->i_mapping);
1571         /* reset wb rc if we were able to write out dirty pages */
1572         if (!rc) {
1573                 rc = CIFS_I(inode)->write_behind_rc;
1574                 CIFS_I(inode)->write_behind_rc = 0;
1575         }
1576
1577         cFYI(1, ("Flush inode %p file %p rc %d", inode, file, rc));
1578
1579         return rc;
1580 }
1581
1582 ssize_t cifs_user_read(struct file *file, char __user *read_data,
1583         size_t read_size, loff_t *poffset)
1584 {
1585         int rc = -EACCES;
1586         unsigned int bytes_read = 0;
1587         unsigned int total_read = 0;
1588         unsigned int current_read_size;
1589         struct cifs_sb_info *cifs_sb;
1590         struct cifsTconInfo *pTcon;
1591         int xid;
1592         struct cifsFileInfo *open_file;
1593         char *smb_read_data;
1594         char __user *current_offset;
1595         struct smb_com_read_rsp *pSMBr;
1596
1597         xid = GetXid();
1598         cifs_sb = CIFS_SB(file->f_path.dentry->d_sb);
1599         pTcon = cifs_sb->tcon;
1600
1601         if (file->private_data == NULL) {
1602                 FreeXid(xid);
1603                 return -EBADF;
1604         }
1605         open_file = (struct cifsFileInfo *)file->private_data;
1606
1607         if ((file->f_flags & O_ACCMODE) == O_WRONLY)
1608                 cFYI(1, ("attempting read on write only file instance"));
1609
1610         for (total_read = 0, current_offset = read_data;
1611              read_size > total_read;
1612              total_read += bytes_read, current_offset += bytes_read) {
1613                 current_read_size = min_t(const int, read_size - total_read,
1614                                           cifs_sb->rsize);
1615                 rc = -EAGAIN;
1616                 smb_read_data = NULL;
1617                 while (rc == -EAGAIN) {
1618                         int buf_type = CIFS_NO_BUFFER;
1619                         if ((open_file->invalidHandle) &&
1620                             (!open_file->closePend)) {
1621                                 rc = cifs_reopen_file(file, true);
1622                                 if (rc != 0)
1623                                         break;
1624                         }
1625                         rc = CIFSSMBRead(xid, pTcon,
1626                                          open_file->netfid,
1627                                          current_read_size, *poffset,
1628                                          &bytes_read, &smb_read_data,
1629                                          &buf_type);
1630                         pSMBr = (struct smb_com_read_rsp *)smb_read_data;
1631                         if (smb_read_data) {
1632                                 if (copy_to_user(current_offset,
1633                                                 smb_read_data +
1634                                                 4 /* RFC1001 length field */ +
1635                                                 le16_to_cpu(pSMBr->DataOffset),
1636                                                 bytes_read))
1637                                         rc = -EFAULT;
1638
1639                                 if (buf_type == CIFS_SMALL_BUFFER)
1640                                         cifs_small_buf_release(smb_read_data);
1641                                 else if (buf_type == CIFS_LARGE_BUFFER)
1642                                         cifs_buf_release(smb_read_data);
1643                                 smb_read_data = NULL;
1644                         }
1645                 }
1646                 if (rc || (bytes_read == 0)) {
1647                         if (total_read) {
1648                                 break;
1649                         } else {
1650                                 FreeXid(xid);
1651                                 return rc;
1652                         }
1653                 } else {
1654                         cifs_stats_bytes_read(pTcon, bytes_read);
1655                         *poffset += bytes_read;
1656                 }
1657         }
1658         FreeXid(xid);
1659         return total_read;
1660 }
1661
1662
1663 static ssize_t cifs_read(struct file *file, char *read_data, size_t read_size,
1664         loff_t *poffset)
1665 {
1666         int rc = -EACCES;
1667         unsigned int bytes_read = 0;
1668         unsigned int total_read;
1669         unsigned int current_read_size;
1670         struct cifs_sb_info *cifs_sb;
1671         struct cifsTconInfo *pTcon;
1672         int xid;
1673         char *current_offset;
1674         struct cifsFileInfo *open_file;
1675         int buf_type = CIFS_NO_BUFFER;
1676
1677         xid = GetXid();
1678         cifs_sb = CIFS_SB(file->f_path.dentry->d_sb);
1679         pTcon = cifs_sb->tcon;
1680
1681         if (file->private_data == NULL) {
1682                 FreeXid(xid);
1683                 return -EBADF;
1684         }
1685         open_file = (struct cifsFileInfo *)file->private_data;
1686
1687         if ((file->f_flags & O_ACCMODE) == O_WRONLY)
1688                 cFYI(1, ("attempting read on write only file instance"));
1689
1690         for (total_read = 0, current_offset = read_data;
1691              read_size > total_read;
1692              total_read += bytes_read, current_offset += bytes_read) {
1693                 current_read_size = min_t(const int, read_size - total_read,
1694                                           cifs_sb->rsize);
1695                 /* For windows me and 9x we do not want to request more
1696                 than it negotiated since it will refuse the read then */
1697                 if ((pTcon->ses) &&
1698                         !(pTcon->ses->capabilities & CAP_LARGE_FILES)) {
1699                         current_read_size = min_t(const int, current_read_size,
1700                                         pTcon->ses->server->maxBuf - 128);
1701                 }
1702                 rc = -EAGAIN;
1703                 while (rc == -EAGAIN) {
1704                         if ((open_file->invalidHandle) &&
1705                             (!open_file->closePend)) {
1706                                 rc = cifs_reopen_file(file, true);
1707                                 if (rc != 0)
1708                                         break;
1709                         }
1710                         rc = CIFSSMBRead(xid, pTcon,
1711                                          open_file->netfid,
1712                                          current_read_size, *poffset,
1713                                          &bytes_read, &current_offset,
1714                                          &buf_type);
1715                 }
1716                 if (rc || (bytes_read == 0)) {
1717                         if (total_read) {
1718                                 break;
1719                         } else {
1720                                 FreeXid(xid);
1721                                 return rc;
1722                         }
1723                 } else {
1724                         cifs_stats_bytes_read(pTcon, total_read);
1725                         *poffset += bytes_read;
1726                 }
1727         }
1728         FreeXid(xid);
1729         return total_read;
1730 }
1731
1732 int cifs_file_mmap(struct file *file, struct vm_area_struct *vma)
1733 {
1734         struct dentry *dentry = file->f_path.dentry;
1735         int rc, xid;
1736
1737         xid = GetXid();
1738         rc = cifs_revalidate(dentry);
1739         if (rc) {
1740                 cFYI(1, ("Validation prior to mmap failed, error=%d", rc));
1741                 FreeXid(xid);
1742                 return rc;
1743         }
1744         rc = generic_file_mmap(file, vma);
1745         FreeXid(xid);
1746         return rc;
1747 }
1748
1749
1750 static void cifs_copy_cache_pages(struct address_space *mapping,
1751         struct list_head *pages, int bytes_read, char *data,
1752         struct pagevec *plru_pvec)
1753 {
1754         struct page *page;
1755         char *target;
1756
1757         while (bytes_read > 0) {
1758                 if (list_empty(pages))
1759                         break;
1760
1761                 page = list_entry(pages->prev, struct page, lru);
1762                 list_del(&page->lru);
1763
1764                 if (add_to_page_cache(page, mapping, page->index,
1765                                       GFP_KERNEL)) {
1766                         page_cache_release(page);
1767                         cFYI(1, ("Add page cache failed"));
1768                         data += PAGE_CACHE_SIZE;
1769                         bytes_read -= PAGE_CACHE_SIZE;
1770                         continue;
1771                 }
1772
1773                 target = kmap_atomic(page, KM_USER0);
1774
1775                 if (PAGE_CACHE_SIZE > bytes_read) {
1776                         memcpy(target, data, bytes_read);
1777                         /* zero the tail end of this partial page */
1778                         memset(target + bytes_read, 0,
1779                                PAGE_CACHE_SIZE - bytes_read);
1780                         bytes_read = 0;
1781                 } else {
1782                         memcpy(target, data, PAGE_CACHE_SIZE);
1783                         bytes_read -= PAGE_CACHE_SIZE;
1784                 }
1785                 kunmap_atomic(target, KM_USER0);
1786
1787                 flush_dcache_page(page);
1788                 SetPageUptodate(page);
1789                 unlock_page(page);
1790                 if (!pagevec_add(plru_pvec, page))
1791                         __pagevec_lru_add(plru_pvec);
1792                 data += PAGE_CACHE_SIZE;
1793         }
1794         return;
1795 }
1796
1797 static int cifs_readpages(struct file *file, struct address_space *mapping,
1798         struct list_head *page_list, unsigned num_pages)
1799 {
1800         int rc = -EACCES;
1801         int xid;
1802         loff_t offset;
1803         struct page *page;
1804         struct cifs_sb_info *cifs_sb;
1805         struct cifsTconInfo *pTcon;
1806         unsigned int bytes_read = 0;
1807         unsigned int read_size, i;
1808         char *smb_read_data = NULL;
1809         struct smb_com_read_rsp *pSMBr;
1810         struct pagevec lru_pvec;
1811         struct cifsFileInfo *open_file;
1812         int buf_type = CIFS_NO_BUFFER;
1813
1814         xid = GetXid();
1815         if (file->private_data == NULL) {
1816                 FreeXid(xid);
1817                 return -EBADF;
1818         }
1819         open_file = (struct cifsFileInfo *)file->private_data;
1820         cifs_sb = CIFS_SB(file->f_path.dentry->d_sb);
1821         pTcon = cifs_sb->tcon;
1822
1823         pagevec_init(&lru_pvec, 0);
1824                 cFYI(DBG2, ("rpages: num pages %d", num_pages));
1825         for (i = 0; i < num_pages; ) {
1826                 unsigned contig_pages;
1827                 struct page *tmp_page;
1828                 unsigned long expected_index;
1829
1830                 if (list_empty(page_list))
1831                         break;
1832
1833                 page = list_entry(page_list->prev, struct page, lru);
1834                 offset = (loff_t)page->index << PAGE_CACHE_SHIFT;
1835
1836                 /* count adjacent pages that we will read into */
1837                 contig_pages = 0;
1838                 expected_index =
1839                         list_entry(page_list->prev, struct page, lru)->index;
1840                 list_for_each_entry_reverse(tmp_page, page_list, lru) {
1841                         if (tmp_page->index == expected_index) {
1842                                 contig_pages++;
1843                                 expected_index++;
1844                         } else
1845                                 break;
1846                 }
1847                 if (contig_pages + i >  num_pages)
1848                         contig_pages = num_pages - i;
1849
1850                 /* for reads over a certain size could initiate async
1851                    read ahead */
1852
1853                 read_size = contig_pages * PAGE_CACHE_SIZE;
1854                 /* Read size needs to be in multiples of one page */
1855                 read_size = min_t(const unsigned int, read_size,
1856                                   cifs_sb->rsize & PAGE_CACHE_MASK);
1857                 cFYI(DBG2, ("rpages: read size 0x%x  contiguous pages %d",
1858                                 read_size, contig_pages));
1859                 rc = -EAGAIN;
1860                 while (rc == -EAGAIN) {
1861                         if ((open_file->invalidHandle) &&
1862                             (!open_file->closePend)) {
1863                                 rc = cifs_reopen_file(file, true);
1864                                 if (rc != 0)
1865                                         break;
1866                         }
1867
1868                         rc = CIFSSMBRead(xid, pTcon,
1869                                          open_file->netfid,
1870                                          read_size, offset,
1871                                          &bytes_read, &smb_read_data,
1872                                          &buf_type);
1873                         /* BB more RC checks ? */
1874                         if (rc == -EAGAIN) {
1875                                 if (smb_read_data) {
1876                                         if (buf_type == CIFS_SMALL_BUFFER)
1877                                                 cifs_small_buf_release(smb_read_data);
1878                                         else if (buf_type == CIFS_LARGE_BUFFER)
1879                                                 cifs_buf_release(smb_read_data);
1880                                         smb_read_data = NULL;
1881                                 }
1882                         }
1883                 }
1884                 if ((rc < 0) || (smb_read_data == NULL)) {
1885                         cFYI(1, ("Read error in readpages: %d", rc));
1886                         break;
1887                 } else if (bytes_read > 0) {
1888                         task_io_account_read(bytes_read);
1889                         pSMBr = (struct smb_com_read_rsp *)smb_read_data;
1890                         cifs_copy_cache_pages(mapping, page_list, bytes_read,
1891                                 smb_read_data + 4 /* RFC1001 hdr */ +
1892                                 le16_to_cpu(pSMBr->DataOffset), &lru_pvec);
1893
1894                         i +=  bytes_read >> PAGE_CACHE_SHIFT;
1895                         cifs_stats_bytes_read(pTcon, bytes_read);
1896                         if ((bytes_read & PAGE_CACHE_MASK) != bytes_read) {
1897                                 i++; /* account for partial page */
1898
1899                                 /* server copy of file can have smaller size
1900                                    than client */
1901                                 /* BB do we need to verify this common case ?
1902                                    this case is ok - if we are at server EOF
1903                                    we will hit it on next read */
1904
1905                                 /* break; */
1906                         }
1907                 } else {
1908                         cFYI(1, ("No bytes read (%d) at offset %lld . "
1909                                  "Cleaning remaining pages from readahead list",
1910                                  bytes_read, offset));
1911                         /* BB turn off caching and do new lookup on
1912                            file size at server? */
1913                         break;
1914                 }
1915                 if (smb_read_data) {
1916                         if (buf_type == CIFS_SMALL_BUFFER)
1917                                 cifs_small_buf_release(smb_read_data);
1918                         else if (buf_type == CIFS_LARGE_BUFFER)
1919                                 cifs_buf_release(smb_read_data);
1920                         smb_read_data = NULL;
1921                 }
1922                 bytes_read = 0;
1923         }
1924
1925         pagevec_lru_add(&lru_pvec);
1926
1927 /* need to free smb_read_data buf before exit */
1928         if (smb_read_data) {
1929                 if (buf_type == CIFS_SMALL_BUFFER)
1930                         cifs_small_buf_release(smb_read_data);
1931                 else if (buf_type == CIFS_LARGE_BUFFER)
1932                         cifs_buf_release(smb_read_data);
1933                 smb_read_data = NULL;
1934         }
1935
1936         FreeXid(xid);
1937         return rc;
1938 }
1939
1940 static int cifs_readpage_worker(struct file *file, struct page *page,
1941         loff_t *poffset)
1942 {
1943         char *read_data;
1944         int rc;
1945
1946         page_cache_get(page);
1947         read_data = kmap(page);
1948         /* for reads over a certain size could initiate async read ahead */
1949
1950         rc = cifs_read(file, read_data, PAGE_CACHE_SIZE, poffset);
1951
1952         if (rc < 0)
1953                 goto io_error;
1954         else
1955                 cFYI(1, ("Bytes read %d", rc));
1956
1957         file->f_path.dentry->d_inode->i_atime =
1958                 current_fs_time(file->f_path.dentry->d_inode->i_sb);
1959
1960         if (PAGE_CACHE_SIZE > rc)
1961                 memset(read_data + rc, 0, PAGE_CACHE_SIZE - rc);
1962
1963         flush_dcache_page(page);
1964         SetPageUptodate(page);
1965         rc = 0;
1966
1967 io_error:
1968         kunmap(page);
1969         page_cache_release(page);
1970         return rc;
1971 }
1972
1973 static int cifs_readpage(struct file *file, struct page *page)
1974 {
1975         loff_t offset = (loff_t)page->index << PAGE_CACHE_SHIFT;
1976         int rc = -EACCES;
1977         int xid;
1978
1979         xid = GetXid();
1980
1981         if (file->private_data == NULL) {
1982                 FreeXid(xid);
1983                 return -EBADF;
1984         }
1985
1986         cFYI(1, ("readpage %p at offset %d 0x%x\n",
1987                  page, (int)offset, (int)offset));
1988
1989         rc = cifs_readpage_worker(file, page, &offset);
1990
1991         unlock_page(page);
1992
1993         FreeXid(xid);
1994         return rc;
1995 }
1996
1997 static int is_inode_writable(struct cifsInodeInfo *cifs_inode)
1998 {
1999         struct cifsFileInfo *open_file;
2000
2001         read_lock(&GlobalSMBSeslock);
2002         list_for_each_entry(open_file, &cifs_inode->openFileList, flist) {
2003                 if (open_file->closePend)
2004                         continue;
2005                 if (open_file->pfile &&
2006                     ((open_file->pfile->f_flags & O_RDWR) ||
2007                      (open_file->pfile->f_flags & O_WRONLY))) {
2008                         read_unlock(&GlobalSMBSeslock);
2009                         return 1;
2010                 }
2011         }
2012         read_unlock(&GlobalSMBSeslock);
2013         return 0;
2014 }
2015
2016 /* We do not want to update the file size from server for inodes
2017    open for write - to avoid races with writepage extending
2018    the file - in the future we could consider allowing
2019    refreshing the inode only on increases in the file size
2020    but this is tricky to do without racing with writebehind
2021    page caching in the current Linux kernel design */
2022 bool is_size_safe_to_change(struct cifsInodeInfo *cifsInode, __u64 end_of_file)
2023 {
2024         if (!cifsInode)
2025                 return true;
2026
2027         if (is_inode_writable(cifsInode)) {
2028                 /* This inode is open for write at least once */
2029                 struct cifs_sb_info *cifs_sb;
2030
2031                 cifs_sb = CIFS_SB(cifsInode->vfs_inode.i_sb);
2032                 if (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_DIRECT_IO) {
2033                         /* since no page cache to corrupt on directio
2034                         we can change size safely */
2035                         return true;
2036                 }
2037
2038                 if (i_size_read(&cifsInode->vfs_inode) < end_of_file)
2039                         return true;
2040
2041                 return false;
2042         } else
2043                 return true;
2044 }
2045
2046 static int cifs_prepare_write(struct file *file, struct page *page,
2047         unsigned from, unsigned to)
2048 {
2049         int rc = 0;
2050         loff_t i_size;
2051         loff_t offset;
2052
2053         cFYI(1, ("prepare write for page %p from %d to %d", page, from, to));
2054         if (PageUptodate(page))
2055                 return 0;
2056
2057         /* If we are writing a full page it will be up to date,
2058            no need to read from the server */
2059         if ((to == PAGE_CACHE_SIZE) && (from == 0)) {
2060                 SetPageUptodate(page);
2061                 return 0;
2062         }
2063
2064         offset = (loff_t)page->index << PAGE_CACHE_SHIFT;
2065         i_size = i_size_read(page->mapping->host);
2066
2067         if ((offset >= i_size) ||
2068             ((from == 0) && (offset + to) >= i_size)) {
2069                 /*
2070                  * We don't need to read data beyond the end of the file.
2071                  * zero it, and set the page uptodate
2072                  */
2073                 simple_prepare_write(file, page, from, to);
2074                 SetPageUptodate(page);
2075         } else if ((file->f_flags & O_ACCMODE) != O_WRONLY) {
2076                 /* might as well read a page, it is fast enough */
2077                 rc = cifs_readpage_worker(file, page, &offset);
2078         } else {
2079                 /* we could try using another file handle if there is one -
2080                    but how would we lock it to prevent close of that handle
2081                    racing with this read? In any case
2082                    this will be written out by commit_write so is fine */
2083         }
2084
2085         /* we do not need to pass errors back
2086            e.g. if we do not have read access to the file
2087            because cifs_commit_write will do the right thing.  -- shaggy */
2088
2089         return 0;
2090 }
2091
2092 const struct address_space_operations cifs_addr_ops = {
2093         .readpage = cifs_readpage,
2094         .readpages = cifs_readpages,
2095         .writepage = cifs_writepage,
2096         .writepages = cifs_writepages,
2097         .prepare_write = cifs_prepare_write,
2098         .commit_write = cifs_commit_write,
2099         .set_page_dirty = __set_page_dirty_nobuffers,
2100         /* .sync_page = cifs_sync_page, */
2101         /* .direct_IO = */
2102 };
2103
2104 /*
2105  * cifs_readpages requires the server to support a buffer large enough to
2106  * contain the header plus one complete page of data.  Otherwise, we need
2107  * to leave cifs_readpages out of the address space operations.
2108  */
2109 const struct address_space_operations cifs_addr_ops_smallbuf = {
2110         .readpage = cifs_readpage,
2111         .writepage = cifs_writepage,
2112         .writepages = cifs_writepages,
2113         .prepare_write = cifs_prepare_write,
2114         .commit_write = cifs_commit_write,
2115         .set_page_dirty = __set_page_dirty_nobuffers,
2116         /* .sync_page = cifs_sync_page, */
2117         /* .direct_IO = */
2118 };