Merge branch 'stable-3.2' into pandora-3.2
[pandora-kernel.git] / fs / cifs / cifssmb.c
1 /*
2  *   fs/cifs/cifssmb.c
3  *
4  *   Copyright (C) International Business Machines  Corp., 2002,2010
5  *   Author(s): Steve French (sfrench@us.ibm.com)
6  *
7  *   Contains the routines for constructing the SMB PDUs themselves
8  *
9  *   This library is free software; you can redistribute it and/or modify
10  *   it under the terms of the GNU Lesser General Public License as published
11  *   by the Free Software Foundation; either version 2.1 of the License, or
12  *   (at your option) any later version.
13  *
14  *   This library is distributed in the hope that it will be useful,
15  *   but WITHOUT ANY WARRANTY; without even the implied warranty of
16  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See
17  *   the GNU Lesser General Public License for more details.
18  *
19  *   You should have received a copy of the GNU Lesser General Public License
20  *   along with this library; if not, write to the Free Software
21  *   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
22  */
23
24  /* SMB/CIFS PDU handling routines here - except for leftovers in connect.c   */
25  /* These are mostly routines that operate on a pathname, or on a tree id     */
26  /* (mounted volume), but there are eight handle based routines which must be */
27  /* treated slightly differently for reconnection purposes since we never     */
28  /* want to reuse a stale file handle and only the caller knows the file info */
29
30 #include <linux/fs.h>
31 #include <linux/kernel.h>
32 #include <linux/vfs.h>
33 #include <linux/slab.h>
34 #include <linux/posix_acl_xattr.h>
35 #include <linux/pagemap.h>
36 #include <linux/swap.h>
37 #include <linux/task_io_accounting_ops.h>
38 #include <asm/uaccess.h>
39 #include "cifspdu.h"
40 #include "cifsglob.h"
41 #include "cifsacl.h"
42 #include "cifsproto.h"
43 #include "cifs_unicode.h"
44 #include "cifs_debug.h"
45 #include "fscache.h"
46
47 #ifdef CONFIG_CIFS_POSIX
48 static struct {
49         int index;
50         char *name;
51 } protocols[] = {
52 #ifdef CONFIG_CIFS_WEAK_PW_HASH
53         {LANMAN_PROT, "\2LM1.2X002"},
54         {LANMAN2_PROT, "\2LANMAN2.1"},
55 #endif /* weak password hashing for legacy clients */
56         {CIFS_PROT, "\2NT LM 0.12"},
57         {POSIX_PROT, "\2POSIX 2"},
58         {BAD_PROT, "\2"}
59 };
60 #else
61 static struct {
62         int index;
63         char *name;
64 } protocols[] = {
65 #ifdef CONFIG_CIFS_WEAK_PW_HASH
66         {LANMAN_PROT, "\2LM1.2X002"},
67         {LANMAN2_PROT, "\2LANMAN2.1"},
68 #endif /* weak password hashing for legacy clients */
69         {CIFS_PROT, "\2NT LM 0.12"},
70         {BAD_PROT, "\2"}
71 };
72 #endif
73
74 /* define the number of elements in the cifs dialect array */
75 #ifdef CONFIG_CIFS_POSIX
76 #ifdef CONFIG_CIFS_WEAK_PW_HASH
77 #define CIFS_NUM_PROT 4
78 #else
79 #define CIFS_NUM_PROT 2
80 #endif /* CIFS_WEAK_PW_HASH */
81 #else /* not posix */
82 #ifdef CONFIG_CIFS_WEAK_PW_HASH
83 #define CIFS_NUM_PROT 3
84 #else
85 #define CIFS_NUM_PROT 1
86 #endif /* CONFIG_CIFS_WEAK_PW_HASH */
87 #endif /* CIFS_POSIX */
88
89 /* Forward declarations */
90 static void cifs_readv_complete(struct work_struct *work);
91
92 #ifdef CONFIG_HIGHMEM
93 /*
94  * On arches that have high memory, kmap address space is limited. By
95  * serializing the kmap operations on those arches, we ensure that we don't
96  * end up with a bunch of threads in writeback with partially mapped page
97  * arrays, stuck waiting for kmap to come back. That situation prevents
98  * progress and can deadlock.
99  */
100 static DEFINE_MUTEX(cifs_kmap_mutex);
101
102 static inline void
103 cifs_kmap_lock(void)
104 {
105         mutex_lock(&cifs_kmap_mutex);
106 }
107
108 static inline void
109 cifs_kmap_unlock(void)
110 {
111         mutex_unlock(&cifs_kmap_mutex);
112 }
113 #else /* !CONFIG_HIGHMEM */
114 #define cifs_kmap_lock() do { ; } while(0)
115 #define cifs_kmap_unlock() do { ; } while(0)
116 #endif /* CONFIG_HIGHMEM */
117
118 /* Mark as invalid, all open files on tree connections since they
119    were closed when session to server was lost */
120 static void mark_open_files_invalid(struct cifs_tcon *pTcon)
121 {
122         struct cifsFileInfo *open_file = NULL;
123         struct list_head *tmp;
124         struct list_head *tmp1;
125
126 /* list all files open on tree connection and mark them invalid */
127         spin_lock(&cifs_file_list_lock);
128         list_for_each_safe(tmp, tmp1, &pTcon->openFileList) {
129                 open_file = list_entry(tmp, struct cifsFileInfo, tlist);
130                 open_file->invalidHandle = true;
131                 open_file->oplock_break_cancelled = true;
132         }
133         spin_unlock(&cifs_file_list_lock);
134         /* BB Add call to invalidate_inodes(sb) for all superblocks mounted
135            to this tcon */
136 }
137
138 /* reconnect the socket, tcon, and smb session if needed */
139 static int
140 cifs_reconnect_tcon(struct cifs_tcon *tcon, int smb_command)
141 {
142         int rc;
143         struct cifs_ses *ses;
144         struct TCP_Server_Info *server;
145         struct nls_table *nls_codepage;
146
147         /*
148          * SMBs NegProt, SessSetup, uLogoff do not have tcon yet so check for
149          * tcp and smb session status done differently for those three - in the
150          * calling routine
151          */
152         if (!tcon)
153                 return 0;
154
155         ses = tcon->ses;
156         server = ses->server;
157
158         /*
159          * only tree disconnect, open, and write, (and ulogoff which does not
160          * have tcon) are allowed as we start force umount
161          */
162         if (tcon->tidStatus == CifsExiting) {
163                 if (smb_command != SMB_COM_WRITE_ANDX &&
164                     smb_command != SMB_COM_OPEN_ANDX &&
165                     smb_command != SMB_COM_TREE_DISCONNECT) {
166                         cFYI(1, "can not send cmd %d while umounting",
167                                 smb_command);
168                         return -ENODEV;
169                 }
170         }
171
172         /*
173          * Give demultiplex thread up to 10 seconds to reconnect, should be
174          * greater than cifs socket timeout which is 7 seconds
175          */
176         while (server->tcpStatus == CifsNeedReconnect) {
177                 wait_event_interruptible_timeout(server->response_q,
178                         (server->tcpStatus != CifsNeedReconnect), 10 * HZ);
179
180                 /* are we still trying to reconnect? */
181                 if (server->tcpStatus != CifsNeedReconnect)
182                         break;
183
184                 /*
185                  * on "soft" mounts we wait once. Hard mounts keep
186                  * retrying until process is killed or server comes
187                  * back on-line
188                  */
189                 if (!tcon->retry) {
190                         cFYI(1, "gave up waiting on reconnect in smb_init");
191                         return -EHOSTDOWN;
192                 }
193         }
194
195         if (!ses->need_reconnect && !tcon->need_reconnect)
196                 return 0;
197
198         nls_codepage = load_nls_default();
199
200         /*
201          * need to prevent multiple threads trying to simultaneously
202          * reconnect the same SMB session
203          */
204         mutex_lock(&ses->session_mutex);
205         rc = cifs_negotiate_protocol(0, ses);
206         if (rc == 0 && ses->need_reconnect)
207                 rc = cifs_setup_session(0, ses, nls_codepage);
208
209         /* do we need to reconnect tcon? */
210         if (rc || !tcon->need_reconnect) {
211                 mutex_unlock(&ses->session_mutex);
212                 goto out;
213         }
214
215         mark_open_files_invalid(tcon);
216         rc = CIFSTCon(0, ses, tcon->treeName, tcon, nls_codepage);
217         mutex_unlock(&ses->session_mutex);
218         cFYI(1, "reconnect tcon rc = %d", rc);
219
220         if (rc)
221                 goto out;
222
223         /*
224          * FIXME: check if wsize needs updated due to negotiated smb buffer
225          *        size shrinking
226          */
227         atomic_inc(&tconInfoReconnectCount);
228
229         /* tell server Unix caps we support */
230         if (ses->capabilities & CAP_UNIX)
231                 reset_cifs_unix_caps(0, tcon, NULL, NULL);
232
233         /*
234          * Removed call to reopen open files here. It is safer (and faster) to
235          * reopen files one at a time as needed in read and write.
236          *
237          * FIXME: what about file locks? don't we need to reclaim them ASAP?
238          */
239
240 out:
241         /*
242          * Check if handle based operation so we know whether we can continue
243          * or not without returning to caller to reset file handle
244          */
245         switch (smb_command) {
246         case SMB_COM_READ_ANDX:
247         case SMB_COM_WRITE_ANDX:
248         case SMB_COM_CLOSE:
249         case SMB_COM_FIND_CLOSE2:
250         case SMB_COM_LOCKING_ANDX:
251                 rc = -EAGAIN;
252         }
253
254         unload_nls(nls_codepage);
255         return rc;
256 }
257
258 /* Allocate and return pointer to an SMB request buffer, and set basic
259    SMB information in the SMB header.  If the return code is zero, this
260    function must have filled in request_buf pointer */
261 static int
262 small_smb_init(int smb_command, int wct, struct cifs_tcon *tcon,
263                 void **request_buf)
264 {
265         int rc;
266
267         rc = cifs_reconnect_tcon(tcon, smb_command);
268         if (rc)
269                 return rc;
270
271         *request_buf = cifs_small_buf_get();
272         if (*request_buf == NULL) {
273                 /* BB should we add a retry in here if not a writepage? */
274                 return -ENOMEM;
275         }
276
277         header_assemble((struct smb_hdr *) *request_buf, smb_command,
278                         tcon, wct);
279
280         if (tcon != NULL)
281                 cifs_stats_inc(&tcon->num_smbs_sent);
282
283         return 0;
284 }
285
286 int
287 small_smb_init_no_tc(const int smb_command, const int wct,
288                      struct cifs_ses *ses, void **request_buf)
289 {
290         int rc;
291         struct smb_hdr *buffer;
292
293         rc = small_smb_init(smb_command, wct, NULL, request_buf);
294         if (rc)
295                 return rc;
296
297         buffer = (struct smb_hdr *)*request_buf;
298         buffer->Mid = GetNextMid(ses->server);
299         if (ses->capabilities & CAP_UNICODE)
300                 buffer->Flags2 |= SMBFLG2_UNICODE;
301         if (ses->capabilities & CAP_STATUS32)
302                 buffer->Flags2 |= SMBFLG2_ERR_STATUS;
303
304         /* uid, tid can stay at zero as set in header assemble */
305
306         /* BB add support for turning on the signing when
307         this function is used after 1st of session setup requests */
308
309         return rc;
310 }
311
312 /* If the return code is zero, this function must fill in request_buf pointer */
313 static int
314 __smb_init(int smb_command, int wct, struct cifs_tcon *tcon,
315                         void **request_buf, void **response_buf)
316 {
317         *request_buf = cifs_buf_get();
318         if (*request_buf == NULL) {
319                 /* BB should we add a retry in here if not a writepage? */
320                 return -ENOMEM;
321         }
322     /* Although the original thought was we needed the response buf for  */
323     /* potential retries of smb operations it turns out we can determine */
324     /* from the mid flags when the request buffer can be resent without  */
325     /* having to use a second distinct buffer for the response */
326         if (response_buf)
327                 *response_buf = *request_buf;
328
329         header_assemble((struct smb_hdr *) *request_buf, smb_command, tcon,
330                         wct);
331
332         if (tcon != NULL)
333                 cifs_stats_inc(&tcon->num_smbs_sent);
334
335         return 0;
336 }
337
338 /* If the return code is zero, this function must fill in request_buf pointer */
339 static int
340 smb_init(int smb_command, int wct, struct cifs_tcon *tcon,
341          void **request_buf, void **response_buf)
342 {
343         int rc;
344
345         rc = cifs_reconnect_tcon(tcon, smb_command);
346         if (rc)
347                 return rc;
348
349         return __smb_init(smb_command, wct, tcon, request_buf, response_buf);
350 }
351
352 static int
353 smb_init_no_reconnect(int smb_command, int wct, struct cifs_tcon *tcon,
354                         void **request_buf, void **response_buf)
355 {
356         if (tcon->ses->need_reconnect || tcon->need_reconnect)
357                 return -EHOSTDOWN;
358
359         return __smb_init(smb_command, wct, tcon, request_buf, response_buf);
360 }
361
362 static int validate_t2(struct smb_t2_rsp *pSMB)
363 {
364         unsigned int total_size;
365
366         /* check for plausible wct */
367         if (pSMB->hdr.WordCount < 10)
368                 goto vt2_err;
369
370         /* check for parm and data offset going beyond end of smb */
371         if (get_unaligned_le16(&pSMB->t2_rsp.ParameterOffset) > 1024 ||
372             get_unaligned_le16(&pSMB->t2_rsp.DataOffset) > 1024)
373                 goto vt2_err;
374
375         total_size = get_unaligned_le16(&pSMB->t2_rsp.ParameterCount);
376         if (total_size >= 512)
377                 goto vt2_err;
378
379         /* check that bcc is at least as big as parms + data, and that it is
380          * less than negotiated smb buffer
381          */
382         total_size += get_unaligned_le16(&pSMB->t2_rsp.DataCount);
383         if (total_size > get_bcc(&pSMB->hdr) ||
384             total_size >= CIFSMaxBufSize + MAX_CIFS_HDR_SIZE)
385                 goto vt2_err;
386
387         return 0;
388 vt2_err:
389         cifs_dump_mem("Invalid transact2 SMB: ", (char *)pSMB,
390                 sizeof(struct smb_t2_rsp) + 16);
391         return -EINVAL;
392 }
393
394 static inline void inc_rfc1001_len(void *pSMB, int count)
395 {
396         struct smb_hdr *hdr = (struct smb_hdr *)pSMB;
397
398         be32_add_cpu(&hdr->smb_buf_length, count);
399 }
400
401 int
402 CIFSSMBNegotiate(unsigned int xid, struct cifs_ses *ses)
403 {
404         NEGOTIATE_REQ *pSMB;
405         NEGOTIATE_RSP *pSMBr;
406         int rc = 0;
407         int bytes_returned;
408         int i;
409         struct TCP_Server_Info *server;
410         u16 count;
411         unsigned int secFlags;
412
413         if (ses->server)
414                 server = ses->server;
415         else {
416                 rc = -EIO;
417                 return rc;
418         }
419         rc = smb_init(SMB_COM_NEGOTIATE, 0, NULL /* no tcon yet */ ,
420                       (void **) &pSMB, (void **) &pSMBr);
421         if (rc)
422                 return rc;
423
424         /* if any of auth flags (ie not sign or seal) are overriden use them */
425         if (ses->overrideSecFlg & (~(CIFSSEC_MUST_SIGN | CIFSSEC_MUST_SEAL)))
426                 secFlags = ses->overrideSecFlg;  /* BB FIXME fix sign flags? */
427         else /* if override flags set only sign/seal OR them with global auth */
428                 secFlags = global_secflags | ses->overrideSecFlg;
429
430         cFYI(1, "secFlags 0x%x", secFlags);
431
432         pSMB->hdr.Mid = GetNextMid(server);
433         pSMB->hdr.Flags2 |= (SMBFLG2_UNICODE | SMBFLG2_ERR_STATUS);
434
435         if ((secFlags & CIFSSEC_MUST_KRB5) == CIFSSEC_MUST_KRB5)
436                 pSMB->hdr.Flags2 |= SMBFLG2_EXT_SEC;
437         else if ((secFlags & CIFSSEC_AUTH_MASK) == CIFSSEC_MAY_KRB5) {
438                 cFYI(1, "Kerberos only mechanism, enable extended security");
439                 pSMB->hdr.Flags2 |= SMBFLG2_EXT_SEC;
440         } else if ((secFlags & CIFSSEC_MUST_NTLMSSP) == CIFSSEC_MUST_NTLMSSP)
441                 pSMB->hdr.Flags2 |= SMBFLG2_EXT_SEC;
442         else if ((secFlags & CIFSSEC_AUTH_MASK) == CIFSSEC_MAY_NTLMSSP) {
443                 cFYI(1, "NTLMSSP only mechanism, enable extended security");
444                 pSMB->hdr.Flags2 |= SMBFLG2_EXT_SEC;
445         }
446
447         count = 0;
448         for (i = 0; i < CIFS_NUM_PROT; i++) {
449                 strncpy(pSMB->DialectsArray+count, protocols[i].name, 16);
450                 count += strlen(protocols[i].name) + 1;
451                 /* null at end of source and target buffers anyway */
452         }
453         inc_rfc1001_len(pSMB, count);
454         pSMB->ByteCount = cpu_to_le16(count);
455
456         rc = SendReceive(xid, ses, (struct smb_hdr *) pSMB,
457                          (struct smb_hdr *) pSMBr, &bytes_returned, 0);
458         if (rc != 0)
459                 goto neg_err_exit;
460
461         server->dialect = le16_to_cpu(pSMBr->DialectIndex);
462         cFYI(1, "Dialect: %d", server->dialect);
463         /* Check wct = 1 error case */
464         if ((pSMBr->hdr.WordCount < 13) || (server->dialect == BAD_PROT)) {
465                 /* core returns wct = 1, but we do not ask for core - otherwise
466                 small wct just comes when dialect index is -1 indicating we
467                 could not negotiate a common dialect */
468                 rc = -EOPNOTSUPP;
469                 goto neg_err_exit;
470 #ifdef CONFIG_CIFS_WEAK_PW_HASH
471         } else if ((pSMBr->hdr.WordCount == 13)
472                         && ((server->dialect == LANMAN_PROT)
473                                 || (server->dialect == LANMAN2_PROT))) {
474                 __s16 tmp;
475                 struct lanman_neg_rsp *rsp = (struct lanman_neg_rsp *)pSMBr;
476
477                 if ((secFlags & CIFSSEC_MAY_LANMAN) ||
478                         (secFlags & CIFSSEC_MAY_PLNTXT))
479                         server->secType = LANMAN;
480                 else {
481                         cERROR(1, "mount failed weak security disabled"
482                                    " in /proc/fs/cifs/SecurityFlags");
483                         rc = -EOPNOTSUPP;
484                         goto neg_err_exit;
485                 }
486                 server->sec_mode = (__u8)le16_to_cpu(rsp->SecurityMode);
487                 server->maxReq = min_t(unsigned int,
488                                        le16_to_cpu(rsp->MaxMpxCount),
489                                        cifs_max_pending);
490                 server->oplocks = server->maxReq > 1 ? enable_oplocks : false;
491                 server->maxBuf = le16_to_cpu(rsp->MaxBufSize);
492                 server->max_vcs = le16_to_cpu(rsp->MaxNumberVcs);
493                 /* even though we do not use raw we might as well set this
494                 accurately, in case we ever find a need for it */
495                 if ((le16_to_cpu(rsp->RawMode) & RAW_ENABLE) == RAW_ENABLE) {
496                         server->max_rw = 0xFF00;
497                         server->capabilities = CAP_MPX_MODE | CAP_RAW_MODE;
498                 } else {
499                         server->max_rw = 0;/* do not need to use raw anyway */
500                         server->capabilities = CAP_MPX_MODE;
501                 }
502                 tmp = (__s16)le16_to_cpu(rsp->ServerTimeZone);
503                 if (tmp == -1) {
504                         /* OS/2 often does not set timezone therefore
505                          * we must use server time to calc time zone.
506                          * Could deviate slightly from the right zone.
507                          * Smallest defined timezone difference is 15 minutes
508                          * (i.e. Nepal).  Rounding up/down is done to match
509                          * this requirement.
510                          */
511                         int val, seconds, remain, result;
512                         struct timespec ts, utc;
513                         utc = CURRENT_TIME;
514                         ts = cnvrtDosUnixTm(rsp->SrvTime.Date,
515                                             rsp->SrvTime.Time, 0);
516                         cFYI(1, "SrvTime %d sec since 1970 (utc: %d) diff: %d",
517                                 (int)ts.tv_sec, (int)utc.tv_sec,
518                                 (int)(utc.tv_sec - ts.tv_sec));
519                         val = (int)(utc.tv_sec - ts.tv_sec);
520                         seconds = abs(val);
521                         result = (seconds / MIN_TZ_ADJ) * MIN_TZ_ADJ;
522                         remain = seconds % MIN_TZ_ADJ;
523                         if (remain >= (MIN_TZ_ADJ / 2))
524                                 result += MIN_TZ_ADJ;
525                         if (val < 0)
526                                 result = -result;
527                         server->timeAdj = result;
528                 } else {
529                         server->timeAdj = (int)tmp;
530                         server->timeAdj *= 60; /* also in seconds */
531                 }
532                 cFYI(1, "server->timeAdj: %d seconds", server->timeAdj);
533
534
535                 /* BB get server time for time conversions and add
536                 code to use it and timezone since this is not UTC */
537
538                 if (rsp->EncryptionKeyLength ==
539                                 cpu_to_le16(CIFS_CRYPTO_KEY_SIZE)) {
540                         memcpy(ses->server->cryptkey, rsp->EncryptionKey,
541                                 CIFS_CRYPTO_KEY_SIZE);
542                 } else if (server->sec_mode & SECMODE_PW_ENCRYPT) {
543                         rc = -EIO; /* need cryptkey unless plain text */
544                         goto neg_err_exit;
545                 }
546
547                 cFYI(1, "LANMAN negotiated");
548                 /* we will not end up setting signing flags - as no signing
549                 was in LANMAN and server did not return the flags on */
550                 goto signing_check;
551 #else /* weak security disabled */
552         } else if (pSMBr->hdr.WordCount == 13) {
553                 cERROR(1, "mount failed, cifs module not built "
554                           "with CIFS_WEAK_PW_HASH support");
555                 rc = -EOPNOTSUPP;
556 #endif /* WEAK_PW_HASH */
557                 goto neg_err_exit;
558         } else if (pSMBr->hdr.WordCount != 17) {
559                 /* unknown wct */
560                 rc = -EOPNOTSUPP;
561                 goto neg_err_exit;
562         }
563         /* else wct == 17 NTLM */
564         server->sec_mode = pSMBr->SecurityMode;
565         if ((server->sec_mode & SECMODE_USER) == 0)
566                 cFYI(1, "share mode security");
567
568         if ((server->sec_mode & SECMODE_PW_ENCRYPT) == 0)
569 #ifdef CONFIG_CIFS_WEAK_PW_HASH
570                 if ((secFlags & CIFSSEC_MAY_PLNTXT) == 0)
571 #endif /* CIFS_WEAK_PW_HASH */
572                         cERROR(1, "Server requests plain text password"
573                                   " but client support disabled");
574
575         if ((secFlags & CIFSSEC_MUST_NTLMV2) == CIFSSEC_MUST_NTLMV2)
576                 server->secType = NTLMv2;
577         else if (secFlags & CIFSSEC_MAY_NTLM)
578                 server->secType = NTLM;
579         else if (secFlags & CIFSSEC_MAY_NTLMV2)
580                 server->secType = NTLMv2;
581         else if (secFlags & CIFSSEC_MAY_KRB5)
582                 server->secType = Kerberos;
583         else if (secFlags & CIFSSEC_MAY_NTLMSSP)
584                 server->secType = RawNTLMSSP;
585         else if (secFlags & CIFSSEC_MAY_LANMAN)
586                 server->secType = LANMAN;
587         else {
588                 rc = -EOPNOTSUPP;
589                 cERROR(1, "Invalid security type");
590                 goto neg_err_exit;
591         }
592         /* else ... any others ...? */
593
594         /* one byte, so no need to convert this or EncryptionKeyLen from
595            little endian */
596         server->maxReq = min_t(unsigned int, le16_to_cpu(pSMBr->MaxMpxCount),
597                                cifs_max_pending);
598         server->oplocks = server->maxReq > 1 ? enable_oplocks : false;
599         /* probably no need to store and check maxvcs */
600         server->maxBuf = le32_to_cpu(pSMBr->MaxBufferSize);
601         server->max_rw = le32_to_cpu(pSMBr->MaxRawSize);
602         cFYI(DBG2, "Max buf = %d", ses->server->maxBuf);
603         server->capabilities = le32_to_cpu(pSMBr->Capabilities);
604         server->timeAdj = (int)(__s16)le16_to_cpu(pSMBr->ServerTimeZone);
605         server->timeAdj *= 60;
606         if (pSMBr->EncryptionKeyLength == CIFS_CRYPTO_KEY_SIZE) {
607                 memcpy(ses->server->cryptkey, pSMBr->u.EncryptionKey,
608                        CIFS_CRYPTO_KEY_SIZE);
609         } else if ((pSMBr->hdr.Flags2 & SMBFLG2_EXT_SEC ||
610                         server->capabilities & CAP_EXTENDED_SECURITY) &&
611                                 (pSMBr->EncryptionKeyLength == 0)) {
612                 /* decode security blob */
613                 count = get_bcc(&pSMBr->hdr);
614                 if (count < 16) {
615                         rc = -EIO;
616                         goto neg_err_exit;
617                 }
618                 spin_lock(&cifs_tcp_ses_lock);
619                 if (server->srv_count > 1) {
620                         spin_unlock(&cifs_tcp_ses_lock);
621                         if (memcmp(server->server_GUID,
622                                    pSMBr->u.extended_response.
623                                    GUID, 16) != 0) {
624                                 cFYI(1, "server UID changed");
625                                 memcpy(server->server_GUID,
626                                         pSMBr->u.extended_response.GUID,
627                                         16);
628                         }
629                 } else {
630                         spin_unlock(&cifs_tcp_ses_lock);
631                         memcpy(server->server_GUID,
632                                pSMBr->u.extended_response.GUID, 16);
633                 }
634
635                 if (count == 16) {
636                         server->secType = RawNTLMSSP;
637                 } else {
638                         rc = decode_negTokenInit(pSMBr->u.extended_response.
639                                                  SecurityBlob, count - 16,
640                                                  server);
641                         if (rc == 1)
642                                 rc = 0;
643                         else
644                                 rc = -EINVAL;
645                         if (server->secType == Kerberos) {
646                                 if (!server->sec_kerberos &&
647                                                 !server->sec_mskerberos)
648                                         rc = -EOPNOTSUPP;
649                         } else if (server->secType == RawNTLMSSP) {
650                                 if (!server->sec_ntlmssp)
651                                         rc = -EOPNOTSUPP;
652                         } else
653                                         rc = -EOPNOTSUPP;
654                 }
655         } else if (server->sec_mode & SECMODE_PW_ENCRYPT) {
656                 rc = -EIO; /* no crypt key only if plain text pwd */
657                 goto neg_err_exit;
658         } else
659                 server->capabilities &= ~CAP_EXTENDED_SECURITY;
660
661 #ifdef CONFIG_CIFS_WEAK_PW_HASH
662 signing_check:
663 #endif
664         if ((secFlags & CIFSSEC_MAY_SIGN) == 0) {
665                 /* MUST_SIGN already includes the MAY_SIGN FLAG
666                    so if this is zero it means that signing is disabled */
667                 cFYI(1, "Signing disabled");
668                 if (server->sec_mode & SECMODE_SIGN_REQUIRED) {
669                         cERROR(1, "Server requires "
670                                    "packet signing to be enabled in "
671                                    "/proc/fs/cifs/SecurityFlags.");
672                         rc = -EOPNOTSUPP;
673                 }
674                 server->sec_mode &=
675                         ~(SECMODE_SIGN_ENABLED | SECMODE_SIGN_REQUIRED);
676         } else if ((secFlags & CIFSSEC_MUST_SIGN) == CIFSSEC_MUST_SIGN) {
677                 /* signing required */
678                 cFYI(1, "Must sign - secFlags 0x%x", secFlags);
679                 if ((server->sec_mode &
680                         (SECMODE_SIGN_ENABLED | SECMODE_SIGN_REQUIRED)) == 0) {
681                         cERROR(1, "signing required but server lacks support");
682                         rc = -EOPNOTSUPP;
683                 } else
684                         server->sec_mode |= SECMODE_SIGN_REQUIRED;
685         } else {
686                 /* signing optional ie CIFSSEC_MAY_SIGN */
687                 if ((server->sec_mode & SECMODE_SIGN_REQUIRED) == 0)
688                         server->sec_mode &=
689                                 ~(SECMODE_SIGN_ENABLED | SECMODE_SIGN_REQUIRED);
690         }
691
692 neg_err_exit:
693         cifs_buf_release(pSMB);
694
695         cFYI(1, "negprot rc %d", rc);
696         return rc;
697 }
698
699 int
700 CIFSSMBTDis(const int xid, struct cifs_tcon *tcon)
701 {
702         struct smb_hdr *smb_buffer;
703         int rc = 0;
704
705         cFYI(1, "In tree disconnect");
706
707         /* BB: do we need to check this? These should never be NULL. */
708         if ((tcon->ses == NULL) || (tcon->ses->server == NULL))
709                 return -EIO;
710
711         /*
712          * No need to return error on this operation if tid invalidated and
713          * closed on server already e.g. due to tcp session crashing. Also,
714          * the tcon is no longer on the list, so no need to take lock before
715          * checking this.
716          */
717         if ((tcon->need_reconnect) || (tcon->ses->need_reconnect))
718                 return 0;
719
720         rc = small_smb_init(SMB_COM_TREE_DISCONNECT, 0, tcon,
721                             (void **)&smb_buffer);
722         if (rc)
723                 return rc;
724
725         rc = SendReceiveNoRsp(xid, tcon->ses, smb_buffer, 0);
726         if (rc)
727                 cFYI(1, "Tree disconnect failed %d", rc);
728
729         /* No need to return error on this operation if tid invalidated and
730            closed on server already e.g. due to tcp session crashing */
731         if (rc == -EAGAIN)
732                 rc = 0;
733
734         return rc;
735 }
736
737 /*
738  * This is a no-op for now. We're not really interested in the reply, but
739  * rather in the fact that the server sent one and that server->lstrp
740  * gets updated.
741  *
742  * FIXME: maybe we should consider checking that the reply matches request?
743  */
744 static void
745 cifs_echo_callback(struct mid_q_entry *mid)
746 {
747         struct TCP_Server_Info *server = mid->callback_data;
748
749         DeleteMidQEntry(mid);
750         atomic_dec(&server->inFlight);
751         wake_up(&server->request_q);
752 }
753
754 int
755 CIFSSMBEcho(struct TCP_Server_Info *server)
756 {
757         ECHO_REQ *smb;
758         int rc = 0;
759         struct kvec iov;
760
761         cFYI(1, "In echo request");
762
763         rc = small_smb_init(SMB_COM_ECHO, 0, NULL, (void **)&smb);
764         if (rc)
765                 return rc;
766
767         if (server->capabilities & CAP_UNICODE)
768                 smb->hdr.Flags2 |= SMBFLG2_UNICODE;
769
770         /* set up echo request */
771         smb->hdr.Tid = 0xffff;
772         smb->hdr.WordCount = 1;
773         put_unaligned_le16(1, &smb->EchoCount);
774         put_bcc(1, &smb->hdr);
775         smb->Data[0] = 'a';
776         inc_rfc1001_len(smb, 3);
777         iov.iov_base = smb;
778         iov.iov_len = be32_to_cpu(smb->hdr.smb_buf_length) + 4;
779
780         rc = cifs_call_async(server, &iov, 1, NULL, cifs_echo_callback,
781                              server, true);
782         if (rc)
783                 cFYI(1, "Echo request failed: %d", rc);
784
785         cifs_small_buf_release(smb);
786
787         return rc;
788 }
789
790 int
791 CIFSSMBLogoff(const int xid, struct cifs_ses *ses)
792 {
793         LOGOFF_ANDX_REQ *pSMB;
794         int rc = 0;
795
796         cFYI(1, "In SMBLogoff for session disconnect");
797
798         /*
799          * BB: do we need to check validity of ses and server? They should
800          * always be valid since we have an active reference. If not, that
801          * should probably be a BUG()
802          */
803         if (!ses || !ses->server)
804                 return -EIO;
805
806         mutex_lock(&ses->session_mutex);
807         if (ses->need_reconnect)
808                 goto session_already_dead; /* no need to send SMBlogoff if uid
809                                               already closed due to reconnect */
810         rc = small_smb_init(SMB_COM_LOGOFF_ANDX, 2, NULL, (void **)&pSMB);
811         if (rc) {
812                 mutex_unlock(&ses->session_mutex);
813                 return rc;
814         }
815
816         pSMB->hdr.Mid = GetNextMid(ses->server);
817
818         if (ses->server->sec_mode &
819                    (SECMODE_SIGN_REQUIRED | SECMODE_SIGN_ENABLED))
820                         pSMB->hdr.Flags2 |= SMBFLG2_SECURITY_SIGNATURE;
821
822         pSMB->hdr.Uid = ses->Suid;
823
824         pSMB->AndXCommand = 0xFF;
825         rc = SendReceiveNoRsp(xid, ses, (struct smb_hdr *) pSMB, 0);
826 session_already_dead:
827         mutex_unlock(&ses->session_mutex);
828
829         /* if session dead then we do not need to do ulogoff,
830                 since server closed smb session, no sense reporting
831                 error */
832         if (rc == -EAGAIN)
833                 rc = 0;
834         return rc;
835 }
836
837 int
838 CIFSPOSIXDelFile(const int xid, struct cifs_tcon *tcon, const char *fileName,
839                  __u16 type, const struct nls_table *nls_codepage, int remap)
840 {
841         TRANSACTION2_SPI_REQ *pSMB = NULL;
842         TRANSACTION2_SPI_RSP *pSMBr = NULL;
843         struct unlink_psx_rq *pRqD;
844         int name_len;
845         int rc = 0;
846         int bytes_returned = 0;
847         __u16 params, param_offset, offset, byte_count;
848
849         cFYI(1, "In POSIX delete");
850 PsxDelete:
851         rc = smb_init(SMB_COM_TRANSACTION2, 15, tcon, (void **) &pSMB,
852                       (void **) &pSMBr);
853         if (rc)
854                 return rc;
855
856         if (pSMB->hdr.Flags2 & SMBFLG2_UNICODE) {
857                 name_len =
858                     cifsConvertToUCS((__le16 *) pSMB->FileName, fileName,
859                                      PATH_MAX, nls_codepage, remap);
860                 name_len++;     /* trailing null */
861                 name_len *= 2;
862         } else { /* BB add path length overrun check */
863                 name_len = strnlen(fileName, PATH_MAX);
864                 name_len++;     /* trailing null */
865                 strncpy(pSMB->FileName, fileName, name_len);
866         }
867
868         params = 6 + name_len;
869         pSMB->MaxParameterCount = cpu_to_le16(2);
870         pSMB->MaxDataCount = 0; /* BB double check this with jra */
871         pSMB->MaxSetupCount = 0;
872         pSMB->Reserved = 0;
873         pSMB->Flags = 0;
874         pSMB->Timeout = 0;
875         pSMB->Reserved2 = 0;
876         param_offset = offsetof(struct smb_com_transaction2_spi_req,
877                                 InformationLevel) - 4;
878         offset = param_offset + params;
879
880         /* Setup pointer to Request Data (inode type) */
881         pRqD = (struct unlink_psx_rq *)(((char *)&pSMB->hdr.Protocol) + offset);
882         pRqD->type = cpu_to_le16(type);
883         pSMB->ParameterOffset = cpu_to_le16(param_offset);
884         pSMB->DataOffset = cpu_to_le16(offset);
885         pSMB->SetupCount = 1;
886         pSMB->Reserved3 = 0;
887         pSMB->SubCommand = cpu_to_le16(TRANS2_SET_PATH_INFORMATION);
888         byte_count = 3 /* pad */  + params + sizeof(struct unlink_psx_rq);
889
890         pSMB->DataCount = cpu_to_le16(sizeof(struct unlink_psx_rq));
891         pSMB->TotalDataCount = cpu_to_le16(sizeof(struct unlink_psx_rq));
892         pSMB->ParameterCount = cpu_to_le16(params);
893         pSMB->TotalParameterCount = pSMB->ParameterCount;
894         pSMB->InformationLevel = cpu_to_le16(SMB_POSIX_UNLINK);
895         pSMB->Reserved4 = 0;
896         inc_rfc1001_len(pSMB, byte_count);
897         pSMB->ByteCount = cpu_to_le16(byte_count);
898         rc = SendReceive(xid, tcon->ses, (struct smb_hdr *) pSMB,
899                          (struct smb_hdr *) pSMBr, &bytes_returned, 0);
900         if (rc)
901                 cFYI(1, "Posix delete returned %d", rc);
902         cifs_buf_release(pSMB);
903
904         cifs_stats_inc(&tcon->num_deletes);
905
906         if (rc == -EAGAIN)
907                 goto PsxDelete;
908
909         return rc;
910 }
911
912 int
913 CIFSSMBDelFile(const int xid, struct cifs_tcon *tcon, const char *fileName,
914                const struct nls_table *nls_codepage, int remap)
915 {
916         DELETE_FILE_REQ *pSMB = NULL;
917         DELETE_FILE_RSP *pSMBr = NULL;
918         int rc = 0;
919         int bytes_returned;
920         int name_len;
921
922 DelFileRetry:
923         rc = smb_init(SMB_COM_DELETE, 1, tcon, (void **) &pSMB,
924                       (void **) &pSMBr);
925         if (rc)
926                 return rc;
927
928         if (pSMB->hdr.Flags2 & SMBFLG2_UNICODE) {
929                 name_len =
930                     cifsConvertToUCS((__le16 *) pSMB->fileName, fileName,
931                                      PATH_MAX, nls_codepage, remap);
932                 name_len++;     /* trailing null */
933                 name_len *= 2;
934         } else {                /* BB improve check for buffer overruns BB */
935                 name_len = strnlen(fileName, PATH_MAX);
936                 name_len++;     /* trailing null */
937                 strncpy(pSMB->fileName, fileName, name_len);
938         }
939         pSMB->SearchAttributes =
940             cpu_to_le16(ATTR_READONLY | ATTR_HIDDEN | ATTR_SYSTEM);
941         pSMB->BufferFormat = 0x04;
942         inc_rfc1001_len(pSMB, name_len + 1);
943         pSMB->ByteCount = cpu_to_le16(name_len + 1);
944         rc = SendReceive(xid, tcon->ses, (struct smb_hdr *) pSMB,
945                          (struct smb_hdr *) pSMBr, &bytes_returned, 0);
946         cifs_stats_inc(&tcon->num_deletes);
947         if (rc)
948                 cFYI(1, "Error in RMFile = %d", rc);
949
950         cifs_buf_release(pSMB);
951         if (rc == -EAGAIN)
952                 goto DelFileRetry;
953
954         return rc;
955 }
956
957 int
958 CIFSSMBRmDir(const int xid, struct cifs_tcon *tcon, const char *dirName,
959              const struct nls_table *nls_codepage, int remap)
960 {
961         DELETE_DIRECTORY_REQ *pSMB = NULL;
962         DELETE_DIRECTORY_RSP *pSMBr = NULL;
963         int rc = 0;
964         int bytes_returned;
965         int name_len;
966
967         cFYI(1, "In CIFSSMBRmDir");
968 RmDirRetry:
969         rc = smb_init(SMB_COM_DELETE_DIRECTORY, 0, tcon, (void **) &pSMB,
970                       (void **) &pSMBr);
971         if (rc)
972                 return rc;
973
974         if (pSMB->hdr.Flags2 & SMBFLG2_UNICODE) {
975                 name_len = cifsConvertToUCS((__le16 *) pSMB->DirName, dirName,
976                                          PATH_MAX, nls_codepage, remap);
977                 name_len++;     /* trailing null */
978                 name_len *= 2;
979         } else {                /* BB improve check for buffer overruns BB */
980                 name_len = strnlen(dirName, PATH_MAX);
981                 name_len++;     /* trailing null */
982                 strncpy(pSMB->DirName, dirName, name_len);
983         }
984
985         pSMB->BufferFormat = 0x04;
986         inc_rfc1001_len(pSMB, name_len + 1);
987         pSMB->ByteCount = cpu_to_le16(name_len + 1);
988         rc = SendReceive(xid, tcon->ses, (struct smb_hdr *) pSMB,
989                          (struct smb_hdr *) pSMBr, &bytes_returned, 0);
990         cifs_stats_inc(&tcon->num_rmdirs);
991         if (rc)
992                 cFYI(1, "Error in RMDir = %d", rc);
993
994         cifs_buf_release(pSMB);
995         if (rc == -EAGAIN)
996                 goto RmDirRetry;
997         return rc;
998 }
999
1000 int
1001 CIFSSMBMkDir(const int xid, struct cifs_tcon *tcon,
1002              const char *name, const struct nls_table *nls_codepage, int remap)
1003 {
1004         int rc = 0;
1005         CREATE_DIRECTORY_REQ *pSMB = NULL;
1006         CREATE_DIRECTORY_RSP *pSMBr = NULL;
1007         int bytes_returned;
1008         int name_len;
1009
1010         cFYI(1, "In CIFSSMBMkDir");
1011 MkDirRetry:
1012         rc = smb_init(SMB_COM_CREATE_DIRECTORY, 0, tcon, (void **) &pSMB,
1013                       (void **) &pSMBr);
1014         if (rc)
1015                 return rc;
1016
1017         if (pSMB->hdr.Flags2 & SMBFLG2_UNICODE) {
1018                 name_len = cifsConvertToUCS((__le16 *) pSMB->DirName, name,
1019                                             PATH_MAX, nls_codepage, remap);
1020                 name_len++;     /* trailing null */
1021                 name_len *= 2;
1022         } else {                /* BB improve check for buffer overruns BB */
1023                 name_len = strnlen(name, PATH_MAX);
1024                 name_len++;     /* trailing null */
1025                 strncpy(pSMB->DirName, name, name_len);
1026         }
1027
1028         pSMB->BufferFormat = 0x04;
1029         inc_rfc1001_len(pSMB, name_len + 1);
1030         pSMB->ByteCount = cpu_to_le16(name_len + 1);
1031         rc = SendReceive(xid, tcon->ses, (struct smb_hdr *) pSMB,
1032                          (struct smb_hdr *) pSMBr, &bytes_returned, 0);
1033         cifs_stats_inc(&tcon->num_mkdirs);
1034         if (rc)
1035                 cFYI(1, "Error in Mkdir = %d", rc);
1036
1037         cifs_buf_release(pSMB);
1038         if (rc == -EAGAIN)
1039                 goto MkDirRetry;
1040         return rc;
1041 }
1042
1043 int
1044 CIFSPOSIXCreate(const int xid, struct cifs_tcon *tcon, __u32 posix_flags,
1045                 __u64 mode, __u16 *netfid, FILE_UNIX_BASIC_INFO *pRetData,
1046                 __u32 *pOplock, const char *name,
1047                 const struct nls_table *nls_codepage, int remap)
1048 {
1049         TRANSACTION2_SPI_REQ *pSMB = NULL;
1050         TRANSACTION2_SPI_RSP *pSMBr = NULL;
1051         int name_len;
1052         int rc = 0;
1053         int bytes_returned = 0;
1054         __u16 params, param_offset, offset, byte_count, count;
1055         OPEN_PSX_REQ *pdata;
1056         OPEN_PSX_RSP *psx_rsp;
1057
1058         cFYI(1, "In POSIX Create");
1059 PsxCreat:
1060         rc = smb_init(SMB_COM_TRANSACTION2, 15, tcon, (void **) &pSMB,
1061                       (void **) &pSMBr);
1062         if (rc)
1063                 return rc;
1064
1065         if (pSMB->hdr.Flags2 & SMBFLG2_UNICODE) {
1066                 name_len =
1067                     cifsConvertToUCS((__le16 *) pSMB->FileName, name,
1068                                      PATH_MAX, nls_codepage, remap);
1069                 name_len++;     /* trailing null */
1070                 name_len *= 2;
1071         } else {        /* BB improve the check for buffer overruns BB */
1072                 name_len = strnlen(name, PATH_MAX);
1073                 name_len++;     /* trailing null */
1074                 strncpy(pSMB->FileName, name, name_len);
1075         }
1076
1077         params = 6 + name_len;
1078         count = sizeof(OPEN_PSX_REQ);
1079         pSMB->MaxParameterCount = cpu_to_le16(2);
1080         pSMB->MaxDataCount = cpu_to_le16(1000); /* large enough */
1081         pSMB->MaxSetupCount = 0;
1082         pSMB->Reserved = 0;
1083         pSMB->Flags = 0;
1084         pSMB->Timeout = 0;
1085         pSMB->Reserved2 = 0;
1086         param_offset = offsetof(struct smb_com_transaction2_spi_req,
1087                                 InformationLevel) - 4;
1088         offset = param_offset + params;
1089         pdata = (OPEN_PSX_REQ *)(((char *)&pSMB->hdr.Protocol) + offset);
1090         pdata->Level = cpu_to_le16(SMB_QUERY_FILE_UNIX_BASIC);
1091         pdata->Permissions = cpu_to_le64(mode);
1092         pdata->PosixOpenFlags = cpu_to_le32(posix_flags);
1093         pdata->OpenFlags =  cpu_to_le32(*pOplock);
1094         pSMB->ParameterOffset = cpu_to_le16(param_offset);
1095         pSMB->DataOffset = cpu_to_le16(offset);
1096         pSMB->SetupCount = 1;
1097         pSMB->Reserved3 = 0;
1098         pSMB->SubCommand = cpu_to_le16(TRANS2_SET_PATH_INFORMATION);
1099         byte_count = 3 /* pad */  + params + count;
1100
1101         pSMB->DataCount = cpu_to_le16(count);
1102         pSMB->ParameterCount = cpu_to_le16(params);
1103         pSMB->TotalDataCount = pSMB->DataCount;
1104         pSMB->TotalParameterCount = pSMB->ParameterCount;
1105         pSMB->InformationLevel = cpu_to_le16(SMB_POSIX_OPEN);
1106         pSMB->Reserved4 = 0;
1107         inc_rfc1001_len(pSMB, byte_count);
1108         pSMB->ByteCount = cpu_to_le16(byte_count);
1109         rc = SendReceive(xid, tcon->ses, (struct smb_hdr *) pSMB,
1110                          (struct smb_hdr *) pSMBr, &bytes_returned, 0);
1111         if (rc) {
1112                 cFYI(1, "Posix create returned %d", rc);
1113                 goto psx_create_err;
1114         }
1115
1116         cFYI(1, "copying inode info");
1117         rc = validate_t2((struct smb_t2_rsp *)pSMBr);
1118
1119         if (rc || get_bcc(&pSMBr->hdr) < sizeof(OPEN_PSX_RSP)) {
1120                 rc = -EIO;      /* bad smb */
1121                 goto psx_create_err;
1122         }
1123
1124         /* copy return information to pRetData */
1125         psx_rsp = (OPEN_PSX_RSP *)((char *) &pSMBr->hdr.Protocol
1126                         + le16_to_cpu(pSMBr->t2.DataOffset));
1127
1128         *pOplock = le16_to_cpu(psx_rsp->OplockFlags);
1129         if (netfid)
1130                 *netfid = psx_rsp->Fid;   /* cifs fid stays in le */
1131         /* Let caller know file was created so we can set the mode. */
1132         /* Do we care about the CreateAction in any other cases? */
1133         if (cpu_to_le32(FILE_CREATE) == psx_rsp->CreateAction)
1134                 *pOplock |= CIFS_CREATE_ACTION;
1135         /* check to make sure response data is there */
1136         if (psx_rsp->ReturnedLevel != cpu_to_le16(SMB_QUERY_FILE_UNIX_BASIC)) {
1137                 pRetData->Type = cpu_to_le32(-1); /* unknown */
1138                 cFYI(DBG2, "unknown type");
1139         } else {
1140                 if (get_bcc(&pSMBr->hdr) < sizeof(OPEN_PSX_RSP)
1141                                         + sizeof(FILE_UNIX_BASIC_INFO)) {
1142                         cERROR(1, "Open response data too small");
1143                         pRetData->Type = cpu_to_le32(-1);
1144                         goto psx_create_err;
1145                 }
1146                 memcpy((char *) pRetData,
1147                         (char *)psx_rsp + sizeof(OPEN_PSX_RSP),
1148                         sizeof(FILE_UNIX_BASIC_INFO));
1149         }
1150
1151 psx_create_err:
1152         cifs_buf_release(pSMB);
1153
1154         if (posix_flags & SMB_O_DIRECTORY)
1155                 cifs_stats_inc(&tcon->num_posixmkdirs);
1156         else
1157                 cifs_stats_inc(&tcon->num_posixopens);
1158
1159         if (rc == -EAGAIN)
1160                 goto PsxCreat;
1161
1162         return rc;
1163 }
1164
1165 static __u16 convert_disposition(int disposition)
1166 {
1167         __u16 ofun = 0;
1168
1169         switch (disposition) {
1170                 case FILE_SUPERSEDE:
1171                         ofun = SMBOPEN_OCREATE | SMBOPEN_OTRUNC;
1172                         break;
1173                 case FILE_OPEN:
1174                         ofun = SMBOPEN_OAPPEND;
1175                         break;
1176                 case FILE_CREATE:
1177                         ofun = SMBOPEN_OCREATE;
1178                         break;
1179                 case FILE_OPEN_IF:
1180                         ofun = SMBOPEN_OCREATE | SMBOPEN_OAPPEND;
1181                         break;
1182                 case FILE_OVERWRITE:
1183                         ofun = SMBOPEN_OTRUNC;
1184                         break;
1185                 case FILE_OVERWRITE_IF:
1186                         ofun = SMBOPEN_OCREATE | SMBOPEN_OTRUNC;
1187                         break;
1188                 default:
1189                         cFYI(1, "unknown disposition %d", disposition);
1190                         ofun =  SMBOPEN_OAPPEND; /* regular open */
1191         }
1192         return ofun;
1193 }
1194
1195 static int
1196 access_flags_to_smbopen_mode(const int access_flags)
1197 {
1198         int masked_flags = access_flags & (GENERIC_READ | GENERIC_WRITE);
1199
1200         if (masked_flags == GENERIC_READ)
1201                 return SMBOPEN_READ;
1202         else if (masked_flags == GENERIC_WRITE)
1203                 return SMBOPEN_WRITE;
1204
1205         /* just go for read/write */
1206         return SMBOPEN_READWRITE;
1207 }
1208
1209 int
1210 SMBLegacyOpen(const int xid, struct cifs_tcon *tcon,
1211             const char *fileName, const int openDisposition,
1212             const int access_flags, const int create_options, __u16 *netfid,
1213             int *pOplock, FILE_ALL_INFO *pfile_info,
1214             const struct nls_table *nls_codepage, int remap)
1215 {
1216         int rc = -EACCES;
1217         OPENX_REQ *pSMB = NULL;
1218         OPENX_RSP *pSMBr = NULL;
1219         int bytes_returned;
1220         int name_len;
1221         __u16 count;
1222
1223 OldOpenRetry:
1224         rc = smb_init(SMB_COM_OPEN_ANDX, 15, tcon, (void **) &pSMB,
1225                       (void **) &pSMBr);
1226         if (rc)
1227                 return rc;
1228
1229         pSMB->AndXCommand = 0xFF;       /* none */
1230
1231         if (pSMB->hdr.Flags2 & SMBFLG2_UNICODE) {
1232                 count = 1;      /* account for one byte pad to word boundary */
1233                 name_len =
1234                    cifsConvertToUCS((__le16 *) (pSMB->fileName + 1),
1235                                     fileName, PATH_MAX, nls_codepage, remap);
1236                 name_len++;     /* trailing null */
1237                 name_len *= 2;
1238         } else {                /* BB improve check for buffer overruns BB */
1239                 count = 0;      /* no pad */
1240                 name_len = strnlen(fileName, PATH_MAX);
1241                 name_len++;     /* trailing null */
1242                 strncpy(pSMB->fileName, fileName, name_len);
1243         }
1244         if (*pOplock & REQ_OPLOCK)
1245                 pSMB->OpenFlags = cpu_to_le16(REQ_OPLOCK);
1246         else if (*pOplock & REQ_BATCHOPLOCK)
1247                 pSMB->OpenFlags = cpu_to_le16(REQ_BATCHOPLOCK);
1248
1249         pSMB->OpenFlags |= cpu_to_le16(REQ_MORE_INFO);
1250         pSMB->Mode = cpu_to_le16(access_flags_to_smbopen_mode(access_flags));
1251         pSMB->Mode |= cpu_to_le16(0x40); /* deny none */
1252         /* set file as system file if special file such
1253            as fifo and server expecting SFU style and
1254            no Unix extensions */
1255
1256         if (create_options & CREATE_OPTION_SPECIAL)
1257                 pSMB->FileAttributes = cpu_to_le16(ATTR_SYSTEM);
1258         else /* BB FIXME BB */
1259                 pSMB->FileAttributes = cpu_to_le16(0/*ATTR_NORMAL*/);
1260
1261         if (create_options & CREATE_OPTION_READONLY)
1262                 pSMB->FileAttributes |= cpu_to_le16(ATTR_READONLY);
1263
1264         /* BB FIXME BB */
1265 /*      pSMB->CreateOptions = cpu_to_le32(create_options &
1266                                                  CREATE_OPTIONS_MASK); */
1267         /* BB FIXME END BB */
1268
1269         pSMB->Sattr = cpu_to_le16(ATTR_HIDDEN | ATTR_SYSTEM | ATTR_DIRECTORY);
1270         pSMB->OpenFunction = cpu_to_le16(convert_disposition(openDisposition));
1271         count += name_len;
1272         inc_rfc1001_len(pSMB, count);
1273
1274         pSMB->ByteCount = cpu_to_le16(count);
1275         /* long_op set to 1 to allow for oplock break timeouts */
1276         rc = SendReceive(xid, tcon->ses, (struct smb_hdr *) pSMB,
1277                         (struct smb_hdr *)pSMBr, &bytes_returned, 0);
1278         cifs_stats_inc(&tcon->num_opens);
1279         if (rc) {
1280                 cFYI(1, "Error in Open = %d", rc);
1281         } else {
1282         /* BB verify if wct == 15 */
1283
1284 /*              *pOplock = pSMBr->OplockLevel; */ /* BB take from action field*/
1285
1286                 *netfid = pSMBr->Fid;   /* cifs fid stays in le */
1287                 /* Let caller know file was created so we can set the mode. */
1288                 /* Do we care about the CreateAction in any other cases? */
1289         /* BB FIXME BB */
1290 /*              if (cpu_to_le32(FILE_CREATE) == pSMBr->CreateAction)
1291                         *pOplock |= CIFS_CREATE_ACTION; */
1292         /* BB FIXME END */
1293
1294                 if (pfile_info) {
1295                         pfile_info->CreationTime = 0; /* BB convert CreateTime*/
1296                         pfile_info->LastAccessTime = 0; /* BB fixme */
1297                         pfile_info->LastWriteTime = 0; /* BB fixme */
1298                         pfile_info->ChangeTime = 0;  /* BB fixme */
1299                         pfile_info->Attributes =
1300                                 cpu_to_le32(le16_to_cpu(pSMBr->FileAttributes));
1301                         /* the file_info buf is endian converted by caller */
1302                         pfile_info->AllocationSize =
1303                                 cpu_to_le64(le32_to_cpu(pSMBr->EndOfFile));
1304                         pfile_info->EndOfFile = pfile_info->AllocationSize;
1305                         pfile_info->NumberOfLinks = cpu_to_le32(1);
1306                         pfile_info->DeletePending = 0;
1307                 }
1308         }
1309
1310         cifs_buf_release(pSMB);
1311         if (rc == -EAGAIN)
1312                 goto OldOpenRetry;
1313         return rc;
1314 }
1315
1316 int
1317 CIFSSMBOpen(const int xid, struct cifs_tcon *tcon,
1318             const char *fileName, const int openDisposition,
1319             const int access_flags, const int create_options, __u16 *netfid,
1320             int *pOplock, FILE_ALL_INFO *pfile_info,
1321             const struct nls_table *nls_codepage, int remap)
1322 {
1323         int rc = -EACCES;
1324         OPEN_REQ *pSMB = NULL;
1325         OPEN_RSP *pSMBr = NULL;
1326         int bytes_returned;
1327         int name_len;
1328         __u16 count;
1329
1330 openRetry:
1331         rc = smb_init(SMB_COM_NT_CREATE_ANDX, 24, tcon, (void **) &pSMB,
1332                       (void **) &pSMBr);
1333         if (rc)
1334                 return rc;
1335
1336         pSMB->AndXCommand = 0xFF;       /* none */
1337
1338         if (pSMB->hdr.Flags2 & SMBFLG2_UNICODE) {
1339                 count = 1;      /* account for one byte pad to word boundary */
1340                 name_len =
1341                     cifsConvertToUCS((__le16 *) (pSMB->fileName + 1),
1342                                      fileName, PATH_MAX, nls_codepage, remap);
1343                 name_len++;     /* trailing null */
1344                 name_len *= 2;
1345                 pSMB->NameLength = cpu_to_le16(name_len);
1346         } else {                /* BB improve check for buffer overruns BB */
1347                 count = 0;      /* no pad */
1348                 name_len = strnlen(fileName, PATH_MAX);
1349                 name_len++;     /* trailing null */
1350                 pSMB->NameLength = cpu_to_le16(name_len);
1351                 strncpy(pSMB->fileName, fileName, name_len);
1352         }
1353         if (*pOplock & REQ_OPLOCK)
1354                 pSMB->OpenFlags = cpu_to_le32(REQ_OPLOCK);
1355         else if (*pOplock & REQ_BATCHOPLOCK)
1356                 pSMB->OpenFlags = cpu_to_le32(REQ_BATCHOPLOCK);
1357         pSMB->DesiredAccess = cpu_to_le32(access_flags);
1358         pSMB->AllocationSize = 0;
1359         /* set file as system file if special file such
1360            as fifo and server expecting SFU style and
1361            no Unix extensions */
1362         if (create_options & CREATE_OPTION_SPECIAL)
1363                 pSMB->FileAttributes = cpu_to_le32(ATTR_SYSTEM);
1364         else
1365                 pSMB->FileAttributes = cpu_to_le32(ATTR_NORMAL);
1366
1367         /* XP does not handle ATTR_POSIX_SEMANTICS */
1368         /* but it helps speed up case sensitive checks for other
1369         servers such as Samba */
1370         if (tcon->ses->capabilities & CAP_UNIX)
1371                 pSMB->FileAttributes |= cpu_to_le32(ATTR_POSIX_SEMANTICS);
1372
1373         if (create_options & CREATE_OPTION_READONLY)
1374                 pSMB->FileAttributes |= cpu_to_le32(ATTR_READONLY);
1375
1376         pSMB->ShareAccess = cpu_to_le32(FILE_SHARE_ALL);
1377         pSMB->CreateDisposition = cpu_to_le32(openDisposition);
1378         pSMB->CreateOptions = cpu_to_le32(create_options & CREATE_OPTIONS_MASK);
1379         /* BB Expirement with various impersonation levels and verify */
1380         pSMB->ImpersonationLevel = cpu_to_le32(SECURITY_IMPERSONATION);
1381         pSMB->SecurityFlags =
1382             SECURITY_CONTEXT_TRACKING | SECURITY_EFFECTIVE_ONLY;
1383
1384         count += name_len;
1385         inc_rfc1001_len(pSMB, count);
1386
1387         pSMB->ByteCount = cpu_to_le16(count);
1388         /* long_op set to 1 to allow for oplock break timeouts */
1389         rc = SendReceive(xid, tcon->ses, (struct smb_hdr *) pSMB,
1390                         (struct smb_hdr *)pSMBr, &bytes_returned, 0);
1391         cifs_stats_inc(&tcon->num_opens);
1392         if (rc) {
1393                 cFYI(1, "Error in Open = %d", rc);
1394         } else {
1395                 *pOplock = pSMBr->OplockLevel; /* 1 byte no need to le_to_cpu */
1396                 *netfid = pSMBr->Fid;   /* cifs fid stays in le */
1397                 /* Let caller know file was created so we can set the mode. */
1398                 /* Do we care about the CreateAction in any other cases? */
1399                 if (cpu_to_le32(FILE_CREATE) == pSMBr->CreateAction)
1400                         *pOplock |= CIFS_CREATE_ACTION;
1401                 if (pfile_info) {
1402                         memcpy((char *)pfile_info, (char *)&pSMBr->CreationTime,
1403                                 36 /* CreationTime to Attributes */);
1404                         /* the file_info buf is endian converted by caller */
1405                         pfile_info->AllocationSize = pSMBr->AllocationSize;
1406                         pfile_info->EndOfFile = pSMBr->EndOfFile;
1407                         pfile_info->NumberOfLinks = cpu_to_le32(1);
1408                         pfile_info->DeletePending = 0;
1409                 }
1410         }
1411
1412         cifs_buf_release(pSMB);
1413         if (rc == -EAGAIN)
1414                 goto openRetry;
1415         return rc;
1416 }
1417
1418 struct cifs_readdata *
1419 cifs_readdata_alloc(unsigned int nr_pages)
1420 {
1421         struct cifs_readdata *rdata;
1422
1423         /* readdata + 1 kvec for each page */
1424         rdata = kzalloc(sizeof(*rdata) +
1425                         sizeof(struct kvec) * nr_pages, GFP_KERNEL);
1426         if (rdata != NULL) {
1427                 INIT_WORK(&rdata->work, cifs_readv_complete);
1428                 INIT_LIST_HEAD(&rdata->pages);
1429         }
1430         return rdata;
1431 }
1432
1433 void
1434 cifs_readdata_free(struct cifs_readdata *rdata)
1435 {
1436         cifsFileInfo_put(rdata->cfile);
1437         kfree(rdata);
1438 }
1439
1440 /*
1441  * Discard any remaining data in the current SMB. To do this, we borrow the
1442  * current bigbuf.
1443  */
1444 static int
1445 cifs_readv_discard(struct TCP_Server_Info *server, struct mid_q_entry *mid)
1446 {
1447         READ_RSP *rsp = (READ_RSP *)server->smallbuf;
1448         unsigned int rfclen = be32_to_cpu(rsp->hdr.smb_buf_length);
1449         int remaining = rfclen + 4 - server->total_read;
1450         struct cifs_readdata *rdata = mid->callback_data;
1451
1452         while (remaining > 0) {
1453                 int length;
1454
1455                 length = cifs_read_from_socket(server, server->bigbuf,
1456                                 min_t(unsigned int, remaining,
1457                                         CIFSMaxBufSize + MAX_CIFS_HDR_SIZE));
1458                 if (length < 0)
1459                         return length;
1460                 server->total_read += length;
1461                 remaining -= length;
1462         }
1463
1464         dequeue_mid(mid, rdata->result);
1465         return 0;
1466 }
1467
1468 static int
1469 cifs_readv_receive(struct TCP_Server_Info *server, struct mid_q_entry *mid)
1470 {
1471         int length, len;
1472         unsigned int data_offset, remaining, data_len;
1473         struct cifs_readdata *rdata = mid->callback_data;
1474         READ_RSP *rsp = (READ_RSP *)server->smallbuf;
1475         unsigned int rfclen = be32_to_cpu(rsp->hdr.smb_buf_length) + 4;
1476         u64 eof;
1477         pgoff_t eof_index;
1478         struct page *page, *tpage;
1479
1480         cFYI(1, "%s: mid=%u offset=%llu bytes=%u", __func__,
1481                 mid->mid, rdata->offset, rdata->bytes);
1482
1483         /*
1484          * read the rest of READ_RSP header (sans Data array), or whatever we
1485          * can if there's not enough data. At this point, we've read down to
1486          * the Mid.
1487          */
1488         len = min_t(unsigned int, rfclen, sizeof(*rsp)) -
1489                         sizeof(struct smb_hdr) + 1;
1490
1491         rdata->iov[0].iov_base = server->smallbuf + sizeof(struct smb_hdr) - 1;
1492         rdata->iov[0].iov_len = len;
1493
1494         length = cifs_readv_from_socket(server, rdata->iov, 1, len);
1495         if (length < 0)
1496                 return length;
1497         server->total_read += length;
1498
1499         /* Was the SMB read successful? */
1500         rdata->result = map_smb_to_linux_error(&rsp->hdr, false);
1501         if (rdata->result != 0) {
1502                 cFYI(1, "%s: server returned error %d", __func__,
1503                         rdata->result);
1504                 return cifs_readv_discard(server, mid);
1505         }
1506
1507         /* Is there enough to get to the rest of the READ_RSP header? */
1508         if (server->total_read < sizeof(READ_RSP)) {
1509                 cFYI(1, "%s: server returned short header. got=%u expected=%zu",
1510                         __func__, server->total_read, sizeof(READ_RSP));
1511                 rdata->result = -EIO;
1512                 return cifs_readv_discard(server, mid);
1513         }
1514
1515         data_offset = le16_to_cpu(rsp->DataOffset) + 4;
1516         if (data_offset < server->total_read) {
1517                 /*
1518                  * win2k8 sometimes sends an offset of 0 when the read
1519                  * is beyond the EOF. Treat it as if the data starts just after
1520                  * the header.
1521                  */
1522                 cFYI(1, "%s: data offset (%u) inside read response header",
1523                         __func__, data_offset);
1524                 data_offset = server->total_read;
1525         } else if (data_offset > MAX_CIFS_SMALL_BUFFER_SIZE) {
1526                 /* data_offset is beyond the end of smallbuf */
1527                 cFYI(1, "%s: data offset (%u) beyond end of smallbuf",
1528                         __func__, data_offset);
1529                 rdata->result = -EIO;
1530                 return cifs_readv_discard(server, mid);
1531         }
1532
1533         cFYI(1, "%s: total_read=%u data_offset=%u", __func__,
1534                 server->total_read, data_offset);
1535
1536         len = data_offset - server->total_read;
1537         if (len > 0) {
1538                 /* read any junk before data into the rest of smallbuf */
1539                 rdata->iov[0].iov_base = server->smallbuf + server->total_read;
1540                 rdata->iov[0].iov_len = len;
1541                 length = cifs_readv_from_socket(server, rdata->iov, 1, len);
1542                 if (length < 0)
1543                         return length;
1544                 server->total_read += length;
1545         }
1546
1547         /* set up first iov for signature check */
1548         rdata->iov[0].iov_base = server->smallbuf;
1549         rdata->iov[0].iov_len = server->total_read;
1550         cFYI(1, "0: iov_base=%p iov_len=%zu",
1551                 rdata->iov[0].iov_base, rdata->iov[0].iov_len);
1552
1553         /* how much data is in the response? */
1554         data_len = le16_to_cpu(rsp->DataLengthHigh) << 16;
1555         data_len += le16_to_cpu(rsp->DataLength);
1556         if (data_offset + data_len > rfclen) {
1557                 /* data_len is corrupt -- discard frame */
1558                 rdata->result = -EIO;
1559                 return cifs_readv_discard(server, mid);
1560         }
1561
1562         /* marshal up the page array */
1563         len = 0;
1564         remaining = data_len;
1565         rdata->nr_iov = 1;
1566
1567         /* determine the eof that the server (probably) has */
1568         eof = CIFS_I(rdata->mapping->host)->server_eof;
1569         eof_index = eof ? (eof - 1) >> PAGE_CACHE_SHIFT : 0;
1570         cFYI(1, "eof=%llu eof_index=%lu", eof, eof_index);
1571
1572         cifs_kmap_lock();
1573         list_for_each_entry_safe(page, tpage, &rdata->pages, lru) {
1574                 if (remaining >= PAGE_CACHE_SIZE) {
1575                         /* enough data to fill the page */
1576                         rdata->iov[rdata->nr_iov].iov_base = kmap(page);
1577                         rdata->iov[rdata->nr_iov].iov_len = PAGE_CACHE_SIZE;
1578                         cFYI(1, "%u: idx=%lu iov_base=%p iov_len=%zu",
1579                                 rdata->nr_iov, page->index,
1580                                 rdata->iov[rdata->nr_iov].iov_base,
1581                                 rdata->iov[rdata->nr_iov].iov_len);
1582                         ++rdata->nr_iov;
1583                         len += PAGE_CACHE_SIZE;
1584                         remaining -= PAGE_CACHE_SIZE;
1585                 } else if (remaining > 0) {
1586                         /* enough for partial page, fill and zero the rest */
1587                         rdata->iov[rdata->nr_iov].iov_base = kmap(page);
1588                         rdata->iov[rdata->nr_iov].iov_len = remaining;
1589                         cFYI(1, "%u: idx=%lu iov_base=%p iov_len=%zu",
1590                                 rdata->nr_iov, page->index,
1591                                 rdata->iov[rdata->nr_iov].iov_base,
1592                                 rdata->iov[rdata->nr_iov].iov_len);
1593                         memset(rdata->iov[rdata->nr_iov].iov_base + remaining,
1594                                 '\0', PAGE_CACHE_SIZE - remaining);
1595                         ++rdata->nr_iov;
1596                         len += remaining;
1597                         remaining = 0;
1598                 } else if (page->index > eof_index) {
1599                         /*
1600                          * The VFS will not try to do readahead past the
1601                          * i_size, but it's possible that we have outstanding
1602                          * writes with gaps in the middle and the i_size hasn't
1603                          * caught up yet. Populate those with zeroed out pages
1604                          * to prevent the VFS from repeatedly attempting to
1605                          * fill them until the writes are flushed.
1606                          */
1607                         zero_user(page, 0, PAGE_CACHE_SIZE);
1608                         list_del(&page->lru);
1609                         lru_cache_add_file(page);
1610                         flush_dcache_page(page);
1611                         SetPageUptodate(page);
1612                         unlock_page(page);
1613                         page_cache_release(page);
1614                 } else {
1615                         /* no need to hold page hostage */
1616                         list_del(&page->lru);
1617                         lru_cache_add_file(page);
1618                         unlock_page(page);
1619                         page_cache_release(page);
1620                 }
1621         }
1622         cifs_kmap_unlock();
1623
1624         /* issue the read if we have any iovecs left to fill */
1625         if (rdata->nr_iov > 1) {
1626                 length = cifs_readv_from_socket(server, &rdata->iov[1],
1627                                                 rdata->nr_iov - 1, len);
1628                 if (length < 0)
1629                         return length;
1630                 server->total_read += length;
1631         } else {
1632                 length = 0;
1633         }
1634
1635         rdata->bytes = length;
1636
1637         cFYI(1, "total_read=%u rfclen=%u remaining=%u", server->total_read,
1638                 rfclen, remaining);
1639
1640         /* discard anything left over */
1641         if (server->total_read < rfclen)
1642                 return cifs_readv_discard(server, mid);
1643
1644         dequeue_mid(mid, false);
1645         return length;
1646 }
1647
1648 static void
1649 cifs_readv_complete(struct work_struct *work)
1650 {
1651         struct cifs_readdata *rdata = container_of(work,
1652                                                 struct cifs_readdata, work);
1653         struct page *page, *tpage;
1654
1655         list_for_each_entry_safe(page, tpage, &rdata->pages, lru) {
1656                 list_del(&page->lru);
1657                 lru_cache_add_file(page);
1658
1659                 if (rdata->result == 0) {
1660                         kunmap(page);
1661                         flush_dcache_page(page);
1662                         SetPageUptodate(page);
1663                 }
1664
1665                 unlock_page(page);
1666
1667                 if (rdata->result == 0)
1668                         cifs_readpage_to_fscache(rdata->mapping->host, page);
1669
1670                 page_cache_release(page);
1671         }
1672         cifs_readdata_free(rdata);
1673 }
1674
1675 static void
1676 cifs_readv_callback(struct mid_q_entry *mid)
1677 {
1678         struct cifs_readdata *rdata = mid->callback_data;
1679         struct cifs_tcon *tcon = tlink_tcon(rdata->cfile->tlink);
1680         struct TCP_Server_Info *server = tcon->ses->server;
1681
1682         cFYI(1, "%s: mid=%u state=%d result=%d bytes=%u", __func__,
1683                 mid->mid, mid->midState, rdata->result, rdata->bytes);
1684
1685         switch (mid->midState) {
1686         case MID_RESPONSE_RECEIVED:
1687                 /* result already set, check signature */
1688                 if (server->sec_mode &
1689                     (SECMODE_SIGN_REQUIRED | SECMODE_SIGN_ENABLED)) {
1690                         if (cifs_verify_signature(rdata->iov, rdata->nr_iov,
1691                                           server, mid->sequence_number + 1))
1692                                 cERROR(1, "Unexpected SMB signature");
1693                 }
1694                 /* FIXME: should this be counted toward the initiating task? */
1695                 task_io_account_read(rdata->bytes);
1696                 cifs_stats_bytes_read(tcon, rdata->bytes);
1697                 break;
1698         case MID_REQUEST_SUBMITTED:
1699         case MID_RETRY_NEEDED:
1700                 rdata->result = -EAGAIN;
1701                 break;
1702         default:
1703                 rdata->result = -EIO;
1704         }
1705
1706         queue_work(system_nrt_wq, &rdata->work);
1707         DeleteMidQEntry(mid);
1708         atomic_dec(&server->inFlight);
1709         wake_up(&server->request_q);
1710 }
1711
1712 /* cifs_async_readv - send an async write, and set up mid to handle result */
1713 int
1714 cifs_async_readv(struct cifs_readdata *rdata)
1715 {
1716         int rc;
1717         READ_REQ *smb = NULL;
1718         int wct;
1719         struct cifs_tcon *tcon = tlink_tcon(rdata->cfile->tlink);
1720
1721         cFYI(1, "%s: offset=%llu bytes=%u", __func__,
1722                 rdata->offset, rdata->bytes);
1723
1724         if (tcon->ses->capabilities & CAP_LARGE_FILES)
1725                 wct = 12;
1726         else {
1727                 wct = 10; /* old style read */
1728                 if ((rdata->offset >> 32) > 0)  {
1729                         /* can not handle this big offset for old */
1730                         return -EIO;
1731                 }
1732         }
1733
1734         rc = small_smb_init(SMB_COM_READ_ANDX, wct, tcon, (void **)&smb);
1735         if (rc)
1736                 return rc;
1737
1738         smb->hdr.Pid = cpu_to_le16((__u16)rdata->pid);
1739         smb->hdr.PidHigh = cpu_to_le16((__u16)(rdata->pid >> 16));
1740
1741         smb->AndXCommand = 0xFF;        /* none */
1742         smb->Fid = rdata->cfile->netfid;
1743         smb->OffsetLow = cpu_to_le32(rdata->offset & 0xFFFFFFFF);
1744         if (wct == 12)
1745                 smb->OffsetHigh = cpu_to_le32(rdata->offset >> 32);
1746         smb->Remaining = 0;
1747         smb->MaxCount = cpu_to_le16(rdata->bytes & 0xFFFF);
1748         smb->MaxCountHigh = cpu_to_le32(rdata->bytes >> 16);
1749         if (wct == 12)
1750                 smb->ByteCount = 0;
1751         else {
1752                 /* old style read */
1753                 struct smb_com_readx_req *smbr =
1754                         (struct smb_com_readx_req *)smb;
1755                 smbr->ByteCount = 0;
1756         }
1757
1758         /* 4 for RFC1001 length + 1 for BCC */
1759         rdata->iov[0].iov_base = smb;
1760         rdata->iov[0].iov_len = be32_to_cpu(smb->hdr.smb_buf_length) + 4;
1761
1762         rc = cifs_call_async(tcon->ses->server, rdata->iov, 1,
1763                              cifs_readv_receive, cifs_readv_callback,
1764                              rdata, false);
1765
1766         if (rc == 0)
1767                 cifs_stats_inc(&tcon->num_reads);
1768
1769         cifs_small_buf_release(smb);
1770         return rc;
1771 }
1772
1773 int
1774 CIFSSMBRead(const int xid, struct cifs_io_parms *io_parms, unsigned int *nbytes,
1775             char **buf, int *pbuf_type)
1776 {
1777         int rc = -EACCES;
1778         READ_REQ *pSMB = NULL;
1779         READ_RSP *pSMBr = NULL;
1780         char *pReadData = NULL;
1781         int wct;
1782         int resp_buf_type = 0;
1783         struct kvec iov[1];
1784         __u32 pid = io_parms->pid;
1785         __u16 netfid = io_parms->netfid;
1786         __u64 offset = io_parms->offset;
1787         struct cifs_tcon *tcon = io_parms->tcon;
1788         unsigned int count = io_parms->length;
1789
1790         cFYI(1, "Reading %d bytes on fid %d", count, netfid);
1791         if (tcon->ses->capabilities & CAP_LARGE_FILES)
1792                 wct = 12;
1793         else {
1794                 wct = 10; /* old style read */
1795                 if ((offset >> 32) > 0)  {
1796                         /* can not handle this big offset for old */
1797                         return -EIO;
1798                 }
1799         }
1800
1801         *nbytes = 0;
1802         rc = small_smb_init(SMB_COM_READ_ANDX, wct, tcon, (void **) &pSMB);
1803         if (rc)
1804                 return rc;
1805
1806         pSMB->hdr.Pid = cpu_to_le16((__u16)pid);
1807         pSMB->hdr.PidHigh = cpu_to_le16((__u16)(pid >> 16));
1808
1809         /* tcon and ses pointer are checked in smb_init */
1810         if (tcon->ses->server == NULL)
1811                 return -ECONNABORTED;
1812
1813         pSMB->AndXCommand = 0xFF;       /* none */
1814         pSMB->Fid = netfid;
1815         pSMB->OffsetLow = cpu_to_le32(offset & 0xFFFFFFFF);
1816         if (wct == 12)
1817                 pSMB->OffsetHigh = cpu_to_le32(offset >> 32);
1818
1819         pSMB->Remaining = 0;
1820         pSMB->MaxCount = cpu_to_le16(count & 0xFFFF);
1821         pSMB->MaxCountHigh = cpu_to_le32(count >> 16);
1822         if (wct == 12)
1823                 pSMB->ByteCount = 0;  /* no need to do le conversion since 0 */
1824         else {
1825                 /* old style read */
1826                 struct smb_com_readx_req *pSMBW =
1827                         (struct smb_com_readx_req *)pSMB;
1828                 pSMBW->ByteCount = 0;
1829         }
1830
1831         iov[0].iov_base = (char *)pSMB;
1832         iov[0].iov_len = be32_to_cpu(pSMB->hdr.smb_buf_length) + 4;
1833         rc = SendReceive2(xid, tcon->ses, iov, 1 /* num iovecs */,
1834                          &resp_buf_type, CIFS_LOG_ERROR);
1835         cifs_stats_inc(&tcon->num_reads);
1836         pSMBr = (READ_RSP *)iov[0].iov_base;
1837         if (rc) {
1838                 cERROR(1, "Send error in read = %d", rc);
1839         } else {
1840                 int data_length = le16_to_cpu(pSMBr->DataLengthHigh);
1841                 data_length = data_length << 16;
1842                 data_length += le16_to_cpu(pSMBr->DataLength);
1843                 *nbytes = data_length;
1844
1845                 /*check that DataLength would not go beyond end of SMB */
1846                 if ((data_length > CIFSMaxBufSize)
1847                                 || (data_length > count)) {
1848                         cFYI(1, "bad length %d for count %d",
1849                                  data_length, count);
1850                         rc = -EIO;
1851                         *nbytes = 0;
1852                 } else {
1853                         pReadData = (char *) (&pSMBr->hdr.Protocol) +
1854                                         le16_to_cpu(pSMBr->DataOffset);
1855 /*                      if (rc = copy_to_user(buf, pReadData, data_length)) {
1856                                 cERROR(1, "Faulting on read rc = %d",rc);
1857                                 rc = -EFAULT;
1858                         }*/ /* can not use copy_to_user when using page cache*/
1859                         if (*buf)
1860                                 memcpy(*buf, pReadData, data_length);
1861                 }
1862         }
1863
1864 /*      cifs_small_buf_release(pSMB); */ /* Freed earlier now in SendReceive2 */
1865         if (*buf) {
1866                 if (resp_buf_type == CIFS_SMALL_BUFFER)
1867                         cifs_small_buf_release(iov[0].iov_base);
1868                 else if (resp_buf_type == CIFS_LARGE_BUFFER)
1869                         cifs_buf_release(iov[0].iov_base);
1870         } else if (resp_buf_type != CIFS_NO_BUFFER) {
1871                 /* return buffer to caller to free */
1872                 *buf = iov[0].iov_base;
1873                 if (resp_buf_type == CIFS_SMALL_BUFFER)
1874                         *pbuf_type = CIFS_SMALL_BUFFER;
1875                 else if (resp_buf_type == CIFS_LARGE_BUFFER)
1876                         *pbuf_type = CIFS_LARGE_BUFFER;
1877         } /* else no valid buffer on return - leave as null */
1878
1879         /* Note: On -EAGAIN error only caller can retry on handle based calls
1880                 since file handle passed in no longer valid */
1881         return rc;
1882 }
1883
1884
1885 int
1886 CIFSSMBWrite(const int xid, struct cifs_io_parms *io_parms,
1887              unsigned int *nbytes, const char *buf,
1888              const char __user *ubuf, const int long_op)
1889 {
1890         int rc = -EACCES;
1891         WRITE_REQ *pSMB = NULL;
1892         WRITE_RSP *pSMBr = NULL;
1893         int bytes_returned, wct;
1894         __u32 bytes_sent;
1895         __u16 byte_count;
1896         __u32 pid = io_parms->pid;
1897         __u16 netfid = io_parms->netfid;
1898         __u64 offset = io_parms->offset;
1899         struct cifs_tcon *tcon = io_parms->tcon;
1900         unsigned int count = io_parms->length;
1901
1902         *nbytes = 0;
1903
1904         /* cFYI(1, "write at %lld %d bytes", offset, count);*/
1905         if (tcon->ses == NULL)
1906                 return -ECONNABORTED;
1907
1908         if (tcon->ses->capabilities & CAP_LARGE_FILES)
1909                 wct = 14;
1910         else {
1911                 wct = 12;
1912                 if ((offset >> 32) > 0) {
1913                         /* can not handle big offset for old srv */
1914                         return -EIO;
1915                 }
1916         }
1917
1918         rc = smb_init(SMB_COM_WRITE_ANDX, wct, tcon, (void **) &pSMB,
1919                       (void **) &pSMBr);
1920         if (rc)
1921                 return rc;
1922
1923         pSMB->hdr.Pid = cpu_to_le16((__u16)pid);
1924         pSMB->hdr.PidHigh = cpu_to_le16((__u16)(pid >> 16));
1925
1926         /* tcon and ses pointer are checked in smb_init */
1927         if (tcon->ses->server == NULL)
1928                 return -ECONNABORTED;
1929
1930         pSMB->AndXCommand = 0xFF;       /* none */
1931         pSMB->Fid = netfid;
1932         pSMB->OffsetLow = cpu_to_le32(offset & 0xFFFFFFFF);
1933         if (wct == 14)
1934                 pSMB->OffsetHigh = cpu_to_le32(offset >> 32);
1935
1936         pSMB->Reserved = 0xFFFFFFFF;
1937         pSMB->WriteMode = 0;
1938         pSMB->Remaining = 0;
1939
1940         /* Can increase buffer size if buffer is big enough in some cases ie we
1941         can send more if LARGE_WRITE_X capability returned by the server and if
1942         our buffer is big enough or if we convert to iovecs on socket writes
1943         and eliminate the copy to the CIFS buffer */
1944         if (tcon->ses->capabilities & CAP_LARGE_WRITE_X) {
1945                 bytes_sent = min_t(const unsigned int, CIFSMaxBufSize, count);
1946         } else {
1947                 bytes_sent = (tcon->ses->server->maxBuf - MAX_CIFS_HDR_SIZE)
1948                          & ~0xFF;
1949         }
1950
1951         if (bytes_sent > count)
1952                 bytes_sent = count;
1953         pSMB->DataOffset =
1954                 cpu_to_le16(offsetof(struct smb_com_write_req, Data) - 4);
1955         if (buf)
1956                 memcpy(pSMB->Data, buf, bytes_sent);
1957         else if (ubuf) {
1958                 if (copy_from_user(pSMB->Data, ubuf, bytes_sent)) {
1959                         cifs_buf_release(pSMB);
1960                         return -EFAULT;
1961                 }
1962         } else if (count != 0) {
1963                 /* No buffer */
1964                 cifs_buf_release(pSMB);
1965                 return -EINVAL;
1966         } /* else setting file size with write of zero bytes */
1967         if (wct == 14)
1968                 byte_count = bytes_sent + 1; /* pad */
1969         else /* wct == 12 */
1970                 byte_count = bytes_sent + 5; /* bigger pad, smaller smb hdr */
1971
1972         pSMB->DataLengthLow = cpu_to_le16(bytes_sent & 0xFFFF);
1973         pSMB->DataLengthHigh = cpu_to_le16(bytes_sent >> 16);
1974         inc_rfc1001_len(pSMB, byte_count);
1975
1976         if (wct == 14)
1977                 pSMB->ByteCount = cpu_to_le16(byte_count);
1978         else { /* old style write has byte count 4 bytes earlier
1979                   so 4 bytes pad  */
1980                 struct smb_com_writex_req *pSMBW =
1981                         (struct smb_com_writex_req *)pSMB;
1982                 pSMBW->ByteCount = cpu_to_le16(byte_count);
1983         }
1984
1985         rc = SendReceive(xid, tcon->ses, (struct smb_hdr *) pSMB,
1986                          (struct smb_hdr *) pSMBr, &bytes_returned, long_op);
1987         cifs_stats_inc(&tcon->num_writes);
1988         if (rc) {
1989                 cFYI(1, "Send error in write = %d", rc);
1990         } else {
1991                 *nbytes = le16_to_cpu(pSMBr->CountHigh);
1992                 *nbytes = (*nbytes) << 16;
1993                 *nbytes += le16_to_cpu(pSMBr->Count);
1994
1995                 /*
1996                  * Mask off high 16 bits when bytes written as returned by the
1997                  * server is greater than bytes requested by the client. Some
1998                  * OS/2 servers are known to set incorrect CountHigh values.
1999                  */
2000                 if (*nbytes > count)
2001                         *nbytes &= 0xFFFF;
2002         }
2003
2004         cifs_buf_release(pSMB);
2005
2006         /* Note: On -EAGAIN error only caller can retry on handle based calls
2007                 since file handle passed in no longer valid */
2008
2009         return rc;
2010 }
2011
2012 void
2013 cifs_writedata_release(struct kref *refcount)
2014 {
2015         struct cifs_writedata *wdata = container_of(refcount,
2016                                         struct cifs_writedata, refcount);
2017
2018         if (wdata->cfile)
2019                 cifsFileInfo_put(wdata->cfile);
2020
2021         kfree(wdata);
2022 }
2023
2024 /*
2025  * Write failed with a retryable error. Resend the write request. It's also
2026  * possible that the page was redirtied so re-clean the page.
2027  */
2028 static void
2029 cifs_writev_requeue(struct cifs_writedata *wdata)
2030 {
2031         int i, rc;
2032         struct inode *inode = wdata->cfile->dentry->d_inode;
2033
2034         for (i = 0; i < wdata->nr_pages; i++) {
2035                 lock_page(wdata->pages[i]);
2036                 clear_page_dirty_for_io(wdata->pages[i]);
2037         }
2038
2039         do {
2040                 rc = cifs_async_writev(wdata);
2041         } while (rc == -EAGAIN);
2042
2043         for (i = 0; i < wdata->nr_pages; i++) {
2044                 if (rc != 0)
2045                         SetPageError(wdata->pages[i]);
2046                 unlock_page(wdata->pages[i]);
2047         }
2048
2049         mapping_set_error(inode->i_mapping, rc);
2050         kref_put(&wdata->refcount, cifs_writedata_release);
2051 }
2052
2053 static void
2054 cifs_writev_complete(struct work_struct *work)
2055 {
2056         struct cifs_writedata *wdata = container_of(work,
2057                                                 struct cifs_writedata, work);
2058         struct inode *inode = wdata->cfile->dentry->d_inode;
2059         int i = 0;
2060
2061         if (wdata->result == 0) {
2062                 cifs_update_eof(CIFS_I(inode), wdata->offset, wdata->bytes);
2063                 cifs_stats_bytes_written(tlink_tcon(wdata->cfile->tlink),
2064                                          wdata->bytes);
2065         } else if (wdata->sync_mode == WB_SYNC_ALL && wdata->result == -EAGAIN)
2066                 return cifs_writev_requeue(wdata);
2067
2068         for (i = 0; i < wdata->nr_pages; i++) {
2069                 struct page *page = wdata->pages[i];
2070                 if (wdata->result == -EAGAIN)
2071                         __set_page_dirty_nobuffers(page);
2072                 else if (wdata->result < 0)
2073                         SetPageError(page);
2074                 end_page_writeback(page);
2075                 page_cache_release(page);
2076         }
2077         if (wdata->result != -EAGAIN)
2078                 mapping_set_error(inode->i_mapping, wdata->result);
2079         kref_put(&wdata->refcount, cifs_writedata_release);
2080 }
2081
2082 struct cifs_writedata *
2083 cifs_writedata_alloc(unsigned int nr_pages)
2084 {
2085         struct cifs_writedata *wdata;
2086
2087         /* this would overflow */
2088         if (nr_pages == 0) {
2089                 cERROR(1, "%s: called with nr_pages == 0!", __func__);
2090                 return NULL;
2091         }
2092
2093         /* writedata + number of page pointers */
2094         wdata = kzalloc(sizeof(*wdata) +
2095                         sizeof(struct page *) * (nr_pages - 1), GFP_NOFS);
2096         if (wdata != NULL) {
2097                 INIT_WORK(&wdata->work, cifs_writev_complete);
2098                 kref_init(&wdata->refcount);
2099         }
2100         return wdata;
2101 }
2102
2103 /*
2104  * Check the midState and signature on received buffer (if any), and queue the
2105  * workqueue completion task.
2106  */
2107 static void
2108 cifs_writev_callback(struct mid_q_entry *mid)
2109 {
2110         struct cifs_writedata *wdata = mid->callback_data;
2111         struct cifs_tcon *tcon = tlink_tcon(wdata->cfile->tlink);
2112         unsigned int written;
2113         WRITE_RSP *smb = (WRITE_RSP *)mid->resp_buf;
2114
2115         switch (mid->midState) {
2116         case MID_RESPONSE_RECEIVED:
2117                 wdata->result = cifs_check_receive(mid, tcon->ses->server, 0);
2118                 if (wdata->result != 0)
2119                         break;
2120
2121                 written = le16_to_cpu(smb->CountHigh);
2122                 written <<= 16;
2123                 written += le16_to_cpu(smb->Count);
2124                 /*
2125                  * Mask off high 16 bits when bytes written as returned
2126                  * by the server is greater than bytes requested by the
2127                  * client. OS/2 servers are known to set incorrect
2128                  * CountHigh values.
2129                  */
2130                 if (written > wdata->bytes)
2131                         written &= 0xFFFF;
2132
2133                 if (written < wdata->bytes)
2134                         wdata->result = -ENOSPC;
2135                 else
2136                         wdata->bytes = written;
2137                 break;
2138         case MID_REQUEST_SUBMITTED:
2139         case MID_RETRY_NEEDED:
2140                 wdata->result = -EAGAIN;
2141                 break;
2142         default:
2143                 wdata->result = -EIO;
2144                 break;
2145         }
2146
2147         queue_work(system_nrt_wq, &wdata->work);
2148         DeleteMidQEntry(mid);
2149         atomic_dec(&tcon->ses->server->inFlight);
2150         wake_up(&tcon->ses->server->request_q);
2151 }
2152
2153 /* cifs_async_writev - send an async write, and set up mid to handle result */
2154 int
2155 cifs_async_writev(struct cifs_writedata *wdata)
2156 {
2157         int i, rc = -EACCES;
2158         WRITE_REQ *smb = NULL;
2159         int wct;
2160         struct cifs_tcon *tcon = tlink_tcon(wdata->cfile->tlink);
2161         struct inode *inode = wdata->cfile->dentry->d_inode;
2162         struct kvec *iov = NULL;
2163
2164         if (tcon->ses->capabilities & CAP_LARGE_FILES) {
2165                 wct = 14;
2166         } else {
2167                 wct = 12;
2168                 if (wdata->offset >> 32 > 0) {
2169                         /* can not handle big offset for old srv */
2170                         return -EIO;
2171                 }
2172         }
2173
2174         rc = small_smb_init(SMB_COM_WRITE_ANDX, wct, tcon, (void **)&smb);
2175         if (rc)
2176                 goto async_writev_out;
2177
2178         /* 1 iov per page + 1 for header */
2179         iov = kzalloc((wdata->nr_pages + 1) * sizeof(*iov), GFP_NOFS);
2180         if (iov == NULL) {
2181                 rc = -ENOMEM;
2182                 goto async_writev_out;
2183         }
2184
2185         smb->hdr.Pid = cpu_to_le16((__u16)wdata->cfile->pid);
2186         smb->hdr.PidHigh = cpu_to_le16((__u16)(wdata->cfile->pid >> 16));
2187
2188         smb->AndXCommand = 0xFF;        /* none */
2189         smb->Fid = wdata->cfile->netfid;
2190         smb->OffsetLow = cpu_to_le32(wdata->offset & 0xFFFFFFFF);
2191         if (wct == 14)
2192                 smb->OffsetHigh = cpu_to_le32(wdata->offset >> 32);
2193         smb->Reserved = 0xFFFFFFFF;
2194         smb->WriteMode = 0;
2195         smb->Remaining = 0;
2196
2197         smb->DataOffset =
2198             cpu_to_le16(offsetof(struct smb_com_write_req, Data) - 4);
2199
2200         /* 4 for RFC1001 length + 1 for BCC */
2201         iov[0].iov_len = be32_to_cpu(smb->hdr.smb_buf_length) + 4 + 1;
2202         iov[0].iov_base = smb;
2203
2204         /* marshal up the pages into iov array */
2205         cifs_kmap_lock();
2206         wdata->bytes = 0;
2207         for (i = 0; i < wdata->nr_pages; i++) {
2208                 iov[i + 1].iov_len = min(inode->i_size -
2209                                       page_offset(wdata->pages[i]),
2210                                         (loff_t)PAGE_CACHE_SIZE);
2211                 iov[i + 1].iov_base = kmap(wdata->pages[i]);
2212                 wdata->bytes += iov[i + 1].iov_len;
2213         }
2214         cifs_kmap_unlock();
2215
2216         cFYI(1, "async write at %llu %u bytes", wdata->offset, wdata->bytes);
2217
2218         smb->DataLengthLow = cpu_to_le16(wdata->bytes & 0xFFFF);
2219         smb->DataLengthHigh = cpu_to_le16(wdata->bytes >> 16);
2220
2221         if (wct == 14) {
2222                 inc_rfc1001_len(&smb->hdr, wdata->bytes + 1);
2223                 put_bcc(wdata->bytes + 1, &smb->hdr);
2224         } else {
2225                 /* wct == 12 */
2226                 struct smb_com_writex_req *smbw =
2227                                 (struct smb_com_writex_req *)smb;
2228                 inc_rfc1001_len(&smbw->hdr, wdata->bytes + 5);
2229                 put_bcc(wdata->bytes + 5, &smbw->hdr);
2230                 iov[0].iov_len += 4; /* pad bigger by four bytes */
2231         }
2232
2233         kref_get(&wdata->refcount);
2234         rc = cifs_call_async(tcon->ses->server, iov, wdata->nr_pages + 1,
2235                              NULL, cifs_writev_callback, wdata, false);
2236
2237         if (rc == 0)
2238                 cifs_stats_inc(&tcon->num_writes);
2239         else
2240                 kref_put(&wdata->refcount, cifs_writedata_release);
2241
2242         /* send is done, unmap pages */
2243         for (i = 0; i < wdata->nr_pages; i++)
2244                 kunmap(wdata->pages[i]);
2245
2246 async_writev_out:
2247         cifs_small_buf_release(smb);
2248         kfree(iov);
2249         return rc;
2250 }
2251
2252 int
2253 CIFSSMBWrite2(const int xid, struct cifs_io_parms *io_parms,
2254               unsigned int *nbytes, struct kvec *iov, int n_vec,
2255               const int long_op)
2256 {
2257         int rc = -EACCES;
2258         WRITE_REQ *pSMB = NULL;
2259         int wct;
2260         int smb_hdr_len;
2261         int resp_buf_type = 0;
2262         __u32 pid = io_parms->pid;
2263         __u16 netfid = io_parms->netfid;
2264         __u64 offset = io_parms->offset;
2265         struct cifs_tcon *tcon = io_parms->tcon;
2266         unsigned int count = io_parms->length;
2267
2268         *nbytes = 0;
2269
2270         cFYI(1, "write2 at %lld %d bytes", (long long)offset, count);
2271
2272         if (tcon->ses->capabilities & CAP_LARGE_FILES) {
2273                 wct = 14;
2274         } else {
2275                 wct = 12;
2276                 if ((offset >> 32) > 0) {
2277                         /* can not handle big offset for old srv */
2278                         return -EIO;
2279                 }
2280         }
2281         rc = small_smb_init(SMB_COM_WRITE_ANDX, wct, tcon, (void **) &pSMB);
2282         if (rc)
2283                 return rc;
2284
2285         pSMB->hdr.Pid = cpu_to_le16((__u16)pid);
2286         pSMB->hdr.PidHigh = cpu_to_le16((__u16)(pid >> 16));
2287
2288         /* tcon and ses pointer are checked in smb_init */
2289         if (tcon->ses->server == NULL)
2290                 return -ECONNABORTED;
2291
2292         pSMB->AndXCommand = 0xFF;       /* none */
2293         pSMB->Fid = netfid;
2294         pSMB->OffsetLow = cpu_to_le32(offset & 0xFFFFFFFF);
2295         if (wct == 14)
2296                 pSMB->OffsetHigh = cpu_to_le32(offset >> 32);
2297         pSMB->Reserved = 0xFFFFFFFF;
2298         pSMB->WriteMode = 0;
2299         pSMB->Remaining = 0;
2300
2301         pSMB->DataOffset =
2302             cpu_to_le16(offsetof(struct smb_com_write_req, Data) - 4);
2303
2304         pSMB->DataLengthLow = cpu_to_le16(count & 0xFFFF);
2305         pSMB->DataLengthHigh = cpu_to_le16(count >> 16);
2306         /* header + 1 byte pad */
2307         smb_hdr_len = be32_to_cpu(pSMB->hdr.smb_buf_length) + 1;
2308         if (wct == 14)
2309                 inc_rfc1001_len(pSMB, count + 1);
2310         else /* wct == 12 */
2311                 inc_rfc1001_len(pSMB, count + 5); /* smb data starts later */
2312         if (wct == 14)
2313                 pSMB->ByteCount = cpu_to_le16(count + 1);
2314         else /* wct == 12 */ /* bigger pad, smaller smb hdr, keep offset ok */ {
2315                 struct smb_com_writex_req *pSMBW =
2316                                 (struct smb_com_writex_req *)pSMB;
2317                 pSMBW->ByteCount = cpu_to_le16(count + 5);
2318         }
2319         iov[0].iov_base = pSMB;
2320         if (wct == 14)
2321                 iov[0].iov_len = smb_hdr_len + 4;
2322         else /* wct == 12 pad bigger by four bytes */
2323                 iov[0].iov_len = smb_hdr_len + 8;
2324
2325
2326         rc = SendReceive2(xid, tcon->ses, iov, n_vec + 1, &resp_buf_type,
2327                           long_op);
2328         cifs_stats_inc(&tcon->num_writes);
2329         if (rc) {
2330                 cFYI(1, "Send error Write2 = %d", rc);
2331         } else if (resp_buf_type == 0) {
2332                 /* presumably this can not happen, but best to be safe */
2333                 rc = -EIO;
2334         } else {
2335                 WRITE_RSP *pSMBr = (WRITE_RSP *)iov[0].iov_base;
2336                 *nbytes = le16_to_cpu(pSMBr->CountHigh);
2337                 *nbytes = (*nbytes) << 16;
2338                 *nbytes += le16_to_cpu(pSMBr->Count);
2339
2340                 /*
2341                  * Mask off high 16 bits when bytes written as returned by the
2342                  * server is greater than bytes requested by the client. OS/2
2343                  * servers are known to set incorrect CountHigh values.
2344                  */
2345                 if (*nbytes > count)
2346                         *nbytes &= 0xFFFF;
2347         }
2348
2349 /*      cifs_small_buf_release(pSMB); */ /* Freed earlier now in SendReceive2 */
2350         if (resp_buf_type == CIFS_SMALL_BUFFER)
2351                 cifs_small_buf_release(iov[0].iov_base);
2352         else if (resp_buf_type == CIFS_LARGE_BUFFER)
2353                 cifs_buf_release(iov[0].iov_base);
2354
2355         /* Note: On -EAGAIN error only caller can retry on handle based calls
2356                 since file handle passed in no longer valid */
2357
2358         return rc;
2359 }
2360
2361 int cifs_lockv(const int xid, struct cifs_tcon *tcon, const __u16 netfid,
2362                const __u8 lock_type, const __u32 num_unlock,
2363                const __u32 num_lock, LOCKING_ANDX_RANGE *buf)
2364 {
2365         int rc = 0;
2366         LOCK_REQ *pSMB = NULL;
2367         struct kvec iov[2];
2368         int resp_buf_type;
2369         __u16 count;
2370
2371         cFYI(1, "cifs_lockv num lock %d num unlock %d", num_lock, num_unlock);
2372
2373         rc = small_smb_init(SMB_COM_LOCKING_ANDX, 8, tcon, (void **) &pSMB);
2374         if (rc)
2375                 return rc;
2376
2377         pSMB->Timeout = 0;
2378         pSMB->NumberOfLocks = cpu_to_le16(num_lock);
2379         pSMB->NumberOfUnlocks = cpu_to_le16(num_unlock);
2380         pSMB->LockType = lock_type;
2381         pSMB->AndXCommand = 0xFF; /* none */
2382         pSMB->Fid = netfid; /* netfid stays le */
2383
2384         count = (num_unlock + num_lock) * sizeof(LOCKING_ANDX_RANGE);
2385         inc_rfc1001_len(pSMB, count);
2386         pSMB->ByteCount = cpu_to_le16(count);
2387
2388         iov[0].iov_base = (char *)pSMB;
2389         iov[0].iov_len = be32_to_cpu(pSMB->hdr.smb_buf_length) + 4 -
2390                          (num_unlock + num_lock) * sizeof(LOCKING_ANDX_RANGE);
2391         iov[1].iov_base = (char *)buf;
2392         iov[1].iov_len = (num_unlock + num_lock) * sizeof(LOCKING_ANDX_RANGE);
2393
2394         cifs_stats_inc(&tcon->num_locks);
2395         rc = SendReceive2(xid, tcon->ses, iov, 2, &resp_buf_type, CIFS_NO_RESP);
2396         if (rc)
2397                 cFYI(1, "Send error in cifs_lockv = %d", rc);
2398
2399         return rc;
2400 }
2401
2402 int
2403 CIFSSMBLock(const int xid, struct cifs_tcon *tcon,
2404             const __u16 smb_file_id, const __u32 netpid, const __u64 len,
2405             const __u64 offset, const __u32 numUnlock,
2406             const __u32 numLock, const __u8 lockType,
2407             const bool waitFlag, const __u8 oplock_level)
2408 {
2409         int rc = 0;
2410         LOCK_REQ *pSMB = NULL;
2411 /*      LOCK_RSP *pSMBr = NULL; */ /* No response data other than rc to parse */
2412         int bytes_returned;
2413         int timeout = 0;
2414         __u16 count;
2415
2416         cFYI(1, "CIFSSMBLock timeout %d numLock %d", (int)waitFlag, numLock);
2417         rc = small_smb_init(SMB_COM_LOCKING_ANDX, 8, tcon, (void **) &pSMB);
2418
2419         if (rc)
2420                 return rc;
2421
2422         if (lockType == LOCKING_ANDX_OPLOCK_RELEASE) {
2423                 timeout = CIFS_ASYNC_OP; /* no response expected */
2424                 pSMB->Timeout = 0;
2425         } else if (waitFlag) {
2426                 timeout = CIFS_BLOCKING_OP; /* blocking operation, no timeout */
2427                 pSMB->Timeout = cpu_to_le32(-1);/* blocking - do not time out */
2428         } else {
2429                 pSMB->Timeout = 0;
2430         }
2431
2432         pSMB->NumberOfLocks = cpu_to_le16(numLock);
2433         pSMB->NumberOfUnlocks = cpu_to_le16(numUnlock);
2434         pSMB->LockType = lockType;
2435         pSMB->OplockLevel = oplock_level;
2436         pSMB->AndXCommand = 0xFF;       /* none */
2437         pSMB->Fid = smb_file_id; /* netfid stays le */
2438
2439         if ((numLock != 0) || (numUnlock != 0)) {
2440                 pSMB->Locks[0].Pid = cpu_to_le16(netpid);
2441                 /* BB where to store pid high? */
2442                 pSMB->Locks[0].LengthLow = cpu_to_le32((u32)len);
2443                 pSMB->Locks[0].LengthHigh = cpu_to_le32((u32)(len>>32));
2444                 pSMB->Locks[0].OffsetLow = cpu_to_le32((u32)offset);
2445                 pSMB->Locks[0].OffsetHigh = cpu_to_le32((u32)(offset>>32));
2446                 count = sizeof(LOCKING_ANDX_RANGE);
2447         } else {
2448                 /* oplock break */
2449                 count = 0;
2450         }
2451         inc_rfc1001_len(pSMB, count);
2452         pSMB->ByteCount = cpu_to_le16(count);
2453
2454         if (waitFlag) {
2455                 rc = SendReceiveBlockingLock(xid, tcon, (struct smb_hdr *) pSMB,
2456                         (struct smb_hdr *) pSMB, &bytes_returned);
2457                 cifs_small_buf_release(pSMB);
2458         } else {
2459                 rc = SendReceiveNoRsp(xid, tcon->ses, (struct smb_hdr *)pSMB,
2460                                       timeout);
2461                 /* SMB buffer freed by function above */
2462         }
2463         cifs_stats_inc(&tcon->num_locks);
2464         if (rc)
2465                 cFYI(1, "Send error in Lock = %d", rc);
2466
2467         /* Note: On -EAGAIN error only caller can retry on handle based calls
2468         since file handle passed in no longer valid */
2469         return rc;
2470 }
2471
2472 int
2473 CIFSSMBPosixLock(const int xid, struct cifs_tcon *tcon,
2474                 const __u16 smb_file_id, const __u32 netpid, const int get_flag,
2475                 const __u64 len, struct file_lock *pLockData,
2476                 const __u16 lock_type, const bool waitFlag)
2477 {
2478         struct smb_com_transaction2_sfi_req *pSMB  = NULL;
2479         struct smb_com_transaction2_sfi_rsp *pSMBr = NULL;
2480         struct cifs_posix_lock *parm_data;
2481         int rc = 0;
2482         int timeout = 0;
2483         int bytes_returned = 0;
2484         int resp_buf_type = 0;
2485         __u16 params, param_offset, offset, byte_count, count;
2486         struct kvec iov[1];
2487
2488         cFYI(1, "Posix Lock");
2489
2490         if (pLockData == NULL)
2491                 return -EINVAL;
2492
2493         rc = small_smb_init(SMB_COM_TRANSACTION2, 15, tcon, (void **) &pSMB);
2494
2495         if (rc)
2496                 return rc;
2497
2498         pSMBr = (struct smb_com_transaction2_sfi_rsp *)pSMB;
2499
2500         params = 6;
2501         pSMB->MaxSetupCount = 0;
2502         pSMB->Reserved = 0;
2503         pSMB->Flags = 0;
2504         pSMB->Reserved2 = 0;
2505         param_offset = offsetof(struct smb_com_transaction2_sfi_req, Fid) - 4;
2506         offset = param_offset + params;
2507
2508         count = sizeof(struct cifs_posix_lock);
2509         pSMB->MaxParameterCount = cpu_to_le16(2);
2510         pSMB->MaxDataCount = cpu_to_le16(1000); /* BB find max SMB from sess */
2511         pSMB->SetupCount = 1;
2512         pSMB->Reserved3 = 0;
2513         if (get_flag)
2514                 pSMB->SubCommand = cpu_to_le16(TRANS2_QUERY_FILE_INFORMATION);
2515         else
2516                 pSMB->SubCommand = cpu_to_le16(TRANS2_SET_FILE_INFORMATION);
2517         byte_count = 3 /* pad */  + params + count;
2518         pSMB->DataCount = cpu_to_le16(count);
2519         pSMB->ParameterCount = cpu_to_le16(params);
2520         pSMB->TotalDataCount = pSMB->DataCount;
2521         pSMB->TotalParameterCount = pSMB->ParameterCount;
2522         pSMB->ParameterOffset = cpu_to_le16(param_offset);
2523         parm_data = (struct cifs_posix_lock *)
2524                         (((char *) &pSMB->hdr.Protocol) + offset);
2525
2526         parm_data->lock_type = cpu_to_le16(lock_type);
2527         if (waitFlag) {
2528                 timeout = CIFS_BLOCKING_OP; /* blocking operation, no timeout */
2529                 parm_data->lock_flags = cpu_to_le16(1);
2530                 pSMB->Timeout = cpu_to_le32(-1);
2531         } else
2532                 pSMB->Timeout = 0;
2533
2534         parm_data->pid = cpu_to_le32(netpid);
2535         parm_data->start = cpu_to_le64(pLockData->fl_start);
2536         parm_data->length = cpu_to_le64(len);  /* normalize negative numbers */
2537
2538         pSMB->DataOffset = cpu_to_le16(offset);
2539         pSMB->Fid = smb_file_id;
2540         pSMB->InformationLevel = cpu_to_le16(SMB_SET_POSIX_LOCK);
2541         pSMB->Reserved4 = 0;
2542         inc_rfc1001_len(pSMB, byte_count);
2543         pSMB->ByteCount = cpu_to_le16(byte_count);
2544         if (waitFlag) {
2545                 rc = SendReceiveBlockingLock(xid, tcon, (struct smb_hdr *) pSMB,
2546                         (struct smb_hdr *) pSMBr, &bytes_returned);
2547         } else {
2548                 iov[0].iov_base = (char *)pSMB;
2549                 iov[0].iov_len = be32_to_cpu(pSMB->hdr.smb_buf_length) + 4;
2550                 rc = SendReceive2(xid, tcon->ses, iov, 1 /* num iovecs */,
2551                                 &resp_buf_type, timeout);
2552                 pSMB = NULL; /* request buf already freed by SendReceive2. Do
2553                                 not try to free it twice below on exit */
2554                 pSMBr = (struct smb_com_transaction2_sfi_rsp *)iov[0].iov_base;
2555         }
2556
2557         if (rc) {
2558                 cFYI(1, "Send error in Posix Lock = %d", rc);
2559         } else if (get_flag) {
2560                 /* lock structure can be returned on get */
2561                 __u16 data_offset;
2562                 __u16 data_count;
2563                 rc = validate_t2((struct smb_t2_rsp *)pSMBr);
2564
2565                 if (rc || get_bcc(&pSMBr->hdr) < sizeof(*parm_data)) {
2566                         rc = -EIO;      /* bad smb */
2567                         goto plk_err_exit;
2568                 }
2569                 data_offset = le16_to_cpu(pSMBr->t2.DataOffset);
2570                 data_count  = le16_to_cpu(pSMBr->t2.DataCount);
2571                 if (data_count < sizeof(struct cifs_posix_lock)) {
2572                         rc = -EIO;
2573                         goto plk_err_exit;
2574                 }
2575                 parm_data = (struct cifs_posix_lock *)
2576                         ((char *)&pSMBr->hdr.Protocol + data_offset);
2577                 if (parm_data->lock_type == __constant_cpu_to_le16(CIFS_UNLCK))
2578                         pLockData->fl_type = F_UNLCK;
2579                 else {
2580                         if (parm_data->lock_type ==
2581                                         __constant_cpu_to_le16(CIFS_RDLCK))
2582                                 pLockData->fl_type = F_RDLCK;
2583                         else if (parm_data->lock_type ==
2584                                         __constant_cpu_to_le16(CIFS_WRLCK))
2585                                 pLockData->fl_type = F_WRLCK;
2586
2587                         pLockData->fl_start = le64_to_cpu(parm_data->start);
2588                         pLockData->fl_end = pLockData->fl_start +
2589                                         le64_to_cpu(parm_data->length) - 1;
2590                         pLockData->fl_pid = le32_to_cpu(parm_data->pid);
2591                 }
2592         }
2593
2594 plk_err_exit:
2595         if (pSMB)
2596                 cifs_small_buf_release(pSMB);
2597
2598         if (resp_buf_type == CIFS_SMALL_BUFFER)
2599                 cifs_small_buf_release(iov[0].iov_base);
2600         else if (resp_buf_type == CIFS_LARGE_BUFFER)
2601                 cifs_buf_release(iov[0].iov_base);
2602
2603         /* Note: On -EAGAIN error only caller can retry on handle based calls
2604            since file handle passed in no longer valid */
2605
2606         return rc;
2607 }
2608
2609
2610 int
2611 CIFSSMBClose(const int xid, struct cifs_tcon *tcon, int smb_file_id)
2612 {
2613         int rc = 0;
2614         CLOSE_REQ *pSMB = NULL;
2615         cFYI(1, "In CIFSSMBClose");
2616
2617 /* do not retry on dead session on close */
2618         rc = small_smb_init(SMB_COM_CLOSE, 3, tcon, (void **) &pSMB);
2619         if (rc == -EAGAIN)
2620                 return 0;
2621         if (rc)
2622                 return rc;
2623
2624         pSMB->FileID = (__u16) smb_file_id;
2625         pSMB->LastWriteTime = 0xFFFFFFFF;
2626         pSMB->ByteCount = 0;
2627         rc = SendReceiveNoRsp(xid, tcon->ses, (struct smb_hdr *) pSMB, 0);
2628         cifs_stats_inc(&tcon->num_closes);
2629         if (rc) {
2630                 if (rc != -EINTR) {
2631                         /* EINTR is expected when user ctl-c to kill app */
2632                         cERROR(1, "Send error in Close = %d", rc);
2633                 }
2634         }
2635
2636         /* Since session is dead, file will be closed on server already */
2637         if (rc == -EAGAIN)
2638                 rc = 0;
2639
2640         return rc;
2641 }
2642
2643 int
2644 CIFSSMBFlush(const int xid, struct cifs_tcon *tcon, int smb_file_id)
2645 {
2646         int rc = 0;
2647         FLUSH_REQ *pSMB = NULL;
2648         cFYI(1, "In CIFSSMBFlush");
2649
2650         rc = small_smb_init(SMB_COM_FLUSH, 1, tcon, (void **) &pSMB);
2651         if (rc)
2652                 return rc;
2653
2654         pSMB->FileID = (__u16) smb_file_id;
2655         pSMB->ByteCount = 0;
2656         rc = SendReceiveNoRsp(xid, tcon->ses, (struct smb_hdr *) pSMB, 0);
2657         cifs_stats_inc(&tcon->num_flushes);
2658         if (rc)
2659                 cERROR(1, "Send error in Flush = %d", rc);
2660
2661         return rc;
2662 }
2663
2664 int
2665 CIFSSMBRename(const int xid, struct cifs_tcon *tcon,
2666               const char *fromName, const char *toName,
2667               const struct nls_table *nls_codepage, int remap)
2668 {
2669         int rc = 0;
2670         RENAME_REQ *pSMB = NULL;
2671         RENAME_RSP *pSMBr = NULL;
2672         int bytes_returned;
2673         int name_len, name_len2;
2674         __u16 count;
2675
2676         cFYI(1, "In CIFSSMBRename");
2677 renameRetry:
2678         rc = smb_init(SMB_COM_RENAME, 1, tcon, (void **) &pSMB,
2679                       (void **) &pSMBr);
2680         if (rc)
2681                 return rc;
2682
2683         pSMB->BufferFormat = 0x04;
2684         pSMB->SearchAttributes =
2685             cpu_to_le16(ATTR_READONLY | ATTR_HIDDEN | ATTR_SYSTEM |
2686                         ATTR_DIRECTORY);
2687
2688         if (pSMB->hdr.Flags2 & SMBFLG2_UNICODE) {
2689                 name_len =
2690                     cifsConvertToUCS((__le16 *) pSMB->OldFileName, fromName,
2691                                      PATH_MAX, nls_codepage, remap);
2692                 name_len++;     /* trailing null */
2693                 name_len *= 2;
2694                 pSMB->OldFileName[name_len] = 0x04;     /* pad */
2695         /* protocol requires ASCII signature byte on Unicode string */
2696                 pSMB->OldFileName[name_len + 1] = 0x00;
2697                 name_len2 =
2698                     cifsConvertToUCS((__le16 *)&pSMB->OldFileName[name_len + 2],
2699                                      toName, PATH_MAX, nls_codepage, remap);
2700                 name_len2 += 1 /* trailing null */  + 1 /* Signature word */ ;
2701                 name_len2 *= 2; /* convert to bytes */
2702         } else {        /* BB improve the check for buffer overruns BB */
2703                 name_len = strnlen(fromName, PATH_MAX);
2704                 name_len++;     /* trailing null */
2705                 strncpy(pSMB->OldFileName, fromName, name_len);
2706                 name_len2 = strnlen(toName, PATH_MAX);
2707                 name_len2++;    /* trailing null */
2708                 pSMB->OldFileName[name_len] = 0x04;  /* 2nd buffer format */
2709                 strncpy(&pSMB->OldFileName[name_len + 1], toName, name_len2);
2710                 name_len2++;    /* trailing null */
2711                 name_len2++;    /* signature byte */
2712         }
2713
2714         count = 1 /* 1st signature byte */  + name_len + name_len2;
2715         inc_rfc1001_len(pSMB, count);
2716         pSMB->ByteCount = cpu_to_le16(count);
2717
2718         rc = SendReceive(xid, tcon->ses, (struct smb_hdr *) pSMB,
2719                          (struct smb_hdr *) pSMBr, &bytes_returned, 0);
2720         cifs_stats_inc(&tcon->num_renames);
2721         if (rc)
2722                 cFYI(1, "Send error in rename = %d", rc);
2723
2724         cifs_buf_release(pSMB);
2725
2726         if (rc == -EAGAIN)
2727                 goto renameRetry;
2728
2729         return rc;
2730 }
2731
2732 int CIFSSMBRenameOpenFile(const int xid, struct cifs_tcon *pTcon,
2733                 int netfid, const char *target_name,
2734                 const struct nls_table *nls_codepage, int remap)
2735 {
2736         struct smb_com_transaction2_sfi_req *pSMB  = NULL;
2737         struct smb_com_transaction2_sfi_rsp *pSMBr = NULL;
2738         struct set_file_rename *rename_info;
2739         char *data_offset;
2740         char dummy_string[30];
2741         int rc = 0;
2742         int bytes_returned = 0;
2743         int len_of_str;
2744         __u16 params, param_offset, offset, count, byte_count;
2745
2746         cFYI(1, "Rename to File by handle");
2747         rc = smb_init(SMB_COM_TRANSACTION2, 15, pTcon, (void **) &pSMB,
2748                         (void **) &pSMBr);
2749         if (rc)
2750                 return rc;
2751
2752         params = 6;
2753         pSMB->MaxSetupCount = 0;
2754         pSMB->Reserved = 0;
2755         pSMB->Flags = 0;
2756         pSMB->Timeout = 0;
2757         pSMB->Reserved2 = 0;
2758         param_offset = offsetof(struct smb_com_transaction2_sfi_req, Fid) - 4;
2759         offset = param_offset + params;
2760
2761         data_offset = (char *) (&pSMB->hdr.Protocol) + offset;
2762         rename_info = (struct set_file_rename *) data_offset;
2763         pSMB->MaxParameterCount = cpu_to_le16(2);
2764         pSMB->MaxDataCount = cpu_to_le16(1000); /* BB find max SMB from sess */
2765         pSMB->SetupCount = 1;
2766         pSMB->Reserved3 = 0;
2767         pSMB->SubCommand = cpu_to_le16(TRANS2_SET_FILE_INFORMATION);
2768         byte_count = 3 /* pad */  + params;
2769         pSMB->ParameterCount = cpu_to_le16(params);
2770         pSMB->TotalParameterCount = pSMB->ParameterCount;
2771         pSMB->ParameterOffset = cpu_to_le16(param_offset);
2772         pSMB->DataOffset = cpu_to_le16(offset);
2773         /* construct random name ".cifs_tmp<inodenum><mid>" */
2774         rename_info->overwrite = cpu_to_le32(1);
2775         rename_info->root_fid  = 0;
2776         /* unicode only call */
2777         if (target_name == NULL) {
2778                 sprintf(dummy_string, "cifs%x", pSMB->hdr.Mid);
2779                 len_of_str = cifsConvertToUCS((__le16 *)rename_info->target_name,
2780                                         dummy_string, 24, nls_codepage, remap);
2781         } else {
2782                 len_of_str = cifsConvertToUCS((__le16 *)rename_info->target_name,
2783                                         target_name, PATH_MAX, nls_codepage,
2784                                         remap);
2785         }
2786         rename_info->target_name_len = cpu_to_le32(2 * len_of_str);
2787         count = 12 /* sizeof(struct set_file_rename) */ + (2 * len_of_str);
2788         byte_count += count;
2789         pSMB->DataCount = cpu_to_le16(count);
2790         pSMB->TotalDataCount = pSMB->DataCount;
2791         pSMB->Fid = netfid;
2792         pSMB->InformationLevel =
2793                 cpu_to_le16(SMB_SET_FILE_RENAME_INFORMATION);
2794         pSMB->Reserved4 = 0;
2795         inc_rfc1001_len(pSMB, byte_count);
2796         pSMB->ByteCount = cpu_to_le16(byte_count);
2797         rc = SendReceive(xid, pTcon->ses, (struct smb_hdr *) pSMB,
2798                          (struct smb_hdr *) pSMBr, &bytes_returned, 0);
2799         cifs_stats_inc(&pTcon->num_t2renames);
2800         if (rc)
2801                 cFYI(1, "Send error in Rename (by file handle) = %d", rc);
2802
2803         cifs_buf_release(pSMB);
2804
2805         /* Note: On -EAGAIN error only caller can retry on handle based calls
2806                 since file handle passed in no longer valid */
2807
2808         return rc;
2809 }
2810
2811 int
2812 CIFSSMBCopy(const int xid, struct cifs_tcon *tcon, const char *fromName,
2813             const __u16 target_tid, const char *toName, const int flags,
2814             const struct nls_table *nls_codepage, int remap)
2815 {
2816         int rc = 0;
2817         COPY_REQ *pSMB = NULL;
2818         COPY_RSP *pSMBr = NULL;
2819         int bytes_returned;
2820         int name_len, name_len2;
2821         __u16 count;
2822
2823         cFYI(1, "In CIFSSMBCopy");
2824 copyRetry:
2825         rc = smb_init(SMB_COM_COPY, 1, tcon, (void **) &pSMB,
2826                         (void **) &pSMBr);
2827         if (rc)
2828                 return rc;
2829
2830         pSMB->BufferFormat = 0x04;
2831         pSMB->Tid2 = target_tid;
2832
2833         pSMB->Flags = cpu_to_le16(flags & COPY_TREE);
2834
2835         if (pSMB->hdr.Flags2 & SMBFLG2_UNICODE) {
2836                 name_len = cifsConvertToUCS((__le16 *) pSMB->OldFileName,
2837                                             fromName, PATH_MAX, nls_codepage,
2838                                             remap);
2839                 name_len++;     /* trailing null */
2840                 name_len *= 2;
2841                 pSMB->OldFileName[name_len] = 0x04;     /* pad */
2842                 /* protocol requires ASCII signature byte on Unicode string */
2843                 pSMB->OldFileName[name_len + 1] = 0x00;
2844                 name_len2 =
2845                     cifsConvertToUCS((__le16 *)&pSMB->OldFileName[name_len + 2],
2846                                 toName, PATH_MAX, nls_codepage, remap);
2847                 name_len2 += 1 /* trailing null */  + 1 /* Signature word */ ;
2848                 name_len2 *= 2; /* convert to bytes */
2849         } else {        /* BB improve the check for buffer overruns BB */
2850                 name_len = strnlen(fromName, PATH_MAX);
2851                 name_len++;     /* trailing null */
2852                 strncpy(pSMB->OldFileName, fromName, name_len);
2853                 name_len2 = strnlen(toName, PATH_MAX);
2854                 name_len2++;    /* trailing null */
2855                 pSMB->OldFileName[name_len] = 0x04;  /* 2nd buffer format */
2856                 strncpy(&pSMB->OldFileName[name_len + 1], toName, name_len2);
2857                 name_len2++;    /* trailing null */
2858                 name_len2++;    /* signature byte */
2859         }
2860
2861         count = 1 /* 1st signature byte */  + name_len + name_len2;
2862         inc_rfc1001_len(pSMB, count);
2863         pSMB->ByteCount = cpu_to_le16(count);
2864
2865         rc = SendReceive(xid, tcon->ses, (struct smb_hdr *) pSMB,
2866                 (struct smb_hdr *) pSMBr, &bytes_returned, 0);
2867         if (rc) {
2868                 cFYI(1, "Send error in copy = %d with %d files copied",
2869                         rc, le16_to_cpu(pSMBr->CopyCount));
2870         }
2871         cifs_buf_release(pSMB);
2872
2873         if (rc == -EAGAIN)
2874                 goto copyRetry;
2875
2876         return rc;
2877 }
2878
2879 int
2880 CIFSUnixCreateSymLink(const int xid, struct cifs_tcon *tcon,
2881                       const char *fromName, const char *toName,
2882                       const struct nls_table *nls_codepage)
2883 {
2884         TRANSACTION2_SPI_REQ *pSMB = NULL;
2885         TRANSACTION2_SPI_RSP *pSMBr = NULL;
2886         char *data_offset;
2887         int name_len;
2888         int name_len_target;
2889         int rc = 0;
2890         int bytes_returned = 0;
2891         __u16 params, param_offset, offset, byte_count;
2892
2893         cFYI(1, "In Symlink Unix style");
2894 createSymLinkRetry:
2895         rc = smb_init(SMB_COM_TRANSACTION2, 15, tcon, (void **) &pSMB,
2896                       (void **) &pSMBr);
2897         if (rc)
2898                 return rc;
2899
2900         if (pSMB->hdr.Flags2 & SMBFLG2_UNICODE) {
2901                 name_len =
2902                     cifs_strtoUCS((__le16 *) pSMB->FileName, fromName, PATH_MAX
2903                                   /* find define for this maxpathcomponent */
2904                                   , nls_codepage);
2905                 name_len++;     /* trailing null */
2906                 name_len *= 2;
2907
2908         } else {        /* BB improve the check for buffer overruns BB */
2909                 name_len = strnlen(fromName, PATH_MAX);
2910                 name_len++;     /* trailing null */
2911                 strncpy(pSMB->FileName, fromName, name_len);
2912         }
2913         params = 6 + name_len;
2914         pSMB->MaxSetupCount = 0;
2915         pSMB->Reserved = 0;
2916         pSMB->Flags = 0;
2917         pSMB->Timeout = 0;
2918         pSMB->Reserved2 = 0;
2919         param_offset = offsetof(struct smb_com_transaction2_spi_req,
2920                                 InformationLevel) - 4;
2921         offset = param_offset + params;
2922
2923         data_offset = (char *) (&pSMB->hdr.Protocol) + offset;
2924         if (pSMB->hdr.Flags2 & SMBFLG2_UNICODE) {
2925                 name_len_target =
2926                     cifs_strtoUCS((__le16 *) data_offset, toName, PATH_MAX
2927                                   /* find define for this maxpathcomponent */
2928                                   , nls_codepage);
2929                 name_len_target++;      /* trailing null */
2930                 name_len_target *= 2;
2931         } else {        /* BB improve the check for buffer overruns BB */
2932                 name_len_target = strnlen(toName, PATH_MAX);
2933                 name_len_target++;      /* trailing null */
2934                 strncpy(data_offset, toName, name_len_target);
2935         }
2936
2937         pSMB->MaxParameterCount = cpu_to_le16(2);
2938         /* BB find exact max on data count below from sess */
2939         pSMB->MaxDataCount = cpu_to_le16(1000);
2940         pSMB->SetupCount = 1;
2941         pSMB->Reserved3 = 0;
2942         pSMB->SubCommand = cpu_to_le16(TRANS2_SET_PATH_INFORMATION);
2943         byte_count = 3 /* pad */  + params + name_len_target;
2944         pSMB->DataCount = cpu_to_le16(name_len_target);
2945         pSMB->ParameterCount = cpu_to_le16(params);
2946         pSMB->TotalDataCount = pSMB->DataCount;
2947         pSMB->TotalParameterCount = pSMB->ParameterCount;
2948         pSMB->ParameterOffset = cpu_to_le16(param_offset);
2949         pSMB->DataOffset = cpu_to_le16(offset);
2950         pSMB->InformationLevel = cpu_to_le16(SMB_SET_FILE_UNIX_LINK);
2951         pSMB->Reserved4 = 0;
2952         inc_rfc1001_len(pSMB, byte_count);
2953         pSMB->ByteCount = cpu_to_le16(byte_count);
2954         rc = SendReceive(xid, tcon->ses, (struct smb_hdr *) pSMB,
2955                          (struct smb_hdr *) pSMBr, &bytes_returned, 0);
2956         cifs_stats_inc(&tcon->num_symlinks);
2957         if (rc)
2958                 cFYI(1, "Send error in SetPathInfo create symlink = %d", rc);
2959
2960         cifs_buf_release(pSMB);
2961
2962         if (rc == -EAGAIN)
2963                 goto createSymLinkRetry;
2964
2965         return rc;
2966 }
2967
2968 int
2969 CIFSUnixCreateHardLink(const int xid, struct cifs_tcon *tcon,
2970                        const char *fromName, const char *toName,
2971                        const struct nls_table *nls_codepage, int remap)
2972 {
2973         TRANSACTION2_SPI_REQ *pSMB = NULL;
2974         TRANSACTION2_SPI_RSP *pSMBr = NULL;
2975         char *data_offset;
2976         int name_len;
2977         int name_len_target;
2978         int rc = 0;
2979         int bytes_returned = 0;
2980         __u16 params, param_offset, offset, byte_count;
2981
2982         cFYI(1, "In Create Hard link Unix style");
2983 createHardLinkRetry:
2984         rc = smb_init(SMB_COM_TRANSACTION2, 15, tcon, (void **) &pSMB,
2985                       (void **) &pSMBr);
2986         if (rc)
2987                 return rc;
2988
2989         if (pSMB->hdr.Flags2 & SMBFLG2_UNICODE) {
2990                 name_len = cifsConvertToUCS((__le16 *) pSMB->FileName, toName,
2991                                             PATH_MAX, nls_codepage, remap);
2992                 name_len++;     /* trailing null */
2993                 name_len *= 2;
2994
2995         } else {        /* BB improve the check for buffer overruns BB */
2996                 name_len = strnlen(toName, PATH_MAX);
2997                 name_len++;     /* trailing null */
2998                 strncpy(pSMB->FileName, toName, name_len);
2999         }
3000         params = 6 + name_len;
3001         pSMB->MaxSetupCount = 0;
3002         pSMB->Reserved = 0;
3003         pSMB->Flags = 0;
3004         pSMB->Timeout = 0;
3005         pSMB->Reserved2 = 0;
3006         param_offset = offsetof(struct smb_com_transaction2_spi_req,
3007                                 InformationLevel) - 4;
3008         offset = param_offset + params;
3009
3010         data_offset = (char *) (&pSMB->hdr.Protocol) + offset;
3011         if (pSMB->hdr.Flags2 & SMBFLG2_UNICODE) {
3012                 name_len_target =
3013                     cifsConvertToUCS((__le16 *) data_offset, fromName, PATH_MAX,
3014                                      nls_codepage, remap);
3015                 name_len_target++;      /* trailing null */
3016                 name_len_target *= 2;
3017         } else {        /* BB improve the check for buffer overruns BB */
3018                 name_len_target = strnlen(fromName, PATH_MAX);
3019                 name_len_target++;      /* trailing null */
3020                 strncpy(data_offset, fromName, name_len_target);
3021         }
3022
3023         pSMB->MaxParameterCount = cpu_to_le16(2);
3024         /* BB find exact max on data count below from sess*/
3025         pSMB->MaxDataCount = cpu_to_le16(1000);
3026         pSMB->SetupCount = 1;
3027         pSMB->Reserved3 = 0;
3028         pSMB->SubCommand = cpu_to_le16(TRANS2_SET_PATH_INFORMATION);
3029         byte_count = 3 /* pad */  + params + name_len_target;
3030         pSMB->ParameterCount = cpu_to_le16(params);
3031         pSMB->TotalParameterCount = pSMB->ParameterCount;
3032         pSMB->DataCount = cpu_to_le16(name_len_target);
3033         pSMB->TotalDataCount = pSMB->DataCount;
3034         pSMB->ParameterOffset = cpu_to_le16(param_offset);
3035         pSMB->DataOffset = cpu_to_le16(offset);
3036         pSMB->InformationLevel = cpu_to_le16(SMB_SET_FILE_UNIX_HLINK);
3037         pSMB->Reserved4 = 0;
3038         inc_rfc1001_len(pSMB, byte_count);
3039         pSMB->ByteCount = cpu_to_le16(byte_count);
3040         rc = SendReceive(xid, tcon->ses, (struct smb_hdr *) pSMB,
3041                          (struct smb_hdr *) pSMBr, &bytes_returned, 0);
3042         cifs_stats_inc(&tcon->num_hardlinks);
3043         if (rc)
3044                 cFYI(1, "Send error in SetPathInfo (hard link) = %d", rc);
3045
3046         cifs_buf_release(pSMB);
3047         if (rc == -EAGAIN)
3048                 goto createHardLinkRetry;
3049
3050         return rc;
3051 }
3052
3053 int
3054 CIFSCreateHardLink(const int xid, struct cifs_tcon *tcon,
3055                    const char *fromName, const char *toName,
3056                    const struct nls_table *nls_codepage, int remap)
3057 {
3058         int rc = 0;
3059         NT_RENAME_REQ *pSMB = NULL;
3060         RENAME_RSP *pSMBr = NULL;
3061         int bytes_returned;
3062         int name_len, name_len2;
3063         __u16 count;
3064
3065         cFYI(1, "In CIFSCreateHardLink");
3066 winCreateHardLinkRetry:
3067
3068         rc = smb_init(SMB_COM_NT_RENAME, 4, tcon, (void **) &pSMB,
3069                       (void **) &pSMBr);
3070         if (rc)
3071                 return rc;
3072
3073         pSMB->SearchAttributes =
3074             cpu_to_le16(ATTR_READONLY | ATTR_HIDDEN | ATTR_SYSTEM |
3075                         ATTR_DIRECTORY);
3076         pSMB->Flags = cpu_to_le16(CREATE_HARD_LINK);
3077         pSMB->ClusterCount = 0;
3078
3079         pSMB->BufferFormat = 0x04;
3080
3081         if (pSMB->hdr.Flags2 & SMBFLG2_UNICODE) {
3082                 name_len =
3083                     cifsConvertToUCS((__le16 *) pSMB->OldFileName, fromName,
3084                                      PATH_MAX, nls_codepage, remap);
3085                 name_len++;     /* trailing null */
3086                 name_len *= 2;
3087
3088                 /* protocol specifies ASCII buffer format (0x04) for unicode */
3089                 pSMB->OldFileName[name_len] = 0x04;
3090                 pSMB->OldFileName[name_len + 1] = 0x00; /* pad */
3091                 name_len2 =
3092                     cifsConvertToUCS((__le16 *)&pSMB->OldFileName[name_len + 2],
3093                                      toName, PATH_MAX, nls_codepage, remap);
3094                 name_len2 += 1 /* trailing null */  + 1 /* Signature word */ ;
3095                 name_len2 *= 2; /* convert to bytes */
3096         } else {        /* BB improve the check for buffer overruns BB */
3097                 name_len = strnlen(fromName, PATH_MAX);
3098                 name_len++;     /* trailing null */
3099                 strncpy(pSMB->OldFileName, fromName, name_len);
3100                 name_len2 = strnlen(toName, PATH_MAX);
3101                 name_len2++;    /* trailing null */
3102                 pSMB->OldFileName[name_len] = 0x04;     /* 2nd buffer format */
3103                 strncpy(&pSMB->OldFileName[name_len + 1], toName, name_len2);
3104                 name_len2++;    /* trailing null */
3105                 name_len2++;    /* signature byte */
3106         }
3107
3108         count = 1 /* string type byte */  + name_len + name_len2;
3109         inc_rfc1001_len(pSMB, count);
3110         pSMB->ByteCount = cpu_to_le16(count);
3111
3112         rc = SendReceive(xid, tcon->ses, (struct smb_hdr *) pSMB,
3113                          (struct smb_hdr *) pSMBr, &bytes_returned, 0);
3114         cifs_stats_inc(&tcon->num_hardlinks);
3115         if (rc)
3116                 cFYI(1, "Send error in hard link (NT rename) = %d", rc);
3117
3118         cifs_buf_release(pSMB);
3119         if (rc == -EAGAIN)
3120                 goto winCreateHardLinkRetry;
3121
3122         return rc;
3123 }
3124
3125 int
3126 CIFSSMBUnixQuerySymLink(const int xid, struct cifs_tcon *tcon,
3127                         const unsigned char *searchName, char **symlinkinfo,
3128                         const struct nls_table *nls_codepage)